code stringlengths 582 165k | apis list | extract_api stringlengths 325 147k |
|---|---|---|
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2018-10-11 17:51:43
# @Last modified by: <NAME>
# @Last Modified time: 2018-11-29 17:23:15
from __future__ import print_function, division, absolute_import
import numpy as np
import astropy
import astropy.units as u
import marvin.tools
from marvin.tools.quantities.spectrum import Spectrum
from marvin.utils.general.general import get_drpall_table
from marvin.utils.plot.scatter import plot as scatplot
from marvin import log
from .base import VACMixIn, VACTarget
def choose_best_spectrum(par1, par2, conf_thresh=0.1):
'''choose optimal HI spectrum based on the following criteria:
(1) If both detected and unconfused, choose highest SNR
(2) If both detected and both confused, choose lower confusion prob.
(3) If both detected and one confused, choose non-confused
(4) If one non-confused detection and one non-detection, go with detection
(5) If one confused detetion and one non-detection, go with non-detection
(6) If niether detected, choose lowest rms
par1 and par2 are dictionaries with the following parameters:
program - gbt or alfalfa
snr - integrated SNR
rms - rms noise level
conf_prob - confusion probability
conf_thresh = maximum confusion probability below which we classify
the object as essentially unconfused. Default to 0.1 following
(Stark+21)
'''
programs = [par1['program'],par2['program']]
sel_high_snr = np.argmax([par1['snr'],par2['snr']])
sel_low_rms = np.argmin([par1['rms'],par2['rms']])
sel_low_conf = np.argmin([par1['conf_prob'],par2['conf_prob']])
#both detected
if (par1['snr'] > 0) & (par2['snr'] > 0):
if (par1['conf_prob'] <= conf_thresh) & (par2['conf_prob'] <= conf_thresh):
pick = sel_high_snr
elif (par1['conf_prob'] <= conf_thresh) & (par2['conf_prob'] > conf_thresh):
pick = 0
elif (par1['conf_prob'] > conf_thresh) & (par2['conf_prob'] <= conf_thresh):
pick = 1
elif (par1['conf_prob'] > conf_thresh) & (par2['conf_prob'] > conf_thresh):
pick = sel_low_conf
#both nondetected
elif (par1['snr'] <= 0) & (par2['snr'] <= 0):
pick = sel_low_rms
#one detected
elif (par1['snr'] > 0) & (par2['snr'] <= 0):
if par1['conf_prob'] < conf_thresh:
pick=0
else:
pick=1
elif (par1['snr'] <= 0) & (par2['snr'] > 0):
if par2['conf_prob'] < conf_thresh:
pick=1
else:
pick=0
return programs[pick]
class HIVAC(VACMixIn):
"""Provides access to the MaNGA-HI VAC.
VAC name: HI
URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=hi-manga-data-release-1
Description: Returns HI summary data and spectra
Authors: <NAME> and <NAME>
"""
# Required parameters
name = 'HI'
description = 'Returns HI summary data and spectra'
version = {'MPL-7': 'v1_0_1', 'DR15': 'v1_0_1', 'DR16': 'v1_0_2', 'DR17': 'v2_0_1', 'MPL-11': 'v2_0_1'}
display_name = 'HI'
url = 'https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=hi-manga-data-release-1'
# optional Marvin Tools to attach your vac to
include = (marvin.tools.cube.Cube, marvin.tools.maps.Maps, marvin.tools.modelcube.ModelCube)
# optional methods to attach to your main VAC tool in ~marvin.tools.vacs.VACs
add_methods = ['plot_mass_fraction']
# Required method
def set_summary_file(self, release):
''' Sets the path to the HI summary file '''
# define the variables to build a unique path to your VAC file
self.path_params = {'ver': self.version[release], 'type': 'all', 'program': 'GBT16A_095'}
# get_path returns False if the files do not exist locally
self.summary_file = self.get_path("mangahisum", path_params=self.path_params)
def set_program(self,plateifu):
# download the vac from the SAS if it does not already exist locally
if not self.file_exists(self.summary_file):
self.summary_file = self.download_vac('mangahisum', path_params=self.path_params)
# Find all entries in summary file with this plate-ifu.
# Need the full summary file data.
# Find best entry between GBT/ALFALFA based on dept and confusion.
# Then update self.path_params['program'] with alfalfa or gbt.
summary = HITarget(plateifu, vacfile=self.summary_file)._data
galinfo = summary[summary['plateifu'] == plateifu]
if len(galinfo) == 1 and galinfo['session']=='ALFALFA':
program = 'alfalfa'
elif len(galinfo) in [0, 1]:
# if no entry found or session is GBT, default program to gbt
program = 'gbt'
else:
par1 = {'program': 'gbt','snr': 0.,'rms': galinfo[0]['rms'], 'conf_prob': galinfo[0]['conf_prob']}
par2 = {'program': 'gbt','snr': 0.,'rms': galinfo[1]['rms'], 'conf_prob': galinfo[1]['conf_prob']}
if galinfo[0]['session']=='ALFALFA':
par1['program'] = 'alfalfa'
if galinfo[1]['session']=='ALFALFA':
par2['program'] = 'alfalfa'
if galinfo[0]['fhi'] > 0:
par1['snr'] = galinfo[0]['fhi']/galinfo[0]['efhi']
if galinfo[1]['fhi'] > 0:
par2['snr'] = galinfo[1]['fhi']/galinfo[1]['efhi']
program = choose_best_spectrum(par1,par2)
log.info('Using HI data from {0}'.format(program))
# get path to ancillary VAC file for target HI spectra
self.update_path_params({'program':program})
# Required method
def get_target(self, parent_object):
''' Accesses VAC data for a specific target from a Marvin Tool object '''
# get any parameters you need from the parent object
plateifu = parent_object.plateifu
self.update_path_params({'plateifu': plateifu})
if parent_object.release in ['DR17', 'MPL-11']:
self.set_program(plateifu)
specfile = self.get_path('mangahispectra', path_params=self.path_params)
# create container for more complex return data
hidata = HITarget(plateifu, vacfile=self.summary_file, specfile=specfile)
# get the spectral data for that row if it exists
if hidata._indata and not self.file_exists(specfile):
hidata._specfile = self.download_vac('mangahispectra', path_params=self.path_params)
return hidata
class HITarget(VACTarget):
''' A customized target class to also display HI spectra
This class handles data from both the HI summary file and the
individual spectral files. Row data from the summary file for the given target
is returned via the `data` property. Spectral data can be displayed via
the the `plot_spectrum` method.
Parameters:
targetid (str):
The plateifu or mangaid designation
vacfile (str):
The path of the VAC summary file
specfile (str):
The path to the HI spectra
Attributes:
data:
The target row data from the main VAC file
targetid (str):
The target identifier
'''
def __init__(self, targetid, vacfile, specfile=None):
super(HITarget, self).__init__(targetid, vacfile)
self._specfile = specfile
self._specdata = None
def plot_spectrum(self):
''' Plot the HI spectrum '''
if self._specfile:
if not self._specdata:
self._specdata = self._get_data(self._specfile)
vel = self._specdata['VHI'][0]
flux = self._specdata['FHI'][0]
spec = Spectrum(flux, unit=u.Jy, wavelength=vel,
wavelength_unit=u.km / u.s)
ax = spec.plot(
ylabel='HI\ Flux\ Density', xlabel='Velocity', title=self.targetid, ytrim='minmax'
)
return ax
return None
#
# Functions to become available on your VAC in marvin.tools.vacs.VACs
def plot_mass_fraction(vacdata_object):
''' Plot the HI mass fraction
Computes and plots the HI mass fraction using
the NSA elliptical Petrosian stellar mass from the
MaNGA DRPall file. Only plots data for subset of
targets in both the HI VAC and the DRPall file.
Parameters:
vacdata_object (object):
The `~.VACDataClass` instance of the HI VAC
Example:
>>> from marvin.tools.vacs import VACs
>>> v = VACs()
>>> hi = v.HI
>>> hi.plot_mass_fraction()
'''
drpall = get_drpall_table()
drpall.add_index('plateifu')
data = vacdata_object.data[1].data
subset = drpall.loc[data['plateifu']]
log_stmass = np.log10(subset['nsa_elpetro_mass'])
diff = data['logMHI'] - log_stmass
fig, axes = scatplot(
log_stmass,
diff,
with_hist=False,
ylim=[-5, 5],
xlabel=r'log $M_*$',
ylabel=r'log $M_{HI}/M_*$',
)
return axes[0]
| [
"marvin.utils.general.general.get_drpall_table",
"marvin.utils.plot.scatter.plot",
"marvin.tools.quantities.spectrum.Spectrum"
] | [((1530, 1567), 'numpy.argmax', 'np.argmax', (["[par1['snr'], par2['snr']]"], {}), "([par1['snr'], par2['snr']])\n", (1539, 1567), True, 'import numpy as np\n'), ((1585, 1622), 'numpy.argmin', 'np.argmin', (["[par1['rms'], par2['rms']]"], {}), "([par1['rms'], par2['rms']])\n", (1594, 1622), True, 'import numpy as np\n'), ((1641, 1690), 'numpy.argmin', 'np.argmin', (["[par1['conf_prob'], par2['conf_prob']]"], {}), "([par1['conf_prob'], par2['conf_prob']])\n", (1650, 1690), True, 'import numpy as np\n'), ((8779, 8797), 'marvin.utils.general.general.get_drpall_table', 'get_drpall_table', ([], {}), '()\n', (8795, 8797), False, 'from marvin.utils.general.general import get_drpall_table\n'), ((8929, 8965), 'numpy.log10', 'np.log10', (["subset['nsa_elpetro_mass']"], {}), "(subset['nsa_elpetro_mass'])\n", (8937, 8965), True, 'import numpy as np\n'), ((9021, 9130), 'marvin.utils.plot.scatter.plot', 'scatplot', (['log_stmass', 'diff'], {'with_hist': '(False)', 'ylim': '[-5, 5]', 'xlabel': '"""log $M_*$"""', 'ylabel': '"""log $M_{HI}/M_*$"""'}), "(log_stmass, diff, with_hist=False, ylim=[-5, 5], xlabel=\n 'log $M_*$', ylabel='log $M_{HI}/M_*$')\n", (9029, 9130), True, 'from marvin.utils.plot.scatter import plot as scatplot\n'), ((7863, 7932), 'marvin.tools.quantities.spectrum.Spectrum', 'Spectrum', (['flux'], {'unit': 'u.Jy', 'wavelength': 'vel', 'wavelength_unit': '(u.km / u.s)'}), '(flux, unit=u.Jy, wavelength=vel, wavelength_unit=u.km / u.s)\n', (7871, 7932), False, 'from marvin.tools.quantities.spectrum import Spectrum\n')] |
#!/usr/bin/env python
# encoding: utf-8
#
# bpt.py
#
# Created by <NAME> on 19 Jan 2017.
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from packaging.version import parse
import warnings
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import ImageGrid
from marvin.core.exceptions import MarvinDeprecationWarning, MarvinError
from marvin.utils.plot import bind_to_figure
__ALL__ = ('get_snr', 'kewley_sf_nii', 'kewley_sf_sii', 'kewley_sf_oi',
'kewley_comp_nii', 'kewley_agn_sii', 'kewley_agn_oi',
'bpt_kewley06')
def get_snr(snr_min, emission_line, default=3):
"""Convenience function to get the minimum SNR for a certain emission line.
If ``snr_min`` is a dictionary and ``emision_line`` is one of the keys,
returns that value. If the emission line is not included in the dictionary,
returns ``default``. If ``snr_min`` is a float, returns that value
regardless of the ``emission_line``.
"""
if not isinstance(snr_min, dict):
return snr_min
if emission_line in snr_min:
return snr_min[emission_line]
else:
return default
def get_masked(maps, emline, snr=1):
"""Convenience function to get masked arrays without negative values."""
gflux = maps['emline_gflux_' + emline]
gflux_masked = gflux.masked
# Masks spaxels with flux <= 0
gflux_masked.mask |= (gflux_masked.data <= 0)
# Masks all spaxels that don't reach the cutoff SNR
gflux_masked.mask |= gflux.snr < snr
gflux_masked.mask |= gflux.ivar == 0
return gflux_masked
def _get_kewley06_axes(use_oi=True):
"""Creates custom axes for displaying Kewley06 plots."""
fig = plt.figure(None, (8.5, 10))
fig.clf()
plt.subplots_adjust(top=0.99, bottom=0.08, hspace=0.01)
# The axes for the three classification plots
imgrid_kwargs = {'add_all': True} if parse(matplotlib.__version__) < parse('3.5.0') else {}
grid_bpt = ImageGrid(fig, 211,
nrows_ncols=(1, 3) if use_oi else (1, 2),
direction='row',
axes_pad=0.1,
label_mode='L',
share_all=False, **imgrid_kwargs)
# The axes for the galaxy display
gal_bpt = ImageGrid(fig, 212, nrows_ncols=(1, 1))
# Plots the classification boundary lines
xx_sf_nii = np.linspace(-1.281, 0.045, int(1e4))
xx_sf_sii = np.linspace(-2, 0.315, int(1e4))
xx_sf_oi = np.linspace(-2.5, -0.7, int(1e4))
xx_comp_nii = np.linspace(-2, 0.4, int(1e4))
xx_agn_sii = np.array([-0.308, 1.0])
xx_agn_oi = np.array([-1.12, 0.5])
grid_bpt[0].plot(xx_sf_nii, kewley_sf_nii(xx_sf_nii), 'k--', zorder=90)
grid_bpt[1].plot(xx_sf_sii, kewley_sf_sii(xx_sf_sii), 'r-', zorder=90)
if use_oi:
grid_bpt[2].plot(xx_sf_oi, kewley_sf_oi(xx_sf_oi), 'r-', zorder=90)
grid_bpt[0].plot(xx_comp_nii, kewley_comp_nii(xx_comp_nii), 'r-', zorder=90)
grid_bpt[1].plot(xx_agn_sii, kewley_agn_sii(xx_agn_sii), 'b-', zorder=80)
if use_oi:
grid_bpt[2].plot(xx_agn_oi, kewley_agn_oi(xx_agn_oi), 'b-', zorder=80)
# Adds captions
grid_bpt[0].text(-1, -0.5, 'SF', ha='center', fontsize=12, zorder=100, color='c')
grid_bpt[0].text(0.5, 0.5, 'AGN', ha='left', fontsize=12, zorder=100)
grid_bpt[0].text(-0.08, -1.2, 'Comp', ha='left', fontsize=12, zorder=100, color='g')
grid_bpt[1].text(-1.2, -0.5, 'SF', ha='center', fontsize=12, zorder=100)
grid_bpt[1].text(-1, 1.2, 'Seyfert', ha='left', fontsize=12, zorder=100, color='r')
grid_bpt[1].text(0.3, -1, 'LINER', ha='left', fontsize=12, zorder=100, color='m')
if use_oi:
grid_bpt[2].text(-2, -0.5, 'SF', ha='center', fontsize=12, zorder=100)
grid_bpt[2].text(-1.5, 1, 'Seyfert', ha='left', fontsize=12, zorder=100)
grid_bpt[2].text(-0.1, -1, 'LINER', ha='right', fontsize=12, zorder=100)
# Sets the ticks, ticklabels, and other details
xtick_limits = ((-2, 1), (-1.5, 1), (-2.5, 0.5))
axes = [0, 1, 2] if use_oi else [0, 1]
for ii in axes:
grid_bpt[ii].get_xaxis().set_tick_params(direction='in')
grid_bpt[ii].get_yaxis().set_tick_params(direction='in')
grid_bpt[ii].set_xticks(np.arange(xtick_limits[ii][0], xtick_limits[ii][1] + 0.5, 0.5))
grid_bpt[ii].set_xticks(np.arange(xtick_limits[ii][0],
xtick_limits[ii][1] + 0.1, 0.1), minor=True)
grid_bpt[ii].set_yticks(np.arange(-1.5, 2.0, 0.5))
grid_bpt[ii].set_yticks(np.arange(-1.5, 1.6, 0.1), minor=True)
grid_bpt[ii].grid(which='minor', alpha=0.2)
grid_bpt[ii].grid(which='major', alpha=0.5)
grid_bpt[ii].set_xlim(xtick_limits[ii][0], xtick_limits[ii][1])
grid_bpt[ii].set_ylim(-1.5, 1.6)
if use_oi:
grid_bpt[ii].set_ylim(-1.5, 1.8)
grid_bpt[ii].spines['top'].set_visible(True)
if ii in [0, 1]:
if not use_oi and ii == 1:
continue
grid_bpt[ii].get_xticklabels()[-1].set_visible(False)
grid_bpt[0].set_ylabel(r'log([OIII]/H$\beta$)')
grid_bpt[0].set_xlabel(r'log([NII]/H$\alpha$)')
grid_bpt[1].set_xlabel(r'log([SII]/H$\alpha$)')
if use_oi:
grid_bpt[2].set_xlabel(r'log([OI]/H$\alpha$)')
gal_bpt[0].grid(False)
return fig, grid_bpt, gal_bpt[0]
def kewley_sf_nii(log_nii_ha):
"""Star forming classification line for log([NII]/Ha)."""
return 0.61 / (log_nii_ha - 0.05) + 1.3
def kewley_sf_sii(log_sii_ha):
"""Star forming classification line for log([SII]/Ha)."""
return 0.72 / (log_sii_ha - 0.32) + 1.3
def kewley_sf_oi(log_oi_ha):
"""Star forming classification line for log([OI]/Ha)."""
return 0.73 / (log_oi_ha + 0.59) + 1.33
def kewley_comp_nii(log_nii_ha):
"""Composite classification line for log([NII]/Ha)."""
return 0.61 / (log_nii_ha - 0.47) + 1.19
def kewley_agn_sii(log_sii_ha):
"""Seyfert/LINER classification line for log([SII]/Ha)."""
return 1.89 * log_sii_ha + 0.76
def kewley_agn_oi(log_oi_ha):
"""Seyfert/LINER classification line for log([OI]/Ha)."""
return 1.18 * log_oi_ha + 1.30
def bpt_kewley06(maps, snr_min=3, return_figure=True, use_oi=True, **kwargs):
"""Returns a classification of ionisation regions, as defined in Kewley+06.
Makes use of the classification system defined by
`Kewley et al. (2006) <https://ui.adsabs.harvard.edu/#abs/2006MNRAS.372..961K/abstract>`_
to return classification masks for different ionisation mechanisms. If ``return_figure=True``,
produces and returns a matplotlib figure with the classification plots (based on
Kewley+06 Fig. 4) and the 2D spatial distribution of classified spaxels (i.e., a map of the
galaxy in which each spaxel is colour-coded based on its emission mechanism).
While it is possible to call this function directly, its normal use will be via the
:func:`~marvin.tools.maps.Maps.get_bpt` method.
Parameters:
maps (a Marvin :class:`~marvin.tools.maps.Maps` object)
The Marvin Maps object that contains the emission line maps to be used to determine
the BPT classification.
snr_min (float or dict):
The signal-to-noise cutoff value for the emission lines used to generate the BPT
diagram. If ``snr_min`` is a single value, that signal-to-noise will be used for all
the lines. Alternatively, a dictionary of signal-to-noise values, with the
emission line channels as keys, can be used.
E.g., ``snr_min={'ha': 5, 'nii': 3, 'oi': 1}``. If some values are not provided,
they will default to ``SNR>=3``. Note that the value ``sii`` will be applied to both
``[SII 6718]`` and ``[SII 6732]``.
return_figure (bool):
If ``True``, it also returns the matplotlib figure_ of the BPT diagram plot,
which can be used to modify the style of the plot.
use_oi (bool):
If ``True``, uses the OI diagnostic diagram for spaxel classification.
Returns:
bpt_return:
``bpt_kewley06`` returns a dictionary of dictionaries of classification masks.
The classification masks (not to be confused with bitmasks) are boolean arrays with the
same shape as the Maps or Cube (without the spectral dimension) that can be used
to select spaxels belonging to a certain excitation process (e.g., star forming).
The returned dictionary has the following keys: ``'sf'`` (star forming), ``'comp'``
(composite), ``'agn'``, ``'seyfert'``, ``'liner'``, ``'invalid'``
(spaxels that are masked out at the DAP level), and ``'ambiguous'`` (good spaxels that
do not fall in any classification or fall in more than one). Each key provides access
to a new dictionary with keys ``'nii'`` (for the constraints in the diagram NII/Halpha
vs OIII/Hbeta), ``'sii'`` (SII/Halpha vs OIII/Hbeta), ``'oi'`` (OI/Halpha vs
OIII/Hbeta; only if ``use_oi=True``), and ``'global'``, which applies all the previous
constraints at once. The ``'ambiguous'`` mask only contains the ``'global'``
subclassification, while the ``'comp'`` dictionary only contains ``'nii'``.
``'nii'`` is not available for ``'seyfert'`` and ``'liner'``. All the global masks are
unique (a spaxel can only belong to one of them) with the exception of ``'agn'``, which
intersects with ``'seyfert'`` and ``'liner'``. Additionally, if ``return_figure=True``,
``bpt_kewley06`` will also return the matplotlib figure for the generated plot, and a
list of axes for each one of the subplots.
Example:
>>> maps_8485_1901 = Maps(plateifu='8485-1901')
>>> bpt_masks, fig, axes = bpt_kewley06(maps_8485_1901)
Gets the global mask for star forming spaxels
>>> sf = bpt_masks['sf']['global']
Gets the seyfert mask based only on the SII/Halpha vs OIII/Hbeta diagnostics
>>> seyfert_sii = bpt_masks['seyfert']['sii']
"""
if 'snr' in kwargs:
warnings.warn('snr is deprecated. Use snr_min instead. '
'snr will be removed in a future version of marvin',
MarvinDeprecationWarning)
snr_min = kwargs.pop('snr')
if len(kwargs.keys()) > 0:
raise MarvinError('unknown keyword {0}'.format(list(kwargs.keys())[0]))
# Gets the necessary emission line maps
oiii = get_masked(maps, 'oiii_5008', snr=get_snr(snr_min, 'oiii'))
nii = get_masked(maps, 'nii_6585', snr=get_snr(snr_min, 'nii'))
ha = get_masked(maps, 'ha_6564', snr=get_snr(snr_min, 'ha'))
hb = get_masked(maps, 'hb_4862', snr=get_snr(snr_min, 'hb'))
oi = get_masked(maps, 'oi_6302', snr=get_snr(snr_min, 'oi'))
sii_6718 = get_masked(maps, 'sii_6718', snr=get_snr(snr_min, 'sii'))
sii_6732 = get_masked(maps, 'sii_6732', snr=get_snr(snr_min, 'sii'))
sii = sii_6718 + sii_6732
# Calculate masked logarithms
log_oiii_hb = np.ma.log10(oiii / hb)
log_nii_ha = np.ma.log10(nii / ha)
log_sii_ha = np.ma.log10(sii / ha)
log_oi_ha = np.ma.log10(oi / ha)
# Calculates masks for each emission mechanism according to the paper boundaries.
# The log_nii_ha < 0.05, log_sii_ha < 0.32, etc are necessary because the classification lines
# diverge and we only want the region before the asymptota.
sf_mask_nii = ((log_oiii_hb < kewley_sf_nii(log_nii_ha)) & (log_nii_ha < 0.05)).filled(False)
sf_mask_sii = ((log_oiii_hb < kewley_sf_sii(log_sii_ha)) & (log_sii_ha < 0.32)).filled(False)
sf_mask_oi = ((log_oiii_hb < kewley_sf_oi(log_oi_ha)) & (log_oi_ha < -0.59)).filled(False)
sf_mask = sf_mask_nii & sf_mask_sii & sf_mask_oi if use_oi else sf_mask_nii & sf_mask_sii
comp_mask = ((log_oiii_hb > kewley_sf_nii(log_nii_ha)) & (log_nii_ha < 0.05)).filled(False) & \
((log_oiii_hb < kewley_comp_nii(log_nii_ha)) & (log_nii_ha < 0.465)).filled(False)
comp_mask &= (sf_mask_sii & sf_mask_oi) if use_oi else sf_mask_sii
agn_mask_nii = ((log_oiii_hb > kewley_comp_nii(log_nii_ha)) |
(log_nii_ha > 0.465)).filled(False)
agn_mask_sii = ((log_oiii_hb > kewley_sf_sii(log_sii_ha)) |
(log_sii_ha > 0.32)).filled(False)
agn_mask_oi = ((log_oiii_hb > kewley_sf_oi(log_oi_ha)) |
(log_oi_ha > -0.59)).filled(False)
agn_mask = agn_mask_nii & agn_mask_sii & agn_mask_oi if use_oi else agn_mask_nii & agn_mask_sii
seyfert_mask_sii = agn_mask & (kewley_agn_sii(log_sii_ha) < log_oiii_hb).filled(False)
seyfert_mask_oi = agn_mask & (kewley_agn_oi(log_oi_ha) < log_oiii_hb).filled(False)
seyfert_mask = seyfert_mask_sii & seyfert_mask_oi if use_oi else seyfert_mask_sii
liner_mask_sii = agn_mask & (kewley_agn_sii(log_sii_ha) > log_oiii_hb).filled(False)
liner_mask_oi = agn_mask & (kewley_agn_oi(log_oi_ha) > log_oiii_hb).filled(False)
liner_mask = liner_mask_sii & liner_mask_oi if use_oi else liner_mask_sii
# The invalid mask is the combination of spaxels that are invalid in all of the emission maps
invalid_mask_nii = ha.mask | oiii.mask | nii.mask | hb.mask
invalid_mask_sii = ha.mask | oiii.mask | sii.mask | hb.mask
invalid_mask_oi = ha.mask | oiii.mask | oi.mask | hb.mask
invalid_mask = ha.mask | oiii.mask | nii.mask | hb.mask | sii.mask
if use_oi:
invalid_mask |= oi.mask
# The ambiguous mask are spaxels that are not invalid but don't fall into any of the
# emission mechanism classifications.
ambiguous_mask = ~(sf_mask | comp_mask | seyfert_mask | liner_mask) & ~invalid_mask
sf_classification = {'global': sf_mask,
'nii': sf_mask_nii,
'sii': sf_mask_sii}
comp_classification = {'global': comp_mask,
'nii': comp_mask}
agn_classification = {'global': agn_mask,
'nii': agn_mask_nii,
'sii': agn_mask_sii}
seyfert_classification = {'global': seyfert_mask,
'sii': seyfert_mask_sii}
liner_classification = {'global': liner_mask,
'sii': liner_mask_sii}
invalid_classification = {'global': invalid_mask,
'nii': invalid_mask_nii,
'sii': invalid_mask_sii}
ambiguous_classification = {'global': ambiguous_mask}
if use_oi:
sf_classification['oi'] = sf_mask_oi
agn_classification['oi'] = agn_mask_oi
seyfert_classification['oi'] = seyfert_mask_oi
liner_classification['oi'] = liner_mask_oi
invalid_classification['oi'] = invalid_mask_oi
bpt_return_classification = {'sf': sf_classification,
'comp': comp_classification,
'agn': agn_classification,
'seyfert': seyfert_classification,
'liner': liner_classification,
'invalid': invalid_classification,
'ambiguous': ambiguous_classification}
if not return_figure:
return bpt_return_classification
# Does all the plotting
with plt.style.context('seaborn-darkgrid'):
fig, grid_bpt, gal_bpt = _get_kewley06_axes(use_oi=use_oi)
sf_kwargs = {'marker': 's', 's': 12, 'color': 'c', 'zorder': 50, 'alpha': 0.7, 'lw': 0.0,
'label': 'Star-forming'}
sf_handler = grid_bpt[0].scatter(log_nii_ha[sf_mask], log_oiii_hb[sf_mask], **sf_kwargs)
grid_bpt[1].scatter(log_sii_ha[sf_mask], log_oiii_hb[sf_mask], **sf_kwargs)
comp_kwargs = {'marker': 's', 's': 12, 'color': 'g', 'zorder': 45, 'alpha': 0.7, 'lw': 0.0,
'label': 'Composite'}
comp_handler = grid_bpt[0].scatter(log_nii_ha[comp_mask], log_oiii_hb[comp_mask],
**comp_kwargs)
grid_bpt[1].scatter(log_sii_ha[comp_mask], log_oiii_hb[comp_mask], **comp_kwargs)
seyfert_kwargs = {'marker': 's', 's': 12, 'color': 'r', 'zorder': 40, 'alpha': 0.7, 'lw': 0.0,
'label': 'Seyfert'}
seyfert_handler = grid_bpt[0].scatter(log_nii_ha[seyfert_mask], log_oiii_hb[seyfert_mask],
**seyfert_kwargs)
grid_bpt[1].scatter(log_sii_ha[seyfert_mask], log_oiii_hb[seyfert_mask], **seyfert_kwargs)
liner_kwargs = {'marker': 's', 's': 12, 'color': 'm', 'zorder': 35, 'alpha': 0.7, 'lw': 0.0,
'label': 'LINER'}
liner_handler = grid_bpt[0].scatter(log_nii_ha[liner_mask], log_oiii_hb[liner_mask],
**liner_kwargs)
grid_bpt[1].scatter(log_sii_ha[liner_mask], log_oiii_hb[liner_mask], **liner_kwargs)
amb_kwargs = {'marker': 's', 's': 12, 'color': '0.6', 'zorder': 30, 'alpha': 0.7, 'lw': 0.0,
'label': 'Ambiguous '}
amb_handler = grid_bpt[0].scatter(log_nii_ha[ambiguous_mask], log_oiii_hb[ambiguous_mask],
**amb_kwargs)
grid_bpt[1].scatter(log_sii_ha[ambiguous_mask], log_oiii_hb[ambiguous_mask], **amb_kwargs)
if use_oi:
grid_bpt[2].scatter(log_oi_ha[sf_mask], log_oiii_hb[sf_mask], **sf_kwargs)
grid_bpt[2].scatter(log_oi_ha[comp_mask], log_oiii_hb[comp_mask], **comp_kwargs)
grid_bpt[2].scatter(log_oi_ha[seyfert_mask], log_oiii_hb[seyfert_mask], **seyfert_kwargs)
grid_bpt[2].scatter(log_oi_ha[liner_mask], log_oiii_hb[liner_mask], **liner_kwargs)
grid_bpt[2].scatter(log_oi_ha[ambiguous_mask], log_oiii_hb[ambiguous_mask], **amb_kwargs)
# Creates the legend
grid_bpt[0].legend([sf_handler, comp_handler, seyfert_handler, liner_handler, amb_handler],
['Star-forming', 'Composite', 'Seyfert', 'LINER', 'Ambiguous'], ncol=2,
loc='upper left', frameon=True, labelspacing=0.1, columnspacing=0.1,
handletextpad=0.1, fontsize=9)
# Creates a RGB image of the galaxy, and sets the colours of the spaxels to match the
# classification masks
gal_rgb = np.zeros((ha.shape[0], ha.shape[1], 3), dtype=np.uint8)
for ii in [1, 2]: # Cyan
gal_rgb[:, :, ii][sf_mask] = 255
gal_rgb[:, :, 1][comp_mask] = 128 # Green
gal_rgb[:, :, 0][seyfert_mask] = 255 # Red
# Magenta
gal_rgb[:, :, 0][liner_mask] = 255
gal_rgb[:, :, 2][liner_mask] = 255
for ii in [0, 1, 2]:
gal_rgb[:, :, ii][invalid_mask] = 255 # White
gal_rgb[:, :, ii][ambiguous_mask] = 169 # Grey
# Shows the image.
gal_bpt.imshow(gal_rgb, origin='lower', aspect='auto', interpolation='nearest')
gal_bpt.set_xlim(0, ha.shape[1] - 1)
gal_bpt.set_ylim(0, ha.shape[0] - 1)
gal_bpt.set_xlabel('x [spaxels]')
gal_bpt.set_ylabel('y [spaxels]')
axes = grid_bpt.axes_all + [gal_bpt]
# Adds custom method to create figure
for ax in axes:
setattr(ax.__class__, 'bind_to_figure', _bind_to_figure)
return (bpt_return_classification, fig, axes)
def _bind_to_figure(self, fig=None):
"""Copies axes to a new figure.
Uses ``marvin.utils.plot.utils.bind_to_figure`` with a number
of tweaks.
"""
new_figure = bind_to_figure(self, fig=fig)
if new_figure.axes[0].get_ylabel() == '':
new_figure.axes[0].set_ylabel('log([OIII]/H$\\beta$)')
return new_figure
| [
"marvin.utils.plot.bind_to_figure"
] | [((1783, 1810), 'matplotlib.pyplot.figure', 'plt.figure', (['None', '(8.5, 10)'], {}), '(None, (8.5, 10))\n', (1793, 1810), True, 'import matplotlib.pyplot as plt\n'), ((1830, 1885), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'top': '(0.99)', 'bottom': '(0.08)', 'hspace': '(0.01)'}), '(top=0.99, bottom=0.08, hspace=0.01)\n', (1849, 1885), True, 'import matplotlib.pyplot as plt\n'), ((2048, 2195), 'mpl_toolkits.axes_grid1.ImageGrid', 'ImageGrid', (['fig', '(211)'], {'nrows_ncols': '((1, 3) if use_oi else (1, 2))', 'direction': '"""row"""', 'axes_pad': '(0.1)', 'label_mode': '"""L"""', 'share_all': '(False)'}), "(fig, 211, nrows_ncols=(1, 3) if use_oi else (1, 2), direction=\n 'row', axes_pad=0.1, label_mode='L', share_all=False, **imgrid_kwargs)\n", (2057, 2195), False, 'from mpl_toolkits.axes_grid1 import ImageGrid\n'), ((2369, 2408), 'mpl_toolkits.axes_grid1.ImageGrid', 'ImageGrid', (['fig', '(212)'], {'nrows_ncols': '(1, 1)'}), '(fig, 212, nrows_ncols=(1, 1))\n', (2378, 2408), False, 'from mpl_toolkits.axes_grid1 import ImageGrid\n'), ((2675, 2698), 'numpy.array', 'np.array', (['[-0.308, 1.0]'], {}), '([-0.308, 1.0])\n', (2683, 2698), True, 'import numpy as np\n'), ((2715, 2737), 'numpy.array', 'np.array', (['[-1.12, 0.5]'], {}), '([-1.12, 0.5])\n', (2723, 2737), True, 'import numpy as np\n'), ((11267, 11289), 'numpy.ma.log10', 'np.ma.log10', (['(oiii / hb)'], {}), '(oiii / hb)\n', (11278, 11289), True, 'import numpy as np\n'), ((11307, 11328), 'numpy.ma.log10', 'np.ma.log10', (['(nii / ha)'], {}), '(nii / ha)\n', (11318, 11328), True, 'import numpy as np\n'), ((11346, 11367), 'numpy.ma.log10', 'np.ma.log10', (['(sii / ha)'], {}), '(sii / ha)\n', (11357, 11367), True, 'import numpy as np\n'), ((11384, 11404), 'numpy.ma.log10', 'np.ma.log10', (['(oi / ha)'], {}), '(oi / ha)\n', (11395, 11404), True, 'import numpy as np\n'), ((18444, 18499), 'numpy.zeros', 'np.zeros', (['(ha.shape[0], ha.shape[1], 3)'], {'dtype': 'np.uint8'}), '((ha.shape[0], ha.shape[1], 3), dtype=np.uint8)\n', (18452, 18499), True, 'import numpy as np\n'), ((19571, 19600), 'marvin.utils.plot.bind_to_figure', 'bind_to_figure', (['self'], {'fig': 'fig'}), '(self, fig=fig)\n', (19585, 19600), False, 'from marvin.utils.plot import bind_to_figure\n'), ((10330, 10472), 'warnings.warn', 'warnings.warn', (['"""snr is deprecated. Use snr_min instead. snr will be removed in a future version of marvin"""', 'MarvinDeprecationWarning'], {}), "(\n 'snr is deprecated. Use snr_min instead. snr will be removed in a future version of marvin'\n , MarvinDeprecationWarning)\n", (10343, 10472), False, 'import warnings\n'), ((15550, 15587), 'matplotlib.pyplot.style.context', 'plt.style.context', (['"""seaborn-darkgrid"""'], {}), "('seaborn-darkgrid')\n", (15567, 15587), True, 'import matplotlib.pyplot as plt\n'), ((1978, 2007), 'packaging.version.parse', 'parse', (['matplotlib.__version__'], {}), '(matplotlib.__version__)\n', (1983, 2007), False, 'from packaging.version import parse\n'), ((2010, 2024), 'packaging.version.parse', 'parse', (['"""3.5.0"""'], {}), "('3.5.0')\n", (2015, 2024), False, 'from packaging.version import parse\n'), ((4349, 4411), 'numpy.arange', 'np.arange', (['xtick_limits[ii][0]', '(xtick_limits[ii][1] + 0.5)', '(0.5)'], {}), '(xtick_limits[ii][0], xtick_limits[ii][1] + 0.5, 0.5)\n', (4358, 4411), True, 'import numpy as np\n'), ((4445, 4507), 'numpy.arange', 'np.arange', (['xtick_limits[ii][0]', '(xtick_limits[ii][1] + 0.1)', '(0.1)'], {}), '(xtick_limits[ii][0], xtick_limits[ii][1] + 0.1, 0.1)\n', (4454, 4507), True, 'import numpy as np\n'), ((4595, 4620), 'numpy.arange', 'np.arange', (['(-1.5)', '(2.0)', '(0.5)'], {}), '(-1.5, 2.0, 0.5)\n', (4604, 4620), True, 'import numpy as np\n'), ((4654, 4679), 'numpy.arange', 'np.arange', (['(-1.5)', '(1.6)', '(0.1)'], {}), '(-1.5, 1.6, 0.1)\n', (4663, 4679), True, 'import numpy as np\n')] |
# Imports
from time import sleep as wait # import sleep as wait for timer
from marvin.essentials import speak # speak function
from word2number import w2n
##############################
# File containing Timer code #
##############################
class TimerService():
def __init__(self, time_for, speak_type):
self.speak_type = speak_type
self.time_for = time_for
self.bob = 1
try:
if time_for == '':
raise Exception
except Exception:
self.bob = 0
def timerLogic(self):
time_for_timer = self.time_for.split(" ")[0]
if time_for_timer.lower() == 'zero' or time_for_timer == '0':
self.bob = 0
speak('You can\'t have a timer for 0 time')
if self.bob >= 1:
time_unit = marvin.essentials.splitJoin(self.time_for, 1)
if time_unit == '':
time_unit = 'minutes'
try:
bob = float(time_for_timer)
self.time_for_timer = float(time_for_timer)
except ValueError:
self.time_for_timer = float(w2n.word_to_num(str(time_for_timer)))
if 'min' in time_unit:
abs_time = abs(float(self.time_for_timer))
seconds_in_minutes = abs_time * 60
self.timer(seconds_in_minutes)
elif 'sec' in time_unit:
abs_time = abs(float(self.time_for_timer))
if abs_time >= 5.0:
self.timer(float(abs_time))
else:
speak('Any timer less than 5 seconds is to small count thousands', self.speak_type)
elif 'hr' in time_unit:
abs_time = abs(float(self.time_for_timer))
if abs_time <= 3:
seconds_in_hour = abs_time * 3600
self.timer(seconds_in_hour)
else:
speak('Timer does not support reminders over 3 hours use a calander reminder for long reminders', self.speak_type)
elif 'day' in time_unit:
speak('Timer does not support days use a calander reminder for long reminders', self.speak_type)
else:
speak('I couldn\'t find the time unit you wanted to use', self.speak_type)
else:
speak('You need to input a number for the timer', self.speak_type)
def timer(self, delay):
print('Timer Started')
time.sleep(float(delay))
speak('Timer Done!', self.speak_type) | [
"marvin.essentials.speak"
] | [((2512, 2549), 'marvin.essentials.speak', 'speak', (['"""Timer Done!"""', 'self.speak_type'], {}), "('Timer Done!', self.speak_type)\n", (2517, 2549), False, 'from marvin.essentials import speak\n'), ((725, 767), 'marvin.essentials.speak', 'speak', (['"""You can\'t have a timer for 0 time"""'], {}), '("You can\'t have a timer for 0 time")\n', (730, 767), False, 'from marvin.essentials import speak\n'), ((2344, 2410), 'marvin.essentials.speak', 'speak', (['"""You need to input a number for the timer"""', 'self.speak_type'], {}), "('You need to input a number for the timer', self.speak_type)\n", (2349, 2410), False, 'from marvin.essentials import speak\n'), ((1585, 1673), 'marvin.essentials.speak', 'speak', (['"""Any timer less than 5 seconds is to small count thousands"""', 'self.speak_type'], {}), "('Any timer less than 5 seconds is to small count thousands', self.\n speak_type)\n", (1590, 1673), False, 'from marvin.essentials import speak\n'), ((1943, 2067), 'marvin.essentials.speak', 'speak', (['"""Timer does not support reminders over 3 hours use a calander reminder for long reminders"""', 'self.speak_type'], {}), "(\n 'Timer does not support reminders over 3 hours use a calander reminder for long reminders'\n , self.speak_type)\n", (1948, 2067), False, 'from marvin.essentials import speak\n'), ((2112, 2212), 'marvin.essentials.speak', 'speak', (['"""Timer does not support days use a calander reminder for long reminders"""', 'self.speak_type'], {}), "('Timer does not support days use a calander reminder for long reminders',\n self.speak_type)\n", (2117, 2212), False, 'from marvin.essentials import speak\n'), ((2243, 2316), 'marvin.essentials.speak', 'speak', (['"""I couldn\'t find the time unit you wanted to use"""', 'self.speak_type'], {}), '("I couldn\'t find the time unit you wanted to use", self.speak_type)\n', (2248, 2316), False, 'from marvin.essentials import speak\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: <NAME>, <NAME>, and <NAME>
# @Date: 2017-03-20
# @Filename: conftest.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: <NAME>
# @Last modified time: 2018-07-21 21:51:06
import copy
import itertools
import os
import warnings
from collections import OrderedDict
import pytest
import yaml
from brain import bconfig
from flask_jwt_extended import tokens
from sdss_access.path import Path
from marvin import config, marvindb
from marvin.api.api import Interaction
from marvin.tools.cube import Cube
from marvin.tools.maps import Maps
from marvin.tools.modelcube import ModelCube
from marvin.tools.query import Query
from marvin.utils.datamodel.dap import datamodel
from marvin.utils.general import check_versions
from brain.utils.general import get_yaml_loader
warnings.simplefilter('always')
# PYTEST MODIFIERS
# -----------------
def pytest_addoption(parser):
"""Add new options"""
# run slow tests
parser.addoption('--runslow', action='store_true', default=False, help='Run slow tests.')
# control releases run
parser.addoption('--travis-only', action='store_true', default=False, help='Run a Travis only subset')
def pytest_runtest_setup(item):
"""Skip slow tests."""
if 'slow' in item.keywords and not item.config.getoption('--runslow'):
pytest.skip('Requires --runslow option to run.')
def pytest_configure(config):
''' Runs during configuration of conftest. Checks and sets a global instance for a
TravisSubset based on the pytest command line input of --travis-only
'''
option = config.getoption('--travis-only')
global travis
if option:
travis = TravisSubset()
# specific release instance
travis = None
class TravisSubset(object):
def __init__(self):
self.new_gals = ['8485-1901']
self.new_releases = ['MPL-6']
self.new_bintypes = ['SPX', 'HYB10']
self.new_templates = ['GAU-MILESHC']
self.new_dbs = ['nodb']
self.new_origins = ['file', 'api']
self.new_modes = ['local', 'remote', 'auto']
# Global Parameters for FIXTURES
# ------------------------------
#releases = ['MPL-6', 'MPL-5', 'MPL-4'] # to loop over releases (see release fixture)
releases = ['MPL-8']
bintypes_accepted = {'MPL-4': ['NONE', 'VOR10'],
'MPL-5': ['SPX', 'VOR10'],
'MPL-6': ['SPX', 'HYB10'],
'MPL-7': ['HYB10', 'VOR10'],
'MPL-8': ['HYB10', 'SPX']}
templates_accepted = {'MPL-4': ['MIUSCAT_THIN', 'MILES_THIN'],
'MPL-5': ['GAU-MILESHC'],
'MPL-6': ['GAU-MILESHC'],
'MPL-7': ['GAU-MILESHC'],
'MPL-8': ['MILESHC-MILESHC']}
def populate_bintypes_templates(releases):
''' Generates bintype and template dictionaries for each release '''
bintypes = OrderedDict((release, []) for release in releases)
templates = OrderedDict((release, []) for release in releases)
for release in releases:
bintemps = datamodel[release].get_bintemps()
for bintemp in bintemps:
bintype = bintemp.split('-')[0]
template = '-'.join(bintemp.split('-')[1:])
if release in bintypes_accepted and bintype not in bintypes_accepted[release]:
continue
if release in templates_accepted and template not in templates_accepted[release]:
continue
if bintype not in bintypes[release]:
bintypes[release].append(bintype)
if template not in templates[release]:
templates[release].append(template)
return bintypes, templates
bintypes, templates = populate_bintypes_templates(releases)
# TODO reduce modes to only local and remote
modes = ['local', 'remote', 'auto'] # to loop over modes (see mode fixture)
dbs = ['db', 'nodb'] # to loop over dbs (see db fixture)
origins = ['file', 'db', 'api'] # to loop over data origins (see data_origin fixture)
# Galaxy and Query data is stored in a YAML file
with open(os.path.join(os.path.dirname(__file__), 'data/galaxy_test_data.dat')) as f:
galaxy_data = yaml.load(f, Loader=get_yaml_loader())
with open(os.path.join(os.path.dirname(__file__), 'data/query_test_data.dat')) as f:
query_data = yaml.load(f, Loader=get_yaml_loader())
@pytest.fixture(scope='session', params=releases)
def release(request):
"""Yield a release."""
if travis and request.param not in travis.new_releases:
pytest.skip('Skipping non-requested release')
return request.param
def _get_release_generator_chain():
"""Return all valid combinations of (release, bintype, template)."""
return itertools.chain(*[itertools.product([release], bintypes[release],
templates[release]) for release in releases])
def _params_ids(fixture_value):
"""Return a test id for the release chain."""
return '-'.join(fixture_value)
@pytest.fixture(scope='session', params=sorted(_get_release_generator_chain()), ids=_params_ids)
def get_params(request):
"""Yield a tuple of (release, bintype, template)."""
# placeholder until the marvin_test_if decorator works in 2.7
release, bintype, template = request.param
if travis and release not in travis.new_releases:
pytest.skip('Skipping non-requested release')
if travis and bintype not in travis.new_bintypes:
pytest.skip('Skipping non-requested bintype')
if travis and template not in travis.new_templates:
pytest.skip('Skipping non-requested template')
return request.param
@pytest.fixture(scope='session', params=sorted(galaxy_data.keys()))
def plateifu(request):
"""Yield a plate-ifu."""
if travis and request.param not in travis.new_gals:
pytest.skip('Skipping non-requested galaxies')
return request.param
@pytest.fixture(scope='session', params=origins)
def data_origin(request):
"""Yield a data access mode."""
if travis and request.param not in travis.new_origins:
pytest.skip('Skipping non-requested origins')
return request.param
@pytest.fixture(scope='session', params=modes)
def mode(request):
"""Yield a data mode."""
if travis and request.param not in travis.new_modes:
pytest.skip('Skipping non-requested modes')
return request.param
# Config-based FIXTURES
# ----------------------
@pytest.fixture(scope='session', autouse=True)
def set_config():
"""Set config."""
config.use_sentry = False
config.add_github_message = False
config._traceback = None
@pytest.fixture()
def check_config():
"""Check the config to see if a db is on."""
return config.db is None
URLMAP = None
def set_sasurl(loc='local', port=None):
"""Set the sasurl to local or test-utah, and regenerate the urlmap."""
if not port:
port = int(os.environ.get('LOCAL_MARVIN_PORT', 5000))
istest = True if loc == 'utah' else False
config.switchSasUrl(loc, test=istest, port=port)
global URLMAP
if not URLMAP:
response = Interaction('/marvin/api/general/getroutemap', request_type='get', auth='netrc')
config.urlmap = response.getRouteMap()
URLMAP = config.urlmap
@pytest.fixture(scope='session', autouse=True)
def saslocal():
"""Set sasurl to local."""
set_sasurl(loc='local')
@pytest.fixture(scope='session')
def urlmap(saslocal):
"""Yield the config urlmap."""
return config.urlmap
@pytest.fixture(scope='session')
def set_release(release):
"""Set the release in the config."""
config.setMPL(release)
@pytest.fixture(scope='session')
def versions(release):
"""Yield the DRP and DAP versions for a release."""
drpver, dapver = config.lookUpVersions(release)
return drpver, dapver
@pytest.fixture(scope='session')
def drpver(versions):
"""Return DRP version."""
drpver, __ = versions
return drpver
@pytest.fixture(scope='session')
def dapver(versions):
"""Return DAP version."""
__, dapver = versions
return dapver
def set_the_config(release):
"""Set config release without parametrizing.
Using ``set_release`` combined with ``galaxy`` double parametrizes!"""
config.access = 'collab'
config.setRelease(release)
set_sasurl(loc='local')
config.login()
config._traceback = None
def custom_login():
config.token = tokens.encode_access_token('test', os.environ.get('MARVIN_SECRET'), 'HS256', False, True, 'user_claims', True, 'identity', 'user_claims')
def custom_auth(self, authtype=None):
authtype = 'token'
super(Interaction, self).setAuth(authtype=authtype)
# DB-based FIXTURES
# -----------------
class DB(object):
"""Object representing aspects of the marvin db.
Useful for tests needing direct DB access.
"""
def __init__(self):
"""Initialize with DBs."""
self._marvindb = marvindb
self.session = marvindb.session
self.datadb = marvindb.datadb
self.sampledb = marvindb.sampledb
self.dapdb = marvindb.dapdb
@pytest.fixture(scope='session')
def maindb():
"""Yield an instance of the DB object."""
yield DB()
@pytest.fixture(scope='function')
def db_off():
"""Turn the DB off for a test, and reset it after."""
config.forceDbOff()
yield
config.forceDbOn()
@pytest.fixture(autouse=True)
def db_on():
"""Automatically turn on the DB at collection time."""
config.forceDbOn()
@pytest.fixture()
def usedb(request):
''' fixture for optional turning off the db '''
if request.param:
config.forceDbOn()
else:
config.forceDbOff()
return config.db is not None
@pytest.fixture(params=dbs)
def db(request):
"""Turn local db on or off.
Use this to parametrize over all db options.
"""
if travis and request.param not in travis.new_dbs:
pytest.skip('Skipping non-requested dbs')
if request.param == 'db':
config.forceDbOn()
else:
config.forceDbOff()
yield config.db is not None
config.forceDbOn()
@pytest.fixture()
def exporigin(mode, db):
"""Return the expected origins for a given db/mode combo."""
if mode == 'local' and not db:
return 'file'
elif mode == 'local' and db:
return 'db'
elif mode == 'remote' and not db:
return 'api'
elif mode == 'remote' and db:
return 'api'
elif mode == 'auto' and db:
return 'db'
elif mode == 'auto' and not db:
return 'file'
@pytest.fixture()
def expmode(mode, db):
''' expected modes for a given db/mode combo '''
if mode == 'local' and not db:
return None
elif mode == 'local' and db:
return 'local'
elif mode == 'remote' and not db:
return 'remote'
elif mode == 'remote' and db:
return 'remote'
elif mode == 'auto' and db:
return 'local'
elif mode == 'auto' and not db:
return 'remote'
@pytest.fixture()
def user(maindb):
username = 'test'
password = '<PASSWORD>'
model = maindb.datadb.User
user = maindb.session.query(model).filter(model.username == username).one_or_none()
if not user:
user = model(username=username, login_count=1)
user.set_password(password)
maindb.session.add(user)
yield user
maindb.session.delete(user)
# Monkeypatch-based FIXTURES
# --------------------------
@pytest.fixture()
def monkeyconfig(request, monkeypatch):
"""Monkeypatch a variable on the Marvin config.
Example at line 160 in utils/test_general.
"""
name, value = request.param
monkeypatch.setattr(config, name, value=value)
@pytest.fixture()
def monkeymanga(monkeypatch, temp_scratch):
"""Monkeypatch the environ to create a temp SAS dir for reading/writing/downloading.
Example at line 141 in utils/test_images.
"""
monkeypatch.setitem(os.environ, 'SAS_BASE_DIR', str(temp_scratch))
monkeypatch.setitem(os.environ, 'MANGA_SPECTRO_REDUX',
str(temp_scratch.join('mangawork/manga/spectro/redux')))
monkeypatch.setitem(os.environ, 'MANGA_SPECTRO_ANALYSIS',
str(temp_scratch.join('mangawork/manga/spectro/analysis')))
@pytest.fixture()
def monkeyauth(monkeypatch):
monkeypatch.setattr(config, 'login', custom_login)
monkeypatch.setattr(Interaction, 'setAuth', custom_auth)
monkeypatch.setattr(bconfig, '_public_api_url', config.sasurl)
monkeypatch.setattr(bconfig, '_collab_api_url', config.sasurl)
# Temp Dir/File-based FIXTURES
# ----------------------------
@pytest.fixture(scope='function')
def temp_scratch(tmpdir_factory):
"""Create a temporary scratch space for reading/writing.
Use for creating temp dirs and files.
Example at line 208 in tools/test_query, line 254 in tools/test_results, and
misc/test_marvin_pickle.
"""
fn = tmpdir_factory.mktemp('scratch')
return fn
def tempafile(path, temp_scratch):
"""Return a pytest temporary file given the original file path.
Example at line 141 in utils/test_images.
"""
redux = os.getenv('MANGA_SPECTRO_REDUX')
anal = os.getenv('MANGA_SPECTRO_ANALYSIS')
endredux = path.partition(redux)[-1]
endanal = path.partition(anal)[-1]
end = (endredux or endanal)
return temp_scratch.join(end)
# Object-based FIXTURES
# ---------------------
class Galaxy(object):
"""An example galaxy for Marvin-tools testing."""
sasbasedir = os.getenv('SAS_BASE_DIR')
mangaredux = os.getenv('MANGA_SPECTRO_REDUX')
mangaanalysis = os.getenv('MANGA_SPECTRO_ANALYSIS')
dir3d = 'stack'
def __init__(self, plateifu):
"""Initialize plate and ifu."""
self.plateifu = plateifu
self.plate, self.ifu = self.plateifu.split('-')
self.plate = int(self.plate)
def set_galaxy_data(self, data_origin=None):
"""Set galaxy properties from the configuration file."""
if self.plateifu not in galaxy_data:
return
data = copy.deepcopy(galaxy_data[self.plateifu])
for key in data.keys():
setattr(self, key, data[key])
# sets specfic data per release
releasedata = self.releasedata[self.release]
for key in releasedata.keys():
setattr(self, key, releasedata[key])
# remap NSA drpall names for MPL-4 vs 5+
drpcopy = self.nsa_data['drpall'].copy()
for key, val in self.nsa_data['drpall'].items():
if isinstance(val, list):
newval, newkey = drpcopy.pop(key)
if self.release == 'MPL-4':
drpcopy[newkey] = newval
else:
drpcopy[key] = newval
self.nsa_data['drpall'] = drpcopy
def set_params(self, bintype=None, template=None, release=None):
"""Set bintype, template, etc."""
self.release = release
self.drpver, self.dapver = config.lookUpVersions(self.release)
self.drpall = 'drpall-{0}.fits'.format(self.drpver)
self.bintype = datamodel[self.dapver].get_bintype(bintype)
self.template = datamodel[self.dapver].get_template(template)
self.bintemp = '{0}-{1}'.format(self.bintype.name, self.template.name)
if release == 'MPL-4':
self.niter = int('{0}{1}'.format(self.template.n, self.bintype.n))
else:
self.niter = '*'
self.access_kwargs = {'plate': self.plate, 'ifu': self.ifu, 'drpver': self.drpver,
'dapver': self.dapver, 'dir3d': self.dir3d, 'mpl': self.release,
'bintype': self.bintype.name, 'n': self.niter, 'mode': '*',
'daptype': self.bintemp}
def set_filepaths(self, pathtype='full'):
"""Set the paths for cube, maps, etc."""
self.path = Path()
if check_versions(self.drpver, 'v2_5_3'):
self.imgpath = self.path.__getattribute__(pathtype)('mangaimagenew', **self.access_kwargs)
else:
self.imgpath = self.path.__getattribute__(pathtype)('mangaimage', **self.access_kwargs)
self.cubepath = self.path.__getattribute__(pathtype)('mangacube', **self.access_kwargs)
self.rsspath = self.path.__getattribute__(pathtype)('mangarss', **self.access_kwargs)
if self.release == 'MPL-4':
self.mapspath = self.path.__getattribute__(pathtype)('mangamap', **self.access_kwargs)
self.modelpath = None
else:
self.access_kwargs.pop('mode')
self.mapspath = self.path.__getattribute__(pathtype)('mangadap5', mode='MAPS',
**self.access_kwargs)
self.modelpath = self.path.__getattribute__(pathtype)('mangadap5', mode='LOGCUBE',
**self.access_kwargs)
def get_location(self, path):
"""Extract the location from the input path."""
return self.path.location("", full=path)
def partition_path(self, path):
"""Partition the path into non-redux/analysis parts."""
endredux = path.partition(self.mangaredux)[-1]
endanalysis = path.partition(self.mangaanalysis)[-1]
end = (endredux or endanalysis)
return end
def new_path(self, name, newvar):
''' Sets a new path with the subsituted name '''
access_copy = self.access_kwargs.copy()
access_copy['mode'] = '*'
access_copy.update(**newvar)
if name == 'maps':
access_copy['mode'] = 'MAPS'
name = 'mangamap' if self.release == 'MPL-4' else 'mangadap5'
elif name == 'modelcube':
access_copy['mode'] = 'LOGCUBE'
name = None if self.release == 'MPL-4' else 'mangadap5'
path = self.path.full(name, **access_copy) if name else None
return path
@pytest.fixture(scope='function')
def galaxy(monkeyauth, get_params, plateifu):
"""Yield an instance of a Galaxy object for use in tests."""
release, bintype, template = get_params
set_the_config(release)
gal = Galaxy(plateifu=plateifu)
gal.set_params(bintype=bintype, template=template, release=release)
gal.set_filepaths()
gal.set_galaxy_data()
yield gal
gal = None
@pytest.fixture(scope='function')
def cube(galaxy, exporigin, mode):
''' Yield a Marvin Cube based on the expected origin combo of (mode+db).
Fixture tests 6 cube origins from (mode+db) combos [file, db and api]
'''
if str(galaxy.bintype) != 'SPX':
pytest.skip()
if exporigin == 'file':
c = Cube(filename=galaxy.cubepath, release=galaxy.release, mode=mode)
else:
c = Cube(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode)
c.exporigin = exporigin
c.initial_mode = mode
yield c
c = None
@pytest.fixture(scope='function')
def modelcube(galaxy, exporigin, mode):
''' Yield a Marvin ModelCube based on the expected origin combo of (mode+db).
Fixture tests 6 modelcube origins from (mode+db) combos [file, db and api]
'''
if exporigin == 'file':
mc = ModelCube(filename=galaxy.modelpath, release=galaxy.release, mode=mode, bintype=galaxy.bintype)
else:
mc = ModelCube(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode, bintype=galaxy.bintype)
mc.exporigin = exporigin
mc.initial_mode = mode
yield mc
mc = None
@pytest.fixture(scope='function')
def maps(galaxy, exporigin, mode):
''' Yield a Marvin Maps based on the expected origin combo of (mode+db).
Fixture tests 6 cube origins from (mode+db) combos [file, db and api]
'''
if exporigin == 'file':
m = Maps(filename=galaxy.mapspath, release=galaxy.release, mode=mode, bintype=galaxy.bintype)
else:
m = Maps(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode, bintype=galaxy.bintype)
m.exporigin = exporigin
yield m
m = None
modes = ['local', 'remote', 'auto'] # to loop over modes (see mode fixture)
dbs = ['db', 'nodb'] # to loop over dbs (see db fixture)
origins = ['file', 'db', 'api'] # to loop over data origins (see data_origin fixture)
@pytest.fixture(scope='class')
def maps_release_only(release):
return Maps(plateifu='8485-1901', release=release)
@pytest.fixture(scope='function')
def query(request, allow_dap, monkeyauth, release, mode, db):
''' Yields a Query that loops over all modes and db options '''
data = query_data[release]
set_the_config(release)
if mode == 'local' and not db:
pytest.skip('cannot use queries in local mode without a db')
searchfilter = request.param if hasattr(request, 'param') else None
q = Query(search_filter=searchfilter, mode=mode, release=release)
q.expdata = data
if q.mode == 'remote':
pytest.xfail('cannot control for DAP spaxel queries on server side; failing all remotes until then')
yield q
config.forceDbOn()
q = None
# @pytest.fixture(autouse=True)
# def skipall():
# pytest.skip('skipping everything')
| [
"marvin.config.login",
"marvin.config.forceDbOn",
"marvin.config.forceDbOff",
"marvin.config.setMPL",
"marvin.tools.modelcube.ModelCube",
"marvin.tools.maps.Maps",
"marvin.config.getoption",
"marvin.api.api.Interaction",
"marvin.tools.query.Query",
"marvin.utils.general.check_versions",
"marvin.... | [((872, 903), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (893, 903), False, 'import warnings\n'), ((4462, 4510), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""', 'params': 'releases'}), "(scope='session', params=releases)\n", (4476, 4510), False, 'import pytest\n'), ((6011, 6058), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""', 'params': 'origins'}), "(scope='session', params=origins)\n", (6025, 6058), False, 'import pytest\n'), ((6262, 6307), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""', 'params': 'modes'}), "(scope='session', params=modes)\n", (6276, 6307), False, 'import pytest\n'), ((6542, 6587), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""', 'autouse': '(True)'}), "(scope='session', autouse=True)\n", (6556, 6587), False, 'import pytest\n'), ((6728, 6744), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (6742, 6744), False, 'import pytest\n'), ((7371, 7416), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""', 'autouse': '(True)'}), "(scope='session', autouse=True)\n", (7385, 7416), False, 'import pytest\n'), ((7495, 7526), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (7509, 7526), False, 'import pytest\n'), ((7612, 7643), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (7626, 7643), False, 'import pytest\n'), ((7741, 7772), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (7755, 7772), False, 'import pytest\n'), ((7933, 7964), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (7947, 7964), False, 'import pytest\n'), ((8064, 8095), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (8078, 8095), False, 'import pytest\n'), ((9205, 9236), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (9219, 9236), False, 'import pytest\n'), ((9315, 9347), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (9329, 9347), False, 'import pytest\n'), ((9480, 9508), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (9494, 9508), False, 'import pytest\n'), ((9607, 9623), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (9621, 9623), False, 'import pytest\n'), ((9819, 9845), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'dbs'}), '(params=dbs)\n', (9833, 9845), False, 'import pytest\n'), ((10211, 10227), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (10225, 10227), False, 'import pytest\n'), ((10655, 10671), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (10669, 10671), False, 'import pytest\n'), ((11097, 11113), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (11111, 11113), False, 'import pytest\n'), ((11550, 11566), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (11564, 11566), False, 'import pytest\n'), ((11801, 11817), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (11815, 11817), False, 'import pytest\n'), ((12366, 12382), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (12380, 12382), False, 'import pytest\n'), ((12727, 12759), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (12741, 12759), False, 'import pytest\n'), ((18064, 18096), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (18078, 18096), False, 'import pytest\n'), ((18471, 18503), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (18485, 18503), False, 'import pytest\n'), ((19042, 19074), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (19056, 19074), False, 'import pytest\n'), ((19629, 19661), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (19643, 19661), False, 'import pytest\n'), ((20410, 20439), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""class"""'}), "(scope='class')\n", (20424, 20439), False, 'import pytest\n'), ((20530, 20562), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (20544, 20562), False, 'import pytest\n'), ((1661, 1694), 'marvin.config.getoption', 'config.getoption', (['"""--travis-only"""'], {}), "('--travis-only')\n", (1677, 1694), False, 'from marvin import config, marvindb\n'), ((2965, 3015), 'collections.OrderedDict', 'OrderedDict', (['((release, []) for release in releases)'], {}), '((release, []) for release in releases)\n', (2976, 3015), False, 'from collections import OrderedDict\n'), ((3032, 3082), 'collections.OrderedDict', 'OrderedDict', (['((release, []) for release in releases)'], {}), '((release, []) for release in releases)\n', (3043, 3082), False, 'from collections import OrderedDict\n'), ((7104, 7152), 'marvin.config.switchSasUrl', 'config.switchSasUrl', (['loc'], {'test': 'istest', 'port': 'port'}), '(loc, test=istest, port=port)\n', (7123, 7152), False, 'from marvin import config, marvindb\n'), ((7715, 7737), 'marvin.config.setMPL', 'config.setMPL', (['release'], {}), '(release)\n', (7728, 7737), False, 'from marvin import config, marvindb\n'), ((7873, 7903), 'marvin.config.lookUpVersions', 'config.lookUpVersions', (['release'], {}), '(release)\n', (7894, 7903), False, 'from marvin import config, marvindb\n'), ((8381, 8407), 'marvin.config.setRelease', 'config.setRelease', (['release'], {}), '(release)\n', (8398, 8407), False, 'from marvin import config, marvindb\n'), ((8440, 8454), 'marvin.config.login', 'config.login', ([], {}), '()\n', (8452, 8454), False, 'from marvin import config, marvindb\n'), ((9424, 9443), 'marvin.config.forceDbOff', 'config.forceDbOff', ([], {}), '()\n', (9441, 9443), False, 'from marvin import config, marvindb\n'), ((9458, 9476), 'marvin.config.forceDbOn', 'config.forceDbOn', ([], {}), '()\n', (9474, 9476), False, 'from marvin import config, marvindb\n'), ((9585, 9603), 'marvin.config.forceDbOn', 'config.forceDbOn', ([], {}), '()\n', (9601, 9603), False, 'from marvin import config, marvindb\n'), ((10189, 10207), 'marvin.config.forceDbOn', 'config.forceDbOn', ([], {}), '()\n', (10205, 10207), False, 'from marvin import config, marvindb\n'), ((13245, 13277), 'os.getenv', 'os.getenv', (['"""MANGA_SPECTRO_REDUX"""'], {}), "('MANGA_SPECTRO_REDUX')\n", (13254, 13277), False, 'import os\n'), ((13289, 13324), 'os.getenv', 'os.getenv', (['"""MANGA_SPECTRO_ANALYSIS"""'], {}), "('MANGA_SPECTRO_ANALYSIS')\n", (13298, 13324), False, 'import os\n'), ((13617, 13642), 'os.getenv', 'os.getenv', (['"""SAS_BASE_DIR"""'], {}), "('SAS_BASE_DIR')\n", (13626, 13642), False, 'import os\n'), ((13660, 13692), 'os.getenv', 'os.getenv', (['"""MANGA_SPECTRO_REDUX"""'], {}), "('MANGA_SPECTRO_REDUX')\n", (13669, 13692), False, 'import os\n'), ((13713, 13748), 'os.getenv', 'os.getenv', (['"""MANGA_SPECTRO_ANALYSIS"""'], {}), "('MANGA_SPECTRO_ANALYSIS')\n", (13722, 13748), False, 'import os\n'), ((20483, 20526), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': '"""8485-1901"""', 'release': 'release'}), "(plateifu='8485-1901', release=release)\n", (20487, 20526), False, 'from marvin.tools.maps import Maps\n'), ((20936, 20997), 'marvin.tools.query.Query', 'Query', ([], {'search_filter': 'searchfilter', 'mode': 'mode', 'release': 'release'}), '(search_filter=searchfilter, mode=mode, release=release)\n', (20941, 20997), False, 'from marvin.tools.query import Query\n'), ((21171, 21189), 'marvin.config.forceDbOn', 'config.forceDbOn', ([], {}), '()\n', (21187, 21189), False, 'from marvin import config, marvindb\n'), ((1394, 1442), 'pytest.skip', 'pytest.skip', (['"""Requires --runslow option to run."""'], {}), "('Requires --runslow option to run.')\n", (1405, 1442), False, 'import pytest\n'), ((4628, 4673), 'pytest.skip', 'pytest.skip', (['"""Skipping non-requested release"""'], {}), "('Skipping non-requested release')\n", (4639, 4673), False, 'import pytest\n'), ((5457, 5502), 'pytest.skip', 'pytest.skip', (['"""Skipping non-requested release"""'], {}), "('Skipping non-requested release')\n", (5468, 5502), False, 'import pytest\n'), ((5566, 5611), 'pytest.skip', 'pytest.skip', (['"""Skipping non-requested bintype"""'], {}), "('Skipping non-requested bintype')\n", (5577, 5611), False, 'import pytest\n'), ((5677, 5723), 'pytest.skip', 'pytest.skip', (['"""Skipping non-requested template"""'], {}), "('Skipping non-requested template')\n", (5688, 5723), False, 'import pytest\n'), ((5936, 5982), 'pytest.skip', 'pytest.skip', (['"""Skipping non-requested galaxies"""'], {}), "('Skipping non-requested galaxies')\n", (5947, 5982), False, 'import pytest\n'), ((6188, 6233), 'pytest.skip', 'pytest.skip', (['"""Skipping non-requested origins"""'], {}), "('Skipping non-requested origins')\n", (6199, 6233), False, 'import pytest\n'), ((6421, 6464), 'pytest.skip', 'pytest.skip', (['"""Skipping non-requested modes"""'], {}), "('Skipping non-requested modes')\n", (6432, 6464), False, 'import pytest\n'), ((7209, 7294), 'marvin.api.api.Interaction', 'Interaction', (['"""/marvin/api/general/getroutemap"""'], {'request_type': '"""get"""', 'auth': '"""netrc"""'}), "('/marvin/api/general/getroutemap', request_type='get', auth='netrc'\n )\n", (7220, 7294), False, 'from marvin.api.api import Interaction\n'), ((8560, 8591), 'os.environ.get', 'os.environ.get', (['"""MARVIN_SECRET"""'], {}), "('MARVIN_SECRET')\n", (8574, 8591), False, 'import os\n'), ((9726, 9744), 'marvin.config.forceDbOn', 'config.forceDbOn', ([], {}), '()\n', (9742, 9744), False, 'from marvin import config, marvindb\n'), ((9763, 9782), 'marvin.config.forceDbOff', 'config.forceDbOff', ([], {}), '()\n', (9780, 9782), False, 'from marvin import config, marvindb\n'), ((10016, 10057), 'pytest.skip', 'pytest.skip', (['"""Skipping non-requested dbs"""'], {}), "('Skipping non-requested dbs')\n", (10027, 10057), False, 'import pytest\n'), ((10096, 10114), 'marvin.config.forceDbOn', 'config.forceDbOn', ([], {}), '()\n', (10112, 10114), False, 'from marvin import config, marvindb\n'), ((10133, 10152), 'marvin.config.forceDbOff', 'config.forceDbOff', ([], {}), '()\n', (10150, 10152), False, 'from marvin import config, marvindb\n'), ((14166, 14207), 'copy.deepcopy', 'copy.deepcopy', (['galaxy_data[self.plateifu]'], {}), '(galaxy_data[self.plateifu])\n', (14179, 14207), False, 'import copy\n'), ((15084, 15119), 'marvin.config.lookUpVersions', 'config.lookUpVersions', (['self.release'], {}), '(self.release)\n', (15105, 15119), False, 'from marvin import config, marvindb\n'), ((15999, 16005), 'sdss_access.path.Path', 'Path', ([], {}), '()\n', (16003, 16005), False, 'from sdss_access.path import Path\n'), ((16017, 16054), 'marvin.utils.general.check_versions', 'check_versions', (['self.drpver', '"""v2_5_3"""'], {}), "(self.drpver, 'v2_5_3')\n", (16031, 16054), False, 'from marvin.utils.general import check_versions\n'), ((18748, 18761), 'pytest.skip', 'pytest.skip', ([], {}), '()\n', (18759, 18761), False, 'import pytest\n'), ((18803, 18868), 'marvin.tools.cube.Cube', 'Cube', ([], {'filename': 'galaxy.cubepath', 'release': 'galaxy.release', 'mode': 'mode'}), '(filename=galaxy.cubepath, release=galaxy.release, mode=mode)\n', (18807, 18868), False, 'from marvin.tools.cube import Cube\n'), ((18891, 18956), 'marvin.tools.cube.Cube', 'Cube', ([], {'plateifu': 'galaxy.plateifu', 'release': 'galaxy.release', 'mode': 'mode'}), '(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode)\n', (18895, 18956), False, 'from marvin.tools.cube import Cube\n'), ((19329, 19428), 'marvin.tools.modelcube.ModelCube', 'ModelCube', ([], {'filename': 'galaxy.modelpath', 'release': 'galaxy.release', 'mode': 'mode', 'bintype': 'galaxy.bintype'}), '(filename=galaxy.modelpath, release=galaxy.release, mode=mode,\n bintype=galaxy.bintype)\n', (19338, 19428), False, 'from marvin.tools.modelcube import ModelCube\n'), ((19448, 19546), 'marvin.tools.modelcube.ModelCube', 'ModelCube', ([], {'plateifu': 'galaxy.plateifu', 'release': 'galaxy.release', 'mode': 'mode', 'bintype': 'galaxy.bintype'}), '(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode,\n bintype=galaxy.bintype)\n', (19457, 19546), False, 'from marvin.tools.modelcube import ModelCube\n'), ((19900, 19994), 'marvin.tools.maps.Maps', 'Maps', ([], {'filename': 'galaxy.mapspath', 'release': 'galaxy.release', 'mode': 'mode', 'bintype': 'galaxy.bintype'}), '(filename=galaxy.mapspath, release=galaxy.release, mode=mode, bintype=\n galaxy.bintype)\n', (19904, 19994), False, 'from marvin.tools.maps import Maps\n'), ((20012, 20106), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu', 'release': 'galaxy.release', 'mode': 'mode', 'bintype': 'galaxy.bintype'}), '(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode, bintype=\n galaxy.bintype)\n', (20016, 20106), False, 'from marvin.tools.maps import Maps\n'), ((20795, 20855), 'pytest.skip', 'pytest.skip', (['"""cannot use queries in local mode without a db"""'], {}), "('cannot use queries in local mode without a db')\n", (20806, 20855), False, 'import pytest\n'), ((21054, 21164), 'pytest.xfail', 'pytest.xfail', (['"""cannot control for DAP spaxel queries on server side; failing all remotes until then"""'], {}), "(\n 'cannot control for DAP spaxel queries on server side; failing all remotes until then'\n )\n", (21066, 21164), False, 'import pytest\n'), ((4198, 4223), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4213, 4223), False, 'import os\n'), ((4299, 4316), 'brain.utils.general.get_yaml_loader', 'get_yaml_loader', ([], {}), '()\n', (4314, 4316), False, 'from brain.utils.general import get_yaml_loader\n'), ((4341, 4366), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4356, 4366), False, 'import os\n'), ((4440, 4457), 'brain.utils.general.get_yaml_loader', 'get_yaml_loader', ([], {}), '()\n', (4455, 4457), False, 'from brain.utils.general import get_yaml_loader\n'), ((7011, 7052), 'os.environ.get', 'os.environ.get', (['"""LOCAL_MARVIN_PORT"""', '(5000)'], {}), "('LOCAL_MARVIN_PORT', 5000)\n", (7025, 7052), False, 'import os\n'), ((4840, 4907), 'itertools.product', 'itertools.product', (['[release]', 'bintypes[release]', 'templates[release]'], {}), '([release], bintypes[release], templates[release])\n', (4857, 4907), False, 'import itertools\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import (SecurityGroup,
Account)
from marvin.lib.common import (get_zone,
get_domain,
get_template)
from marvin.lib.utils import (validateList,
cleanup_resources)
from marvin.codes import (PASS, EMPTY_LIST)
from nose.plugins.attrib import attr
class TestSecurityGroups(cloudstackTestCase):
@classmethod
def setUpClass(cls):
try:
cls._cleanup = []
cls.testClient = super(TestSecurityGroups, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Domain, Zone, Template
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services['mode'] = cls.zone.networktype
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
# Getting authentication for user in newly created Account
cls.user = cls.account.user[0]
cls.userapiclient = cls.testClient.getUserApiClient(cls.user.username, cls.domain.name)
cls._cleanup.append(cls.account)
except Exception as e:
cls.tearDownClass()
raise Exception("Warning: Exception in setup : %s" % e)
return
def setUp(self):
self.apiClient = self.testClient.getApiClient()
self.cleanup = []
def tearDown(self):
#Clean up, terminate the created resources
cleanup_resources(self.apiClient, self.cleanup)
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def __verify_values(self, expected_vals, actual_vals):
"""
@Desc: Function to verify expected and actual values
@Steps:
Step1: Initializing return flag to True
Step1: Verifying length of expected and actual dictionaries is matching.
If not matching returning false
Step2: Listing all the keys from expected dictionary
Step3: Looping through each key from step2 and verifying expected and actual dictionaries have same value
If not making return flag to False
Step4: returning the return flag after all the values are verified
"""
return_flag = True
if len(expected_vals) != len(actual_vals):
return False
keys = expected_vals.keys()
for i in range(0, len(expected_vals)):
exp_val = expected_vals[keys[i]]
act_val = actual_vals[keys[i]]
if exp_val == act_val:
return_flag = return_flag and True
else:
return_flag = return_flag and False
self.debug("expected Value: %s, is not matching with actual value: %s" % (
exp_val,
act_val
))
return return_flag
@attr(tags=["basic", "provisioning"])
def test_01_list_securitygroups_pagination(self):
"""
@Desc: Test to List Security Groups pagination
@steps:
Step1: Listing all the Security Groups for a user
Step2: Verifying that list size is 1
Step3: Creating (page size) number of Security Groups
Step4: Listing all the Security Groups again for a user
Step5: Verifying that list size is (page size + 1)
Step6: Listing all the Security Groups in page1
Step7: Verifying that list size is (page size)
Step8: Listing all the Security Groups in page2
Step9: Verifying that list size is 1
Step10: Deleting the Security Group present in page 2
Step11: Listing all the Security Groups in page2
Step12: Verifying that no security groups are listed
"""
# Listing all the Security Groups for a User
list_securitygroups_before = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"]
)
# Verifying that default security group is created
status = validateList(list_securitygroups_before)
self.assertEquals(
PASS,
status[0],
"Default Security Groups creation failed"
)
# Verifying the size of the list is 1
self.assertEquals(
1,
len(list_securitygroups_before),
"Count of Security Groups list is not matching"
)
# Creating pagesize number of security groups
for i in range(0, (self.services["pagesize"])):
securitygroup_created = SecurityGroup.create(
self.userapiclient,
self.services["security_group"],
account=self.account.name,
domainid=self.domain.id,
description=self.services["security_group"]["name"]
)
self.assertIsNotNone(
securitygroup_created,
"Security Group creation failed"
)
if (i < self.services["pagesize"]):
self.cleanup.append(securitygroup_created)
# Listing all the security groups for user again
list_securitygroups_after = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"]
)
status = validateList(list_securitygroups_after)
self.assertEquals(
PASS,
status[0],
"Security Groups creation failed"
)
# Verifying that list size is pagesize + 1
self.assertEquals(
self.services["pagesize"] + 1,
len(list_securitygroups_after),
"Failed to create pagesize + 1 number of Security Groups"
)
# Listing all the security groups in page 1
list_securitygroups_page1 = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"],
page=1,
pagesize=self.services["pagesize"]
)
status = validateList(list_securitygroups_page1)
self.assertEquals(
PASS,
status[0],
"Failed to list security groups in page 1"
)
# Verifying the list size to be equal to pagesize
self.assertEquals(
self.services["pagesize"],
len(list_securitygroups_page1),
"Size of security groups in page 1 is not matching"
)
# Listing all the security groups in page 2
list_securitygroups_page2 = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"],
page=2,
pagesize=self.services["pagesize"]
)
status = validateList(list_securitygroups_page2)
self.assertEquals(
PASS,
status[0],
"Failed to list security groups in page 2"
)
# Verifying the list size to be equal to pagesize
self.assertEquals(
1,
len(list_securitygroups_page2),
"Size of security groups in page 2 is not matching"
)
# Deleting the security group present in page 2
SecurityGroup.delete(
securitygroup_created,
self.userapiclient)
self.cleanup.remove(securitygroup_created)
# Listing all the security groups in page 2 again
list_securitygroups_page2 = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"],
page=2,
pagesize=self.services["pagesize"]
)
# Verifying that there are no security groups listed
self.assertIsNone(
list_securitygroups_page2,
"Security Groups not deleted from page 2"
)
return
@attr(tags=["basic", "provisioning"])
def test_02_securitygroups_authorize_revoke_ingress(self):
"""
@Desc: Test to Authorize and Revoke Ingress for Security Group
@steps:
Step1: Listing all the Security Groups for a user
Step2: Verifying that list size is 1
Step3: Creating a Security Groups
Step4: Listing all the Security Groups again for a user
Step5: Verifying that list size is 2
Step6: Authorizing Ingress for the security group created in step3
Step7: Listing the security groups by passing id of security group created in step3
Step8: Verifying that list size is 1
Step9: Verifying that Ingress is authorized to the security group
Step10: Verifying the details of the Ingress rule are as expected
Step11: Revoking Ingress for the security group created in step3
Step12: Listing the security groups by passing id of security group created in step3
Step13: Verifying that list size is 1
Step14: Verifying that Ingress is revoked from the security group
"""
# Listing all the Security Groups for a User
list_securitygroups_before = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"]
)
# Verifying that default security group is created
status = validateList(list_securitygroups_before)
self.assertEquals(
PASS,
status[0],
"Default Security Groups creation failed"
)
# Verifying the size of the list is 1
self.assertEquals(
1,
len(list_securitygroups_before),
"Count of Security Groups list is not matching"
)
# Creating a security group
securitygroup_created = SecurityGroup.create(
self.userapiclient,
self.services["security_group"],
account=self.account.name,
domainid=self.domain.id,
description=self.services["security_group"]["name"]
)
self.assertIsNotNone(
securitygroup_created,
"Security Group creation failed"
)
self.cleanup.append(securitygroup_created)
# Listing all the security groups for user again
list_securitygroups_after = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"]
)
status = validateList(list_securitygroups_after)
self.assertEquals(
PASS,
status[0],
"Security Groups creation failed"
)
# Verifying that list size is 2
self.assertEquals(
2,
len(list_securitygroups_after),
"Failed to create Security Group"
)
# Authorizing Ingress for the security group created in step3
securitygroup_created.authorize(
self.userapiclient,
self.services["ingress_rule"],
self.account.name,
self.domain.id,
)
# Listing the security group by Id
list_securitygroups_byid = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"],
id=securitygroup_created.id,
domainid=self.domain.id
)
# Verifying that security group is listed
status = validateList(list_securitygroups_byid)
self.assertEquals(
PASS,
status[0],
"Listing of Security Groups by id failed"
)
# Verifying size of the list is 1
self.assertEquals(
1,
len(list_securitygroups_byid),
"Count of the listing security group by id is not matching"
)
securitygroup_ingress = list_securitygroups_byid[0].ingressrule
# Validating the Ingress rule
status = validateList(securitygroup_ingress)
self.assertEquals(
PASS,
status[0],
"Security Groups Ingress rule authorization failed"
)
self.assertEquals(
1,
len(securitygroup_ingress),
"Security Group Ingress rules count is not matching"
)
# Verifying the details of the Ingress rule are as expected
#Creating expected and actual values dictionaries
expected_dict = {
"cidr":self.services["ingress_rule"]["cidrlist"],
"protocol":self.services["ingress_rule"]["protocol"],
"startport":self.services["ingress_rule"]["startport"],
"endport":self.services["ingress_rule"]["endport"],
}
actual_dict = {
"cidr":str(securitygroup_ingress[0].cidr),
"protocol":str(securitygroup_ingress[0].protocol.upper()),
"startport":str(securitygroup_ingress[0].startport),
"endport":str(securitygroup_ingress[0].endport),
}
ingress_status = self.__verify_values(
expected_dict,
actual_dict
)
self.assertEqual(
True,
ingress_status,
"Listed Security group Ingress rule details are not as expected"
)
# Revoking the Ingress rule from Security Group
securitygroup_created.revoke(self.userapiclient, securitygroup_ingress[0].ruleid)
# Listing the security group by Id
list_securitygroups_byid = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"],
id=securitygroup_created.id,
domainid=self.domain.id
)
# Verifying that security group is listed
status = validateList(list_securitygroups_byid)
self.assertEquals(
PASS,
status[0],
"Listing of Security Groups by id failed"
)
# Verifying size of the list is 1
self.assertEquals(
1,
len(list_securitygroups_byid),
"Count of the listing security group by id is not matching"
)
securitygroup_ingress = list_securitygroups_byid[0].ingressrule
# Verifying that Ingress rule is empty(revoked)
status = validateList(securitygroup_ingress)
self.assertEquals(
EMPTY_LIST,
status[2],
"Security Groups Ingress rule is not revoked"
)
return
@attr(tags=["basic", "provisioning"])
def test_03_securitygroups_authorize_revoke_egress(self):
"""
@Desc: Test to Authorize and Revoke Egress for Security Group
@steps:
Step1: Listing all the Security Groups for a user
Step2: Verifying that list size is 1
Step3: Creating a Security Groups
Step4: Listing all the Security Groups again for a user
Step5: Verifying that list size is 2
Step6: Authorizing Egress for the security group created in step3
Step7: Listing the security groups by passing id of security group created in step3
Step8: Verifying that list size is 1
Step9: Verifying that Egress is authorized to the security group
Step10: Verifying the details of the Egress rule are as expected
Step11: Revoking Egress for the security group created in step3
Step12: Listing the security groups by passing id of security group created in step3
Step13: Verifying that list size is 1
Step14: Verifying that Egress is revoked from the security group
"""
# Listing all the Security Groups for a User
list_securitygroups_before = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"]
)
# Verifying that default security group is created
status = validateList(list_securitygroups_before)
self.assertEquals(
PASS,
status[0],
"Default Security Groups creation failed"
)
# Verifying the size of the list is 1
self.assertEquals(
1,
len(list_securitygroups_before),
"Count of Security Groups list is not matching"
)
# Creating a security group
securitygroup_created = SecurityGroup.create(
self.userapiclient,
self.services["security_group"],
account=self.account.name,
domainid=self.domain.id,
description=self.services["security_group"]["name"]
)
self.assertIsNotNone(
securitygroup_created,
"Security Group creation failed"
)
self.cleanup.append(securitygroup_created)
# Listing all the security groups for user again
list_securitygroups_after = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"]
)
status = validateList(list_securitygroups_after)
self.assertEquals(
PASS,
status[0],
"Security Groups creation failed"
)
# Verifying that list size is 2
self.assertEquals(
2,
len(list_securitygroups_after),
"Failed to create Security Group"
)
# Authorizing Egress for the security group created in step3
securitygroup_created.authorizeEgress(
self.userapiclient,
self.services["ingress_rule"],
self.account.name,
self.domain.id,
)
# Listing the security group by Id
list_securitygroups_byid = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"],
id=securitygroup_created.id,
domainid=self.domain.id
)
# Verifying that security group is listed
status = validateList(list_securitygroups_byid)
self.assertEquals(
PASS,
status[0],
"Listing of Security Groups by id failed"
)
# Verifying size of the list is 1
self.assertEquals(
1,
len(list_securitygroups_byid),
"Count of the listing security group by id is not matching"
)
securitygroup_egress = list_securitygroups_byid[0].egressrule
# Validating the Ingress rule
status = validateList(securitygroup_egress)
self.assertEquals(
PASS,
status[0],
"Security Groups Egress rule authorization failed"
)
self.assertEquals(
1,
len(securitygroup_egress),
"Security Group Egress rules count is not matching"
)
# Verifying the details of the Egress rule are as expected
#Creating expected and actual values dictionaries
expected_dict = {
"cidr":self.services["ingress_rule"]["cidrlist"],
"protocol":self.services["ingress_rule"]["protocol"],
"startport":self.services["ingress_rule"]["startport"],
"endport":self.services["ingress_rule"]["endport"],
}
actual_dict = {
"cidr":str(securitygroup_egress[0].cidr),
"protocol":str(securitygroup_egress[0].protocol.upper()),
"startport":str(securitygroup_egress[0].startport),
"endport":str(securitygroup_egress[0].endport),
}
ingress_status = self.__verify_values(
expected_dict,
actual_dict
)
self.assertEqual(
True,
ingress_status,
"Listed Security group Egress rule details are not as expected"
)
# Revoking the Egress rule from Security Group
securitygroup_created.revokeEgress(self.userapiclient, securitygroup_egress[0].ruleid)
# Listing the security group by Id
list_securitygroups_byid = SecurityGroup.list(
self.userapiclient,
listall=self.services["listall"],
id=securitygroup_created.id,
domainid=self.domain.id
)
# Verifying that security group is listed
status = validateList(list_securitygroups_byid)
self.assertEquals(
PASS,
status[0],
"Listing of Security Groups by id failed"
)
# Verifying size of the list is 1
self.assertEquals(
1,
len(list_securitygroups_byid),
"Count of the listing security group by id is not matching"
)
securitygroup_egress = list_securitygroups_byid[0].egressrule
# Verifying that Ingress rule is empty(revoked)
status = validateList(securitygroup_egress)
self.assertEquals(
EMPTY_LIST,
status[2],
"Security Groups Egress rule is not revoked"
)
return
| [
"marvin.lib.utils.validateList",
"marvin.lib.base.Account.create",
"marvin.lib.base.SecurityGroup.create",
"marvin.lib.base.SecurityGroup.delete",
"marvin.lib.common.get_domain",
"marvin.lib.base.SecurityGroup.list",
"marvin.lib.common.get_template",
"marvin.lib.utils.cleanup_resources"
] | [((4659, 4695), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['basic', 'provisioning']"}), "(tags=['basic', 'provisioning'])\n", (4663, 4695), False, 'from nose.plugins.attrib import attr\n'), ((11305, 11341), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['basic', 'provisioning']"}), "(tags=['basic', 'provisioning'])\n", (11309, 11341), False, 'from nose.plugins.attrib import attr\n'), ((19815, 19851), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['basic', 'provisioning']"}), "(tags=['basic', 'provisioning'])\n", (19819, 19851), False, 'from nose.plugins.attrib import attr\n'), ((2873, 2920), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiClient', 'self.cleanup'], {}), '(self.apiClient, self.cleanup)\n', (2890, 2920), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((5615, 5687), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']"}), "(self.userapiclient, listall=self.services['listall'])\n", (5633, 5687), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((5934, 5974), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_before'], {}), '(list_securitygroups_before)\n', (5946, 5974), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((7491, 7563), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']"}), "(self.userapiclient, listall=self.services['listall'])\n", (7509, 7563), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((7748, 7787), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_after'], {}), '(list_securitygroups_after)\n', (7760, 7787), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((8365, 8485), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'page': '(1)', 'pagesize': "self.services['pagesize']"}), "(self.userapiclient, listall=self.services['listall'],\n page=1, pagesize=self.services['pagesize'])\n", (8383, 8485), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((8776, 8815), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_page1'], {}), '(list_securitygroups_page1)\n', (8788, 8815), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((9399, 9519), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'page': '(2)', 'pagesize': "self.services['pagesize']"}), "(self.userapiclient, listall=self.services['listall'],\n page=2, pagesize=self.services['pagesize'])\n", (9417, 9519), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((9810, 9849), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_page2'], {}), '(list_securitygroups_page2)\n', (9822, 9849), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((10385, 10448), 'marvin.lib.base.SecurityGroup.delete', 'SecurityGroup.delete', (['securitygroup_created', 'self.userapiclient'], {}), '(securitygroup_created, self.userapiclient)\n', (10405, 10448), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((10653, 10773), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'page': '(2)', 'pagesize': "self.services['pagesize']"}), "(self.userapiclient, listall=self.services['listall'],\n page=2, pagesize=self.services['pagesize'])\n", (10671, 10773), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((12506, 12578), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']"}), "(self.userapiclient, listall=self.services['listall'])\n", (12524, 12578), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((12825, 12865), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_before'], {}), '(list_securitygroups_before)\n', (12837, 12865), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((13389, 13576), 'marvin.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.userapiclient', "self.services['security_group']"], {'account': 'self.account.name', 'domainid': 'self.domain.id', 'description': "self.services['security_group']['name']"}), "(self.userapiclient, self.services['security_group'],\n account=self.account.name, domainid=self.domain.id, description=self.\n services['security_group']['name'])\n", (13409, 13576), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((14208, 14280), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']"}), "(self.userapiclient, listall=self.services['listall'])\n", (14226, 14280), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((14465, 14504), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_after'], {}), '(list_securitygroups_after)\n', (14477, 14504), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((15408, 15539), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'id': 'securitygroup_created.id', 'domainid': 'self.domain.id'}), "(self.userapiclient, listall=self.services['listall'], id\n =securitygroup_created.id, domainid=self.domain.id)\n", (15426, 15539), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((15874, 15912), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_byid'], {}), '(list_securitygroups_byid)\n', (15886, 15912), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((16501, 16536), 'marvin.lib.utils.validateList', 'validateList', (['securitygroup_ingress'], {}), '(securitygroup_ingress)\n', (16513, 16536), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((18445, 18576), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'id': 'securitygroup_created.id', 'domainid': 'self.domain.id'}), "(self.userapiclient, listall=self.services['listall'], id\n =securitygroup_created.id, domainid=self.domain.id)\n", (18463, 18576), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((18911, 18949), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_byid'], {}), '(list_securitygroups_byid)\n', (18923, 18949), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((19556, 19591), 'marvin.lib.utils.validateList', 'validateList', (['securitygroup_ingress'], {}), '(securitygroup_ingress)\n', (19568, 19591), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((21009, 21081), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']"}), "(self.userapiclient, listall=self.services['listall'])\n", (21027, 21081), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((21328, 21368), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_before'], {}), '(list_securitygroups_before)\n', (21340, 21368), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((21892, 22079), 'marvin.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.userapiclient', "self.services['security_group']"], {'account': 'self.account.name', 'domainid': 'self.domain.id', 'description': "self.services['security_group']['name']"}), "(self.userapiclient, self.services['security_group'],\n account=self.account.name, domainid=self.domain.id, description=self.\n services['security_group']['name'])\n", (21912, 22079), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((22711, 22783), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']"}), "(self.userapiclient, listall=self.services['listall'])\n", (22729, 22783), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((22968, 23007), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_after'], {}), '(list_securitygroups_after)\n', (22980, 23007), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((23946, 24077), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'id': 'securitygroup_created.id', 'domainid': 'self.domain.id'}), "(self.userapiclient, listall=self.services['listall'], id\n =securitygroup_created.id, domainid=self.domain.id)\n", (23964, 24077), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((24412, 24450), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_byid'], {}), '(list_securitygroups_byid)\n', (24424, 24450), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((25037, 25071), 'marvin.lib.utils.validateList', 'validateList', (['securitygroup_egress'], {}), '(securitygroup_egress)\n', (25049, 25071), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((26975, 27106), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'id': 'securitygroup_created.id', 'domainid': 'self.domain.id'}), "(self.userapiclient, listall=self.services['listall'], id\n =securitygroup_created.id, domainid=self.domain.id)\n", (26993, 27106), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((27441, 27479), 'marvin.lib.utils.validateList', 'validateList', (['list_securitygroups_byid'], {}), '(list_securitygroups_byid)\n', (27453, 27479), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((28084, 28118), 'marvin.lib.utils.validateList', 'validateList', (['securitygroup_egress'], {}), '(securitygroup_egress)\n', (28096, 28118), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((1655, 1681), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (1665, 1681), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((1791, 1856), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (1803, 1856), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((2069, 2148), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], domainid=cls.domain.id)\n", (2083, 2148), False, 'from marvin.lib.base import SecurityGroup, Account\n'), ((3007, 3054), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (3024, 3054), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((6576, 6763), 'marvin.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.userapiclient', "self.services['security_group']"], {'account': 'self.account.name', 'domainid': 'self.domain.id', 'description': "self.services['security_group']['name']"}), "(self.userapiclient, self.services['security_group'],\n account=self.account.name, domainid=self.domain.id, description=self.\n services['security_group']['name'])\n", (6596, 6763), False, 'from marvin.lib.base import SecurityGroup, Account\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Component tests for VSP Managed Subnets functionality
with Nuage VSP SDN plugin
"""
# Import Local Modules
from nuageTestCase import nuageTestCase, needscleanup
from marvin.lib.base import (Account,
Domain,
VirtualMachine)
from marvin.cloudstackAPI import updateZone
# Import System Modules
from nose.plugins.attrib import attr
import time
class TestNuageManagedSubnets(nuageTestCase):
"""Test Managed Subnets functionality with Nuage VSP SDN plugin
"""
@classmethod
def setUpClass(cls):
super(TestNuageManagedSubnets, cls).setUpClass()
# create a nuage vpc offering
cls.nuage_vpc_offering = \
cls.create_VpcOffering(cls.test_data["nuagevsp"]["vpc_offering"])
# tier network offerings
cls.nuage_vpc_network_offering = \
cls.create_NetworkOffering(cls.test_data["nuagevsp"]
["vpc_network_offering"])
# create a Nuage isolated network offering with vr
cls.nuage_isolated_network_offering = cls.create_NetworkOffering(
cls.test_data["nuagevsp"]["isolated_network_offering"], True)
# create a Nuage isolated network offering with vr and persistent
cls.nuage_isolated_network_offering_persistent = \
cls.create_NetworkOffering(
cls.test_data["nuagevsp"]
["isolated_network_offering_persistent"],
True)
# create a Nuage isolated network offering without vr
cls.nuage_isolated_network_offering_without_vr = \
cls.create_NetworkOffering(
cls.test_data["nuagevsp"]
["isolated_network_offering_without_vr"],
True)
# create a Nuage isolated network offering without vr but persistent
cls.nuage_isolated_network_offering_without_vr_persistent = \
cls.create_NetworkOffering(
cls.test_data["nuagevsp"]
["isolated_network_offering_without_vr_persistent"],
True)
# create a Nuage shared network offering
cls.nuage_shared_network_offering = cls.create_NetworkOffering(
cls.test_data["nuagevsp"]["shared_nuage_network_offering"],
False)
cls._cleanup = [
cls.nuage_isolated_network_offering,
cls.nuage_isolated_network_offering_persistent,
cls.nuage_isolated_network_offering_without_vr,
cls.nuage_isolated_network_offering_without_vr_persistent,
cls.nuage_vpc_offering,
cls.nuage_vpc_network_offering,
cls.nuage_shared_network_offering
]
return
def setUp(self):
# Create an account
self.account = Account.create(self.api_client,
self.test_data["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account]
return
def verify_ping_to_vm(self, src_vm, dst_vm, public_ip, dst_hostname=None):
if self.isSimulator:
self.debug("Simulator Environment: not verifying pinging")
return
try:
src_vm.ssh_ip = public_ip.ipaddress.ipaddress
src_vm.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
src_vm.username = self.test_data["virtual_machine"]["username"]
src_vm.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(src_vm.ssh_ip, src_vm.password))
ssh = self.ssh_into_VM(src_vm, public_ip)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, dst_vm.ipaddress)
if dst_hostname:
self.verify_pingtovmipaddress(ssh, dst_hostname)
def verify_pingtovmipaddress(self, ssh, pingtovmipaddress):
"""verify ping to ipaddress of the vm and retry 3 times"""
successfull_ping = False
nbr_retries = 0
max_retries = 5
cmd = 'ping -c 2 ' + pingtovmipaddress
while not successfull_ping and nbr_retries < max_retries:
self.debug("ping vm by ipaddress with command: " + cmd)
outputlist = ssh.execute(cmd)
self.debug("command is executed properly " + cmd)
completeoutput = str(outputlist).strip('[]')
self.debug("complete output is " + completeoutput)
if '2 received' in completeoutput:
self.debug("PASS as vm is pingeable: " + completeoutput)
successfull_ping = True
else:
self.debug("FAIL as vm is not pingeable: " + completeoutput)
time.sleep(3)
nbr_retries = nbr_retries + 1
if not successfull_ping:
self.fail("FAILED TEST as excepted value not found in vm")
# verify_vsd_vm - Verifies the given CloudStack VM deployment and status in
# VSD
def verify_vsdmngd_vm(self, vm, vsdmngd_subnet, stopped=False):
self.debug("Verifying the deployment and state of VSD Managed VM "
"- %s in VSD" % vm.name)
vsd_vm = self.vsd.get_vm(filter=self.get_externalID_filter(vm.id))
self.assertNotEqual(vsd_vm, None,
"VM data format in VSD should not be of type None"
)
vm_info = VirtualMachine.list(self.api_client, id=vm.id)[0]
for nic in vm_info.nic:
vsd_subnet = vsdmngd_subnet
vsd_vport = self.vsd.get_vport(
subnet=vsd_subnet, filter=self.get_externalID_filter(nic.id))
vsd_vm_interface = self.vsd.get_vm_interface(
filter=self.get_externalID_filter(nic.id))
self.assertEqual(vsd_vport.active, True,
"VSD VM vport should be active"
)
self.assertEqual(vsd_vm_interface.ip_address, nic.ipaddress,
"VSD VM interface IP address should match VM's "
"NIC IP address in CloudStack"
)
if not self.isSimulator:
self.verify_vsd_object_status(vm, stopped)
self.debug("Successfully verified the deployment and state of VM - %s "
"in VSD" % vm.name)
@attr(tags=["advanced", "nuagevsp", "isonw"], required_hardware="false")
def test_01_nuage_mngd_subnets_isonw(self):
"""Test Nuage VSP Managed Subnets for isolated networks
"""
# 1. Create multiple L3DomainTemplate with Zone and Subnet on VSP
# Create Ingress & Egress ACL Top & Bottom Templates
# Add ACL rules to allow intra-subnet traffic
# Instiantiate these L3Domains and store its Subnet VSD ID
# 2. Create a persistent and non persistent isolated network offering
# create offerings with and without VirtualRouter
# 3. Create isolated networks specifying above offerings and
# specifying the stored Subnet ID's of VSP
# 4. Verify ACL rules and connectivity via deploying VM's ,
# Enabling staticNAT, applying firewall and egress rules
# 5. Verify negative tests like uniqueness of vsd subnet
# Create all items on vsd required for this test
enterprise = self.fetch_by_externalID(self._session.user.enterprises,
self.domain)
domain_template = self.create_vsd_domain_template(enterprise)
self.create_vsd_default_acls(domain_template)
domain1 = self.create_vsd_domain(domain_template, enterprise,
"L3DomainToBeConsumedByACS")
zone1 = self.create_vsd_zone(domain1, "ZoneToBeConsumedByACS")
subnet1 = self.create_vsd_subnet(zone1, "SubnetToBeConsumedByACS",
"10.0.0.1/24")
domain2 = self.create_vsd_domain(domain_template, enterprise,
"2ndL3DomainToBeConsumedByACS")
zone2 = self.create_vsd_zone(domain2, "2ndZoneToBeConsumedByACS")
subnet2 = self.create_vsd_subnet(zone2, "2ndSubnetToBeConsumedByACS",
"10.1.0.1/24")
self.create_vsd_dhcp_option(subnet2, 15, ["nuagenetworks2.net"])
domain3 = self.create_vsd_domain(domain_template, enterprise,
"3rdL3DomainToBeConsumedByACS")
zone3 = self.create_vsd_zone(domain3, "3rdZoneToBeConsumedByACS")
subnet3 = self.create_vsd_subnet(zone3, "3rdSubnetToBeConsumedByACS",
"10.2.0.1/24")
for i in range(1, 3):
# On ACS create network using non-persistent nw offering allow
isolated_network = self.create_Network(
self.nuage_isolated_network_offering,
gateway="10.0.0.1", netmask="255.255.255.0",
externalid=subnet1.id, cleanup=False)
# On ACS create network using persistent nw offering allow
isolated_network2 = self.create_Network(
self.nuage_isolated_network_offering_persistent,
gateway="10.5.0.1", netmask="255.255.255.0",
externalid=subnet2.id, cleanup=False)
with self.assertRaises(Exception):
self.create_Network(
self.nuage_shared_network_offering, gateway="10.2.0.1",
netmask="255.255.255.0", vlan=1201, externalid=subnet3.id)
# On ACS create network when VSDSubnet is already in use
with self.assertRaises(Exception):
self.create_Network(
self.nuage_isolated_network_offering_persistent,
gateway="10.3.0.1", netmask="255.255.255.0",
externalid=subnet2.id)
# On ACS create network when VSDSubnet is non-existing
with self.assertRaises(Exception):
self.create_Network(
self.nuage_isolated_network_offering_persistent,
gateway="10.4.0.1", netmask="255.255.255.0",
externalid=subnet2.id+1)
# verify floating ip and intra subnet connectivity
vm_1 = self.create_VM(isolated_network, cleanup=False)
self.test_data["virtual_machine"]["displayname"] = "vm2"
self.test_data["virtual_machine"]["name"] = "vm2"
vm_2 = self.create_VM(isolated_network, cleanup=False)
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
# VSD verification
self.verify_vsd_network_not_present(isolated_network)
self.verify_vsdmngd_vm(vm_1, subnet1)
self.verify_vsdmngd_vm(vm_2, subnet1)
self.debug("Creating Static NAT rule for the deployed VM in the "
"non persistently created Isolated network...")
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.validate_PublicIPAddress(public_ip, isolated_network)
self.create_StaticNatRule_For_VM(vm_1, public_ip, isolated_network)
self.validate_PublicIPAddress(
public_ip, isolated_network, static_nat=True, vm=vm_1)
self.create_FirewallRule(public_ip,
self.test_data["ingress_rule"])
self.verify_ping_to_vm(vm_1, vm_2, public_ip, "vm2")
vm_3 = self.create_VM(isolated_network2, cleanup=False)
self.test_data["virtual_machine"]["displayname"] = "vm4"
self.test_data["virtual_machine"]["name"] = "vm4"
vm_4 = self.create_VM(isolated_network2, cleanup=False)
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
self.verify_vsd_network_not_present(isolated_network2)
self.verify_vsdmngd_vm(vm_3, subnet2)
self.verify_vsdmngd_vm(vm_4, subnet2)
self.debug("Creating Static NAT rule for the deployed VM in the "
"persistently created Isolated network...")
public_ip2 = self.acquire_PublicIPAddress(isolated_network2)
self.validate_PublicIPAddress(public_ip2, isolated_network2)
self.create_StaticNatRule_For_VM(vm_3, public_ip2,
isolated_network2)
self.validate_PublicIPAddress(
public_ip2, isolated_network2, static_nat=True, vm=vm_3)
self.create_FirewallRule(public_ip2,
self.test_data["ingress_rule"])
self.verify_ping_to_vm(vm_3, vm_4, public_ip2)
vm_4.delete(self.api_client, expunge=True)
vm_3.delete(self.api_client, expunge=True)
vm_2.delete(self.api_client, expunge=True)
vm_1.delete(self.api_client, expunge=True)
isolated_network2.delete(self.api_client)
isolated_network.delete(self.api_client)
self.debug("Number of loops %s" % i)
@attr(tags=["advanced", "nuagevsp", "vpc"], required_hardware="false")
def test_02_nuage_mngd_subnets_vpc(self):
"""Test Nuage VSP Managed Subnets for vpc and tier networks
"""
# 1. Create multiple L3DomainTemplate with Zone and Subnet on VSP
# Create Ingress & Egress ACL Top & Bottom Templates
# Add ACL rules to allow intra-subnet traffic
# Instiantiate these L3Domains and store its Subnet VSD ID
# 2. Create a vpc network offering and create a VPC
# create vpc tier network offerings with and without VirtualRouter
# 3. Create vpc tier networks specifying above offerings and
# specifying the stored Subnet ID's of VSP
# 4. Verify ACL rules and connectivity via deploying VM's ,
# Enabling staticNAT, applying firewall and egress rules
# 5. Verify negative tests like uniqueness of vsd subnet
# Create all items on vsd required for this test
enterprise = self.fetch_by_externalID(self._session.user.enterprises,
self.domain)
domain_template = self.create_vsd_domain_template(enterprise)
self.create_vsd_default_acls(domain_template)
domain1 = self.create_vsd_domain(domain_template, enterprise,
"L3DomainToBeConsumedByACS")
zone1 = self.create_vsd_zone(domain1, "ZoneToBeConsumedByACS")
subnet1 = self.create_vsd_subnet(zone1, "SubnetToBeConsumedByACS",
"10.1.0.1/24")
subnet2 = self.create_vsd_subnet(zone1, "2ndSubnetToBeConsumedByACS",
"10.1.128.1/24")
domain2 = self.create_vsd_domain(domain_template, enterprise,
"2ndL3DomainToBeConsumedByACS")
zone2 = self.create_vsd_zone(domain2, "2ndZoneToBeConsumedByACS")
subnet3 = self.create_vsd_subnet(zone2, "3rdSubnetToBeConsumedByACS",
"10.2.128.1/24")
cmd = updateZone.updateZoneCmd()
cmd.id = self.zone.id
cmd.domain = "vpc.com"
self.api_client.updateZone(cmd)
self.debug("Creating a VPC with Static NAT service provider as "
"VpcVirtualRouter")
vpc = self.create_Vpc(self.nuage_vpc_offering, cidr='10.1.0.0/16')
self.validate_Vpc(vpc, state="Enabled")
acl_list = self.create_NetworkAclList(
name="acl", description="acl", vpc=vpc)
self.create_NetworkAclRule(
self.test_data["ingress_rule"], acl_list=acl_list)
self.create_NetworkAclRule(
self.test_data["icmprule"], acl_list=acl_list)
self.debug("Creating another VPC with Static NAT service provider "
"as VpcVirtualRouter")
vpc2 = self.create_Vpc(self.nuage_vpc_offering, cidr='10.2.0.0/16')
self.validate_Vpc(vpc2, state="Enabled")
acl_list2 = self.create_NetworkAclList(
name="acl", description="acl", vpc=vpc2)
self.create_NetworkAclRule(
self.test_data["ingress_rule"], acl_list=acl_list2)
self.create_NetworkAclRule(
self.test_data["icmprule"], acl_list=acl_list2)
self.debug("Creating an unmanaged VPC tier network with Static NAT")
vpc2_tier_unmngd = self.create_Network(self.nuage_vpc_network_offering,
gateway='10.2.0.1',
vpc=vpc2,
acl_list=acl_list2)
self.validate_Network(vpc2_tier_unmngd, state="Implemented")
# VPC Tier Network creation should fail as VPC is unmanaged already
with self.assertRaises(Exception):
self.create_Network(self.nuage_vpc_network_offering,
gateway='10.2.128.1',
vpc=vpc2,
acl_list=acl_list2,
externalid=subnet3.id)
vpc2_tier_unmngd.delete(self.api_client)
vpc2.delete(self.api_client)
# VPC tier network creation fails when cidr does not match on VSD
with self.assertRaises(Exception):
self.create_Network(self.nuage_vpc_network_offering,
gateway='10.1.1.1',
vpc=vpc,
acl_list=acl_list,
externalid=subnet1.id)
for i in range(1, 3):
self.debug("Creating a mngd VPC tier with Static NAT service")
vpc_tier = self.create_Network(self.nuage_vpc_network_offering,
gateway='10.1.0.1',
vpc=vpc,
acl_list=acl_list,
externalid=subnet1.id,
cleanup=False)
self.validate_Network(vpc_tier, state="Implemented")
self.debug("Creating 2nd VPC tier network with Static NAT service")
# VPC 2nd tier creation fails when cidr doesn't match on VSD
with self.assertRaises(Exception):
self.create_Network(self.nuage_vpc_network_offering,
gateway='10.1.129.1',
vpc=vpc,
acl_list=acl_list,
externalid=subnet2.id)
vpc_2ndtier = self.create_Network(self.nuage_vpc_network_offering,
gateway='10.1.128.1',
vpc=vpc,
acl_list=acl_list,
externalid=subnet2.id,
cleanup=False)
self.validate_Network(vpc_2ndtier, state="Implemented")
vpc_vr = self.get_Router(vpc_tier)
self.check_Router_state(vpc_vr, state="Running")
# VSD verification
self.verify_vsd_network_not_present(vpc_tier, vpc)
self.verify_vsd_network_not_present(vpc_2ndtier, vpc)
# On ACS create VPCTier network when VSDSubnet is already in use
with self.assertRaises(Exception):
self.create_Network(self.nuage_vpc_network_offering,
gateway='10.1.128.1',
vpc=vpc,
acl_list=acl_list,
externalid=subnet2.id)
# On ACS create VPCTier network when VSDSubnet does not exist
with self.assertRaises(Exception):
self.create_Network(self.nuage_vpc_network_offering,
gateway='10.1.128.1',
vpc=vpc,
acl_list=acl_list,
externalid=subnet2.id+1)
# On ACS create VPCTier network without VSDSubnet should fail
with self.assertRaises(Exception):
self.create_Network(self.nuage_vpc_network_offering,
gateway='10.1.203.1',
vpc=vpc,
acl_list=acl_list)
self.debug("Creating another VPC with Static NAT service provider "
"as VpcVirtualRouter With same CIDR")
vpc3 = self.create_Vpc(self.nuage_vpc_offering, cidr='10.1.0.0/16')
self.validate_Vpc(vpc3, state="Enabled")
acl_list3 = self.create_NetworkAclList(
name="acl", description="acl", vpc=vpc3)
self.create_NetworkAclRule(
self.test_data["ingress_rule"], acl_list=acl_list3)
self.create_NetworkAclRule(
self.test_data["icmprule"], acl_list=acl_list3)
self.debug("Creating a mngd VPC tier with Static NAT service")
vpc3_tier_unmngd = \
self.create_Network(self.nuage_vpc_network_offering,
gateway='10.1.0.1',
vpc=vpc3,
acl_list=acl_list3)
self.validate_Network(vpc3_tier_unmngd, state="Implemented")
vpc3_tier_unmngd.delete(self.api_client)
vpc3.delete(self.api_client)
self.debug("Deploying a VM in the created VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm1"
self.test_data["virtual_machine"]["name"] = "vpcvm1"
vpc_vm_1 = self.create_VM(vpc_tier, cleanup=False)
self.check_VM_state(vpc_vm_1, state="Running")
self.debug("Deploying another VM in the created VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm2"
self.test_data["virtual_machine"]["name"] = "vpcvm2"
vpc_vm_2 = self.create_VM(vpc_tier, cleanup=False)
self.check_VM_state(vpc_vm_2, state="Running")
self.debug("Deploying a VM in the 2nd VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm12"
self.test_data["virtual_machine"]["name"] = "vpcvm12"
vpc_vm_12 = self.create_VM(vpc_2ndtier, cleanup=False)
self.check_VM_state(vpc_vm_2, state="Running")
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
# VSD verification
self.verify_vsdmngd_vm(vpc_vm_1, subnet1)
self.verify_vsdmngd_vm(vpc_vm_2, subnet1)
self.verify_vsdmngd_vm(vpc_vm_12, subnet2)
self.debug("Creating Static NAT rule for the deployed VM "
"in the created VPC network...")
public_ip_1 = self.acquire_PublicIPAddress(vpc_tier, vpc=vpc)
self.validate_PublicIPAddress(public_ip_1, vpc_tier)
self.create_StaticNatRule_For_VM(vpc_vm_1, public_ip_1, vpc_tier)
self.validate_PublicIPAddress(
public_ip_1, vpc_tier, static_nat=True, vm=vpc_vm_1)
self.verify_ping_to_vm(vpc_vm_1, vpc_vm_2, public_ip_1)
self.verify_ping_to_vm(vpc_vm_1, vpc_vm_12, public_ip_1)
vpc_vm_1.delete(self.api_client, expunge=True)
vpc_vm_2.delete(self.api_client, expunge=True)
vpc_vm_12.delete(self.api_client, expunge=True)
vpc_tier.delete(self.api_client)
vpc_2ndtier.delete(self.api_client)
self.debug("Number of loops %s" % i)
@attr(tags=["advanced", "nuagevsp", "domains"], required_hardware="false")
def test_03_nuage_mngd_subnets_domains(self):
"""Test Nuage VSP Managed Subnets for ACS domains
"""
vsd_enterprise = self.create_vsd_enterprise()
vsd_domain_template = self.create_vsd_domain_template(vsd_enterprise)
self.create_vsd_default_acls(vsd_domain_template)
vsd_domain1 = self.create_vsd_domain(vsd_domain_template,
vsd_enterprise,
"L3DomainToBeConsumedByACS")
vsd_zone1 = self.create_vsd_zone(vsd_domain1, "ZoneToBeConsumedByACS")
vsd_subnet1 = self.create_vsd_subnet(vsd_zone1,
"SubnetToBeConsumedByACS",
"10.0.0.1/24")
acs_domain_1 = Domain.create(
self.api_client,
{},
name="DomainManagedbyVsd",
domainid=vsd_enterprise.id
)
# Create an admin and an user account under domain D1
acs_account_1 = Account.create(
self.api_client,
self.test_data["acl"]["accountD1"],
admin=True,
domainid=acs_domain_1.id
)
self.cleanup.append(acs_domain_1)
self.cleanup.append(acs_account_1)
# On ACS create network using non-persistent nw offering allow
isolated_network = self.create_Network(
self.nuage_isolated_network_offering,
gateway="10.0.0.1", netmask="255.255.255.0",
account=acs_account_1,
externalid=vsd_subnet1.id)
# Creation of a domain with inUse domain UUID is not allowed
with self.assertRaises(Exception):
Domain.create(
self.api_client,
{},
name="AnotherDomainManagedbyVsd",
domainid=vsd_enterprise.id
)
# Creation of a domain with unexisting domain UUID is not allowed
with self.assertRaises(Exception):
Domain.create(
self.api_client,
{},
name="YetAnotherDomainManagedbyVsd",
domainid=vsd_enterprise.id+1
)
vm_1 = self.create_VM(isolated_network, account=acs_account_1)
vm_2 = self.create_VM(isolated_network, account=acs_account_1)
# VSD verification
self.verify_vsd_network_not_present(isolated_network)
self.verify_vsdmngd_vm(vm_1, vsd_subnet1)
self.verify_vsdmngd_vm(vm_2, vsd_subnet1)
self.debug("Creating Static NAT rule for the deployed VM in the "
"non persistently created Isolated network...")
public_ip = self.acquire_PublicIPAddress(isolated_network,
account=acs_account_1)
self.validate_PublicIPAddress(public_ip, isolated_network)
self.create_StaticNatRule_For_VM(vm_1, public_ip, isolated_network)
self.validate_PublicIPAddress(
public_ip, isolated_network, static_nat=True, vm=vm_1)
self.create_FirewallRule(public_ip,
self.test_data["ingress_rule"])
if not self.isSimulator:
vm_public_ip = public_ip.ipaddress.ipaddress
try:
vm_1.ssh_ip = vm_public_ip
vm_1.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_1.username = self.test_data["virtual_machine"]["username"]
vm_1.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_1.ssh_ip, vm_1.password))
ssh = vm_1.get_ssh_client(ipaddress=vm_public_ip)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, vm_2.ipaddress)
@attr(tags=["advanced", "nuagevsp", "account"], required_hardware="false")
def test_04_nuage_mngd_subnets_noadminaccount(self):
"""Test Nuage VSP Managed Subnets for ACS domains without admin account
"""
vsd_enterprise = self.create_vsd_enterprise()
vsd_domain_template = self.create_vsd_domain_template(vsd_enterprise)
self.create_vsd_default_acls(vsd_domain_template)
vsd_domain1 = self.create_vsd_domain(vsd_domain_template,
vsd_enterprise,
"L3DomainToBeConsumedByACS")
vsd_zone1 = self.create_vsd_zone(vsd_domain1, "ZoneToBeConsumedByACS")
vsd_subnet1 = self.create_vsd_subnet(vsd_zone1,
"SubnetToBeConsumedByACS",
"10.0.0.1/24")
acs_domain_1 = Domain.create(
self.api_client,
{},
name="DomainManagedbyVsd",
domainid=vsd_enterprise.id
)
# Create an no admin and an user account under domain D1
acs_account_1 = Account.create(
self.api_client,
self.test_data["acl"]["accountD1"],
admin=False,
domainid=acs_domain_1.id
)
self.cleanup.append(acs_domain_1)
self.cleanup.append(acs_account_1)
# On ACS create network fails as non admin account
with self.assertRaises(Exception):
self.create_Network(
self.nuage_isolated_network_offering,
gateway="10.0.0.1", netmask="255.255.255.0",
account=acs_account_1,
externalid=vsd_subnet1.id)
@needscleanup
def create_vsd_enterprise(self):
enterprise = self.vsdk.NUEnterprise()
enterprise.name = "EnterpriseToBeConsumedByACS"
enterprise.description = "EnterpriseToBeConsumedByACS"
(enterprise, connection) = self._session.user.create_child(enterprise)
return enterprise
def create_vsd_ingress_acl_template(self, domain_template,
priority_type="TOP"):
name = "Ingress ACL " + str(priority_type).capitalize()
acl_template = self.vsdk.NUIngressACLTemplate()
acl_template.name = name
acl_template.description = name
acl_template.priority_type = priority_type
acl_template.active = True
(acl_template, connection) = \
domain_template.create_child(acl_template)
return acl_template
def create_vsd_egress_acl_template(self, domain_template,
priority_type='TOP'):
name = "Egress ACL " + str(priority_type).capitalize()
acl_template = self.vsdk.NUEgressACLTemplate()
acl_template.name = name
acl_template.description = name
acl_template.priority_type = priority_type
acl_template.active = True
(acl_template, connection) = \
domain_template.create_child(acl_template)
return acl_template
@needscleanup
def create_vsd_domain_template(self, enterprise):
domain_template = self.vsdk.NUDomainTemplate()
domain_template.name = "L3DomainTemplateToBeConsumedByACS"
domain_template.description = "L3DomainTemplateToBeConsumedByACS"
(domain_template, connection) = \
enterprise.create_child(domain_template)
return domain_template
def create_vsd_default_acls(self, domain_template):
ingress_vsd_acl_template1 = self.create_vsd_ingress_acl_template(
domain_template, "TOP")
ingress_vsd_acl_template2 = self.create_vsd_ingress_acl_template(
domain_template, "BOTTOM")
ingress_vsd_acl_entry1 = self.vsdk.NUIngressACLEntryTemplate()
ingress_vsd_acl_entry1.name = "Default Intra-Subnet Allow"
ingress_vsd_acl_entry1.description = "Default Intra-Subnet Allow"
ingress_vsd_acl_entry1.priority = '1'
ingress_vsd_acl_entry1.protocol = 'ANY'
ingress_vsd_acl_template1.create_child(ingress_vsd_acl_entry1)
ingress_vsd_acl_entry2 = self.vsdk.NUIngressACLEntryTemplate()
ingress_vsd_acl_entry2.name = "Default Allow TCP"
ingress_vsd_acl_entry2.description = "Default Allow TCP"
ingress_vsd_acl_entry2.priority = '1'
ingress_vsd_acl_entry2.protocol = '6'
ingress_vsd_acl_entry2.source_port = '*'
ingress_vsd_acl_entry2.destination_port = '*'
ingress_vsd_acl_template2.create_child(ingress_vsd_acl_entry2)
ingress_vsd_acl_entry3 = self.vsdk.NUIngressACLEntryTemplate()
ingress_vsd_acl_entry3.name = "Default Allow UDP"
ingress_vsd_acl_entry3.description = "Default Allow UDP"
ingress_vsd_acl_entry3.priority = '2'
ingress_vsd_acl_entry3.protocol = '17'
ingress_vsd_acl_entry3.source_port = '*'
ingress_vsd_acl_entry3.destination_port = '*'
ingress_vsd_acl_template2.create_child(ingress_vsd_acl_entry3)
ingress_vsd_acl_entry4 = self.vsdk.NUIngressACLEntryTemplate()
ingress_vsd_acl_entry4.name = "Default Allow ICMP"
ingress_vsd_acl_entry4.description = "Default Allow ICMP"
ingress_vsd_acl_entry4.priority = '3'
ingress_vsd_acl_entry4.protocol = '1'
ingress_vsd_acl_template2.create_child(ingress_vsd_acl_entry4)
egress_vsd_acl_template1 = self.create_vsd_egress_acl_template(
domain_template, 'TOP')
egress_vsd_acl_template2 = self.create_vsd_egress_acl_template(
domain_template, 'BOTTOM')
egress_vsd_acl_entry1 = self.vsdk.NUEgressACLEntryTemplate()
egress_vsd_acl_entry1.name = "Default Intra-Subnet Allow"
egress_vsd_acl_entry1.description = "Default Intra-Subnet Allow"
egress_vsd_acl_entry1.priority = '1'
egress_vsd_acl_entry1.protocol = 'ANY'
egress_vsd_acl_template1.create_child(egress_vsd_acl_entry1)
egress_vsd_acl_entry2 = self.vsdk.NUEgressACLEntryTemplate()
egress_vsd_acl_entry2.name = "Default Allow ICMP"
egress_vsd_acl_entry2.description = "Default Allow ICMP"
egress_vsd_acl_entry2.priority = '3'
egress_vsd_acl_entry2.protocol = '1'
egress_vsd_acl_template2.create_child(egress_vsd_acl_entry2)
def create_vsd_domain(self, domain_template, enterprise, name):
domain = self.vsdk.NUDomain()
domain.name = name
domain.description = name
(domain, connection) = \
enterprise.instantiate_child(domain, domain_template)
return domain
def create_vsd_zone(self, domain, name):
zone = self.vsdk.NUZone()
zone.name = name
zone.description = name
(zone, connection) = domain.create_child(zone)
return zone
def create_vsd_subnet(self, zone, name, cidr):
subnet = self.vsdk.NUSubnet()
subnet.name = name
subnet.description = name
(subnet.gateway, subnet.netmask, subnet.address) = \
self._cidr_to_netmask(cidr)
(subnet, connection) = zone.create_child(subnet)
return subnet
def create_vsd_dhcp_option(self, subnet, type, value):
dhcp_option = self.vsdk.NUDHCPOption()
dhcp_option.actual_type = type
dhcp_option.actual_values = value
(dhcp_option, connection) = subnet.create_child(dhcp_option)
return dhcp_option
def _cidr_to_netmask(self, cidr):
import socket
import struct
network, net_bits = cidr.split('/')
host_bits = 32 - int(net_bits)
netmask_bits = (1 << 32) - (1 << host_bits)
netmask = socket.inet_ntoa(struct.pack('!I', netmask_bits))
network_bits = struct.unpack('!I', socket.inet_aton(network))[0]
network_masked = socket.inet_ntoa(
struct.pack('!I', netmask_bits & network_bits)
)
return network, netmask, network_masked
| [
"marvin.cloudstackAPI.updateZone.updateZoneCmd",
"marvin.lib.base.Domain.create",
"marvin.lib.base.Account.create",
"marvin.lib.base.VirtualMachine.list"
] | [((7390, 7461), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp', 'isonw']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp', 'isonw'], required_hardware='false')\n", (7394, 7461), False, 'from nose.plugins.attrib import attr\n'), ((14323, 14392), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp', 'vpc']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp', 'vpc'], required_hardware='false')\n", (14327, 14392), False, 'from nose.plugins.attrib import attr\n'), ((25205, 25278), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp', 'domains']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp', 'domains'], required_hardware='false')\n", (25209, 25278), False, 'from nose.plugins.attrib import attr\n'), ((29287, 29360), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp', 'account']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp', 'account'], required_hardware='false')\n", (29291, 29360), False, 'from nose.plugins.attrib import attr\n'), ((3636, 3735), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.test_data['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.test_data['account'], admin=True,\n domainid=self.domain.id)\n", (3650, 3735), False, 'from marvin.lib.base import Account, Domain, VirtualMachine\n'), ((16415, 16441), 'marvin.cloudstackAPI.updateZone.updateZoneCmd', 'updateZone.updateZoneCmd', ([], {}), '()\n', (16439, 16441), False, 'from marvin.cloudstackAPI import updateZone\n'), ((26082, 26176), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.api_client', '{}'], {'name': '"""DomainManagedbyVsd"""', 'domainid': 'vsd_enterprise.id'}), "(self.api_client, {}, name='DomainManagedbyVsd', domainid=\n vsd_enterprise.id)\n", (26095, 26176), False, 'from marvin.lib.base import Account, Domain, VirtualMachine\n'), ((26340, 26450), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.test_data['acl']['accountD1']"], {'admin': '(True)', 'domainid': 'acs_domain_1.id'}), "(self.api_client, self.test_data['acl']['accountD1'], admin=\n True, domainid=acs_domain_1.id)\n", (26354, 26450), False, 'from marvin.lib.base import Account, Domain, VirtualMachine\n'), ((30193, 30287), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.api_client', '{}'], {'name': '"""DomainManagedbyVsd"""', 'domainid': 'vsd_enterprise.id'}), "(self.api_client, {}, name='DomainManagedbyVsd', domainid=\n vsd_enterprise.id)\n", (30206, 30287), False, 'from marvin.lib.base import Account, Domain, VirtualMachine\n'), ((30446, 30557), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.test_data['acl']['accountD1']"], {'admin': '(False)', 'domainid': 'acs_domain_1.id'}), "(self.api_client, self.test_data['acl']['accountD1'], admin=\n False, domainid=acs_domain_1.id)\n", (30460, 30557), False, 'from marvin.lib.base import Account, Domain, VirtualMachine\n'), ((6425, 6471), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'vm.id'}), '(self.api_client, id=vm.id)\n', (6444, 6471), False, 'from marvin.lib.base import Account, Domain, VirtualMachine\n'), ((27055, 27155), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.api_client', '{}'], {'name': '"""AnotherDomainManagedbyVsd"""', 'domainid': 'vsd_enterprise.id'}), "(self.api_client, {}, name='AnotherDomainManagedbyVsd',\n domainid=vsd_enterprise.id)\n", (27068, 27155), False, 'from marvin.lib.base import Account, Domain, VirtualMachine\n'), ((27376, 27483), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.api_client', '{}'], {'name': '"""YetAnotherDomainManagedbyVsd"""', 'domainid': '(vsd_enterprise.id + 1)'}), "(self.api_client, {}, name='YetAnotherDomainManagedbyVsd',\n domainid=vsd_enterprise.id + 1)\n", (27389, 27483), False, 'from marvin.lib.base import Account, Domain, VirtualMachine\n'), ((37066, 37097), 'struct.pack', 'struct.pack', (['"""!I"""', 'netmask_bits'], {}), "('!I', netmask_bits)\n", (37077, 37097), False, 'import struct\n'), ((37227, 37273), 'struct.pack', 'struct.pack', (['"""!I"""', '(netmask_bits & network_bits)'], {}), "('!I', netmask_bits & network_bits)\n", (37238, 37273), False, 'import struct\n'), ((5738, 5751), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (5748, 5751), False, 'import time\n'), ((37142, 37167), 'socket.inet_aton', 'socket.inet_aton', (['network'], {}), '(network)\n', (37158, 37167), False, 'import socket\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Test cases for VM/Volume snapshot Test Path
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.lib.utils import (cleanup_resources,
is_snapshot_on_nfs,
validateList)
from marvin.lib.base import (Account,
ServiceOffering,
DiskOffering,
Template,
VirtualMachine,
Snapshot,
Volume
)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
list_volumes,
list_snapshots,
list_events,
createChecksum,
compareChecksum
)
from marvin.codes import PASS
from threading import Thread
class TestVolumeSnapshot(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestVolumeSnapshot, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
cls.hypervisor = cls.testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
cls._cleanup = []
if cls.hypervisor.lower() not in [
"vmware",
"kvm",
"xenserver"]:
raise unittest.SkipTest(
"Storage migration not supported on %s" %
cls.hypervisor)
try:
# Create an account
cls.account = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
# Create user api client of the account
cls.userapiclient = testClient.getUserApiClient(
UserName=cls.account.name,
DomainName=cls.account.domain
)
# Create Service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
)
cls._cleanup.append(cls.service_offering)
# Create Disk offering
cls.disk_offering = DiskOffering.create(
cls.apiclient,
cls.testdata["disk_offering"],
)
cls._cleanup.append(cls.disk_offering)
#Create VM_1 and VM_2
cls.vm_1 = VirtualMachine.create(
cls.userapiclient,
cls.testdata["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
zoneid=cls.zone.id,
diskofferingid=cls.disk_offering.id,
mode=cls.zone.networktype
)
cls.vm_2 = VirtualMachine.create(
cls.userapiclient,
cls.testdata["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
zoneid=cls.zone.id,
diskofferingid=cls.disk_offering.id,
mode=cls.zone.networktype
)
except Exception as e:
cls.tearDownClass()
raise e
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
root_volume = list_volumes(
self.apiclient,
virtualmachineid=self.vm_1.id,
type='ROOT',
listall=True
)
self.vm_1.stop(self.apiclient)
snaps = []
for i in range(2):
root_vol_snap = Snapshot.create(
self.apiclient,
root_volume[0].id)
self.assertEqual(
root_vol_snap.state,
"BackedUp",
"Check if the data vol snapshot state is correct "
)
snaps.append(root_vol_snap)
for snap in snaps:
self.assertNotEqual(
self.dbclient.execute(
"select status from snapshots where name='%s'" %
snap.name),
"Destroyed"
)
for snap in snaps:
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snap.id))
self.account.delete(self.apiclient)
for snap in snaps:
self.assertEqual(
self.dbclient.execute(
"select status from snapshots where name='%s'" %
snap.name)[0][0],
"Destroyed"
)
for snap in snaps:
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snap.id))
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "basic"], required_hardware="true")
def test_01_volume_snapshot(self):
""" Test Volume (root) Snapshot
# 1. Deploy a VM on primary storage and .
# 2. Take snapshot on root disk
# 3. Verify the snapshot's entry in the "snapshots" table
and presence of the corresponding
snapshot on the Secondary Storage
# 4. Create Template from the Snapshot and Deploy a
VM using the Template
# 5. Log in to the VM from template and make verify
the contents of the ROOT disk matches with the snapshot.
# 6. Delete Snapshot and Deploy a Linux VM from the
Template and verify the successful deployment of the VM.
# 7. Create multiple snapshots on the same volume and
Check the integrity of all the snapshots by creating
a template from the snapshot and deploying a Vm from it
and delete one of the snapshots
# 8. Verify that the original checksum matches with the checksum
of VM's created from remaning snapshots
# 9. Make verify the contents of the ROOT disk
matches with the snapshot
# 10.Verify that Snapshot of both DATA and ROOT volume should
succeed when snapshot of Data disk of a VM is taken
when snapshot of ROOT volume of VM is in progress
# 11.Create snapshot of data disk and verify the original checksum
matches with the volume created from snapshot
# 12.Verify that volume's state should not change when snapshot of
a DATA volume is taken that is attached to a VM
# 13.Verify that volume's state should not change when snapshot of
a DATA volume is taken that is not attached to a VM
# 14.Verify that create Snapshot with quiescevm=True should succeed
# 15.revertSnapshot() to revert VM to a specified
Volume snapshot for root volume
"""
# Step 1
# Get ROOT Volume Id
root_volumes_cluster_list = list_volumes(
self.apiclient,
virtualmachineid=self.vm_1.id,
type='ROOT',
listall=True
)
root_volume_cluster = root_volumes_cluster_list[0]
disk_volumes_cluster_list = list_volumes(
self.apiclient,
virtualmachineid=self.vm_1.id,
type='DATADISK',
listall=True
)
data_disk = disk_volumes_cluster_list[0]
root_vol_state = root_volume_cluster.state
ckecksum_random_root_cluster = createChecksum(
service=self.testdata,
virtual_machine=self.vm_1,
disk=root_volume_cluster,
disk_type="rootdiskdevice")
self.vm_1.stop(self.apiclient)
root_vol_snap = Snapshot.create(
self.apiclient,
root_volume_cluster.id)
self.assertEqual(
root_vol_snap.state,
"BackedUp",
"Check if the snapshot state is correct "
)
self.assertEqual(
root_vol_state,
root_volume_cluster.state,
"Check if volume state has changed"
)
self.vm_1.start(self.apiclient)
# Step 2
snapshot_list = list_snapshots(
self.apiclient,
id=root_vol_snap.id
)
self.assertNotEqual(
snapshot_list,
None,
"Check if result exists in list item call"
)
self.assertEqual(
snapshot_list[0].id,
root_vol_snap.id,
"Check resource id in list resources call"
)
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
root_vol_snap.id))
events = list_events(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
type='SNAPSHOT.CREATE')
event_list_validation_result = validateList(events)
self.assertEqual(
event_list_validation_result[0],
PASS,
"event list validation failed due to %s" %
event_list_validation_result[2])
self.debug("Events list contains event SNAPSHOT.CREATE")
qresultset = self.dbclient.execute(
"select * from event where type='SNAPSHOT.CREATE' AND \
description like '%%%s%%' AND state='Completed';" %
root_volume_cluster.id)
event_validation_result = validateList(qresultset)
self.assertEqual(
event_validation_result[0],
PASS,
"event list validation failed due to %s" %
event_validation_result[2])
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = str(qresultset)
self.assertEqual(
qresult.count('SNAPSHOT.CREATE') > 0,
True,
"Check SNAPSHOT.CREATE event in events table"
)
#Usage_Event
qresultset = self.dbclient.execute(
"select * from usage_event where type='SNAPSHOT.CREATE' AND \
resource_name='%s'" %
root_vol_snap.name)
usage_event_validation_result = validateList(qresultset)
self.assertEqual(
usage_event_validation_result[0],
PASS,
"event list validation failed due to %s" %
usage_event_validation_result[2])
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
self.assertEqual(
self.dbclient.execute("select size from usage_event where type='SNAPSHOT.CREATE' AND \
resource_name='%s'" %
root_vol_snap.name)[0][0],
root_vol_snap.physicalsize)
# Step 3
# create template from snapshot root_vol_snap
templateFromSnapshot = Template.create_from_snapshot(
self.apiclient,
root_vol_snap,
self.testdata["template_2"])
self.assertNotEqual(
templateFromSnapshot,
None,
"Check if result exists in list item call"
)
vm_from_temp = VirtualMachine.create(
self.apiclient,
self.testdata["small"],
templateid=templateFromSnapshot.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
self.assertNotEqual(
vm_from_temp,
None,
"Check if result exists in list item call"
)
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=ckecksum_random_root_cluster,
disk_type="rootdiskdevice",
virt_machine=vm_from_temp
)
vm_from_temp.delete(self.apiclient)
# Step 4
root_vol_snap.delete(self.userapiclient)
self.assertEqual(
list_snapshots(
self.apiclient,
volumeid=root_volume_cluster.id,
), None, "Snapshot list should be empty")
events = list_events(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
type='SNAPSHOT.DELETE')
event_list_validation_result = validateList(events)
self.assertEqual(
event_list_validation_result[0],
PASS,
"event list validation failed due to %s" %
event_list_validation_result[2])
self.debug("Events list contains event SNAPSHOT.DELETE")
self.debug("select id from account where uuid = '%s';"
% self.account.id)
qresultset = self.dbclient.execute(
"select id from account where uuid = '%s';"
% self.account.id
)
account_validation_result = validateList(qresultset)
self.assertEqual(
account_validation_result[0],
PASS,
"event list validation failed due to %s" %
account_validation_result[2])
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
account_id = qresult[0]
qresultset = self.dbclient.execute(
"select * from event where type='SNAPSHOT.DELETE' AND \
account_id='%s' AND state='Completed';" %
account_id)
delete_snap_validation_result = validateList(qresultset)
self.assertEqual(
delete_snap_validation_result[0],
PASS,
"event list validation failed due to %s" %
delete_snap_validation_result[2])
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = str(qresultset)
self.assertEqual(
qresult.count('SNAPSHOT.DELETE') > 0,
True,
"Check SNAPSHOT.DELETE event in events table"
)
# Step 5
# delete snapshot and deploy vm from snapshot
vm_from_temp_2 = VirtualMachine.create(
self.userapiclient,
self.testdata["small"],
templateid=templateFromSnapshot.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
self.assertNotEqual(
vm_from_temp_2,
None,
"Check if result exists in list item call"
)
# Step 6:
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=ckecksum_random_root_cluster,
disk_type="rootdiskdevice",
virt_machine=vm_from_temp_2
)
vm_from_temp_2.delete(self.apiclient)
# Step 7
# Multiple Snapshots
self.vm_1.stop(self.apiclient)
snaps = []
for i in range(2):
root_vol_snap = Snapshot.create(
self.apiclient,
root_volume_cluster.id)
self.assertEqual(
root_vol_snap.state,
"BackedUp",
"Check if the data vol snapshot state is correct "
)
snaps.append(root_vol_snap)
templateFromSnapshot = Template.create_from_snapshot(
self.apiclient,
root_vol_snap,
self.testdata["template_2"])
self.assertNotEqual(
templateFromSnapshot,
None,
"Check if result exists in list item call"
)
vm_from_temp = VirtualMachine.create(
self.userapiclient,
self.testdata["small"],
templateid=templateFromSnapshot.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
self.assertNotEqual(
vm_from_temp,
None,
"Check if result exists in list item call"
)
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=ckecksum_random_root_cluster,
disk_type="rootdiskdevice",
virt_machine=vm_from_temp
)
vm_from_temp.delete(self.apiclient)
templateFromSnapshot.delete(self.apiclient)
self.vm_1.start(self.apiclient)
delete_snap = snaps.pop(1)
delete_snap.delete(self.apiclient)
self.assertEqual(
Snapshot.list(
self.apiclient,
id=delete_snap.id
), None, "Snapshot list should be empty")
# Step 8
for snap in snaps:
templateFromSnapshot = Template.create_from_snapshot(
self.apiclient,
snap,
self.testdata["template_2"])
self.assertNotEqual(
templateFromSnapshot,
None,
"Check if result exists in list item call"
)
vm_from_temp = VirtualMachine.create(
self.userapiclient,
self.testdata["small"],
templateid=templateFromSnapshot.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
self.assertNotEqual(
vm_from_temp,
None,
"Check if result exists in list item call"
)
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=ckecksum_random_root_cluster,
disk_type="rootdiskdevice",
virt_machine=vm_from_temp
)
templateFromSnapshot.delete(self.apiclient)
vm_from_temp.delete(self.apiclient)
for snap in snaps:
snap.delete(self.apiclient)
# Step 9
ckecksum_root_cluster = createChecksum(
service=self.testdata,
virtual_machine=self.vm_1,
disk=root_volume_cluster,
disk_type="rootdiskdevice")
self.vm_1.stop(self.apiclient)
root_vol_snap_2 = Snapshot.create(
self.apiclient,
root_volume_cluster.id)
self.assertEqual(
root_vol_snap_2.state,
"BackedUp",
"Check if the data vol snapshot state is correct "
)
snap_list_validation_result = validateList(events)
self.assertEqual(
snap_list_validation_result[0],
PASS,
"snapshot list validation failed due to %s" %
snap_list_validation_result[2])
self.assertNotEqual(
snapshot_list,
None,
"Check if result exists in list item call"
)
templateFromSnapshot = Template.create_from_snapshot(
self.apiclient,
root_vol_snap_2,
self.testdata["template_2"])
self.debug(
"create template event comlites with template %s name" %
templateFromSnapshot.name)
self.assertNotEqual(
templateFromSnapshot,
None,
"Check if result exists in list item call"
)
vm_from_temp_2 = VirtualMachine.create(
self.userapiclient,
self.testdata["small"],
templateid=templateFromSnapshot.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
self.assertNotEqual(
vm_from_temp_2,
None,
"Check if result exists in list item call"
)
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=ckecksum_root_cluster,
disk_type="rootdiskdevice",
virt_machine=vm_from_temp_2
)
vm_from_temp_2.delete(self.apiclient)
# Step 10
# Take snapshot of Data disk of a VM , when snapshot of ROOT volume of
# VM is in progress
try:
self.vm_1.stop(self.apiclient)
t1 = Thread(
target=Snapshot.create,
args=(
self.apiclient,
root_volume_cluster.id
))
t2 = Thread(
target=Snapshot.create,
args=(
self.apiclient,
data_disk.id
))
t1.start()
t2.start()
t1.join()
t2.join()
except:
self.debug("Error: unable to start thread")
# Step 11
# Data Disk
self.vm_1.start(self.apiclient)
ckecksum_data_disk = createChecksum(
service=self.testdata,
virtual_machine=self.vm_1,
disk=data_disk,
disk_type="datadiskdevice_1")
data_vol_state = data_disk.state
self.vm_1.stop(self.apiclient)
data_vol_snap = Snapshot.create(
self.apiclient,
data_disk.id)
self.assertEqual(
data_vol_snap.state,
"BackedUp",
"Check if the data vol snapshot state is correct "
)
self.assertEqual(
data_vol_state,
data_disk.state,
"Check if volume state has changed"
)
data_snapshot_list = list_snapshots(
self.apiclient,
id=data_vol_snap.id
)
self.assertNotEqual(
data_snapshot_list,
None,
"Check if result exists in list item call"
)
self.assertEqual(
data_snapshot_list[0].id,
data_vol_snap.id,
"Check resource id in list resources call"
)
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
data_vol_snap.id))
events = list_events(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
type='SNAPSHOT.CREATE')
event_list_validation_result = validateList(events)
self.assertEqual(
event_list_validation_result[0],
PASS,
"event list validation failed due to %s" %
event_list_validation_result[2])
self.debug("Events list contains event SNAPSHOT.CREATE")
volumeFromSnap = Volume.create_from_snapshot(
self.apiclient,
data_vol_snap.id,
self.testdata["volume"],
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
data_vol_snap.id))
new_vm = VirtualMachine.create(
self.userapiclient,
self.testdata["small"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
new_vm.attach_volume(
self.apiclient,
volumeFromSnap
)
new_vm.reboot(self.apiclient)
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=ckecksum_data_disk,
disk_type="datadiskdevice_1",
virt_machine=new_vm
)
# Step 12
data_volume_2 = Volume.create(
self.apiclient,
self.testdata["volume"],
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid,
diskofferingid=self.disk_offering.id
)
self.vm_1.start(self.apiclient)
self.vm_1.attach_volume(
self.userapiclient,
data_volume_2
)
self.vm_1.reboot(self.apiclient)
self.vm_1.stop(self.apiclient)
data_vol_snap_1 = Snapshot.create(
self.apiclient,
data_volume_2.id)
self.assertEqual(
data_vol_snap_1.state,
"BackedUp",
"Check if the snapshot state is correct "
)
data_disk_2_list = Volume.list(
self.userapiclient,
listall=self.testdata["listall"],
id=data_volume_2.id
)
self.vm_1.start(self.apiclient)
checksum_data_2 = createChecksum(
service=self.testdata,
virtual_machine=self.vm_1,
disk=data_disk_2_list[0],
disk_type="datadiskdevice_2")
# Step 13
self.vm_1.detach_volume(self.apiclient,
data_volume_2)
self.vm_1.reboot(self.apiclient)
prev_state = data_volume_2.state
data_vol_snap_2 = Snapshot.create(
self.apiclient,
data_volume_2.id)
self.assertEqual(
data_vol_snap_2.state,
prev_state,
"Check if the volume state is correct "
)
data_snapshot_list_2 = list_snapshots(
self.apiclient,
id=data_vol_snap_2.id
)
self.assertNotEqual(
data_snapshot_list_2,
None,
"Check if result exists in list item call"
)
self.assertEqual(
data_snapshot_list_2[0].id,
data_vol_snap_2.id,
"Check resource id in list resources call"
)
volumeFromSnap_2 = Volume.create_from_snapshot(
self.apiclient,
data_vol_snap_2.id,
self.testdata["volume"],
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.vm_2.attach_volume(
self.userapiclient,
volumeFromSnap_2
)
self.vm_2.reboot(self.apiclient)
data_disk_2_list = Volume.list(
self.userapiclient,
listall=self.testdata["listall"],
id=volumeFromSnap_2.id
)
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=checksum_data_2,
disk_type="datadiskdevice_2",
virt_machine=self.vm_2
)
# Step 14
self.vm_1.stop(self.apiclient)
with self.assertRaises(Exception):
root_vol_snap.revertVolToSnapshot(self.apiclient)
# Step 15
root_snap = Snapshot.create(
self.apiclient,
root_volume_cluster.id)
with self.assertRaises(Exception):
root_snap.revertVolToSnapshot(self.apiclient)
return
| [
"marvin.lib.common.list_snapshots",
"marvin.lib.utils.is_snapshot_on_nfs",
"marvin.lib.common.list_volumes",
"marvin.lib.base.Volume.create_from_snapshot",
"marvin.lib.common.get_domain",
"marvin.lib.base.Snapshot.create",
"marvin.lib.base.Template.create_from_snapshot",
"marvin.lib.base.Volume.create... | [((7341, 7399), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (7345, 7399), False, 'from nose.plugins.attrib import attr\n'), ((2248, 2273), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2258, 2273), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((2371, 2435), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.testdata['ostype'])\n", (2383, 2435), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((9489, 9579), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm_1.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.vm_1.id, type='ROOT',\n listall=True)\n", (9501, 9579), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((9731, 9825), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm_1.id', 'type': '"""DATADISK"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.vm_1.id, type='DATADISK',\n listall=True)\n", (9743, 9825), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((10022, 10145), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm_1', 'disk': 'root_volume_cluster', 'disk_type': '"""rootdiskdevice"""'}), "(service=self.testdata, virtual_machine=self.vm_1, disk=\n root_volume_cluster, disk_type='rootdiskdevice')\n", (10036, 10145), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((10254, 10309), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume_cluster.id'], {}), '(self.apiclient, root_volume_cluster.id)\n', (10269, 10309), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((10717, 10768), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'id': 'root_vol_snap.id'}), '(self.apiclient, id=root_vol_snap.id)\n', (10731, 10768), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((11330, 11445), 'marvin.lib.common.list_events', 'list_events', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'type': '"""SNAPSHOT.CREATE"""'}), "(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, type='SNAPSHOT.CREATE')\n", (11341, 11445), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((11530, 11550), 'marvin.lib.utils.validateList', 'validateList', (['events'], {}), '(events)\n', (11542, 11550), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((12062, 12086), 'marvin.lib.utils.validateList', 'validateList', (['qresultset'], {}), '(qresultset)\n', (12074, 12086), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((12855, 12879), 'marvin.lib.utils.validateList', 'validateList', (['qresultset'], {}), '(qresultset)\n', (12867, 12879), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((13565, 13659), 'marvin.lib.base.Template.create_from_snapshot', 'Template.create_from_snapshot', (['self.apiclient', 'root_vol_snap', "self.testdata['template_2']"], {}), "(self.apiclient, root_vol_snap, self.testdata[\n 'template_2'])\n", (13594, 13659), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((13863, 14129), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['small']"], {'templateid': 'templateFromSnapshot.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.testdata['small'], templateid=\n templateFromSnapshot.id, accountid=self.account.name, domainid=self.\n account.domainid, serviceofferingid=self.service_offering.id, zoneid=\n self.zone.id, mode=self.zone.networktype)\n", (13884, 14129), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((14369, 14536), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'ckecksum_random_root_cluster', 'disk_type': '"""rootdiskdevice"""', 'virt_machine': 'vm_from_temp'}), "(self.apiclient, service=self.testdata, original_checksum=\n ckecksum_random_root_cluster, disk_type='rootdiskdevice', virt_machine=\n vm_from_temp)\n", (14384, 14536), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((14915, 15030), 'marvin.lib.common.list_events', 'list_events', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'type': '"""SNAPSHOT.DELETE"""'}), "(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, type='SNAPSHOT.DELETE')\n", (14926, 15030), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((15115, 15135), 'marvin.lib.utils.validateList', 'validateList', (['events'], {}), '(events)\n', (15127, 15135), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((15672, 15696), 'marvin.lib.utils.validateList', 'validateList', (['qresultset'], {}), '(qresultset)\n', (15684, 15696), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((16310, 16334), 'marvin.lib.utils.validateList', 'validateList', (['qresultset'], {}), '(qresultset)\n', (16322, 16334), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((16945, 17213), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.userapiclient', "self.testdata['small']"], {'templateid': 'templateFromSnapshot.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.userapiclient, self.testdata['small'],\n templateid=templateFromSnapshot.id, accountid=self.account.name,\n domainid=self.account.domainid, serviceofferingid=self.service_offering\n .id, zoneid=self.zone.id, mode=self.zone.networktype)\n", (16966, 17213), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((17475, 17644), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'ckecksum_random_root_cluster', 'disk_type': '"""rootdiskdevice"""', 'virt_machine': 'vm_from_temp_2'}), "(self.apiclient, service=self.testdata, original_checksum=\n ckecksum_random_root_cluster, disk_type='rootdiskdevice', virt_machine=\n vm_from_temp_2)\n", (17490, 17644), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((21260, 21383), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm_1', 'disk': 'root_volume_cluster', 'disk_type': '"""rootdiskdevice"""'}), "(service=self.testdata, virtual_machine=self.vm_1, disk=\n root_volume_cluster, disk_type='rootdiskdevice')\n", (21274, 21383), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((21495, 21550), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume_cluster.id'], {}), '(self.apiclient, root_volume_cluster.id)\n', (21510, 21550), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((21773, 21793), 'marvin.lib.utils.validateList', 'validateList', (['events'], {}), '(events)\n', (21785, 21793), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((22157, 22253), 'marvin.lib.base.Template.create_from_snapshot', 'Template.create_from_snapshot', (['self.apiclient', 'root_vol_snap_2', "self.testdata['template_2']"], {}), "(self.apiclient, root_vol_snap_2, self.\n testdata['template_2'])\n", (22186, 22253), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((22588, 22856), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.userapiclient', "self.testdata['small']"], {'templateid': 'templateFromSnapshot.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.userapiclient, self.testdata['small'],\n templateid=templateFromSnapshot.id, accountid=self.account.name,\n domainid=self.account.domainid, serviceofferingid=self.service_offering\n .id, zoneid=self.zone.id, mode=self.zone.networktype)\n", (22609, 22856), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((23100, 23262), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'ckecksum_root_cluster', 'disk_type': '"""rootdiskdevice"""', 'virt_machine': 'vm_from_temp_2'}), "(self.apiclient, service=self.testdata, original_checksum=\n ckecksum_root_cluster, disk_type='rootdiskdevice', virt_machine=\n vm_from_temp_2)\n", (23115, 23262), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((24189, 24304), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm_1', 'disk': 'data_disk', 'disk_type': '"""datadiskdevice_1"""'}), "(service=self.testdata, virtual_machine=self.vm_1, disk=\n data_disk, disk_type='datadiskdevice_1')\n", (24203, 24304), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((24456, 24501), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'data_disk.id'], {}), '(self.apiclient, data_disk.id)\n', (24471, 24501), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((24856, 24907), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'id': 'data_vol_snap.id'}), '(self.apiclient, id=data_vol_snap.id)\n', (24870, 24907), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((25479, 25594), 'marvin.lib.common.list_events', 'list_events', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'type': '"""SNAPSHOT.CREATE"""'}), "(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, type='SNAPSHOT.CREATE')\n", (25490, 25594), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((25679, 25699), 'marvin.lib.utils.validateList', 'validateList', (['events'], {}), '(events)\n', (25691, 25699), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((25981, 26156), 'marvin.lib.base.Volume.create_from_snapshot', 'Volume.create_from_snapshot', (['self.apiclient', 'data_vol_snap.id', "self.testdata['volume']"], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), "(self.apiclient, data_vol_snap.id, self.testdata\n ['volume'], account=self.account.name, domainid=self.account.domainid,\n zoneid=self.zone.id)\n", (26008, 26156), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((26463, 26725), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.userapiclient', "self.testdata['small']"], {'templateid': 'self.template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.userapiclient, self.testdata['small'],\n templateid=self.template.id, accountid=self.account.name, domainid=self\n .account.domainid, serviceofferingid=self.service_offering.id, zoneid=\n self.zone.id, mode=self.zone.networktype)\n", (26484, 26725), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((26962, 27110), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'ckecksum_data_disk', 'disk_type': '"""datadiskdevice_1"""', 'virt_machine': 'new_vm'}), "(self.apiclient, service=self.testdata, original_checksum=\n ckecksum_data_disk, disk_type='datadiskdevice_1', virt_machine=new_vm)\n", (26977, 27110), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((27219, 27399), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.testdata['volume']"], {'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'diskofferingid': 'self.disk_offering.id'}), "(self.apiclient, self.testdata['volume'], zoneid=self.zone.id,\n account=self.account.name, domainid=self.account.domainid,\n diskofferingid=self.disk_offering.id)\n", (27232, 27399), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((27731, 27780), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'data_volume_2.id'], {}), '(self.apiclient, data_volume_2.id)\n', (27746, 27780), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((27984, 28075), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.userapiclient'], {'listall': "self.testdata['listall']", 'id': 'data_volume_2.id'}), "(self.userapiclient, listall=self.testdata['listall'], id=\n data_volume_2.id)\n", (27995, 28075), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((28185, 28310), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm_1', 'disk': 'data_disk_2_list[0]', 'disk_type': '"""datadiskdevice_2"""'}), "(service=self.testdata, virtual_machine=self.vm_1, disk=\n data_disk_2_list[0], disk_type='datadiskdevice_2')\n", (28199, 28310), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((28575, 28624), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'data_volume_2.id'], {}), '(self.apiclient, data_volume_2.id)\n', (28590, 28624), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((28830, 28883), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'id': 'data_vol_snap_2.id'}), '(self.apiclient, id=data_vol_snap_2.id)\n', (28844, 28883), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((29257, 29435), 'marvin.lib.base.Volume.create_from_snapshot', 'Volume.create_from_snapshot', (['self.apiclient', 'data_vol_snap_2.id', "self.testdata['volume']"], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), "(self.apiclient, data_vol_snap_2.id, self.\n testdata['volume'], account=self.account.name, domainid=self.account.\n domainid, zoneid=self.zone.id)\n", (29284, 29435), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((29683, 29777), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.userapiclient'], {'listall': "self.testdata['listall']", 'id': 'volumeFromSnap_2.id'}), "(self.userapiclient, listall=self.testdata['listall'], id=\n volumeFromSnap_2.id)\n", (29694, 29777), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((29828, 29976), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'checksum_data_2', 'disk_type': '"""datadiskdevice_2"""', 'virt_machine': 'self.vm_2'}), "(self.apiclient, service=self.testdata, original_checksum=\n checksum_data_2, disk_type='datadiskdevice_2', virt_machine=self.vm_2)\n", (29843, 29976), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((30244, 30299), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume_cluster.id'], {}), '(self.apiclient, root_volume_cluster.id)\n', (30259, 30299), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((2641, 2716), 'marvin.cloudstackTestCase.unittest.SkipTest', 'unittest.SkipTest', (["('Storage migration not supported on %s' % cls.hypervisor)"], {}), "('Storage migration not supported on %s' % cls.hypervisor)\n", (2658, 2716), False, 'from marvin.cloudstackTestCase import cloudstackTestCase, unittest\n'), ((2822, 2900), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.testdata['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.testdata['account'], domainid=cls.domain.id)\n", (2836, 2900), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((3297, 3368), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {}), "(cls.apiclient, cls.testdata['service_offering'])\n", (3319, 3368), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((3537, 3602), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.apiclient', "cls.testdata['disk_offering']"], {}), "(cls.apiclient, cls.testdata['disk_offering'])\n", (3556, 3602), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((3762, 4053), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.userapiclient', "cls.testdata['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id', 'zoneid': 'cls.zone.id', 'diskofferingid': 'cls.disk_offering.id', 'mode': 'cls.zone.networktype'}), "(cls.userapiclient, cls.testdata['small'], templateid=\n cls.template.id, accountid=cls.account.name, domainid=cls.account.\n domainid, serviceofferingid=cls.service_offering.id, zoneid=cls.zone.id,\n diskofferingid=cls.disk_offering.id, mode=cls.zone.networktype)\n", (3783, 4053), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((4222, 4513), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.userapiclient', "cls.testdata['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id', 'zoneid': 'cls.zone.id', 'diskofferingid': 'cls.disk_offering.id', 'mode': 'cls.zone.networktype'}), "(cls.userapiclient, cls.testdata['small'], templateid=\n cls.template.id, accountid=cls.account.name, domainid=cls.account.\n domainid, serviceofferingid=cls.service_offering.id, zoneid=cls.zone.id,\n diskofferingid=cls.disk_offering.id, mode=cls.zone.networktype)\n", (4243, 4513), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((4828, 4874), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (4845, 4874), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((5206, 5296), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm_1.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.vm_1.id, type='ROOT',\n listall=True)\n", (5218, 5296), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((7167, 7214), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (7184, 7214), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((11135, 11233), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'root_vol_snap.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n root_vol_snap.id)\n', (11153, 11233), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((14746, 14809), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'root_volume_cluster.id'}), '(self.apiclient, volumeid=root_volume_cluster.id)\n', (14760, 14809), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((17912, 17967), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume_cluster.id'], {}), '(self.apiclient, root_volume_cluster.id)\n', (17927, 17967), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((18255, 18349), 'marvin.lib.base.Template.create_from_snapshot', 'Template.create_from_snapshot', (['self.apiclient', 'root_vol_snap', "self.testdata['template_2']"], {}), "(self.apiclient, root_vol_snap, self.testdata[\n 'template_2'])\n", (18284, 18349), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((18589, 18857), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.userapiclient', "self.testdata['small']"], {'templateid': 'templateFromSnapshot.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.userapiclient, self.testdata['small'],\n templateid=templateFromSnapshot.id, accountid=self.account.name,\n domainid=self.account.domainid, serviceofferingid=self.service_offering\n .id, zoneid=self.zone.id, mode=self.zone.networktype)\n", (18610, 18857), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((19159, 19326), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'ckecksum_random_root_cluster', 'disk_type': '"""rootdiskdevice"""', 'virt_machine': 'vm_from_temp'}), "(self.apiclient, service=self.testdata, original_checksum=\n ckecksum_random_root_cluster, disk_type='rootdiskdevice', virt_machine=\n vm_from_temp)\n", (19174, 19326), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((19674, 19722), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.apiclient'], {'id': 'delete_snap.id'}), '(self.apiclient, id=delete_snap.id)\n', (19687, 19722), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((19890, 19975), 'marvin.lib.base.Template.create_from_snapshot', 'Template.create_from_snapshot', (['self.apiclient', 'snap', "self.testdata['template_2']"], {}), "(self.apiclient, snap, self.testdata['template_2']\n )\n", (19919, 19975), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((20215, 20483), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.userapiclient', "self.testdata['small']"], {'templateid': 'templateFromSnapshot.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.userapiclient, self.testdata['small'],\n templateid=templateFromSnapshot.id, accountid=self.account.name,\n domainid=self.account.domainid, serviceofferingid=self.service_offering\n .id, zoneid=self.zone.id, mode=self.zone.networktype)\n", (20236, 20483), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((20785, 20952), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'ckecksum_random_root_cluster', 'disk_type': '"""rootdiskdevice"""', 'virt_machine': 'vm_from_temp'}), "(self.apiclient, service=self.testdata, original_checksum=\n ckecksum_random_root_cluster, disk_type='rootdiskdevice', virt_machine=\n vm_from_temp)\n", (20800, 20952), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_events, createChecksum, compareChecksum\n'), ((23571, 23648), 'threading.Thread', 'Thread', ([], {'target': 'Snapshot.create', 'args': '(self.apiclient, root_volume_cluster.id)'}), '(target=Snapshot.create, args=(self.apiclient, root_volume_cluster.id))\n', (23577, 23648), False, 'from threading import Thread\n'), ((23758, 23825), 'threading.Thread', 'Thread', ([], {'target': 'Snapshot.create', 'args': '(self.apiclient, data_disk.id)'}), '(target=Snapshot.create, args=(self.apiclient, data_disk.id))\n', (23764, 23825), False, 'from threading import Thread\n'), ((25284, 25382), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'data_vol_snap.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n data_vol_snap.id)\n', (25302, 25382), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((26268, 26366), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'data_vol_snap.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n data_vol_snap.id)\n', (26286, 26366), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((5526, 5576), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume[0].id'], {}), '(self.apiclient, root_volume[0].id)\n', (5541, 5576), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, Template, VirtualMachine, Snapshot, Volume\n'), ((6260, 6349), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snap.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snap.id)\n', (6278, 6349), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((6931, 7020), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snap.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snap.id)\n', (6949, 7020), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for Kubernetes supported version """
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.cloudstackAPI import (listInfrastructure,
listTemplates,
listKubernetesSupportedVersions,
addKubernetesSupportedVersion,
deleteKubernetesSupportedVersion,
listKubernetesClusters,
createKubernetesCluster,
stopKubernetesCluster,
startKubernetesCluster,
deleteKubernetesCluster,
upgradeKubernetesCluster,
scaleKubernetesCluster,
getKubernetesClusterConfig,
destroyVirtualMachine,
deleteNetwork)
from marvin.cloudstackException import CloudstackAPIException
from marvin.codes import PASS, FAILED
from marvin.lib.base import (Template,
ServiceOffering,
Account,
StoragePool,
Configurations)
from marvin.lib.utils import (cleanup_resources,
validateList,
random_gen)
from marvin.lib.common import (get_zone,
get_domain)
from marvin.sshClient import SshClient
from nose.plugins.attrib import attr
from marvin.lib.decoratorGenerators import skipTestIf
from kubernetes import client, config
import time, io, yaml
_multiprocess_shared_ = True
k8s_cluster = None
class TestKubernetesCluster(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestKubernetesCluster, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.hypervisor = testClient.getHypervisorInfo()
cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
cls.hypervisorNotSupported = False
if cls.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
cls.hypervisorNotSupported = True
cls.setup_failed = False
cls._cleanup = []
cls.kubernetes_version_ids = []
if cls.hypervisorNotSupported == False:
cls.endpoint_url = Configurations.list(cls.apiclient, name="endpoint.url")[0].value
if "localhost" in cls.endpoint_url:
endpoint_url = "http://%s:%d/client/api " %(cls.mgtSvrDetails["mgtSvrIp"], cls.mgtSvrDetails["port"])
cls.debug("Setting endpoint.url to %s" %(endpoint_url))
Configurations.update(cls.apiclient, "endpoint.url", endpoint_url)
cls.initial_configuration_cks_enabled = Configurations.list(cls.apiclient, name="cloud.kubernetes.service.enabled")[0].value
if cls.initial_configuration_cks_enabled not in ["true", True]:
cls.debug("Enabling CloudStack Kubernetes Service plugin and restarting management server")
Configurations.update(cls.apiclient,
"cloud.kubernetes.service.enabled",
"true")
cls.restartServer()
cls.updateVmwareSettings(False)
cls.cks_service_offering = None
if cls.setup_failed == False:
try:
cls.kubernetes_version_1_20_9 = cls.addKubernetesSupportedVersion(cls.services["cks_kubernetes_versions"]["1.20.9"])
cls.kubernetes_version_ids.append(cls.kubernetes_version_1_20_9.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, version=%s, url=%s, %s" %
(cls.services["cks_kubernetes_versions"]["1.20.9"]["semanticversion"], cls.services["cks_kubernetes_versions"]["1.20.9"]["url"], e))
if cls.setup_failed == False:
try:
cls.kubernetes_version_1_21_3 = cls.addKubernetesSupportedVersion(cls.services["cks_kubernetes_versions"]["1.21.3"])
cls.kubernetes_version_ids.append(cls.kubernetes_version_1_21_3.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, version=%s, url=%s, %s" %
(cls.services["cks_kubernetes_versions"]["1.21.3"]["semanticversion"], cls.services["cks_kubernetes_versions"]["1.21.3"]["url"], e))
if cls.setup_failed == False:
cks_offering_data = cls.services["cks_service_offering"]
cks_offering_data["name"] = 'CKS-Instance-' + random_gen()
cls.cks_service_offering = ServiceOffering.create(
cls.apiclient,
cks_offering_data
)
cls._cleanup.append(cls.cks_service_offering)
cls.domain = get_domain(cls.apiclient)
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
return
@classmethod
def tearDownClass(cls):
if k8s_cluster != None and k8s_cluster.id != None:
clsObj = TestKubernetesCluster()
clsObj.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
version_delete_failed = False
# Delete added Kubernetes supported version
for version_id in cls.kubernetes_version_ids:
try:
cls.deleteKubernetesSupportedVersion(version_id)
except Exception as e:
version_delete_failed = True
cls.debug("Error: Exception during cleanup for added Kubernetes supported versions: %s" % e)
try:
# Restore CKS enabled
if cls.initial_configuration_cks_enabled not in ["true", True]:
cls.debug("Restoring Kubernetes Service enabled value")
Configurations.update(cls.apiclient,
"cloud.kubernetes.service.enabled",
"false")
cls.restartServer()
cls.updateVmwareSettings(True)
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
if version_delete_failed == True:
raise Exception("Warning: Exception during cleanup, unable to delete Kubernetes supported versions")
return
@classmethod
def updateVmwareSettings(cls, tearDown):
value = "false"
if not tearDown:
value = "true"
if cls.hypervisor.lower() == 'vmware':
Configurations.update(cls.apiclient,
"vmware.create.full.clone",
value)
allStoragePools = StoragePool.list(
cls.apiclient
)
for pool in allStoragePools:
Configurations.update(cls.apiclient,
storageid=pool.id,
name="vmware.create.full.clone",
value=value)
@classmethod
def restartServer(cls):
"""Restart management server"""
cls.debug("Restarting management server")
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-management stop"
sshClient.execute(command)
command = "service cloudstack-management start"
sshClient.execute(command)
#Waits for management to come up in 5 mins, when it's up it will continue
timeout = time.time() + 300
while time.time() < timeout:
if cls.isManagementUp() is True: return
time.sleep(5)
cls.setup_failed = True
cls.debug("Management server did not come up, failing")
return
@classmethod
def isManagementUp(cls):
try:
cls.apiclient.listInfrastructure(listInfrastructure.listInfrastructureCmd())
return True
except Exception:
return False
@classmethod
def waitForKubernetesSupportedVersionIsoReadyState(cls, version_id, retries=30, interval=60):
"""Check if Kubernetes supported version ISO is in Ready state"""
while retries > 0:
time.sleep(interval)
list_versions_response = cls.listKubernetesSupportedVersion(version_id)
if not hasattr(list_versions_response, 'isostate') or not list_versions_response or not list_versions_response.isostate:
retries = retries - 1
continue
if 'Ready' == list_versions_response.isostate:
return
elif 'Failed' == list_versions_response.isostate:
raise Exception( "Failed to download template: status - %s" % template.status)
retries = retries - 1
raise Exception("Kubernetes supported version Ready state timed out")
@classmethod
def listKubernetesSupportedVersion(cls, version_id):
listKubernetesSupportedVersionsCmd = listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd()
listKubernetesSupportedVersionsCmd.id = version_id
versionResponse = cls.apiclient.listKubernetesSupportedVersions(listKubernetesSupportedVersionsCmd)
return versionResponse[0]
@classmethod
def addKubernetesSupportedVersion(cls, version_service):
addKubernetesSupportedVersionCmd = addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd()
addKubernetesSupportedVersionCmd.semanticversion = version_service["semanticversion"]
addKubernetesSupportedVersionCmd.name = 'v' + version_service["semanticversion"] + '-' + random_gen()
addKubernetesSupportedVersionCmd.url = version_service["url"]
addKubernetesSupportedVersionCmd.mincpunumber = version_service["mincpunumber"]
addKubernetesSupportedVersionCmd.minmemory = version_service["minmemory"]
kubernetes_version = cls.apiclient.addKubernetesSupportedVersion(addKubernetesSupportedVersionCmd)
cls.debug("Waiting for Kubernetes version with ID %s to be ready" % kubernetes_version.id)
cls.waitForKubernetesSupportedVersionIsoReadyState(kubernetes_version.id)
kubernetes_version = cls.listKubernetesSupportedVersion(kubernetes_version.id)
return kubernetes_version
@classmethod
def deleteKubernetesSupportedVersion(cls, version_id):
deleteKubernetesSupportedVersionCmd = deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd()
deleteKubernetesSupportedVersionCmd.id = version_id
cls.apiclient.deleteKubernetesSupportedVersion(deleteKubernetesSupportedVersionCmd)
@classmethod
def listKubernetesCluster(cls, cluster_id = None):
listKubernetesClustersCmd = listKubernetesClusters.listKubernetesClustersCmd()
listKubernetesClustersCmd.listall = True
if cluster_id != None:
listKubernetesClustersCmd.id = cluster_id
clusterResponse = cls.apiclient.listKubernetesClusters(listKubernetesClustersCmd)
if cluster_id != None and clusterResponse != None:
return clusterResponse[0]
return clusterResponse
@classmethod
def deleteKubernetesCluster(cls, cluster_id):
deleteKubernetesClusterCmd = deleteKubernetesCluster.deleteKubernetesClusterCmd()
deleteKubernetesClusterCmd.id = cluster_id
response = cls.apiclient.deleteKubernetesCluster(deleteKubernetesClusterCmd)
return response
@classmethod
def stopKubernetesCluster(cls, cluster_id):
stopKubernetesClusterCmd = stopKubernetesCluster.stopKubernetesClusterCmd()
stopKubernetesClusterCmd.id = cluster_id
response = cls.apiclient.stopKubernetesCluster(stopKubernetesClusterCmd)
return response
def deleteKubernetesClusterAndVerify(self, cluster_id, verify = True, forced = False):
"""Delete Kubernetes cluster and check if it is really deleted"""
delete_response = {}
forceDeleted = False
try:
delete_response = self.deleteKubernetesCluster(cluster_id)
except Exception as e:
if forced:
cluster = self.listKubernetesCluster(cluster_id)
if cluster != None:
if cluster.state in ['Starting', 'Running', 'Upgrading', 'Scaling']:
self.stopKubernetesCluster(cluster_id)
self.deleteKubernetesCluster(cluster_id)
else:
forceDeleted = True
for cluster_vm in cluster.virtualmachines:
cmd = destroyVirtualMachine.destroyVirtualMachineCmd()
cmd.id = cluster_vm.id
cmd.expunge = True
self.apiclient.destroyVirtualMachine(cmd)
cmd = deleteNetwork.deleteNetworkCmd()
cmd.id = cluster.networkid
cmd.forced = True
self.apiclient.deleteNetwork(cmd)
self.dbclient.execute("update kubernetes_cluster set state='Destroyed', removed=now() where uuid = '%s';" % cluster.id)
else:
raise Exception("Error: Exception during delete cluster : %s" % e)
if verify == True and forceDeleted == False:
self.assertEqual(
delete_response.success,
True,
"Check KubernetesCluster delete response {}, {}".format(delete_response.success, True)
)
db_cluster_removed = self.dbclient.execute("select removed from kubernetes_cluster where uuid = '%s';" % cluster_id)[0][0]
self.assertNotEqual(
db_cluster_removed,
None,
"KubernetesCluster not removed in DB, {}".format(db_cluster_removed)
)
def setUp(self):
self.services = self.testClient.getParsedTestDataConfig()
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_01_invalid_upgrade_kubernetes_cluster(self):
"""Test to check for failure while tying to upgrade a Kubernetes cluster to a lower version
# Validate the following:
# 1. upgradeKubernetesCluster should fail
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(version=self.kubernetes_version_1_21_3)
self.debug("Downgrading Kubernetes cluster with ID: %s to a lower version. This should fail!" % k8s_cluster.id)
try:
k8s_cluster = self.upgradeKubernetesCluster(k8s_cluster.id, self.kubernetes_version_1_20_9.id)
self.debug("Invalid CKS Kubernetes HA cluster deployed with ID: %s. Deleting it and failing test." % self.kubernetes_version_1_20_9.id)
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Kubernetes cluster downgrade to a lower Kubernetes supported version. Must be an error.")
except Exception as e:
self.debug("Upgrading Kubernetes cluster with invalid Kubernetes supported version check successful, API failure: %s" % e)
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.verifyKubernetesClusterUpgrade(k8s_cluster, self.kubernetes_version_1_21_3.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_02_upgrade_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster and upgrade it to newer version
# Validate the following:
# 1. upgradeKubernetesCluster should return valid info for the cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(version=self.kubernetes_version_1_20_9)
time.sleep(self.services["sleep"])
self.debug("Upgrading Kubernetes cluster with ID: %s" % k8s_cluster.id)
try:
k8s_cluster = self.upgradeKubernetesCluster(k8s_cluster.id, self.kubernetes_version_1_21_3.id)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to upgrade Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterUpgrade(k8s_cluster, self.kubernetes_version_1_21_3.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_03_deploy_and_scale_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster and check for failure while tying to scale it
# Validate the following:
# 1. scaleKubernetesCluster should return valid info for the cluster when it is scaled up
# 2. scaleKubernetesCluster should return valid info for the cluster when it is scaled down
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster()
self.debug("Upscaling Kubernetes cluster with ID: %s" % k8s_cluster.id)
try:
k8s_cluster = self.scaleKubernetesCluster(k8s_cluster.id, 2)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to upscale Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterScale(k8s_cluster, 2)
self.debug("Kubernetes cluster with ID: %s successfully upscaled, now downscaling it" % k8s_cluster.id)
try:
k8s_cluster = self.scaleKubernetesCluster(k8s_cluster.id, 1)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to downscale Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterScale(k8s_cluster)
self.debug("Kubernetes cluster with ID: %s successfully downscaled" % k8s_cluster.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_04_autoscale_kubernetes_cluster(self):
"""Test to enable autoscaling a Kubernetes cluster
# Validate the following:
# 1. scaleKubernetesCluster should return valid info for the cluster when it is autoscaled
# 2. cluster-autoscaler pod should be running
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(version=self.kubernetes_version_1_21_3)
self.debug("Autoscaling Kubernetes cluster with ID: %s" % k8s_cluster.id)
try:
k8s_cluster = self.autoscaleKubernetesCluster(k8s_cluster.id, 1, 2)
self.verifyKubernetesClusterAutocale(k8s_cluster, 1, 2)
up = self.waitForAutoscalerPodInRunningState(k8s_cluster.id)
self.assertTrue(up, "Autoscaler pod failed to run")
self.debug("Kubernetes cluster with ID: %s has autoscaler running" % k8s_cluster.id)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to autoscale Kubernetes cluster due to: %s" % e)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_05_basic_lifecycle_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
# 3. stopKubernetesCluster should stop the cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster()
self.debug("Kubernetes cluster with ID: %s successfully deployed, now stopping it" % k8s_cluster.id)
self.stopAndVerifyKubernetesCluster(k8s_cluster.id)
self.debug("Kubernetes cluster with ID: %s successfully stopped, now starting it again" % k8s_cluster.id)
try:
k8s_cluster = self.startKubernetesCluster(k8s_cluster.id)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to start Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterState(k8s_cluster, 'Running')
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_06_delete_kubernetes_cluster(self):
"""Test to delete an existing Kubernetes cluster
# Validate the following:
# 1. deleteKubernetesCluster should delete an existing Kubernetes cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster()
self.debug("Deleting Kubernetes cluster with ID: %s" % k8s_cluster.id)
self.deleteKubernetesClusterAndVerify(k8s_cluster.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % k8s_cluster.id)
k8s_cluster = None
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_07_deploy_kubernetes_ha_cluster(self):
"""Test to deploy a new Kubernetes cluster
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(1, 2)
self.debug("HA Kubernetes cluster with ID: %s successfully deployed" % k8s_cluster.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_08_upgrade_kubernetes_ha_cluster(self):
"""Test to upgrade a Kubernetes cluster to newer version
# Validate the following:
# 1. upgradeKubernetesCluster should return valid info for the cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(1, 2)
time.sleep(self.services["sleep"])
self.debug("Upgrading HA Kubernetes cluster with ID: %s" % k8s_cluster.id)
try:
k8s_cluster = self.upgradeKubernetesCluster(k8s_cluster.id, self.kubernetes_version_1_21_3.id)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to upgrade Kubernetes HA cluster due to: %s" % e)
self.verifyKubernetesClusterUpgrade(k8s_cluster, self.kubernetes_version_1_21_3.id)
self.debug("Kubernetes cluster with ID: %s successfully upgraded" % k8s_cluster.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_09_delete_kubernetes_ha_cluster(self):
"""Test to delete a HA Kubernetes cluster
# Validate the following:
# 1. deleteKubernetesCluster should delete an existing HA Kubernetes cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(1, 2)
self.debug("Deleting Kubernetes cluster with ID: %s" % k8s_cluster.id)
return
def createKubernetesCluster(self, name, version_id, size=1, control_nodes=1):
createKubernetesClusterCmd = createKubernetesCluster.createKubernetesClusterCmd()
createKubernetesClusterCmd.name = name
createKubernetesClusterCmd.description = name + "-description"
createKubernetesClusterCmd.kubernetesversionid = version_id
createKubernetesClusterCmd.size = size
createKubernetesClusterCmd.controlnodes = control_nodes
createKubernetesClusterCmd.serviceofferingid = self.cks_service_offering.id
createKubernetesClusterCmd.zoneid = self.zone.id
createKubernetesClusterCmd.noderootdisksize = 10
createKubernetesClusterCmd.account = self.account.name
createKubernetesClusterCmd.domainid = self.domain.id
clusterResponse = self.apiclient.createKubernetesCluster(createKubernetesClusterCmd)
if not clusterResponse:
self.cleanup.append(clusterResponse)
return clusterResponse
def startKubernetesCluster(self, cluster_id):
startKubernetesClusterCmd = startKubernetesCluster.startKubernetesClusterCmd()
startKubernetesClusterCmd.id = cluster_id
response = self.apiclient.startKubernetesCluster(startKubernetesClusterCmd)
return response
def upgradeKubernetesCluster(self, cluster_id, version_id):
upgradeKubernetesClusterCmd = upgradeKubernetesCluster.upgradeKubernetesClusterCmd()
upgradeKubernetesClusterCmd.id = cluster_id
upgradeKubernetesClusterCmd.kubernetesversionid = version_id
response = self.apiclient.upgradeKubernetesCluster(upgradeKubernetesClusterCmd)
return response
def scaleKubernetesCluster(self, cluster_id, size):
scaleKubernetesClusterCmd = scaleKubernetesCluster.scaleKubernetesClusterCmd()
scaleKubernetesClusterCmd.id = cluster_id
scaleKubernetesClusterCmd.size = size
response = self.apiclient.scaleKubernetesCluster(scaleKubernetesClusterCmd)
return response
def autoscaleKubernetesCluster(self, cluster_id, minsize, maxsize):
scaleKubernetesClusterCmd = scaleKubernetesCluster.scaleKubernetesClusterCmd()
scaleKubernetesClusterCmd.id = cluster_id
scaleKubernetesClusterCmd.autoscalingenabled = True
scaleKubernetesClusterCmd.minsize = minsize
scaleKubernetesClusterCmd.maxsize = maxsize
response = self.apiclient.scaleKubernetesCluster(scaleKubernetesClusterCmd)
return response
def fetchKubernetesClusterConfig(self, cluster_id):
getKubernetesClusterConfigCmd = getKubernetesClusterConfig.getKubernetesClusterConfigCmd()
getKubernetesClusterConfigCmd.id = cluster_id
response = self.apiclient.getKubernetesClusterConfig(getKubernetesClusterConfigCmd)
return response
def waitForAutoscalerPodInRunningState(self, cluster_id, retries=5, interval=60):
k8s_config = self.fetchKubernetesClusterConfig(cluster_id)
cfg = io.StringIO(k8s_config.configdata)
cfg = yaml.safe_load(cfg)
# Adding this so we don't get certificate exceptions
cfg['clusters'][0]['cluster']['insecure-skip-tls-verify']=True
config.load_kube_config_from_dict(cfg)
v1 = client.CoreV1Api()
while retries > 0:
time.sleep(interval)
pods = v1.list_pod_for_all_namespaces(watch=False, label_selector="app=cluster-autoscaler").items
if len(pods) == 0 :
self.debug("Autoscaler pod still not up")
continue
pod = pods[0]
if pod.status.phase == 'Running' :
self.debug("Autoscaler pod %s up and running!" % pod.metadata.name)
return True
self.debug("Autoscaler pod %s up but not running on retry %d. State is : %s" %(pod.metadata.name, retries, pod.status.phase))
retries = retries - 1
return False
def getValidKubernetesCluster(self, size=1, control_nodes=1, version={}):
cluster = k8s_cluster
# Does a cluster already exist ?
if cluster == None or cluster.id == None:
if not version:
version = self.kubernetes_version_1_20_9
self.debug("No existing cluster available, k8s_cluster: %s" % cluster)
return self.createNewKubernetesCluster(version, size, control_nodes)
# Is the existing cluster what is needed ?
valid = cluster.size == size and cluster.controlnodes == control_nodes
if version:
# Check the version only if specified
valid = valid and cluster.kubernetesversionid == version.id
else:
version = self.kubernetes_version_1_20_9
if valid:
cluster_id = cluster.id
cluster = self.listKubernetesCluster(cluster_id)
if cluster == None:
# Looks like the cluster disappeared !
self.debug("Existing cluster, k8s_cluster ID: %s not returned by list API" % cluster_id)
return self.createNewKubernetesCluster(version, size, control_nodes)
if valid:
try:
self.verifyKubernetesCluster(cluster, cluster.name, None, size, control_nodes)
self.debug("Existing Kubernetes cluster available with name %s" % cluster.name)
return cluster
except AssertionError as error:
self.debug("Existing cluster failed verification due to %s, need to deploy a new one" % error)
self.deleteKubernetesClusterAndVerify(cluster.id, False, True)
# Can't have too many loose clusters running around
if cluster.id != None:
self.deleteKubernetesClusterAndVerify(cluster.id, False, True)
self.debug("No valid cluster, need to deploy a new one")
return self.createNewKubernetesCluster(version, size, control_nodes)
def createNewKubernetesCluster(self, version, size, control_nodes) :
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
try:
cluster = self.createKubernetesCluster(name, version.id, size, control_nodes)
self.verifyKubernetesCluster(cluster, name, version.id, size, control_nodes)
except Exception as ex:
self.fail("Kubernetes cluster deployment failed: %s" % ex)
except AssertionError as err:
self.fail("Kubernetes cluster deployment failed during cluster verification: %s" % err)
return cluster
def verifyKubernetesCluster(self, cluster_response, name, version_id=None, size=1, control_nodes=1):
"""Check if Kubernetes cluster is valid"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
if name != None:
self.assertEqual(
cluster_response.name,
name,
"Check KubernetesCluster name {}, {}".format(cluster_response.name, name)
)
if version_id != None:
self.verifyKubernetesClusterVersion(cluster_response, version_id)
self.assertEqual(
cluster_response.zoneid,
self.zone.id,
"Check KubernetesCluster zone {}, {}".format(cluster_response.zoneid, self.zone.id)
)
self.verifyKubernetesClusterSize(cluster_response, size, control_nodes)
db_cluster_name = self.dbclient.execute("select name from kubernetes_cluster where uuid = '%s';" % cluster_response.id)[0][0]
self.assertEqual(
str(db_cluster_name),
name,
"Check KubernetesCluster name in DB {}, {}".format(db_cluster_name, name)
)
def verifyKubernetesClusterState(self, cluster_response, state):
"""Check if Kubernetes cluster state is Running"""
self.assertEqual(
cluster_response.state,
'Running',
"Check KubernetesCluster state {}, {}".format(cluster_response.state, state)
)
def verifyKubernetesClusterVersion(self, cluster_response, version_id):
"""Check if Kubernetes cluster node sizes are valid"""
self.assertEqual(
cluster_response.kubernetesversionid,
version_id,
"Check KubernetesCluster version {}, {}".format(cluster_response.kubernetesversionid, version_id)
)
def verifyKubernetesClusterSize(self, cluster_response, size=1, control_nodes=1):
"""Check if Kubernetes cluster node sizes are valid"""
self.assertEqual(
cluster_response.size,
size,
"Check KubernetesCluster size {}, {}".format(cluster_response.size, size)
)
self.assertEqual(
cluster_response.controlnodes,
control_nodes,
"Check KubernetesCluster control nodes {}, {}".format(cluster_response.controlnodes, control_nodes)
)
def verifyKubernetesClusterUpgrade(self, cluster_response, version_id):
"""Check if Kubernetes cluster state and version are valid after upgrade"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
self.verifyKubernetesClusterVersion(cluster_response, version_id)
def verifyKubernetesClusterScale(self, cluster_response, size=1, control_nodes=1):
"""Check if Kubernetes cluster state and node sizes are valid after upgrade"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
self.verifyKubernetesClusterSize(cluster_response, size, control_nodes)
def verifyKubernetesClusterAutocale(self, cluster_response, minsize, maxsize):
"""Check if Kubernetes cluster state and node sizes are valid after upgrade"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
self.assertEqual(
cluster_response.minsize,
minsize,
"Check KubernetesCluster minsize {}, {}".format(cluster_response.minsize, minsize)
)
self.assertEqual(
cluster_response.maxsize,
maxsize,
"Check KubernetesCluster maxsize {}, {}".format(cluster_response.maxsize, maxsize)
)
def stopAndVerifyKubernetesCluster(self, cluster_id):
"""Stop Kubernetes cluster and check if it is really stopped"""
stop_response = self.stopKubernetesCluster(cluster_id)
self.assertEqual(
stop_response.success,
True,
"Check KubernetesCluster stop response {}, {}".format(stop_response.success, True)
)
db_cluster_state = self.dbclient.execute("select state from kubernetes_cluster where uuid = '%s';" % cluster_id)[0][0]
self.assertEqual(
db_cluster_state,
'Stopped',
"KubernetesCluster not stopped in DB, {}".format(db_cluster_state)
)
| [
"marvin.cloudstackAPI.listKubernetesClusters.listKubernetesClustersCmd",
"marvin.lib.base.StoragePool.list",
"marvin.lib.decoratorGenerators.skipTestIf",
"marvin.lib.utils.random_gen",
"marvin.cloudstackAPI.scaleKubernetesCluster.scaleKubernetesClusterCmd",
"marvin.lib.common.get_domain",
"marvin.clouds... | [((16124, 16182), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (16128, 16182), False, 'from nose.plugins.attrib import attr\n'), ((16188, 16224), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (16198, 16224), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((17621, 17679), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (17625, 17679), False, 'from nose.plugins.attrib import attr\n'), ((17685, 17721), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (17695, 17721), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((18726, 18784), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (18730, 18784), False, 'from nose.plugins.attrib import attr\n'), ((18790, 18826), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (18800, 18826), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((20362, 20420), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (20366, 20420), False, 'from nose.plugins.attrib import attr\n'), ((20426, 20462), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (20436, 20462), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((21662, 21720), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (21666, 21720), False, 'from nose.plugins.attrib import attr\n'), ((21726, 21762), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (21736, 21762), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((22925, 22983), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (22929, 22983), False, 'from nose.plugins.attrib import attr\n'), ((22989, 23025), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (22999, 23025), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((23708, 23766), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (23712, 23766), False, 'from nose.plugins.attrib import attr\n'), ((23772, 23808), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (23782, 23808), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((24382, 24440), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (24386, 24440), False, 'from nose.plugins.attrib import attr\n'), ((24446, 24482), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (24456, 24482), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((25536, 25594), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (25540, 25594), False, 'from nose.plugins.attrib import attr\n'), ((25600, 25636), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (25610, 25636), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((8826, 8931), 'marvin.sshClient.SshClient', 'SshClient', (["cls.mgtSvrDetails['mgtSvrIp']", '(22)', "cls.mgtSvrDetails['user']", "cls.mgtSvrDetails['passwd']"], {}), "(cls.mgtSvrDetails['mgtSvrIp'], 22, cls.mgtSvrDetails['user'], cls\n .mgtSvrDetails['passwd'])\n", (8835, 8931), False, 'from marvin.sshClient import SshClient\n'), ((10746, 10814), 'marvin.cloudstackAPI.listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd', 'listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd', ([], {}), '()\n', (10812, 10814), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((11138, 11202), 'marvin.cloudstackAPI.addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd', 'addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd', ([], {}), '()\n', (11200, 11202), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((12179, 12249), 'marvin.cloudstackAPI.deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd', 'deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd', ([], {}), '()\n', (12247, 12249), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((12511, 12561), 'marvin.cloudstackAPI.listKubernetesClusters.listKubernetesClustersCmd', 'listKubernetesClusters.listKubernetesClustersCmd', ([], {}), '()\n', (12559, 12561), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((13019, 13071), 'marvin.cloudstackAPI.deleteKubernetesCluster.deleteKubernetesClusterCmd', 'deleteKubernetesCluster.deleteKubernetesClusterCmd', ([], {}), '()\n', (13069, 13071), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((13333, 13381), 'marvin.cloudstackAPI.stopKubernetesCluster.stopKubernetesClusterCmd', 'stopKubernetesCluster.stopKubernetesClusterCmd', ([], {}), '()\n', (13379, 13381), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((18190, 18224), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (18200, 18224), False, 'import time, io, yaml\n'), ((24901, 24935), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (24911, 24935), False, 'import time, io, yaml\n'), ((26252, 26304), 'marvin.cloudstackAPI.createKubernetesCluster.createKubernetesClusterCmd', 'createKubernetesCluster.createKubernetesClusterCmd', ([], {}), '()\n', (26302, 26304), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((27216, 27266), 'marvin.cloudstackAPI.startKubernetesCluster.startKubernetesClusterCmd', 'startKubernetesCluster.startKubernetesClusterCmd', ([], {}), '()\n', (27264, 27266), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((27528, 27582), 'marvin.cloudstackAPI.upgradeKubernetesCluster.upgradeKubernetesClusterCmd', 'upgradeKubernetesCluster.upgradeKubernetesClusterCmd', ([], {}), '()\n', (27580, 27582), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((27909, 27959), 'marvin.cloudstackAPI.scaleKubernetesCluster.scaleKubernetesClusterCmd', 'scaleKubernetesCluster.scaleKubernetesClusterCmd', ([], {}), '()\n', (27957, 27959), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((28273, 28323), 'marvin.cloudstackAPI.scaleKubernetesCluster.scaleKubernetesClusterCmd', 'scaleKubernetesCluster.scaleKubernetesClusterCmd', ([], {}), '()\n', (28321, 28323), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((28743, 28801), 'marvin.cloudstackAPI.getKubernetesClusterConfig.getKubernetesClusterConfigCmd', 'getKubernetesClusterConfig.getKubernetesClusterConfigCmd', ([], {}), '()\n', (28799, 28801), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((29140, 29174), 'io.StringIO', 'io.StringIO', (['k8s_config.configdata'], {}), '(k8s_config.configdata)\n', (29151, 29174), False, 'import time, io, yaml\n'), ((29189, 29208), 'yaml.safe_load', 'yaml.safe_load', (['cfg'], {}), '(cfg)\n', (29203, 29208), False, 'import time, io, yaml\n'), ((29349, 29387), 'kubernetes.config.load_kube_config_from_dict', 'config.load_kube_config_from_dict', (['cfg'], {}), '(cfg)\n', (29382, 29387), False, 'from kubernetes import client, config\n'), ((29401, 29419), 'kubernetes.client.CoreV1Api', 'client.CoreV1Api', ([], {}), '()\n', (29417, 29419), False, 'from kubernetes import client, config\n'), ((7644, 7690), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (7661, 7690), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((8164, 8235), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""vmware.create.full.clone"""', 'value'], {}), "(cls.apiclient, 'vmware.create.full.clone', value)\n", (8185, 8235), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((8334, 8365), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['cls.apiclient'], {}), '(cls.apiclient)\n', (8350, 8365), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((9276, 9287), 'time.time', 'time.time', ([], {}), '()\n', (9285, 9287), False, 'import time, io, yaml\n'), ((9308, 9319), 'time.time', 'time.time', ([], {}), '()\n', (9317, 9319), False, 'import time, io, yaml\n'), ((9395, 9408), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (9405, 9408), False, 'import time, io, yaml\n'), ((9974, 9994), 'time.sleep', 'time.sleep', (['interval'], {}), '(interval)\n', (9984, 9994), False, 'import time, io, yaml\n'), ((11394, 11406), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (11404, 11406), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((15950, 15997), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (15967, 15997), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((29460, 29480), 'time.sleep', 'time.sleep', (['interval'], {}), '(interval)\n', (29470, 29480), False, 'import time, io, yaml\n'), ((32176, 32188), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (32186, 32188), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((3715, 3781), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""endpoint.url"""', 'endpoint_url'], {}), "(cls.apiclient, 'endpoint.url', endpoint_url)\n", (3736, 3781), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((4119, 4204), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""cloud.kubernetes.service.enabled"""', '"""true"""'], {}), "(cls.apiclient, 'cloud.kubernetes.service.enabled', 'true'\n )\n", (4140, 4204), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((5911, 5967), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', 'cks_offering_data'], {}), '(cls.apiclient, cks_offering_data)\n', (5933, 5967), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((6258, 6283), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (6268, 6283), False, 'from marvin.lib.common import get_zone, get_domain\n'), ((6314, 6392), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (6328, 6392), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((7393, 7478), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""cloud.kubernetes.service.enabled"""', '"""false"""'], {}), "(cls.apiclient, 'cloud.kubernetes.service.enabled',\n 'false')\n", (7414, 7478), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((8453, 8559), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient'], {'storageid': 'pool.id', 'name': '"""vmware.create.full.clone"""', 'value': 'value'}), "(cls.apiclient, storageid=pool.id, name=\n 'vmware.create.full.clone', value=value)\n", (8474, 8559), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((9625, 9667), 'marvin.cloudstackAPI.listInfrastructure.listInfrastructureCmd', 'listInfrastructure.listInfrastructureCmd', ([], {}), '()\n', (9665, 9667), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((3396, 3451), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""endpoint.url"""'}), "(cls.apiclient, name='endpoint.url')\n", (3415, 3451), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((3834, 3909), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""cloud.kubernetes.service.enabled"""'}), "(cls.apiclient, name='cloud.kubernetes.service.enabled')\n", (3853, 3909), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((5855, 5867), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (5865, 5867), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((14637, 14669), 'marvin.cloudstackAPI.deleteNetwork.deleteNetworkCmd', 'deleteNetwork.deleteNetworkCmd', ([], {}), '()\n', (14667, 14669), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n'), ((14390, 14438), 'marvin.cloudstackAPI.destroyVirtualMachine.destroyVirtualMachineCmd', 'destroyVirtualMachine.destroyVirtualMachineCmd', ([], {}), '()\n', (14436, 14438), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, getKubernetesClusterConfig, destroyVirtualMachine, deleteNetwork\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Tests of acquiring IPs in multiple subnets for isolated network or vpc
"""
from nose.plugins.attrib import attr
from marvin.cloudstackAPI import rebootRouter
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.lib.utils import (validateList,
get_host_credentials,
get_process_status,
cleanup_resources)
from marvin.lib.base import (Account,
Domain,
VirtualMachine,
ServiceOffering,
Zone,
Network,
NetworkOffering,
VPC,
VpcOffering,
PrivateGateway,
StaticNATRule,
NATRule,
PublicIPAddress,
PublicIpRange)
from marvin.lib.common import (get_domain,
get_zone,
get_free_vlan,
get_template,
list_hosts,
list_routers)
import logging
import random
class TestMultiplePublicIpSubnets(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(
TestMultiplePublicIpSubnets,
cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.zone = Zone(zone.__dict__)
cls.template = get_template(cls.apiclient, cls.zone.id)
cls._cleanup = []
cls.skip = False
if str(cls.zone.securitygroupsenabled) == "True":
cls.skip = True
return
cls.hypervisor = cls.testClient.getHypervisorInfo()
if cls.hypervisor.lower() not in ['kvm']:
cls.skip = True
return
cls.logger = logging.getLogger("TestMultiplePublicIpSubnets")
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
# Create small service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["small"]
)
cls._cleanup.append(cls.service_offering)
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(cls):
if cls.skip:
cls.skipTest("Test can be run only on advanced zone and KVM hypervisor")
cls.apiclient = cls.testClient.getApiClient()
cls.cleanup = []
return
def tearDown(cls):
try:
cleanup_resources(cls.apiclient, cls.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def get_router(self, router_id):
routers = list_routers(
self.apiclient,
id=router_id,
listall=True)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
return routers[0]
def get_routers(self, network_id):
routers = list_routers(
self.apiclient,
networkid=network_id,
listall=True)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
return routers
def get_vpc_routers(self, vpc_id):
routers = list_routers(
self.apiclient,
vpcid=vpc_id,
listall=True)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
return routers
def get_router_host(self, router):
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
hosts = list_hosts(
self.apiclient,
id=router.hostid)
self.assertEqual(
isinstance(hosts, list),
True,
"Check for list hosts response return valid data")
host = hosts[0]
if host.hypervisor.lower() not in "kvm":
return
host.user, host.password = get_host_credentials(self.config, host.ipaddress)
host.port=22
return host
def get_vpc_router_ips(self, router):
controlIp = None
sourcenatIp = None
tier1_Ip = None
tier2_Ip = None
for nic in router.nic:
if nic.traffictype == "Guest" and nic.ipaddress.startswith("10.250.1."):
tier1_Ip = nic.ipaddress
elif nic.traffictype == "Guest" and nic.ipaddress.startswith("10.250.2."):
tier2_Ip = nic.ipaddress
elif nic.traffictype == "Control":
controlIp = nic.ipaddress
elif sourcenatIp is None and nic.traffictype == "Public":
sourcenatIp = nic.ipaddress
return controlIp, sourcenatIp, tier1_Ip, tier2_Ip
def verify_router_publicnic_state(self, router, host, publicNics):
command = '/opt/cloud/bin/checkrouter.sh | cut -d ":" -f2 |tr -d " "'
self.logger.debug("Executing command '%s'" % command)
result = get_process_status(
host.ipaddress,
host.port,
host.user,
host.password,
router.linklocalip,
command)
self.assertTrue(len(result) > 0, "Cannot get router %s redundant state" % router.name)
redundant_state = result[0]
self.logger.debug("router %s redudnant state is %s" % (router.name, redundant_state))
if redundant_state == "FAULT":
self.logger.debug("Skip as redundant_state is %s" % redundant_state)
return
elif redundant_state == "PRIMARY":
command = 'ip link show |grep BROADCAST | egrep "%s" |grep "state DOWN" |wc -l' % publicNics
elif redundant_state == "BACKUP":
command = 'ip link show |grep BROADCAST | egrep "%s" |grep "state UP" |wc -l' % publicNics
result = get_process_status(
host.ipaddress,
host.port,
host.user,
host.password,
router.linklocalip,
command)
self.assertTrue(len(result) > 0 and result[0] == "0", "Expected result is 0 but actual result is %s" % result[0])
def verify_network_interfaces_in_router(self, router, host, expectedNics):
command = 'ip link show |grep BROADCAST | cut -d ":" -f2 |tr -d " "|tr "\n" ","'
self.logger.debug("Executing command '%s'" % command)
result = get_process_status(
host.ipaddress,
host.port,
host.user,
host.password,
router.linklocalip,
command)[0]
self.assertEqual(result, expectedNics, "Expected nics are %s but actual nics are %s" %(expectedNics, result))
def verify_ip_address_in_router(self, router, host, ipaddress, device, isExist=True):
command = 'ip addr show %s |grep "inet "|cut -d " " -f6 |cut -d "/" -f1 |grep -w %s' % (device,ipaddress)
self.logger.debug("Executing command '%s'" % command)
result = get_process_status(
host.ipaddress,
host.port,
host.user,
host.password,
router.linklocalip,
command)
self.assertEqual(len(result) > 0 and result[0] == ipaddress, isExist, "ip %s verification failed" % ipaddress)
def get_free_ipaddress(self, vlanId):
ipaddresses = PublicIPAddress.list(
self.apiclient,
vlanid=vlanId,
state='Free'
)
self.assertEqual(
isinstance(ipaddresses, list),
True,
"List ipaddresses should return a valid response for Free ipaddresses"
)
random.shuffle(ipaddresses)
return ipaddresses[0].ipaddress
@attr(tags=["advanced"], required_hardware="false")
def test_04_acquire_public_ips_in_vpc_with_redundant_vrs(self):
""" Acquire IPs in multiple subnets in vpc with redundant VRs
# Steps
# 1. get vpc offering with redundant VRs
# 2. create a vpc with the vpc offering
# verify the available nics in VR should be "eth0,eth1"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP
# 3. create a tier in the vpc, and create a vm in the tier.
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1
# 4. get a free public ip, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1
# 5. remove the port forwarding rule, and release the new ip
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1
# 6. create new public ip range 1
# 7. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1
# 8. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/2
# 9. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/2/3
# 10. release new ip 2
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/3
# 11. release new ip 1
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3
# 12. create a tier 2 in the vpc, and create a vm 2 in the tier2.
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2
# 13. create new public ip range 2
# 14. get a free ip 4 in new ip range 2, assign to network, and enable static nat to vm 2 in tier 2
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4
# 15. get a free ip 5 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/5
# 16. get a free ip 6 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/5/6
# 17. release new ip 5
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/6
# 18. release new ip 4
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 6
# 19. release new ip 3
# verify the available nics in VR should be "eth0,eth1,eth2,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth4 -> tier 2, eth5 -> new ip 6
# 20. restart tier1
# 22. restart VPC
# 23. Add private gateway
# verify the available nics in VR should be "eth0,eth1,eth2,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth4 -> tier 2, eth5 -> new ip 6, eth3-> private gateway
# 24. reboot router
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
# 25. restart VPC with cleanup
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
# 26. restart VPC with cleanup, makeredundant=true
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
"""
# Create new domain1
self.domain1 = Domain.create(
self.apiclient,
services=self.services["acl"]["domain1"],
parentdomainid=self.domain.id)
# Create account1
self.account1 = Account.create(
self.apiclient,
self.services["acl"]["accountD1"],
domainid=self.domain1.id
)
self.cleanup.append(self.account1)
self.cleanup.append(self.domain1)
# Create new domain1
self.domain1 = Domain.create(
self.apiclient,
services=self.services["acl"]["domain1"],
parentdomainid=self.domain.id)
# Create account1
self.account1 = Account.create(
self.apiclient,
self.services["acl"]["accountD1"],
domainid=self.domain1.id
)
self.cleanup.append(self.account1)
self.cleanup.append(self.domain1)
# 1. get vpc offering with redundant VRs
vpc_offering = VpcOffering.list(self.apiclient, name="Redundant VPC offering")
# 2. create a vpc with the vpc offering
self.services["vpc"]["cidr"] = "10.250.0.0/16"
self.vpc1 = VPC.create(
apiclient=self.apiclient,
services=self.services["vpc"],
vpcofferingid=vpc_offering[0].id,
zoneid=self.zone.id,
account=self.account1.name,
domainid=self.account1.domainid
)
# verify the available nics in VR should be "eth0,eth1"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
# 3. create a tier in the vpc, and create a vm in the tier.
vpc_tier_offerings = NetworkOffering.list(self.apiclient, name="DefaultIsolatedNetworkOfferingForVpcNetworks")
self.assertTrue(vpc_tier_offerings is not None and len(vpc_tier_offerings) > 0, "No VPC based network offering")
vpc_tier_offering = vpc_tier_offerings[0]
self.services["vpctier"] = {}
self.services["vpctier"]["name"] = "vpc-tier-1"
self.services["vpctier"]["displaytext"] = "vpc-tier-1"
vpc_tier_1 = Network.create(
apiclient=self.apiclient,
services=self.services["vpctier"],
accountid=self.account1.name,
domainid=self.domain1.id,
networkofferingid=vpc_tier_offering.id,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
gateway="10.250.1.1",
netmask="255.255.255.0"
)
try:
self.virtual_machine1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account1.name,
domainid=self.account1.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id,
networkids=vpc_tier_1.id
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_router_publicnic_state(router, host, "eth1")
# 4. get a free public ip, assign to network, and create port forwarding rules (ssh) to the vm
ipaddress = PublicIPAddress.create(
self.apiclient,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
)
nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine1,
self.services["natrule"],
ipaddressid=ipaddress.ipaddress.id,
networkid=vpc_tier_1.id
)
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP/new ip
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress.ipaddress.ipaddress, "eth1", True)
self.verify_router_publicnic_state(router, host, "eth1")
# 5. release the new ip
ipaddress.delete(self.apiclient)
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress.ipaddress.ipaddress, "eth1", False)
self.verify_router_publicnic_state(router, host, "eth1")
# 6. create new public ip range 1
self.services["publiciprange"]["zoneid"] = self.zone.id
self.services["publiciprange"]["forvirtualnetwork"] = "true"
random_subnet_number = random.randrange(10,50)
self.services["publiciprange"]["vlan"] = get_free_vlan(
self.apiclient,
self.zone.id)[1]
self.services["publiciprange"]["gateway"] = "172.16." + str(random_subnet_number) + ".1"
self.services["publiciprange"]["startip"] = "172.16." + str(random_subnet_number) + ".2"
self.services["publiciprange"]["endip"] = "172.16." + str(random_subnet_number) + ".10"
self.services["publiciprange"]["netmask"] = "255.255.255.0"
self.public_ip_range1 = PublicIpRange.create(
self.apiclient,
self.services["publiciprange"]
)
self.cleanup.append(self.public_ip_range1)
# 7. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
ip_address_1 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
ipaddress_1 = PublicIPAddress.create(
self.apiclient,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
ipaddress=ip_address_1
)
StaticNATRule.enable(
self.apiclient,
virtualmachineid=self.virtual_machine1.id,
ipaddressid=ipaddress_1.ipaddress.id,
networkid=vpc_tier_1.id
)
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3")
# 8. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 2,
ip_address_2 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
ipaddress_2 = PublicIPAddress.create(
self.apiclient,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
ipaddress=ip_address_2
)
nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine1,
self.services["natrule"],
ipaddressid=ipaddress_2.ipaddress.id,
networkid=vpc_tier_1.id
)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, ipaddress_2.ipaddress.ipaddress, "eth3", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3")
# 9. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 2, new ip 3
ip_address_3 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
ipaddress_3 = PublicIPAddress.create(
self.apiclient,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
ipaddress=ip_address_3
)
nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine1,
self.services["natrule"],
ipaddressid=ipaddress_3.ipaddress.id,
networkid=vpc_tier_1.id
)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, ipaddress_2.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3")
# 10. release new ip 2
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 3
ipaddress_2.delete(self.apiclient)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, ipaddress_2.ipaddress.ipaddress, "eth3", False)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3")
# 11. release new ip 1
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3
ipaddress_1.delete(self.apiclient)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", False)
self.verify_ip_address_in_router(router, host, ipaddress_2.ipaddress.ipaddress, "eth3", False)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3")
# 12. create a tier in the vpc, and create a vm in the tier.
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2
self.services["vpctier"]["name"] = "vpc-tier-2"
self.services["vpctier"]["displaytext"] = "vpc-tier-2"
vpc_tier_2 = Network.create(
apiclient=self.apiclient,
services=self.services["vpctier"],
accountid=self.account1.name,
domainid=self.domain1.id,
networkofferingid=vpc_tier_offering.id,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
gateway="10.250.2.1",
netmask="255.255.255.0"
)
try:
self.virtual_machine2 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account1.name,
domainid=self.account1.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id,
networkids=vpc_tier_2.id
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3")
# 13. create new public ip range 2
self.services["publiciprange"]["zoneid"] = self.zone.id
self.services["publiciprange"]["forvirtualnetwork"] = "true"
self.services["publiciprange"]["vlan"] = get_free_vlan(
self.apiclient,
self.zone.id)[1]
self.services["publiciprange"]["gateway"] = "172.16." + str(random_subnet_number + 1) + ".1"
self.services["publiciprange"]["startip"] = "172.16." + str(random_subnet_number + 1) + ".2"
self.services["publiciprange"]["endip"] = "172.16." + str(random_subnet_number + 1) + ".10"
self.services["publiciprange"]["netmask"] = "255.255.255.0"
self.public_ip_range2 = PublicIpRange.create(
self.apiclient,
self.services["publiciprange"]
)
self.cleanup.append(self.public_ip_range2)
# 14. get a free ip 4 in new ip range 2, assign to network, and enable static nat to vm 2 in tier 2
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4
ip_address_4 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
ipaddress_4 = PublicIPAddress.create(
self.apiclient,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
ipaddress=ip_address_4
)
StaticNATRule.enable(
self.apiclient,
virtualmachineid=self.virtual_machine2.id,
ipaddressid=ipaddress_4.ipaddress.id,
networkid=vpc_tier_2.id
)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")
# 15. get a free ip 5 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/5
ip_address_5 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
ipaddress_5 = PublicIPAddress.create(
self.apiclient,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
ipaddress=ip_address_5
)
nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine2,
self.services["natrule"],
ipaddressid=ipaddress_5.ipaddress.id,
networkid=vpc_tier_2.id
)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", True)
self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")
# 16. get a free ip 6 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/5/6
ip_address_6 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
ipaddress_6 = PublicIPAddress.create(
self.apiclient,
zoneid=self.zone.id,
vpcid=self.vpc1.id,
ipaddress=ip_address_6
)
nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine2,
self.services["natrule"],
ipaddressid=ipaddress_6.ipaddress.id,
networkid=vpc_tier_2.id
)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", True)
self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", True)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")
# 17. release new ip 5
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/6
ipaddress_5.delete(self.apiclient)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", True)
self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", False)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")
# 18. release new ip 4
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 6
ipaddress_4.delete(self.apiclient)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", False)
self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", False)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")
# 19. release new ip 3
# verify the available nics in VR should be "eth0,eth1,eth2,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth4 -> tier 2, eth5 -> new ip 6
ipaddress_3.delete(self.apiclient)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", False)
self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", False)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth5")
# 20. restart tier1
vpc_tier_1.restart(self.apiclient)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth5")
#21. restart tier2
vpc_tier_2.restart(self.apiclient)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth5")
# 22. restart VPC
self.vpc1.restart(self.apiclient)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth5")
# 23. Add private gateway
# verify the available nics in VR should be "eth0,eth1,eth2,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth4 -> tier 2, eth5 -> new ip 6, eth3-> private gateway
private_gateway_ip = "172.16." + str(random_subnet_number + 2) + ".1"
private_gateway = PrivateGateway.create(
self.apiclient,
gateway=private_gateway_ip,
ipaddress=private_gateway_ip,
netmask='255.255.255.0',
vlan=get_free_vlan(self.apiclient, self.zone.id)[1],
vpcid=self.vpc1.id
)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,eth3,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
self.verify_ip_address_in_router(router, host, private_gateway_ip, "eth3", True)
self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", False)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")
# 24. reboot router
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
routers = self.get_vpc_routers(self.vpc1.id)
if len(routers) > 0:
router = routers[0]
cmd = rebootRouter.rebootRouterCmd()
cmd.id = router.id
self.apiclient.rebootRouter(cmd)
router = self.get_router(router.id)
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth2", True)
self.verify_ip_address_in_router(router, host, private_gateway_ip, "eth3", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth2|eth3")
# 25. restart VPC with cleanup
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
self.vpc1.restart(self.apiclient, cleanup=True)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth2", True)
self.verify_ip_address_in_router(router, host, private_gateway_ip, "eth3", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth2|eth3")
# 26. restart VPC with cleanup, makeredundant=true
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
self.vpc1.restart(self.apiclient, cleanup=True, makeredundant=True)
routers = self.get_vpc_routers(self.vpc1.id)
for router in routers:
host = self.get_router_host(router)
self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth2", True)
self.verify_ip_address_in_router(router, host, private_gateway_ip, "eth3", True)
self.verify_ip_address_in_router(router, host, tier1_Ip, "eth4", True)
self.verify_ip_address_in_router(router, host, tier2_Ip, "eth5", True)
self.verify_router_publicnic_state(router, host, "eth1|eth2|eth3")
| [
"marvin.lib.utils.get_process_status",
"marvin.lib.base.Domain.create",
"marvin.cloudstackAPI.rebootRouter.rebootRouterCmd",
"marvin.lib.base.PublicIPAddress.create",
"marvin.lib.utils.get_host_credentials",
"marvin.lib.base.Zone",
"marvin.lib.common.get_free_vlan",
"marvin.lib.base.PublicIPAddress.li... | [((9746, 9796), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (9750, 9796), False, 'from nose.plugins.attrib import attr\n'), ((2504, 2523), 'marvin.lib.base.Zone', 'Zone', (['zone.__dict__'], {}), '(zone.__dict__)\n', (2508, 2523), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((2547, 2587), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id'], {}), '(cls.apiclient, cls.zone.id)\n', (2559, 2587), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n'), ((2925, 2973), 'logging.getLogger', 'logging.getLogger', (['"""TestMultiplePublicIpSubnets"""'], {}), "('TestMultiplePublicIpSubnets')\n", (2942, 2973), False, 'import logging\n'), ((3003, 3026), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (3024, 3026), False, 'import logging\n'), ((3183, 3208), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (3193, 3208), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n'), ((3281, 3367), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['small']"], {}), "(cls.apiclient, cls.services['service_offerings'][\n 'small'])\n", (3303, 3367), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((4177, 4233), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'id': 'router_id', 'listall': '(True)'}), '(self.apiclient, id=router_id, listall=True)\n', (4189, 4233), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n'), ((4633, 4697), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'networkid': 'network_id', 'listall': '(True)'}), '(self.apiclient, networkid=network_id, listall=True)\n', (4645, 4697), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n'), ((5094, 5150), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'vpcid': 'vpc_id', 'listall': '(True)'}), '(self.apiclient, vpcid=vpc_id, listall=True)\n', (5106, 5150), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n'), ((5688, 5732), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'router.hostid'}), '(self.apiclient, id=router.hostid)\n', (5698, 5732), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n'), ((6029, 6078), 'marvin.lib.utils.get_host_credentials', 'get_host_credentials', (['self.config', 'host.ipaddress'], {}), '(self.config, host.ipaddress)\n', (6049, 6078), False, 'from marvin.lib.utils import validateList, get_host_credentials, get_process_status, cleanup_resources\n'), ((7038, 7142), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', 'host.port', 'host.user', 'host.password', 'router.linklocalip', 'command'], {}), '(host.ipaddress, host.port, host.user, host.password,\n router.linklocalip, command)\n', (7056, 7142), False, 'from marvin.lib.utils import validateList, get_host_credentials, get_process_status, cleanup_resources\n'), ((7886, 7990), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', 'host.port', 'host.user', 'host.password', 'router.linklocalip', 'command'], {}), '(host.ipaddress, host.port, host.user, host.password,\n router.linklocalip, command)\n', (7904, 7990), False, 'from marvin.lib.utils import validateList, get_host_credentials, get_process_status, cleanup_resources\n'), ((9009, 9113), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', 'host.port', 'host.user', 'host.password', 'router.linklocalip', 'command'], {}), '(host.ipaddress, host.port, host.user, host.password,\n router.linklocalip, command)\n', (9027, 9113), False, 'from marvin.lib.utils import validateList, get_host_credentials, get_process_status, cleanup_resources\n'), ((9367, 9432), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.apiclient'], {'vlanid': 'vlanId', 'state': '"""Free"""'}), "(self.apiclient, vlanid=vlanId, state='Free')\n", (9387, 9432), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((9672, 9699), 'random.shuffle', 'random.shuffle', (['ipaddresses'], {}), '(ipaddresses)\n', (9686, 9699), False, 'import random\n'), ((15339, 15445), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.apiclient'], {'services': "self.services['acl']['domain1']", 'parentdomainid': 'self.domain.id'}), "(self.apiclient, services=self.services['acl']['domain1'],\n parentdomainid=self.domain.id)\n", (15352, 15445), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((15529, 15625), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['acl']['accountD1']"], {'domainid': 'self.domain1.id'}), "(self.apiclient, self.services['acl']['accountD1'], domainid=\n self.domain1.id)\n", (15543, 15625), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((15805, 15911), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.apiclient'], {'services': "self.services['acl']['domain1']", 'parentdomainid': 'self.domain.id'}), "(self.apiclient, services=self.services['acl']['domain1'],\n parentdomainid=self.domain.id)\n", (15818, 15911), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((15995, 16091), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['acl']['accountD1']"], {'domainid': 'self.domain1.id'}), "(self.apiclient, self.services['acl']['accountD1'], domainid=\n self.domain1.id)\n", (16009, 16091), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((16291, 16354), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Redundant VPC offering"""'}), "(self.apiclient, name='Redundant VPC offering')\n", (16307, 16354), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((16479, 16671), 'marvin.lib.base.VPC.create', 'VPC.create', ([], {'apiclient': 'self.apiclient', 'services': "self.services['vpc']", 'vpcofferingid': 'vpc_offering[0].id', 'zoneid': 'self.zone.id', 'account': 'self.account1.name', 'domainid': 'self.account1.domainid'}), "(apiclient=self.apiclient, services=self.services['vpc'],\n vpcofferingid=vpc_offering[0].id, zoneid=self.zone.id, account=self.\n account1.name, domainid=self.account1.domainid)\n", (16489, 16671), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((17459, 17553), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.apiclient'], {'name': '"""DefaultIsolatedNetworkOfferingForVpcNetworks"""'}), "(self.apiclient, name=\n 'DefaultIsolatedNetworkOfferingForVpcNetworks')\n", (17479, 17553), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((17898, 18170), 'marvin.lib.base.Network.create', 'Network.create', ([], {'apiclient': 'self.apiclient', 'services': "self.services['vpctier']", 'accountid': 'self.account1.name', 'domainid': 'self.domain1.id', 'networkofferingid': 'vpc_tier_offering.id', 'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id', 'gateway': '"""10.250.1.1"""', 'netmask': '"""255.255.255.0"""'}), "(apiclient=self.apiclient, services=self.services['vpctier'],\n accountid=self.account1.name, domainid=self.domain1.id,\n networkofferingid=vpc_tier_offering.id, zoneid=self.zone.id, vpcid=self\n .vpc1.id, gateway='10.250.1.1', netmask='255.255.255.0')\n", (17912, 18170), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((19729, 19808), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id'}), '(self.apiclient, zoneid=self.zone.id, vpcid=self.vpc1.id)\n', (19751, 19808), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((19875, 20020), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine1', "self.services['natrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'networkid': 'vpc_tier_1.id'}), "(self.apiclient, self.virtual_machine1, self.services[\n 'natrule'], ipaddressid=ipaddress.ipaddress.id, networkid=vpc_tier_1.id)\n", (19889, 20020), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((22134, 22158), 'random.randrange', 'random.randrange', (['(10)', '(50)'], {}), '(10, 50)\n', (22150, 22158), False, 'import random\n'), ((22669, 22737), 'marvin.lib.base.PublicIpRange.create', 'PublicIpRange.create', (['self.apiclient', "self.services['publiciprange']"], {}), "(self.apiclient, self.services['publiciprange'])\n", (22689, 22737), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((23036, 23144), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id', 'ipaddress': 'ip_address_1'}), '(self.apiclient, zoneid=self.zone.id, vpcid=self.vpc1\n .id, ipaddress=ip_address_1)\n', (23058, 23144), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((23207, 23354), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine1.id', 'ipaddressid': 'ipaddress_1.ipaddress.id', 'networkid': 'vpc_tier_1.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine1\n .id, ipaddressid=ipaddress_1.ipaddress.id, networkid=vpc_tier_1.id)\n', (23227, 23354), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((24716, 24824), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id', 'ipaddress': 'ip_address_2'}), '(self.apiclient, zoneid=self.zone.id, vpcid=self.vpc1\n .id, ipaddress=ip_address_2)\n', (24738, 24824), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((24898, 25045), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine1', "self.services['natrule']"], {'ipaddressid': 'ipaddress_2.ipaddress.id', 'networkid': 'vpc_tier_1.id'}), "(self.apiclient, self.virtual_machine1, self.services[\n 'natrule'], ipaddressid=ipaddress_2.ipaddress.id, networkid=vpc_tier_1.id)\n", (24912, 25045), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((26364, 26472), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id', 'ipaddress': 'ip_address_3'}), '(self.apiclient, zoneid=self.zone.id, vpcid=self.vpc1\n .id, ipaddress=ip_address_3)\n', (26386, 26472), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((26546, 26693), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine1', "self.services['natrule']"], {'ipaddressid': 'ipaddress_3.ipaddress.id', 'networkid': 'vpc_tier_1.id'}), "(self.apiclient, self.virtual_machine1, self.services[\n 'natrule'], ipaddressid=ipaddress_3.ipaddress.id, networkid=vpc_tier_1.id)\n", (26560, 26693), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((30530, 30802), 'marvin.lib.base.Network.create', 'Network.create', ([], {'apiclient': 'self.apiclient', 'services': "self.services['vpctier']", 'accountid': 'self.account1.name', 'domainid': 'self.domain1.id', 'networkofferingid': 'vpc_tier_offering.id', 'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id', 'gateway': '"""10.250.2.1"""', 'netmask': '"""255.255.255.0"""'}), "(apiclient=self.apiclient, services=self.services['vpctier'],\n accountid=self.account1.name, domainid=self.domain1.id,\n networkofferingid=vpc_tier_offering.id, zoneid=self.zone.id, vpcid=self\n .vpc1.id, gateway='10.250.2.1', netmask='255.255.255.0')\n", (30544, 30802), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((32995, 33063), 'marvin.lib.base.PublicIpRange.create', 'PublicIpRange.create', (['self.apiclient', "self.services['publiciprange']"], {}), "(self.apiclient, self.services['publiciprange'])\n", (33015, 33063), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((33569, 33677), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id', 'ipaddress': 'ip_address_4'}), '(self.apiclient, zoneid=self.zone.id, vpcid=self.vpc1\n .id, ipaddress=ip_address_4)\n', (33591, 33677), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((33740, 33887), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine2.id', 'ipaddressid': 'ipaddress_4.ipaddress.id', 'networkid': 'vpc_tier_2.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine2\n .id, ipaddressid=ipaddress_4.ipaddress.id, networkid=vpc_tier_2.id)\n', (33760, 33887), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((35322, 35430), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id', 'ipaddress': 'ip_address_5'}), '(self.apiclient, zoneid=self.zone.id, vpcid=self.vpc1\n .id, ipaddress=ip_address_5)\n', (35344, 35430), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((35504, 35651), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine2', "self.services['natrule']"], {'ipaddressid': 'ipaddress_5.ipaddress.id', 'networkid': 'vpc_tier_2.id'}), "(self.apiclient, self.virtual_machine2, self.services[\n 'natrule'], ipaddressid=ipaddress_5.ipaddress.id, networkid=vpc_tier_2.id)\n", (35518, 35651), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((37205, 37313), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'zoneid': 'self.zone.id', 'vpcid': 'self.vpc1.id', 'ipaddress': 'ip_address_6'}), '(self.apiclient, zoneid=self.zone.id, vpcid=self.vpc1\n .id, ipaddress=ip_address_6)\n', (37227, 37313), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((37387, 37534), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine2', "self.services['natrule']"], {'ipaddressid': 'ipaddress_6.ipaddress.id', 'networkid': 'vpc_tier_2.id'}), "(self.apiclient, self.virtual_machine2, self.services[\n 'natrule'], ipaddressid=ipaddress_6.ipaddress.id, networkid=vpc_tier_2.id)\n", (37401, 37534), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((3518, 3564), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (3535, 3564), False, 'from marvin.lib.utils import validateList, get_host_credentials, get_process_status, cleanup_resources\n'), ((3955, 4000), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls.cleanup'], {}), '(cls.apiclient, cls.cleanup)\n', (3972, 4000), False, 'from marvin.lib.utils import validateList, get_host_credentials, get_process_status, cleanup_resources\n'), ((8430, 8534), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', 'host.port', 'host.user', 'host.password', 'router.linklocalip', 'command'], {}), '(host.ipaddress, host.port, host.user, host.password,\n router.linklocalip, command)\n', (8448, 8534), False, 'from marvin.lib.utils import validateList, get_host_credentials, get_process_status, cleanup_resources\n'), ((18326, 18592), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account1.name', 'domainid': 'self.account1.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'networkids': 'vpc_tier_1.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account1.name, domainid=self.account1.domainid,\n serviceofferingid=self.service_offering.id, templateid=self.template.id,\n zoneid=self.zone.id, networkids=vpc_tier_1.id)\n", (18347, 18592), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((22207, 22250), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.apiclient', 'self.zone.id'], {}), '(self.apiclient, self.zone.id)\n', (22220, 22250), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n'), ((30958, 31224), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account1.name', 'domainid': 'self.account1.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'networkids': 'vpc_tier_2.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account1.name, domainid=self.account1.domainid,\n serviceofferingid=self.service_offering.id, templateid=self.template.id,\n zoneid=self.zone.id, networkids=vpc_tier_2.id)\n", (30979, 31224), False, 'from marvin.lib.base import Account, Domain, VirtualMachine, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering, PrivateGateway, StaticNATRule, NATRule, PublicIPAddress, PublicIpRange\n'), ((32521, 32564), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.apiclient', 'self.zone.id'], {}), '(self.apiclient, self.zone.id)\n', (32534, 32564), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n'), ((47731, 47761), 'marvin.cloudstackAPI.rebootRouter.rebootRouterCmd', 'rebootRouter.rebootRouterCmd', ([], {}), '()\n', (47759, 47761), False, 'from marvin.cloudstackAPI import rebootRouter\n'), ((46220, 46263), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.apiclient', 'self.zone.id'], {}), '(self.apiclient, self.zone.id)\n', (46233, 46263), False, 'from marvin.lib.common import get_domain, get_zone, get_free_vlan, get_template, list_hosts, list_routers\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.cloudstackAPI import (listZones,
deleteTemplate,
listConfigurations,
updateConfiguration)
from marvin.lib.utils import (cleanup_resources)
from marvin.lib.base import (Account,
Domain,
Network,
NetworkOffering,
Template,
ServiceOffering,
VirtualMachine,
Snapshot,
Volume)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
get_builtin_template_info)
# Import System modules
import time
import logging
class TestTemplateAccessAcrossDomains(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestTemplateAccessAcrossDomains, cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
cls.logger = logging.getLogger("TestRouterResources")
cls._cleanup = []
cls.unsupportedHypervisor = False
cls.hypervisor = cls.testClient.getHypervisorInfo()
if cls.hypervisor.lower() in ['lxc']:
cls.unsupportedHypervisor = True
return
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
# Create new domain1
cls.domain1 = Domain.create(
cls.apiclient,
services=cls.services["acl"]["domain1"],
parentdomainid=cls.domain.id)
cls._cleanup.append(cls.domain1)
# Create account1
cls.account1 = Account.create(
cls.apiclient,
cls.services["acl"]["accountD1"],
domainid=cls.domain1.id
)
cls._cleanup.append(cls.account1)
# Create new sub-domain
cls.sub_domain = Domain.create(
cls.apiclient,
services=cls.services["acl"]["domain11"],
parentdomainid=cls.domain1.id)
cls._cleanup.append(cls.sub_domain)
# Create account for sub-domain
cls.sub_account = Account.create(
cls.apiclient,
cls.services["acl"]["accountD11"],
domainid=cls.sub_domain.id
)
cls._cleanup.append(cls.sub_account)
# Create new domain2
cls.domain2 = Domain.create(
cls.apiclient,
services=cls.services["acl"]["domain2"],
parentdomainid=cls.domain.id)
cls._cleanup.append(cls.domain2)
# Create account2
cls.account2 = Account.create(
cls.apiclient,
cls.services["acl"]["accountD2"],
domainid=cls.domain2.id
)
cls._cleanup.append(cls.account2)
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offering"]
)
cls._cleanup.append(cls.service_offering)
if cls.hypervisor.lower() in ['kvm']:
# register template under ROOT domain
cls.root_template = Template.register(cls.apiclient,
cls.services["test_templates"]["kvm"],
zoneid=cls.zone.id,
domainid=cls.domain.id,
hypervisor=cls.hypervisor.lower())
cls.root_template.download(cls.apiclient)
cls._cleanup.append(cls.root_template)
cls.services["test_templates"]["kvm"]["name"] = cls.account1.name
cls.template1 = Template.register(cls.apiclient,
cls.services["test_templates"]["kvm"],
zoneid=cls.zone.id,
account=cls.account1.name,
domainid=cls.domain1.id,
hypervisor=cls.hypervisor.lower())
cls.template1.download(cls.apiclient)
cls._cleanup.append(cls.template1)
cls.services["test_templates"]["kvm"]["name"] = cls.sub_account.name
cls.sub_template = Template.register(cls.apiclient,
cls.services["test_templates"]["kvm"],
zoneid=cls.zone.id,
account=cls.sub_account.name,
domainid=cls.sub_domain.id,
hypervisor=cls.hypervisor.lower())
cls.sub_template.download(cls.apiclient)
cls._cleanup.append(cls.sub_template)
cls.template2 = Template.register(cls.apiclient,
cls.services["test_templates"]["kvm"],
zoneid=cls.zone.id,
account=cls.account2.name,
domainid=cls.domain2.id,
hypervisor=cls.hypervisor.lower())
cls.template2.download(cls.apiclient)
cls._cleanup.append(cls.template2)
else:
return
@classmethod
def tearDownClass(cls):
super(TestTemplateAccessAcrossDomains, cls).tearDownClass()
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.domain1_config = self.get_restrict_template_configuration(self.domain1.id)
self.domain2_config = self.get_restrict_template_configuration(self.domain2.id)
self.sub_domain_config = self.get_restrict_template_configuration(self.sub_domain.id)
self.cleanup = []
return
def tearDown(self):
try:
self.update_restrict_template_configuration(self.domain1.id, self.domain1_config)
self.update_restrict_template_configuration(self.domain2.id, self.domain2_config)
self.update_restrict_template_configuration(self.sub_domain.id, self.sub_domain_config)
super(TestTemplateAccessAcrossDomains, self).tearDown()
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_01_check_cross_domain_template_access(self):
"""
Verify that templates belonging to one domain should not be accessible
by other domains except for parent and ROOT domains
Steps:
1. Set global setting restrict.public.access.to.templates to true
2. Make sure template of domain2 should not be accessible by domain1
3. Make sure template of domain1 should not be accessible by domain2
4. Make sure parent and ROOT domain can still access above templates
:return:
"""
# Step 1
self.update_restrict_template_configuration(self.domain1.id, "true")
self.update_restrict_template_configuration(self.domain2.id, "true")
self.validate_uploaded_template(self.apiclient, self.template1.id)
# Step 2
self.validate_template_ownership(self.template2, self.domain1, self.domain2, False)
self.validate_uploaded_template(self.apiclient, self.template2.id)
# Step 3
self.validate_template_ownership(self.template1, self.domain2, self.domain1, False)
# Make sure root domain can still access all subdomain templates
# Step 4
self.validate_template_ownership(self.template1, self.domain, self.domain1, True)
self.validate_template_ownership(self.template2, self.domain, self.domain2, True)
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_02_create_template(self):
"""
Verify that templates belonging to one domain can be accessible
by other domains by default
Steps:
1. Set global setting restrict.public.access.to.templates to false (default behavior)
2. Make sure template of domain2 can be accessible by domain1
3. Make sure template of domain1 can be accessible by domain2
4. Make sure parent and ROOT domain can still access above templates
5. Deploy virtual machine in domain1 using template from domain2
6. Make sure that virtual machine can be deployed and is in running state
:return:
"""
# Step 1
self.update_restrict_template_configuration(self.domain1.id, "false")
self.update_restrict_template_configuration(self.domain2.id, "false")
# Step 2
self.validate_template_ownership(self.template2, self.domain1, self.domain2, True)
# Step 3
self.validate_template_ownership(self.template1, self.domain2, self.domain1, True)
# Step 4
# Make sure root domain can still access all subdomain templates
self.validate_template_ownership(self.template1, self.domain, self.domain1, True)
self.validate_template_ownership(self.template2, self.domain, self.domain2, True)
# Step 5
# Deploy new virtual machine using template
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=self.template2.id,
accountid=self.account1.name,
domainid=self.account1.domainid,
serviceofferingid=self.service_offering.id,
)
self.cleanup.append(self.virtual_machine)
self.debug("creating an instance with template ID: %s" % self.template2.id)
vm_response = VirtualMachine.list(self.apiclient,
id=self.virtual_machine.id,
account=self.account1.name,
domainid=self.account1.domainid)
self.assertEqual(
isinstance(vm_response, list),
True,
"Check for list VMs response after VM deployment"
)
# Verify VM response to check whether VM deployment was successful
self.assertNotEqual(
len(vm_response),
0,
"Check VMs available in List VMs response"
)
# Step 6
vm = vm_response[0]
self.assertEqual(
vm.state,
'Running',
"Check the state of VM created from Template"
)
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_03_check_subdomain_template_access(self):
"""
Verify that templates belonging to parent domain can be accessible
by sub domains
Steps:
1. Set global setting restrict.public.access.to.templates to true
2. Make sure template of ROOT domain can be accessible by domain1
3. Make sure template of ROOT domain can be accessible by domain2
"""
# Step 1
self.update_restrict_template_configuration(self.domain1.id, "true")
self.update_restrict_template_configuration(self.domain2.id, "true")
# Make sure child domains can still access parent domain templates
self.validate_uploaded_template(self.apiclient, self.root_template.id)
# Step 2
self.validate_template_ownership(self.root_template, self.domain1, self.domain, True)
# Step 3
self.validate_template_ownership(self.root_template, self.domain2, self.domain, True)
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_04_check_non_public_template_access(self):
"""
Verify that non public templates belonging to one domain
should not be accessible by other domains by default
Steps:
1. Set global setting restrict.public.access.to.templates to true
2. Change the permission level of "ispublic" of template to false
3. Make sure other domains should not be able to access the template
4. Make sure that ONLY ROOT domain can access the non public template
5. Set global setting restrict.public.access.to.templates to false
6. Repeat the steps 3 and 4
"""
# Step 1
self.update_restrict_template_configuration(self.domain1.id, "true")
self.update_restrict_template_configuration(self.domain2.id, "true")
# Step 2
self.template2.updatePermissions(self.apiclient,
ispublic="False")
list_template_response = self.list_templates('all', self.domain2)
self.assertEqual(
isinstance(list_template_response, list),
True,
"Check list response returns a valid list"
)
for template_response in list_template_response:
if template_response.id == self.template2.id:
break
self.assertIsNotNone(
template_response,
"Check template %s failed" % self.template2.id
)
self.assertEqual(
template_response.ispublic,
int(False),
"Check ispublic permission of template"
)
# Step 3
# Other domains should not access non public template
self.validate_template_ownership(self.template2, self.domain1, self.domain2, False)
# Step 4
# Only ROOT domain can access non public templates of child domain
self.validate_template_ownership(self.template2, self.domain, self.domain2, True)
# Step 5
self.update_restrict_template_configuration(self.domain1.id, "false")
self.update_restrict_template_configuration(self.domain2.id, "false")
# Step 6
self.validate_template_ownership(self.template2, self.domain1, self.domain2, False)
self.validate_template_ownership(self.template2, self.domain, self.domain2, True)
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_05_check_non_public_template_subdomain_access(self):
"""
Verify that non public templates belonging to ROOT domain
should not be accessible by sub domains by default
Steps:
1. Set global setting restrict.public.access.to.templates to true
2. Change the permission level of "ispublic" of template to false
3. Make sure other domains should not be able to access the template
4. Make sure that ONLY ROOT domain can access the non public template
5. Set global setting restrict.public.access.to.templates to false
6. Repeat the steps 3 and 4
"""
self.update_restrict_template_configuration(self.domain1.id, "true")
self.update_restrict_template_configuration(self.domain2.id, "true")
self.root_template.updatePermissions(self.apiclient,
ispublic="False")
list_template_response = self.list_templates('all', self.domain)
self.assertEqual(
isinstance(list_template_response, list),
True,
"Check list response returns a valid list"
)
for template_response in list_template_response:
if template_response.id == self.root_template.id:
break
self.assertIsNotNone(
template_response,
"Check template %s failed" % self.root_template.id
)
self.assertEqual(
template_response.ispublic,
int(False),
"Check ispublic permission of template"
)
# Other domains should not access non public template
self.validate_template_ownership(self.root_template, self.domain1, self.domain, False)
# Only ROOT domain can access non public templates of child domain
self.validate_template_ownership(self.root_template, self.domain2, self.domain, False)
self.update_restrict_template_configuration(self.domain1.id, "false")
self.update_restrict_template_configuration(self.domain2.id, "false")
self.validate_template_ownership(self.root_template, self.domain1, self.domain2, False)
self.validate_template_ownership(self.root_template, self.domain2, self.domain2, False)
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_06_check_sub_public_template_sub_domain_access(self):
"""
Verify that non root admin sub-domains can access parents templates
Steps:
1. Set global setting restrict.public.access.to.templates to true
2. Make sure that sub-domain account can access root templates
3. Make sure that sub-domain account can access parent templates
4. Make sure that ROOT domain can access the sub-domain template
5. Make sure that sibling domain cannot access templates of sub-domain
"""
self.root_template.updatePermissions(self.apiclient,
ispublic="True")
# Step 1
self.update_restrict_template_configuration(self.domain1.id, "true")
self.update_restrict_template_configuration(self.domain2.id, "true")
# Make sure child domains can still access parent domain templates
self.validate_uploaded_template(self.apiclient, self.sub_template.id)
# Step 2
self.validate_template_ownership(self.root_template, self.sub_domain, self.domain, True)
# Step 3
self.validate_template_ownership(self.template1, self.sub_domain, self.domain1, True)
# Step 4
self.validate_template_ownership(self.sub_template, self.domain, self.sub_domain, True)
# Step 5
self.validate_template_ownership(self.sub_template, self.domain2, self.sub_domain, False)
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_07_check_default_public_template_sub_domain_access(self):
"""
Verify that non root admin sub-domains can access parents templates by default
Steps:
1. Set global setting restrict.public.access.to.templates to false
2. Make sure that sub-domain account can access root templates
3. Make sure that sub-domain account can access parent templates
4. Make sure that ROOT domain can access the sub-domain template
5. Make sure that sibling domain cannot access templates of sub-domain
"""
# Step 1
self.update_restrict_template_configuration(self.domain1.id, "false")
self.update_restrict_template_configuration(self.domain2.id, "false")
# Make sure child domains can still access parent domain templates
self.validate_uploaded_template(self.apiclient, self.sub_template.id)
# Step 2
self.validate_template_ownership(self.root_template, self.sub_domain, self.domain, True)
# Step 3
self.validate_template_ownership(self.template1, self.sub_domain, self.domain1, True)
# Step 4
self.validate_template_ownership(self.sub_template, self.domain, self.sub_domain, True)
# Step 5
self.validate_template_ownership(self.sub_template, self.domain2, self.sub_domain, True)
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_08_check_non_public_template_sub_domain_access(self):
"""
Verify that non public templates belonging to one domain
should not be accessible by other domains by default except ROOT domain
Steps:
1. Set global setting restrict.public.access.to.templates to true
2. Change the permission level of "ispublic" of template1 to false
3. Make sure other domains should not be able to access the template
4. Make sure that ONLY ROOT domain can access the non public template
5. Set global setting restrict.public.access.to.templates to false
6. Repeat the steps 3 and 4
"""
# Step 1
self.update_restrict_template_configuration(self.domain1.id, "true")
self.update_restrict_template_configuration(self.domain2.id, "true")
# Step 2
self.template1.updatePermissions(self.apiclient,
ispublic="False")
list_template_response = self.list_templates('all', self.domain1)
for template_response in list_template_response:
if template_response.id == self.template1.id:
break
self.assertEqual(
isinstance(list_template_response, list),
True,
"Check list response returns a valid list"
)
self.assertIsNotNone(
template_response,
"Check template %s failed" % self.template1.id
)
self.assertEqual(
template_response.ispublic,
int(False),
"Check ispublic permission of template"
)
# Step 3
# Other domains should not access non public template
self.validate_template_ownership(self.template1, self.domain2, self.domain1, False)
# Even child domain should not access non public template
self.validate_template_ownership(self.template1, self.sub_domain, self.domain1, False)
# Step 4
# Only ROOT domain can access non public templates of child domain
self.validate_template_ownership(self.template1, self.domain, self.domain1, True)
# Step 5
self.update_restrict_template_configuration(self.domain1.id, "false")
self.update_restrict_template_configuration(self.domain2.id, "false")
# Step 6
self.validate_template_ownership(self.template1, self.domain2, self.domain1, False)
self.validate_template_ownership(self.template1, self.sub_domain, self.domain1, False)
self.validate_template_ownership(self.template1, self.domain, self.domain1, True)
def validate_uploaded_template(self, apiclient, template_id, retries=70, interval=5):
"""Check if template download will finish in 1 minute"""
while retries > -1:
time.sleep(interval)
template_response = Template.list(
apiclient,
id=template_id,
zoneid=self.zone.id,
templatefilter='self'
)
if isinstance(template_response, list):
template = template_response[0]
if not hasattr(template, 'status') or not template or not template.status:
retries = retries - 1
continue
if 'Failed' in template.status:
raise Exception(
"Failed to download template: status - %s" %
template.status)
elif template.status == 'Download Complete' and template.isready:
return
elif 'Downloaded' in template.status:
retries = retries - 1
continue
elif 'Installing' not in template.status:
if retries >= 0:
retries = retries - 1
continue
raise Exception(
"Error in downloading template: status - %s" %
template.status)
else:
retries = retries - 1
raise Exception("Template download failed exception.")
def list_templates(self, templatefilter, domain):
return Template.list(
self.apiclient,
templatefilter=templatefilter,
zoneid=self.zone.id,
domainid=domain.id)
def validate_template_ownership(self, template, owner, nonowner, include_cross_domain_template):
"""List the template belonging to domain which created it
Make sure that other domain can't access it.
"""
list_template_response = self.list_templates('all', owner)
if list_template_response is not None:
"""If global setting is false then public templates of any domain should
be accessible by any other domain
"""
if include_cross_domain_template:
for temp in list_template_response:
if template.name == temp.name:
return
raise Exception("Template %s belonging to domain %s should "
"be accessible by domain %s"
% (template.name, nonowner.name, owner.name))
else:
"""If global setting is true then public templates of any domain should not
be accessible by any other domain except for root domain
"""
for temp in list_template_response:
if template.name == temp.name:
raise Exception("Template %s belonging to domain %s should "
"not be accessible by domain %s"
% (template.name, nonowner.name, owner.name))
def get_restrict_template_configuration(self, domain_id):
"""
Function to get the global setting "restrict.public.access.to.templates" for domain
"""
list_configurations_cmd = listConfigurations.listConfigurationsCmd()
list_configurations_cmd.name = "restrict.public.template.access.to.domain"
list_configurations_cmd.scopename = "domain"
list_configurations_cmd.scopeid = domain_id
response = self.apiclient.listConfigurations(list_configurations_cmd)
return response[0].value
def update_restrict_template_configuration(self, domain_id, value):
"""
Function to update the global setting "restrict.public.access.to.templates" for domain
"""
update_configuration_cmd = updateConfiguration.updateConfigurationCmd()
update_configuration_cmd.name = "restrict.public.template.access.to.domain"
update_configuration_cmd.value = value
update_configuration_cmd.scopename = "domain"
update_configuration_cmd.scopeid = domain_id
return self.apiclient.updateConfiguration(update_configuration_cmd)
| [
"marvin.lib.base.Domain.create",
"marvin.cloudstackAPI.listConfigurations.listConfigurationsCmd",
"marvin.lib.base.Template.list",
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.ServiceO... | [((7684, 7749), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (7688, 7749), False, 'from nose.plugins.attrib import attr\n'), ((9130, 9195), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (9134, 9195), False, 'from nose.plugins.attrib import attr\n'), ((11893, 11958), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (11897, 11958), False, 'from nose.plugins.attrib import attr\n'), ((12930, 12995), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (12934, 12995), False, 'from nose.plugins.attrib import attr\n'), ((15331, 15396), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (15335, 15396), False, 'from nose.plugins.attrib import attr\n'), ((17668, 17733), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (17672, 17733), False, 'from nose.plugins.attrib import attr\n'), ((19198, 19263), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (19202, 19263), False, 'from nose.plugins.attrib import attr\n'), ((20622, 20687), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (20626, 20687), False, 'from nose.plugins.attrib import attr\n'), ((2140, 2165), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2150, 2165), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info\n'), ((2316, 2356), 'logging.getLogger', 'logging.getLogger', (['"""TestRouterResources"""'], {}), "('TestRouterResources')\n", (2333, 2356), False, 'import logging\n'), ((2711, 2814), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient'], {'services': "cls.services['acl']['domain1']", 'parentdomainid': 'cls.domain.id'}), "(cls.apiclient, services=cls.services['acl']['domain1'],\n parentdomainid=cls.domain.id)\n", (2724, 2814), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((2939, 3032), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['acl']['accountD1']"], {'domainid': 'cls.domain1.id'}), "(cls.apiclient, cls.services['acl']['accountD1'], domainid=\n cls.domain1.id)\n", (2953, 3032), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((3174, 3279), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient'], {'services': "cls.services['acl']['domain11']", 'parentdomainid': 'cls.domain1.id'}), "(cls.apiclient, services=cls.services['acl']['domain11'],\n parentdomainid=cls.domain1.id)\n", (3187, 3279), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((3424, 3521), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['acl']['accountD11']"], {'domainid': 'cls.sub_domain.id'}), "(cls.apiclient, cls.services['acl']['accountD11'], domainid=\n cls.sub_domain.id)\n", (3438, 3521), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((3660, 3763), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient'], {'services': "cls.services['acl']['domain2']", 'parentdomainid': 'cls.domain.id'}), "(cls.apiclient, services=cls.services['acl']['domain2'],\n parentdomainid=cls.domain.id)\n", (3673, 3763), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((3888, 3981), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['acl']['accountD2']"], {'domainid': 'cls.domain2.id'}), "(cls.apiclient, cls.services['acl']['accountD2'], domainid=\n cls.domain2.id)\n", (3902, 3981), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((4097, 4168), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offering']"], {}), "(cls.apiclient, cls.services['service_offering'])\n", (4119, 4168), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((10630, 10847), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'templateid': 'self.template2.id', 'accountid': 'self.account1.name', 'domainid': 'self.account1.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.apiclient, self.services['virtual_machine'],\n templateid=self.template2.id, accountid=self.account1.name, domainid=\n self.account1.domainid, serviceofferingid=self.service_offering.id)\n", (10651, 10847), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((11078, 11207), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id', 'account': 'self.account1.name', 'domainid': 'self.account1.domainid'}), '(self.apiclient, id=self.virtual_machine.id, account=\n self.account1.name, domainid=self.account1.domainid)\n', (11097, 11207), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((24925, 25031), 'marvin.lib.base.Template.list', 'Template.list', (['self.apiclient'], {'templatefilter': 'templatefilter', 'zoneid': 'self.zone.id', 'domainid': 'domain.id'}), '(self.apiclient, templatefilter=templatefilter, zoneid=self.\n zone.id, domainid=domain.id)\n', (24938, 25031), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((26771, 26813), 'marvin.cloudstackAPI.listConfigurations.listConfigurationsCmd', 'listConfigurations.listConfigurationsCmd', ([], {}), '()\n', (26811, 26813), False, 'from marvin.cloudstackAPI import listZones, deleteTemplate, listConfigurations, updateConfiguration\n'), ((27340, 27384), 'marvin.cloudstackAPI.updateConfiguration.updateConfigurationCmd', 'updateConfiguration.updateConfigurationCmd', ([], {}), '()\n', (27382, 27384), False, 'from marvin.cloudstackAPI import listZones, deleteTemplate, listConfigurations, updateConfiguration\n'), ((23501, 23521), 'time.sleep', 'time.sleep', (['interval'], {}), '(interval)\n', (23511, 23521), False, 'import time\n'), ((23554, 23642), 'marvin.lib.base.Template.list', 'Template.list', (['apiclient'], {'id': 'template_id', 'zoneid': 'self.zone.id', 'templatefilter': '"""self"""'}), "(apiclient, id=template_id, zoneid=self.zone.id,\n templatefilter='self')\n", (23567, 23642), False, 'from marvin.lib.base import Account, Domain, Network, NetworkOffering, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#Test from the Marvin - Testing in Python wiki
#All tests inherit from cloudstackTestCase
from marvin.cloudstackTestCase import cloudstackTestCase
#Import Integration Libraries
#base - contains all resources as entities and defines create, delete, list operations on them
from marvin.lib.base import Account, VirtualMachine, ServiceOffering
#utils - utility classes for common cleanup, external library wrappers etc
from marvin.lib.utils import cleanup_resources
#common - commonly used methods for all tests are listed here
from marvin.lib.common import get_zone, get_domain, get_template
from marvin.codes import FAILED
from nose.plugins.attrib import attr
class Services:
"""Test VM Life Cycle Services
"""
def __init__(self):
self.services = {
"disk_offering":{
"displaytext": "Small",
"name": "Small",
"disksize": 1
},
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended in create account to
# ensure unique username generated each time
"password": "password",
},
"vgpu260q": # Create a virtual machine instance with vgpu type as 260q
{
"displayname": "testserver",
"username": "root", # VM creds for SSH
"password": "password",
"ssh_port": 22,
"hypervisor": 'XenServer',
"privateport": 22,
"publicport": 22,
"protocol": 'TCP',
},
"vgpu140q": # Create a virtual machine instance with vgpu type as 140q
{
"displayname": "testserver",
"username": "root",
"password": "password",
"ssh_port": 22,
"hypervisor": 'XenServer',
"privateport": 22,
"publicport": 22,
"protocol": 'TCP',
},
"service_offerings":
{
"vgpu260qwin":
{
"name": "Windows Instance with vGPU260Q",
"displaytext": "Windows Instance with vGPU260Q",
"cpunumber": 2,
"cpuspeed": 1600, # in MHz
"memory": 3072, # In MBs
},
"vgpu140qwin":
{
# Small service offering ID to for change VM
# service offering from medium to small
"name": "Windows Instance with vGPU140Q",
"displaytext": "Windows Instance with vGPU140Q",
"cpunumber": 2,
"cpuspeed": 1600,
"memory": 3072,
}
},
"diskdevice": ['/dev/vdc', '/dev/vdb', '/dev/hdb', '/dev/hdc', '/dev/xvdd', '/dev/cdrom', '/dev/sr0', '/dev/cdrom1' ],
# Disk device where ISO is attached to instance
"mount_dir": "/mnt/tmp",
"sleep": 60,
"timeout": 10,
#Migrate VM to hostid
"ostype": 'Windows 7 (32-bit)',
# CentOS 5.3 (64-bit)
}
class TestDeployvGPUenabledVM(cloudstackTestCase):
"""Test deploy a vGPU enabled VM into a user account
"""
def setUp(self):
self.services = Services().services
self.apiclient = self.testClient.getApiClient()
# Get Zone, Domain and Default Built-in template
self.domain = get_domain(self.apiclient)
self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
self.services["mode"] = self.zone.networktype
# Before running this test, register a windows template with ostype as 'Windows 7 (32-bit)'
self.services["ostype"] = 'Windows 7 (32-bit)'
self.template = get_template(self.apiclient, self.zone.id, self.services["ostype"])
if self.template == FAILED:
assert False, "get_template() failed to return template with description %s" % self.services["ostype"]
#create a user account
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id
)
self.services["vgpu260q"]["zoneid"] = self.zone.id
self.services["vgpu260q"]["template"] = self.template.id
self.services["vgpu140q"]["zoneid"] = self.zone.id
self.services["vgpu140q"]["template"] = self.template.id
#create a service offering
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["vgpu260qwin"],
serviceofferingdetails={'pciDevice': 'VGPU'}
)
#build cleanup list
self.cleanup = [
self.service_offering,
self.account
]
@attr(tags = ['advanced', 'simulator', 'basic', 'vgpu', 'provisioning'])
def test_deploy_vgpu_enabled_vm(self):
"""Test Deploy Virtual Machine
# Validate the following:
# 1. Virtual Machine is accessible via SSH
# 2. Virtual Machine is vGPU enabled (via SSH)
# 3. listVirtualMachines returns accurate information
"""
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["vgpu260q"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
mode=self.services['mode']
)
list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s"\
% self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vms, list),
True,
"List VM response was not a valid list"
)
self.assertNotEqual(
len(list_vms),
0,
"List VM response was empty"
)
vm = list_vms[0]
self.assertEqual(
vm.id,
self.virtual_machine.id,
"Virtual Machine ids do not match"
)
self.assertEqual(
vm.name,
self.virtual_machine.name,
"Virtual Machine names do not match"
)
self.assertEqual(
vm.state,
"Running",
msg="VM is not in Running state"
)
list_hosts = list_hosts(
self.apiclient,
id=vm.hostid
)
hostip = list_hosts[0].ipaddress
try:
sshClient = SshClient(host=hostip, port=22, user='root',passwd=self.services["host_password"])
res = sshClient.execute("xe vgpu-list vm-name-label=%s params=type-uuid %s" % (
vm.instancename
))
self.debug("SSH result: %s" % res)
except Exception as e:
self.fail("SSH Access failed for %s: %s" % \
(hostip, e)
)
result = str(res)
self.assertEqual(
result.count("type-uuid"),
1,
"VM is vGPU enabled."
)
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
self.debug("Warning! Exception in tearDown: %s" % e) | [
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.common.get_template",
"marvin.lib.utils.cleanup_resources"
] | [((6057, 6126), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'simulator', 'basic', 'vgpu', 'provisioning']"}), "(tags=['advanced', 'simulator', 'basic', 'vgpu', 'provisioning'])\n", (6061, 6126), False, 'from nose.plugins.attrib import attr\n'), ((4675, 4701), 'marvin.lib.common.get_domain', 'get_domain', (['self.apiclient'], {}), '(self.apiclient)\n', (4685, 4701), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((5015, 5082), 'marvin.lib.common.get_template', 'get_template', (['self.apiclient', 'self.zone.id', "self.services['ostype']"], {}), "(self.apiclient, self.zone.id, self.services['ostype'])\n", (5027, 5082), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((5289, 5375), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (5303, 5375), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering\n'), ((5734, 5874), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['vgpu260qwin']"], {'serviceofferingdetails': "{'pciDevice': 'VGPU'}"}), "(self.apiclient, self.services['service_offerings'][\n 'vgpu260qwin'], serviceofferingdetails={'pciDevice': 'VGPU'})\n", (5756, 5874), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering\n'), ((6457, 6664), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['vgpu260q']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'mode': "self.services['mode']"}), "(self.apiclient, self.services['vgpu260q'], accountid=\n self.account.name, domainid=self.account.domainid, serviceofferingid=\n self.service_offering.id, mode=self.services['mode'])\n", (6478, 6664), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering\n'), ((6757, 6820), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (6776, 6820), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering\n'), ((8548, 8595), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (8565, 8595), False, 'from marvin.lib.utils import cleanup_resources\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" tests for supporting multiple NIC's in advanced zone with security groups in cloudstack 192.168.3.11
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.sshClient import SshClient
from marvin.lib.utils import (validateList,
cleanup_resources,
get_host_credentials,
get_process_status,
execute_command_in_host,
random_gen)
from marvin.lib.base import (PhysicalNetwork,
Account,
Host,
TrafficType,
Domain,
Network,
NetworkOffering,
VirtualMachine,
ServiceOffering,
Zone,
NIC,
SecurityGroup)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
list_virtual_machines,
list_routers,
list_hosts,
get_free_vlan)
from marvin.codes import (PASS, FAILED)
import logging
import random
import time
class TestMulipleNicSupport(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(
TestMulipleNicSupport,
cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.testdata = cls.testClient.getParsedTestDataConfig()
cls.services = cls.testClient.getParsedTestDataConfig()
zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.zone = Zone(zone.__dict__)
cls._cleanup = []
cls.skip = False
if str(cls.zone.securitygroupsenabled) != "True":
cls.skip = True
return
cls.logger = logging.getLogger("TestMulipleNicSupport")
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
# Get Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.services['mode'] = cls.zone.networktype
cls.template = get_template(cls.apiclient, cls.zone.id, hypervisor="KVM")
if cls.template == FAILED:
cls.skip = True
return
# Create new domain, account, network and VM
cls.user_domain = Domain.create(
cls.apiclient,
services=cls.testdata["acl"]["domain2"],
parentdomainid=cls.domain.id)
# Create account
cls.account1 = Account.create(
cls.apiclient,
cls.testdata["acl"]["accountD2"],
admin=True,
domainid=cls.user_domain.id
)
# Create small service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offerings"]["small"]
)
cls._cleanup.append(cls.service_offering)
cls.services["network"]["zoneid"] = cls.zone.id
cls.network_offering = NetworkOffering.create(
cls.apiclient,
cls.services["network_offering"],
)
# Enable Network offering
cls.network_offering.update(cls.apiclient, state='Enabled')
cls._cleanup.append(cls.network_offering)
cls.testdata["virtual_machine"]["zoneid"] = cls.zone.id
cls.testdata["virtual_machine"]["template"] = cls.template.id
if cls.zone.securitygroupsenabled:
# Enable networking for reaching to VM thorugh SSH
security_group = SecurityGroup.create(
cls.apiclient,
cls.testdata["security_group"],
account=cls.account1.name,
domainid=cls.account1.domainid
)
# Authorize Security group to SSH to VM
ingress_rule = security_group.authorize(
cls.apiclient,
cls.testdata["ingress_rule"],
account=cls.account1.name,
domainid=cls.account1.domainid
)
# Authorize Security group to SSH to VM
ingress_rule2 = security_group.authorize(
cls.apiclient,
cls.testdata["ingress_rule_ICMP"],
account=cls.account1.name,
domainid=cls.account1.domainid
)
cls.testdata["shared_network_offering_sg"]["specifyVlan"] = 'True'
cls.testdata["shared_network_offering_sg"]["specifyIpRanges"] = 'True'
cls.shared_network_offering = NetworkOffering.create(
cls.apiclient,
cls.testdata["shared_network_offering_sg"],
conservemode=False
)
NetworkOffering.update(
cls.shared_network_offering,
cls.apiclient,
id=cls.shared_network_offering.id,
state="enabled"
)
physical_network, vlan = get_free_vlan(cls.apiclient, cls.zone.id)
cls.testdata["shared_network_sg"]["physicalnetworkid"] = physical_network.id
random_subnet_number = random.randrange(90, 99)
cls.testdata["shared_network_sg"]["name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["displaytext"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(random_subnet_number) + ".240"
cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(random_subnet_number) + ".250"
cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(random_subnet_number) + ".254"
cls.network1 = Network.create(
cls.apiclient,
cls.testdata["shared_network_sg"],
networkofferingid=cls.shared_network_offering.id,
zoneid=cls.zone.id,
accountid=cls.account1.name,
domainid=cls.account1.domainid
)
random_subnet_number = random.randrange(100, 110)
cls.testdata["shared_network_sg"]["name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["displaytext"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(random_subnet_number) + ".240"
cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(random_subnet_number) + ".250"
cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(random_subnet_number) + ".254"
cls.network2 = Network.create(
cls.apiclient,
cls.testdata["shared_network_sg"],
networkofferingid=cls.shared_network_offering.id,
zoneid=cls.zone.id,
accountid=cls.account1.name,
domainid=cls.account1.domainid
)
random_subnet_number = random.randrange(111, 120)
cls.testdata["shared_network_sg"]["name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["displaytext"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(random_subnet_number)
cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(random_subnet_number) + ".240"
cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(random_subnet_number) + ".250"
cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(random_subnet_number) + ".254"
cls.network3 = Network.create(
cls.apiclient,
cls.testdata["shared_network_sg"],
networkofferingid=cls.shared_network_offering.id,
zoneid=cls.zone.id,
accountid=cls.account1.name,
domainid=cls.account1.domainid
)
try:
cls.virtual_machine1 = VirtualMachine.create(
cls.apiclient,
cls.testdata["virtual_machine"],
accountid=cls.account1.name,
domainid=cls.account1.domainid,
serviceofferingid=cls.service_offering.id,
templateid=cls.template.id,
securitygroupids=[security_group.id],
networkids=cls.network1.id
)
for nic in cls.virtual_machine1.nic:
if nic.isdefault:
cls.virtual_machine1.ssh_ip = nic.ipaddress
cls.virtual_machine1.default_network_id = nic.networkid
break
except Exception as e:
cls.fail("Exception while deploying virtual machine: %s" % {e})
try:
cls.virtual_machine2 = VirtualMachine.create(
cls.apiclient,
cls.testdata["virtual_machine"],
accountid=cls.account1.name,
domainid=cls.account1.domainid,
serviceofferingid=cls.service_offering.id,
templateid=cls.template.id,
securitygroupids=[security_group.id],
networkids=[str(cls.network1.id), str(cls.network2.id)]
)
for nic in cls.virtual_machine2.nic:
if nic.isdefault:
cls.virtual_machine2.ssh_ip = nic.ipaddress
cls.virtual_machine2.default_network_id = nic.networkid
break
except Exception as e:
cls.fail("Exception while deploying virtual machine: %s" % {e})
cls._cleanup.append(cls.virtual_machine1)
cls._cleanup.append(cls.virtual_machine2)
cls._cleanup.append(cls.network1)
cls._cleanup.append(cls.network2)
cls._cleanup.append(cls.network3)
cls._cleanup.append(cls.shared_network_offering)
if cls.zone.securitygroupsenabled:
cls._cleanup.append(security_group)
cls._cleanup.append(cls.account1)
cls._cleanup.append(cls.user_domain)
@classmethod
def tearDownClass(self):
try:
cleanup_resources(self.apiclient, self._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
if self.skip:
self.skipTest("Test can be run only on advanced zone and KVM hypervisor")
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def verify_network_rules(self, vm_id):
virtual_machine = VirtualMachine.list(
self.apiclient,
id=vm_id
)
vm = virtual_machine[0]
hosts = list_hosts(
self.apiclient,
id=vm.hostid
)
host = hosts[0]
if host.hypervisor.lower() not in "kvm":
return
host.user, host.password = get_host_credentials(self.config, host.ipaddress)
for nic in vm.nic:
secips = ""
if len(nic.secondaryip) > 0:
for secip in nic.secondaryip:
secips += secip.ipaddress + ";"
command="/usr/share/cloudstack-common/scripts/vm/network/security_group.py verify_network_rules --vmname %s --vmip %s --vmmac %s --nicsecips '%s'" % (vm.instancename, nic.ipaddress, nic.macaddress, secips)
self.logger.debug("Executing command '%s' in host %s" % (command, host.ipaddress))
result=execute_command_in_host(host.ipaddress, 22,
host.user,
host.password,
command)
if len(result) > 0:
self.fail("The iptables/ebtables rules for nic %s on vm %s on host %s are not correct" %(nic.ipaddress, vm.instancename, host.name))
@attr(tags=["advancedsg"], required_hardware="false")
def test_01_create_vm_with_multiple_nics(self):
"""Create Vm with multiple NIC's
Steps:
# 1. Create more than 1 isolated or shared network
# 2. Create a vm and select more than 1 network while deploying
# 3. Vm is deployed successfully with 1 nic from each network
# 4. All the vm's should be pingable
:return:
"""
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine2.id
)
self.assertEqual(
len(virtual_machine), 1,
"Virtual Machine create with 2 NIC's failed")
nicIdInVm = virtual_machine[0].nic[0]
self.assertIsNotNone(nicIdInVm, "NIC 1 not found in Virtual Machine")
nicIdInVm = virtual_machine[0].nic[1]
self.assertIsNotNone(nicIdInVm, "NIC 2 not found in Virtual Machine")
self.verify_network_rules(self.virtual_machine2.id)
@attr(tags=["advancedsg"], required_hardware="false")
def test_02_add_nic_to_vm(self):
"""Create VM with single NIC and then add additional NIC
Steps:
# 1. Create a VM by selecting one default NIC
# 2. Create few more isolated or shared networks
# 3. Add extra NIC's to the vm from the newly created networks
# 4. The deployed VM should have extra nic's added in the above
# step without any fail
# 5. The IP's of the extra NIC's should be pingable
:return:
"""
self.virtual_machine1.add_nic(self.apiclient, self.network2.id)
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine1.id
)
nicIdInVm = virtual_machine[0].nic[1]
self.assertIsNotNone(nicIdInVm, "Second NIC not found")
self.verify_network_rules(self.virtual_machine1.id)
@attr(tags=["advancedsg"], required_hardware="false")
def test_03_add_ip_to_default_nic(self):
""" Add secondary IP's to the VM
Steps:
# 1. Create a VM with more than 1 NIC
# 2) Navigate to Instances->NIC->Edit Secondary IP's
# ->Aquire new Secondary IP"
# 3) Add as many secondary Ip as possible to the VM
# 4) Configure the secondary IP's by referring to "Configure
# the secondary IP's" in the "Action Item" section
:return:
"""
ipaddress = NIC.addIp(
self.apiclient,
id=self.virtual_machine2.nic[0].id
)
self.assertIsNotNone(
ipaddress,
"Unable to add secondary IP to the default NIC")
self.verify_network_rules(self.virtual_machine2.id)
@attr(tags=["advancedsg"], required_hardware="false")
def test_04_add_ip_to_remaining_nics(self):
""" Add secondary IP's to remaining NIC's
Steps:
# 1) Create a VM with more than 1 NIC
# 2)Navigate to Instances-NIC's->Edit Secondary IP's
# ->Acquire new Secondary IP
# 3) Add secondary IP to all the NIC's of the VM
# 4) Confiugre the secondary IP's by referring to "Configure the
# secondary IP's" in the "Action Item" section
:return:
"""
self.virtual_machine1.add_nic(self.apiclient, self.network3.id)
vms = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine1.id
)
self.assertIsNotNone(
vms[0].nic[2],
"Third NIC is not added successfully to the VM")
vms1_nic1_id = vms[0].nic[1]['id']
vms1_nic2_id = vms[0].nic[2]['id']
ipaddress21 = NIC.addIp(
self.apiclient,
id=vms1_nic1_id
)
ipaddress22 = NIC.addIp(
self.apiclient,
id=vms1_nic1_id
)
self.assertIsNotNone(
ipaddress21,
"Unable to add first secondary IP to the second nic")
self.assertIsNotNone(
ipaddress22,
"Unable to add second secondary IP to second NIC")
ipaddress31 = NIC.addIp(
self.apiclient,
id=vms1_nic2_id
)
ipaddress32 = NIC.addIp(
self.apiclient,
id=vms1_nic2_id
)
self.assertIsNotNone(
ipaddress31,
"Unable to add first secondary IP to third NIC")
self.assertIsNotNone(
ipaddress32,
"Unable to add second secondary IP to third NIC")
self.verify_network_rules(self.virtual_machine1.id)
@attr(tags=["advancedsg"], required_hardware="false")
def test_05_stop_start_vm_with_multiple_nic(self):
""" Stop and Start a VM with Multple NIC
Steps:
# 1) Create a Vm with multiple NIC's
# 2) Configure secondary IP's on the VM
# 3) Try to stop/start the VM
# 4) Ping the IP's of the vm
# 5) Remove Secondary IP from one of the NIC
:return:
"""
ipaddress1 = NIC.addIp(
self.apiclient,
id=self.virtual_machine2.nic[0].id
)
ipaddress2 = NIC.addIp(
self.apiclient,
id=self.virtual_machine2.nic[1].id
)
# Stop the VM with multiple NIC's
self.virtual_machine2.stop(self.apiclient)
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine2.id
)
self.assertEqual(
virtual_machine[0]['state'], 'Stopped',
"Could not stop the VM with multiple NIC's")
if virtual_machine[0]['state'] == 'Stopped':
# If stopped then try to start the VM
self.virtual_machine2.start(self.apiclient)
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine2.id
)
self.assertEqual(
virtual_machine[0]['state'], 'Running',
"Could not start the VM with multiple NIC's")
self.verify_network_rules(self.virtual_machine2.id)
@attr(tags=["advancedsg"], required_hardware="false")
def test_06_migrate_vm_with_multiple_nic(self):
""" Migrate a VM with Multple NIC
Steps:
# 1) Create a Vm with multiple NIC's
# 2) Configure secondary IP's on the VM
# 3) Try to stop/start the VM
# 4) Ping the IP's of the vm
:return:
"""
# Skipping adding Secondary IP to NIC since its already
# done in the previous test cases
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine1.id
)
old_host_id = virtual_machine[0]['hostid']
try:
hosts = Host.list(
self.apiclient,
virtualmachineid=self.virtual_machine1.id,
listall=True)
self.assertEqual(
validateList(hosts)[0],
PASS,
"hosts list validation failed")
# Get a host which is not already assigned to VM
for host in hosts:
if host.id == old_host_id:
continue
else:
host_id = host.id
break
self.virtual_machine1.migrate(self.apiclient, host_id)
except Exception as e:
self.fail("Exception occured: %s" % e)
# List the vm again
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine1.id)
new_host_id = virtual_machine[0]['hostid']
self.assertNotEqual(
old_host_id, new_host_id,
"Migration of VM to new host failed"
)
self.verify_network_rules(self.virtual_machine1.id)
@attr(tags=["advancedsg"], required_hardware="false")
def test_07_remove_secondary_ip_from_nic(self):
""" Remove secondary IP from any NIC
Steps:
# 1) Navigate to Instances
# 2) Select any vm
# 3) NIC's ->Edit secondary IP's->Release IP
# 4) The secondary IP should be successfully removed
"""
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine2.id)
# Check which NIC is having secondary IP
secondary_ips = virtual_machine[0].nic[1].secondaryip
for secondary_ip in secondary_ips:
NIC.removeIp(self.apiclient, ipaddressid=secondary_ip['id'])
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine2.id
)
self.assertFalse(
virtual_machine[0].nic[1].secondaryip,
'Failed to remove secondary IP')
self.verify_network_rules(self.virtual_machine2.id)
@attr(tags=["advancedsg"], required_hardware="false")
def test_08_remove_nic_from_vm(self):
""" Remove NIC from VM
Steps:
# 1) Navigate to Instances->select any vm->NIC's->NIC 2
# ->Click on "X" button to remove the second NIC
# 2) Remove other NIC's as well from the VM
# 3) All the NIC's should be successfully removed from the VM
:return:
"""
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine2.id)
for nic in virtual_machine[0].nic:
if nic.isdefault:
continue
self.virtual_machine2.remove_nic(self.apiclient, nic.id)
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine2.id)
self.assertEqual(
len(virtual_machine[0].nic), 1,
"Failed to remove all the nics from the virtual machine")
self.verify_network_rules(self.virtual_machine2.id)
@attr(tags=["advancedsg"], required_hardware="false")
def test_09_reboot_vm_with_multiple_nic(self):
""" Reboot a VM with Multple NIC
Steps:
# 1) Create a Vm with multiple NIC's
# 2) Configure secondary IP's on the VM
# 3) Try to reboot the VM
# 4) Ping the IP's of the vm
:return:
"""
# Skipping adding Secondary IP to NIC since its already
# done in the previous test cases
virtual_machine = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine1.id
)
try:
self.virtual_machine1.reboot(self.apiclient)
except Exception as e:
self.fail("Exception occured: %s" % e)
self.verify_network_rules(self.virtual_machine1.id)
| [
"marvin.lib.base.Domain.create",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.common.get_free_vlan",
"marvin.lib.base.Zone",
"marvin.lib.utils.get_host_credentials",
"marvin.lib.base.Host.list",
"marvin.lib.utils.execute_command_in_host",
"marvin.lib.base.Network.create",
"marvin.lib.common.ge... | [((13203, 13255), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (13207, 13255), False, 'from nose.plugins.attrib import attr\n'), ((14225, 14277), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (14229, 14277), False, 'from nose.plugins.attrib import attr\n'), ((15178, 15230), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (15182, 15230), False, 'from nose.plugins.attrib import attr\n'), ((16020, 16072), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (16024, 16072), False, 'from nose.plugins.attrib import attr\n'), ((17907, 17959), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (17911, 17959), False, 'from nose.plugins.attrib import attr\n'), ((19462, 19514), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (19466, 19514), False, 'from nose.plugins.attrib import attr\n'), ((21225, 21277), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (21229, 21277), False, 'from nose.plugins.attrib import attr\n'), ((22259, 22311), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (22263, 22311), False, 'from nose.plugins.attrib import attr\n'), ((23301, 23353), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advancedsg'], required_hardware='false')\n", (23305, 23353), False, 'from nose.plugins.attrib import attr\n'), ((2712, 2731), 'marvin.lib.base.Zone', 'Zone', (['zone.__dict__'], {}), '(zone.__dict__)\n', (2716, 2731), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((2911, 2953), 'logging.getLogger', 'logging.getLogger', (['"""TestMulipleNicSupport"""'], {}), "('TestMulipleNicSupport')\n", (2928, 2953), False, 'import logging\n'), ((2983, 3006), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (3004, 3006), False, 'import logging\n'), ((3157, 3182), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (3167, 3182), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_virtual_machines, list_routers, list_hosts, get_free_vlan\n'), ((3259, 3317), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id'], {'hypervisor': '"""KVM"""'}), "(cls.apiclient, cls.zone.id, hypervisor='KVM')\n", (3271, 3317), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_virtual_machines, list_routers, list_hosts, get_free_vlan\n'), ((3480, 3583), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient'], {'services': "cls.testdata['acl']['domain2']", 'parentdomainid': 'cls.domain.id'}), "(cls.apiclient, services=cls.testdata['acl']['domain2'],\n parentdomainid=cls.domain.id)\n", (3493, 3583), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((3666, 3774), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.testdata['acl']['accountD2']"], {'admin': '(True)', 'domainid': 'cls.user_domain.id'}), "(cls.apiclient, cls.testdata['acl']['accountD2'], admin=True,\n domainid=cls.user_domain.id)\n", (3680, 3774), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((3901, 3987), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offerings']['small']"], {}), "(cls.apiclient, cls.testdata['service_offerings'][\n 'small'])\n", (3923, 3987), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((4155, 4226), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['network_offering']"], {}), "(cls.apiclient, cls.services['network_offering'])\n", (4177, 4226), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((5663, 5769), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.testdata['shared_network_offering_sg']"], {'conservemode': '(False)'}), "(cls.apiclient, cls.testdata[\n 'shared_network_offering_sg'], conservemode=False)\n", (5685, 5769), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((5820, 5943), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['cls.shared_network_offering', 'cls.apiclient'], {'id': 'cls.shared_network_offering.id', 'state': '"""enabled"""'}), "(cls.shared_network_offering, cls.apiclient, id=cls.\n shared_network_offering.id, state='enabled')\n", (5842, 5943), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((6031, 6072), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['cls.apiclient', 'cls.zone.id'], {}), '(cls.apiclient, cls.zone.id)\n', (6044, 6072), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_virtual_machines, list_routers, list_hosts, get_free_vlan\n'), ((6190, 6214), 'random.randrange', 'random.randrange', (['(90)', '(99)'], {}), '(90, 99)\n', (6206, 6214), False, 'import random\n'), ((6862, 7065), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.testdata['shared_network_sg']"], {'networkofferingid': 'cls.shared_network_offering.id', 'zoneid': 'cls.zone.id', 'accountid': 'cls.account1.name', 'domainid': 'cls.account1.domainid'}), "(cls.apiclient, cls.testdata['shared_network_sg'],\n networkofferingid=cls.shared_network_offering.id, zoneid=cls.zone.id,\n accountid=cls.account1.name, domainid=cls.account1.domainid)\n", (6876, 7065), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((7172, 7198), 'random.randrange', 'random.randrange', (['(100)', '(110)'], {}), '(100, 110)\n', (7188, 7198), False, 'import random\n'), ((7846, 8049), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.testdata['shared_network_sg']"], {'networkofferingid': 'cls.shared_network_offering.id', 'zoneid': 'cls.zone.id', 'accountid': 'cls.account1.name', 'domainid': 'cls.account1.domainid'}), "(cls.apiclient, cls.testdata['shared_network_sg'],\n networkofferingid=cls.shared_network_offering.id, zoneid=cls.zone.id,\n accountid=cls.account1.name, domainid=cls.account1.domainid)\n", (7860, 8049), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((8156, 8182), 'random.randrange', 'random.randrange', (['(111)', '(120)'], {}), '(111, 120)\n', (8172, 8182), False, 'import random\n'), ((8830, 9033), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.testdata['shared_network_sg']"], {'networkofferingid': 'cls.shared_network_offering.id', 'zoneid': 'cls.zone.id', 'accountid': 'cls.account1.name', 'domainid': 'cls.account1.domainid'}), "(cls.apiclient, cls.testdata['shared_network_sg'],\n networkofferingid=cls.shared_network_offering.id, zoneid=cls.zone.id,\n accountid=cls.account1.name, domainid=cls.account1.domainid)\n", (8844, 9033), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((11985, 12030), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'vm_id'}), '(self.apiclient, id=vm_id)\n', (12004, 12030), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((12115, 12155), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'vm.hostid'}), '(self.apiclient, id=vm.hostid)\n', (12125, 12155), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_virtual_machines, list_routers, list_hosts, get_free_vlan\n'), ((12317, 12366), 'marvin.lib.utils.get_host_credentials', 'get_host_credentials', (['self.config', 'host.ipaddress'], {}), '(self.config, host.ipaddress)\n', (12337, 12366), False, 'from marvin.lib.utils import validateList, cleanup_resources, get_host_credentials, get_process_status, execute_command_in_host, random_gen\n'), ((13686, 13750), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine2.id'}), '(self.apiclient, id=self.virtual_machine2.id)\n', (13705, 13750), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((14901, 14965), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine1.id'}), '(self.apiclient, id=self.virtual_machine1.id)\n', (14920, 14965), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((15742, 15803), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'self.virtual_machine2.nic[0].id'}), '(self.apiclient, id=self.virtual_machine2.nic[0].id)\n', (15751, 15803), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((16661, 16725), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine1.id'}), '(self.apiclient, id=self.virtual_machine1.id)\n', (16680, 16725), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((16989, 17031), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'vms1_nic1_id'}), '(self.apiclient, id=vms1_nic1_id)\n', (16998, 17031), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((17089, 17131), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'vms1_nic1_id'}), '(self.apiclient, id=vms1_nic1_id)\n', (17098, 17131), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((17429, 17471), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'vms1_nic2_id'}), '(self.apiclient, id=vms1_nic2_id)\n', (17438, 17471), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((17529, 17571), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'vms1_nic2_id'}), '(self.apiclient, id=vms1_nic2_id)\n', (17538, 17571), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((18375, 18436), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'self.virtual_machine2.nic[0].id'}), '(self.apiclient, id=self.virtual_machine2.nic[0].id)\n', (18384, 18436), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((18493, 18554), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'self.virtual_machine2.nic[1].id'}), '(self.apiclient, id=self.virtual_machine2.nic[1].id)\n', (18502, 18554), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((18709, 18773), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine2.id'}), '(self.apiclient, id=self.virtual_machine2.id)\n', (18728, 18773), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((19975, 20039), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine1.id'}), '(self.apiclient, id=self.virtual_machine1.id)\n', (19994, 20039), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((20889, 20953), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine1.id'}), '(self.apiclient, id=self.virtual_machine1.id)\n', (20908, 20953), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((21624, 21688), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine2.id'}), '(self.apiclient, id=self.virtual_machine2.id)\n', (21643, 21688), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((21970, 22034), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine2.id'}), '(self.apiclient, id=self.virtual_machine2.id)\n', (21989, 22034), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((22718, 22782), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine2.id'}), '(self.apiclient, id=self.virtual_machine2.id)\n', (22737, 22782), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((23003, 23067), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine2.id'}), '(self.apiclient, id=self.virtual_machine2.id)\n', (23022, 23067), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((23808, 23872), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine1.id'}), '(self.apiclient, id=self.virtual_machine1.id)\n', (23827, 23872), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((4685, 4816), 'marvin.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['cls.apiclient', "cls.testdata['security_group']"], {'account': 'cls.account1.name', 'domainid': 'cls.account1.domainid'}), "(cls.apiclient, cls.testdata['security_group'], account\n =cls.account1.name, domainid=cls.account1.domainid)\n", (4705, 4816), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((9157, 9436), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.testdata['virtual_machine']"], {'accountid': 'cls.account1.name', 'domainid': 'cls.account1.domainid', 'serviceofferingid': 'cls.service_offering.id', 'templateid': 'cls.template.id', 'securitygroupids': '[security_group.id]', 'networkids': 'cls.network1.id'}), "(cls.apiclient, cls.testdata['virtual_machine'],\n accountid=cls.account1.name, domainid=cls.account1.domainid,\n serviceofferingid=cls.service_offering.id, templateid=cls.template.id,\n securitygroupids=[security_group.id], networkids=cls.network1.id)\n", (9178, 9436), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((11301, 11349), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self._cleanup'], {}), '(self.apiclient, self._cleanup)\n', (11318, 11349), False, 'from marvin.lib.utils import validateList, cleanup_resources, get_host_credentials, get_process_status, execute_command_in_host, random_gen\n'), ((11747, 11794), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (11764, 11794), False, 'from marvin.lib.utils import validateList, cleanup_resources, get_host_credentials, get_process_status, execute_command_in_host, random_gen\n'), ((12889, 12967), 'marvin.lib.utils.execute_command_in_host', 'execute_command_in_host', (['host.ipaddress', '(22)', 'host.user', 'host.password', 'command'], {}), '(host.ipaddress, 22, host.user, host.password, command)\n', (12912, 12967), False, 'from marvin.lib.utils import validateList, cleanup_resources, get_host_credentials, get_process_status, execute_command_in_host, random_gen\n'), ((19136, 19200), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine2.id'}), '(self.apiclient, id=self.virtual_machine2.id)\n', (19155, 19200), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((20161, 20247), 'marvin.lib.base.Host.list', 'Host.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine1.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=self.virtual_machine1.id,\n listall=True)\n', (20170, 20247), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((21882, 21942), 'marvin.lib.base.NIC.removeIp', 'NIC.removeIp', (['self.apiclient'], {'ipaddressid': "secondary_ip['id']"}), "(self.apiclient, ipaddressid=secondary_ip['id'])\n", (21894, 21942), False, 'from marvin.lib.base import PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup\n'), ((20339, 20358), 'marvin.lib.utils.validateList', 'validateList', (['hosts'], {}), '(hosts)\n', (20351, 20358), False, 'from marvin.lib.utils import validateList, cleanup_resources, get_host_credentials, get_process_status, execute_command_in_host, random_gen\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from marvin.codes import FAILED
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster
from marvin.lib.common import get_zone, get_domain, get_template
from marvin.lib.utils import cleanup_resources
from nose.plugins.attrib import attr
class TestDeployVmWithVariedPlanners(cloudstackTestCase):
""" Test to create services offerings for deployment planners
- firstfit, userdispersing
"""
@classmethod
def setUpClass(cls):
testClient = super(TestDeployVmWithVariedPlanners, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.services["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["template"] = cls.template.id
cls.services["zoneid"] = cls.zone.id
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id
)
cls.hosts = Host.list(cls.apiclient, type='Routing')
cls.clusters = Cluster.list(cls.apiclient)
cls.cleanup = [
cls.account
]
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_deployvm_firstfit(self):
"""Test to deploy vm with a first fit offering
"""
#FIXME: How do we know that first fit actually happened?
self.service_offering_firstfit = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["tiny"],
deploymentplanner='FirstFitPlanner'
)
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_firstfit.id,
templateid=self.template.id
)
list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s"\
% self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vms, list),
True,
"List VM response was not a valid list"
)
self.assertNotEqual(
len(list_vms),
0,
"List VM response was empty"
)
vm = list_vms[0]
self.assertEqual(
vm.state,
"Running",
msg="VM is not in Running state"
)
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_deployvm_userdispersing(self):
"""Test deploy VMs using user dispersion planner
"""
self.service_offering_userdispersing = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["tiny"],
deploymentplanner='UserDispersingPlanner'
)
self.virtual_machine_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_userdispersing.id,
templateid=self.template.id
)
self.virtual_machine_2 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_userdispersing.id,
templateid=self.template.id
)
list_vm_1 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_1.id)
list_vm_2 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_2.id)
self.assertEqual(
isinstance(list_vm_1, list),
True,
"List VM response was not a valid list"
)
self.assertEqual(
isinstance(list_vm_2, list),
True,
"List VM response was not a valid list"
)
vm1 = list_vm_1[0]
vm2 = list_vm_2[0]
self.assertEqual(
vm1.state,
"Running",
msg="VM is not in Running state"
)
self.assertEqual(
vm2.state,
"Running",
msg="VM is not in Running state"
)
vm1clusterid = filter(lambda c: c.id == vm1.hostid, self.hosts)[0].clusterid
vm2clusterid = filter(lambda c: c.id == vm2.hostid, self.hosts)[0].clusterid
if vm1clusterid == vm2clusterid:
self.debug("VMs (%s, %s) meant to be dispersed are deployed in the same cluster %s" % (
vm1.id, vm2.id, vm1clusterid))
@attr(tags=["advanced", "basic", "sg"], required_hardware="false")
def test_deployvm_userconcentrated(self):
"""Test deploy VMs using user concentrated planner
"""
self.service_offering_userconcentrated = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["tiny"],
deploymentplanner='UserConcentratedPodPlanner'
)
self.virtual_machine_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_userconcentrated.id,
templateid=self.template.id
)
self.virtual_machine_2 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_userconcentrated.id,
templateid=self.template.id
)
list_vm_1 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_1.id)
list_vm_2 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_2.id)
self.assertEqual(
isinstance(list_vm_1, list),
True,
"List VM response was not a valid list"
)
self.assertEqual(
isinstance(list_vm_2, list),
True,
"List VM response was not a valid list"
)
vm1 = list_vm_1[0]
vm2 = list_vm_2[0]
self.assertEqual(
vm1.state,
"Running",
msg="VM is not in Running state"
)
self.assertEqual(
vm2.state,
"Running",
msg="VM is not in Running state"
)
vm1clusterid = filter(lambda c: c.id == vm1.hostid, self.hosts)[0].clusterid
vm2clusterid = filter(lambda c: c.id == vm2.hostid, self.hosts)[0].clusterid
vm1podid = filter(lambda p: p.id == vm1clusterid, self.clusters)[0].podid
vm2podid = filter(lambda p: p.id == vm2clusterid, self.clusters)[0].podid
self.assertEqual(
vm1podid,
vm2podid,
msg="VMs (%s, %s) meant to be pod concentrated are deployed on different pods (%s, %s)" % (vm1.id, vm2.id, vm1clusterid, vm2clusterid)
)
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
| [
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.Host.list",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.common.get_template",
"marvin.lib.utils.cleanup_resources",
"marvin.lib... | [((2436, 2501), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (2440, 2501), False, 'from nose.plugins.attrib import attr\n'), ((3894, 3959), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (3898, 3959), False, 'from nose.plugins.attrib import attr\n'), ((6166, 6231), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'sg'], required_hardware='false')\n", (6170, 6231), False, 'from nose.plugins.attrib import attr\n'), ((1568, 1593), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (1578, 1593), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((1690, 1754), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (1702, 1754), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((2135, 2213), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (2149, 2213), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((2280, 2320), 'marvin.lib.base.Host.list', 'Host.list', (['cls.apiclient'], {'type': '"""Routing"""'}), "(cls.apiclient, type='Routing')\n", (2289, 2320), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((2344, 2371), 'marvin.lib.base.Cluster.list', 'Cluster.list', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2356, 2371), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((2713, 2837), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['tiny']"], {'deploymentplanner': '"""FirstFitPlanner"""'}), "(self.apiclient, self.services['service_offerings'][\n 'tiny'], deploymentplanner='FirstFitPlanner')\n", (2735, 2837), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((2911, 3159), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_firstfit.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_firstfit.id,\n templateid=self.template.id)\n", (2932, 3159), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((3261, 3324), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (3280, 3324), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((4120, 4250), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['tiny']"], {'deploymentplanner': '"""UserDispersingPlanner"""'}), "(self.apiclient, self.services['service_offerings'][\n 'tiny'], deploymentplanner='UserDispersingPlanner')\n", (4142, 4250), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((4326, 4580), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_userdispersing.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_userdispersing.id,\n templateid=self.template.id)\n", (4347, 4580), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((4695, 4949), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_userdispersing.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_userdispersing.id,\n templateid=self.template.id)\n", (4716, 4949), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((5052, 5117), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine_1.id'}), '(self.apiclient, id=self.virtual_machine_1.id)\n', (5071, 5117), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((5138, 5203), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine_2.id'}), '(self.apiclient, id=self.virtual_machine_2.id)\n', (5157, 5203), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((6398, 6533), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['tiny']"], {'deploymentplanner': '"""UserConcentratedPodPlanner"""'}), "(self.apiclient, self.services['service_offerings'][\n 'tiny'], deploymentplanner='UserConcentratedPodPlanner')\n", (6420, 6533), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((6609, 6865), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_userconcentrated.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_userconcentrated.id,\n templateid=self.template.id)\n", (6630, 6865), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((6980, 7236), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_userconcentrated.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_userconcentrated.id,\n templateid=self.template.id)\n", (7001, 7236), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((7339, 7404), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine_1.id'}), '(self.apiclient, id=self.virtual_machine_1.id)\n', (7358, 7404), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((7425, 7490), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine_2.id'}), '(self.apiclient, id=self.virtual_machine_2.id)\n', (7444, 7490), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((8726, 8771), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls.cleanup'], {}), '(cls.apiclient, cls.cleanup)\n', (8743, 8771), False, 'from marvin.lib.utils import cleanup_resources\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.lib.utils import cleanup_resources
from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume
from marvin.codes import FAILED
from marvin.lib.common import list_disk_offering, get_zone, get_suitable_test_template, get_domain
from marvin.cloudstackAPI import listStoragePools, updateStorageCapabilities
from nose.plugins.attrib import attr
class TestDiskProvisioningTypes(cloudstackTestCase):
def setUp(self):
if self.testClient.getHypervisorInfo().lower() != "vmware":
raise unittest.SkipTest("VMWare tests only valid on VMWare hypervisor")
self.services = self.testClient.getParsedTestDataConfig()
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
self.domain = get_domain(self.apiclient)
self.services['mode'] = self.zone.networktype
self.hypervisor = self.hypervisor = self.testClient.getHypervisorInfo()
template = get_suitable_test_template(
self.apiclient,
self.zone.id,
self.services["ostype"],
self.hypervisor
)
if template == FAILED:
assert False, "get_suitable_test_template() failed to return template with description %s" % self.services["ostype"]
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id
)
self.services["small"]["zoneid"] = self.zone.id
self.services["small"]["template"] = template.id
self.services["iso1"]["zoneid"] = self.zone.id
iso = Iso.create(
self.apiclient,
self.services["iso1"],
account=self.account.name,
domainid=self.account.domainid
)
self.cleanup = [
self.account
]
def tearDown(self):
cleanup_resources(self.apiclient, self.cleanup)
@attr(tags=["advanced", "basic", "eip", "sg", "advancedns", "smoke"], required_hardware="false")
def test_01_vm_with_thin_disk_offering(self):
self.runner("thin")
@attr(tags=["advanced", "basic", "eip", "sg", "advancedns", "smoke"], required_hardware="false")
def test_02_vm_with_fat_disk_offering(self):
self.runner("fat")
@attr(tags=["advanced", "basic", "eip", "sg", "advancedns", "smoke"], required_hardware="false")
def test_03_vm_with_sparse_disk_offering(self):
self.runner("sparse")
@attr(tags=["advanced", "basic", "eip", "sg", "advancedns", "smoke"], required_hardware="false")
def test_05_update_cmd(self):
cmd = listStoragePools.listStoragePoolsCmd()
storagePools = self.apiclient.listStoragePools(cmd)
for pool in storagePools:
if pool.type == 'NetworkFilesystem':
cmd = updateStorageCapabilities.updateStorageCapabilitiesCmd()
cmd.id = pool.id
response = self.apiclient.updateStorageCapabilities(cmd)
acceleration = getattr(response[0].storagecapabilities, "HARDWARE_ACCELERATION")
self.assertNotEqual(
acceleration,
None,
"Check Updated storage pool capabilities"
)
def runner(self, provisioning_type):
self.services["disk_offering"]['provisioningtype'] = provisioning_type
self.services["small"]['size'] = "1"
disk_offering = DiskOffering.create(
self.apiclient,
self.services["disk_offering"],
custom=True,
)
self.cleanup.append(disk_offering)
self.debug("Created Disk offering with ID: %s" % disk_offering.id)
self.services["service_offerings"]["small"]["provisioningtype"] = provisioning_type
small_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["small"]
)
self.cleanup.append(small_offering)
self.debug("Created service offering with ID: %s" % small_offering.id)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["small"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=small_offering.id,
diskofferingid=disk_offering.id,
mode=self.services["mode"]
)
self.debug("Created virtual machine with ID: %s" % virtual_machine.id)
volumes = Volume.list(self.apiclient, virtualMachineId=virtual_machine.id, listAll='true')
for volume in volumes:
if volume["type"] == "DATADISK":
VirtualMachine.detach_volume(virtual_machine, self.apiclient, volume)
currentVolume = Volume({})
currentVolume.id = volume.id
Volume.resize(currentVolume, self.apiclient, size='2')
VirtualMachine.attach_volume(virtual_machine, self.apiclient, volume)
| [
"marvin.cloudstackAPI.updateStorageCapabilities.updateStorageCapabilitiesCmd",
"marvin.lib.base.VirtualMachine.attach_volume",
"marvin.lib.base.Volume",
"marvin.cloudstackTestCase.unittest.SkipTest",
"marvin.cloudstackAPI.listStoragePools.listStoragePoolsCmd",
"marvin.lib.base.Account.create",
"marvin.l... | [((2906, 3005), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke'],\n required_hardware='false')\n", (2910, 3005), False, 'from nose.plugins.attrib import attr\n'), ((3086, 3185), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke'],\n required_hardware='false')\n", (3090, 3185), False, 'from nose.plugins.attrib import attr\n'), ((3264, 3363), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke'],\n required_hardware='false')\n", (3268, 3363), False, 'from nose.plugins.attrib import attr\n'), ((3448, 3547), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke'],\n required_hardware='false')\n", (3452, 3547), False, 'from nose.plugins.attrib import attr\n'), ((1754, 1780), 'marvin.lib.common.get_domain', 'get_domain', (['self.apiclient'], {}), '(self.apiclient)\n', (1764, 1780), False, 'from marvin.lib.common import list_disk_offering, get_zone, get_suitable_test_template, get_domain\n'), ((1935, 2038), 'marvin.lib.common.get_suitable_test_template', 'get_suitable_test_template', (['self.apiclient', 'self.zone.id', "self.services['ostype']", 'self.hypervisor'], {}), "(self.apiclient, self.zone.id, self.services[\n 'ostype'], self.hypervisor)\n", (1961, 2038), False, 'from marvin.lib.common import list_disk_offering, get_zone, get_suitable_test_template, get_domain\n'), ((2277, 2363), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (2291, 2363), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((2590, 2702), 'marvin.lib.base.Iso.create', 'Iso.create', (['self.apiclient', "self.services['iso1']"], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['iso1'], account=self.account.name,\n domainid=self.account.domainid)\n", (2600, 2702), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((2852, 2899), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (2869, 2899), False, 'from marvin.lib.utils import cleanup_resources\n'), ((3592, 3630), 'marvin.cloudstackAPI.listStoragePools.listStoragePoolsCmd', 'listStoragePools.listStoragePoolsCmd', ([], {}), '()\n', (3628, 3630), False, 'from marvin.cloudstackAPI import listStoragePools, updateStorageCapabilities\n'), ((4424, 4509), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['self.apiclient', "self.services['disk_offering']"], {'custom': '(True)'}), "(self.apiclient, self.services['disk_offering'], custom=True\n )\n", (4443, 4509), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((4789, 4877), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['small']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'small'])\n", (4811, 4877), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((5059, 5294), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['small']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'small_offering.id', 'diskofferingid': 'disk_offering.id', 'mode': "self.services['mode']"}), "(self.apiclient, self.services['small'], accountid=\n self.account.name, domainid=self.account.domainid, serviceofferingid=\n small_offering.id, diskofferingid=disk_offering.id, mode=self.services[\n 'mode'])\n", (5080, 5294), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((5473, 5558), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualMachineId': 'virtual_machine.id', 'listAll': '"""true"""'}), "(self.apiclient, virtualMachineId=virtual_machine.id, listAll='true'\n )\n", (5484, 5558), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((1405, 1470), 'marvin.cloudstackTestCase.unittest.SkipTest', 'unittest.SkipTest', (['"""VMWare tests only valid on VMWare hypervisor"""'], {}), "('VMWare tests only valid on VMWare hypervisor')\n", (1422, 1470), False, 'from marvin.cloudstackTestCase import cloudstackTestCase, unittest\n'), ((3797, 3853), 'marvin.cloudstackAPI.updateStorageCapabilities.updateStorageCapabilitiesCmd', 'updateStorageCapabilities.updateStorageCapabilitiesCmd', ([], {}), '()\n', (3851, 3853), False, 'from marvin.cloudstackAPI import listStoragePools, updateStorageCapabilities\n'), ((5647, 5716), 'marvin.lib.base.VirtualMachine.detach_volume', 'VirtualMachine.detach_volume', (['virtual_machine', 'self.apiclient', 'volume'], {}), '(virtual_machine, self.apiclient, volume)\n', (5675, 5716), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((5749, 5759), 'marvin.lib.base.Volume', 'Volume', (['{}'], {}), '({})\n', (5755, 5759), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((5821, 5875), 'marvin.lib.base.Volume.resize', 'Volume.resize', (['currentVolume', 'self.apiclient'], {'size': '"""2"""'}), "(currentVolume, self.apiclient, size='2')\n", (5834, 5875), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n'), ((5892, 5961), 'marvin.lib.base.VirtualMachine.attach_volume', 'VirtualMachine.attach_volume', (['virtual_machine', 'self.apiclient', 'volume'], {}), '(virtual_machine, self.apiclient, volume)\n', (5920, 5961), False, 'from marvin.lib.base import DiskOffering, Iso, Account, VirtualMachine, ServiceOffering, Volume\n')] |
from requests import get
from marvin.essentials import speak
#########################
# File to hold Api work #
#########################
class ApiService():
def __init__(self, speak_type):
self.speak_type = speak_type
def tacoFullRand(self):
url = 'http://taco-randomizer.herokuapp.com/random/?full-taco=true'
self.requested_taco = get(url)
title = self.requested_taco.json()['name']
print('Got Taco recipe for ' + title)
spliting = title.split(" ")
title_with_under_scores = ("_").join(spliting)
self.taco_txt = (str(title_with_under_scores) + '.txt')
print(title, file=open(self.taco_txt, 'w'))
def tacoRandRand(self):
url = 'http://taco-randomizer.herokuapp.com/random/'
self.requested_taco = get(url)
def dataTaco(self):
try:
instructions = self.requested_taco.json()['recipe']
print('\n\nInstructions:\n' + instructions, file=open(self.taco_txt + '.txt', 'a'))
except:
print('\n\nInstructions:\nNo recipe for this section', file=open(self.taco_txt + '.txt', 'a'))
if self.requested_taco.json()['shell_url'] is not None:
shell_instructions = self.requested_taco.json()['shell']['recipe']
print('\n\nShell Instructions:\n' + shell_instructions, file=open(self.taco_txt + '.txt', 'a'))
if self.requested_taco.json()['base_layer_url'] is not None:
base_layer_instructions = self.requested_taco.json()['base_layer']['recipe']
print('\n\nBase Layer Instructions:\n' + base_layer_instructions, file=open(self.taco_txt + '.txt', 'a'))
if self.requested_taco.json()['seasoning_url'] is not None:
season_instructions = self.requested_taco.json()['seasoning']['recipe']
print('\n\nSeasoning Instructions:\n' + season_instructions, file=open(self.taco_txt + '.txt', 'a'))
if self.requested_taco.json()['condiment_url'] is not None:
condiment_instructions = self.requested_taco.json()['condiment']['recipe']
print('\n\nCondiment Instructions:\n' + condiment_instructions, file=open(self.taco_txt + '.txt', 'a'))
if self.requested_taco.json()['mixin_url'] is not None:
mixin_instructions = self.requested_taco.json()['mixin']['recipe']
print('\n\nMixin Instructions:\n' + mixin_instructions, file=open(self.taco_txt + '.txt', 'a'))
print('Full Recipe put into file called ' + self.taco_txt)
speak('Opening the full taco recipe for you', self.speak_type) | [
"marvin.essentials.speak"
] | [((371, 379), 'requests.get', 'get', (['url'], {}), '(url)\n', (374, 379), False, 'from requests import get\n'), ((804, 812), 'requests.get', 'get', (['url'], {}), '(url)\n', (807, 812), False, 'from requests import get\n'), ((2529, 2591), 'marvin.essentials.speak', 'speak', (['"""Opening the full taco recipe for you"""', 'self.speak_type'], {}), "('Opening the full taco recipe for you', self.speak_type)\n", (2534, 2591), False, 'from marvin.essentials import speak\n')] |
from marvin.cloudstackAPI import (
listConfigurations,
listNetworkACLLists,
listDomains,
listZones,
listTemplates,
listRouters,
listNetworks,
listSystemVms,
listVirtualMachines,
listLoadBalancerRuleInstances,
listVlanIpRanges,
listHosts,
listPublicIpAddresses,
listPortForwardingRules,
listLoadBalancerRules,
listServiceOfferings,
listNetworkOfferings,
listVPCOfferings,
listVPCs,
listVpnGateways
)
from marvin.codes import (
PASS,
FAILED
)
from utils import validate_list
def get_zone(api_client, zone_name=None, zone_id=None):
"""
@name : get_zone
@Desc :Returns the Zone Information for a given zone id or Zone Name
@Input : zone_name: Name of the Zone
zone_id : Id of the zone
@Output : 1. Zone Information for the passed inputs else first zone
2. FAILED In case the cmd failed
"""
cmd = listZones.listZonesCmd()
if zone_name is not None:
cmd.name = zone_name
if zone_id is not None:
cmd.id = zone_id
cmd_out = api_client.listZones(cmd)
if validate_list(cmd_out)[0] != PASS:
return FAILED
'''
Check if input zone name and zone id is None,
then return first element of List Zones command
'''
return cmd_out[0]
def get_domain(api_client, domain_id=None, domain_name=None):
"""
@name : get_domain
@Desc : Returns the Domain Information for a given domain id or domain name
@Input : domain id : Id of the Domain
domain_name : Name of the Domain
@Output : 1. Domain Information for the passed inputs else first Domain
2. FAILED In case the cmd failed
"""
cmd = listDomains.listDomainsCmd()
if domain_name is not None:
cmd.name = domain_name
if domain_id is not None:
cmd.id = domain_id
cmd_out = api_client.listDomains(cmd)
if validate_list(cmd_out)[0] != PASS:
return FAILED
return cmd_out[0]
def get_template(api_client, zone_id=None, template_filter="featured", template_type='BUILTIN', template_id=None,
template_name=None, account=None, domain_id=None, project_id=None, hypervisor=None):
"""
@Name : get_template
@Desc : Retrieves the template Information based upon inputs provided
Template is retrieved based upon either of the inputs matched
condition
@Input : returns a template"
@Output : FAILED in case of any failure
template Information matching the inputs
"""
cmd = listTemplates.listTemplatesCmd()
cmd.templatefilter = template_filter
if domain_id is not None:
cmd.domainid = domain_id
if zone_id is not None:
cmd.zoneid = zone_id
if template_id is not None:
cmd.id = template_id
if template_name is not None:
cmd.name = template_name
if hypervisor is not None:
cmd.hypervisor = hypervisor
if project_id is not None:
cmd.projectid = project_id
if account is not None:
cmd.account = account
'''
Get the Templates pertaining to the inputs provided
'''
list_templatesout = api_client.listTemplates(cmd)
if validate_list(list_templatesout)[0] != PASS:
return FAILED
for template in list_templatesout:
if template.isready and template.templatetype == template_type:
return template
'''
Return default first template, if no template matched
'''
return list_templatesout[0]
def list_routers(api_client, **kwargs):
"""List all Routers matching criteria"""
cmd = listRouters.listRoutersCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listRouters(cmd)
def list_zones(api_client, **kwargs):
"""List all Zones matching criteria"""
cmd = listZones.listZonesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listZones(cmd)
def list_networks(api_client, **kwargs):
"""List all Networks matching criteria"""
cmd = listNetworks.listNetworksCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listNetworks(cmd)
def list_vpcs(api_client, **kwargs):
"""List all VPCs matching criteria"""
cmd = listVPCs.listVPCsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listVPCs(cmd)
def list_ssvms(api_client, **kwargs):
"""List all SSVMs matching criteria"""
cmd = listSystemVms.listSystemVmsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listSystemVms(cmd)
def list_virtual_machines(api_client, **kwargs):
"""List all VMs matching criteria"""
cmd = listVirtualMachines.listVirtualMachinesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listVirtualMachines(cmd)
def list_hosts(api_client, **kwargs):
"""List all Hosts matching criteria"""
cmd = listHosts.listHostsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listHosts(cmd)
def list_configurations(api_client, **kwargs):
"""List configuration with specified name"""
cmd = listConfigurations.listConfigurationsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listConfigurations(cmd)
def list_public_ip(api_client, **kwargs):
"""List all Public IPs matching criteria"""
cmd = listPublicIpAddresses.listPublicIpAddressesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listPublicIpAddresses(cmd)
def list_nat_rules(api_client, **kwargs):
"""List all NAT rules matching criteria"""
cmd = listPortForwardingRules.listPortForwardingRulesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listPortForwardingRules(cmd)
def list_lb_rules(api_client, **kwargs):
"""List all Load balancing rules matching criteria"""
cmd = listLoadBalancerRules.listLoadBalancerRulesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listLoadBalancerRules(cmd)
def list_lb_instances(api_client, **kwargs):
"""List all Load balancing instances matching criteria"""
cmd = listLoadBalancerRuleInstances.listLoadBalancerRuleInstancesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listLoadBalancerRuleInstances(cmd)
def list_service_offering(api_client, **kwargs):
"""Lists all available service offerings."""
cmd = listServiceOfferings.listServiceOfferingsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listServiceOfferings(cmd)
def list_vlan_ipranges(api_client, **kwargs):
"""Lists all VLAN IP ranges."""
cmd = listVlanIpRanges.listVlanIpRangesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listVlanIpRanges(cmd)
def list_network_offerings(api_client, **kwargs):
"""Lists network offerings"""
cmd = listNetworkOfferings.listNetworkOfferingsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listNetworkOfferings(cmd)
def list_vpngateways(api_client, **kwargs):
""" Lists VPN gateways """
cmd = listVpnGateways.listVpnGatewaysCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listVpnGateways(cmd)
def list_vpc_offerings(api_client, **kwargs):
""" Lists VPC offerings """
cmd = listVPCOfferings.listVPCOfferingsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listVPCOfferings(cmd)
def list_network_acl_lists(api_client, **kwargs):
"""List Network ACL lists"""
cmd = listNetworkACLLists.listNetworkACLListsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():
cmd.listall = True
return api_client.listNetworkACLLists(cmd)
def get_hypervisor_type(api_client):
"""Return the hypervisor type of the hosts in setup"""
cmd = listHosts.listHostsCmd()
cmd.type = 'Routing'
cmd.listall = True
hosts = api_client.listHosts(cmd)
hosts_list_validation_result = validate_list(hosts)
assert hosts_list_validation_result[0] == PASS, "host list validation failed"
return hosts_list_validation_result[1].hypervisor
def get_vpc_offering(api_client, name):
offerings = list_vpc_offerings(api_client, name=name)
return find_exact_match_by_name(offerings, name)
def get_default_vpc_offering(api_client):
return get_vpc_offering(api_client, 'Default VPC offering')
def get_default_redundant_vpc_offering(api_client):
return get_vpc_offering(api_client, 'Redundant VPC offering')
def get_network_offering(api_client, name):
offerings = list_network_offerings(api_client, name=name)
return find_exact_match_by_name(offerings, name)
def get_default_network_offering(api_client):
return get_network_offering(api_client, 'DefaultIsolatedNetworkOfferingForVpcNetworks')
def get_default_guest_network_offering(api_client):
return get_network_offering(api_client, 'DefaultIsolatedNetworkOfferingWithSourceNatService')
def get_default_network_offering_no_load_balancer(api_client):
return get_network_offering(api_client, 'DefaultIsolatedNetworkOfferingForVpcNetworksNoLB')
def get_default_isolated_network_offering(api_client):
return get_network_offering(api_client, 'DefaultIsolatedNetworkOffering')
def get_default_isolated_network_offering_with_egress(api_client):
return get_network_offering(api_client, 'DefaultIsolatedNetworkOfferingWithEgress')
def get_default_redundant_isolated_network_offering(api_client):
return get_network_offering(api_client, 'DefaultRedundantIsolatedNetworkOffering')
def get_default_redundant_isolated_network_offering_with_egress(api_client):
return get_network_offering(api_client, 'DefaultRedundantIsolatedNetworkOfferingWithEgress')
def get_default_private_network_offering(api_client):
return get_network_offering(api_client, 'DefaultPrivateGatewayNetworkOffering')
def get_default_virtual_machine_offering(api_client):
return get_virtual_machine_offering(api_client, 'Small Instance')
def get_virtual_machine_offering(api_client, name):
offerings = list_service_offering(api_client, name=name)
return find_exact_match_by_name(offerings, name)
def get_network_acl(api_client, name=None, id=None, vpc=None):
if vpc:
acls = list_network_acl_lists(api_client, name=name, id=id, vpcid=vpc.id, listall=True)
else:
acls = list_network_acl_lists(api_client, name=name, id=id, listall=True)
return find_exact_match_by_name(acls, name) if name else acls[0]
def get_default_allow_vpc_acl(api_client, vpc):
return get_network_acl(api_client, 'default_allow', vpc)
def get_default_deny_vpc_acl(api_client, vpc):
return get_network_acl(api_client, 'default_deny', vpc)
def get_vpc(api_client, name):
vpcs = list_vpcs(api_client, name=name, listall=True)
return find_exact_match_by_name(vpcs, name)
def get_network(api_client, name=None, id=None, vpc=None):
if vpc:
networks = list_networks(api_client, name=name, id=id, vpcid=vpc.id)
else:
networks = list_networks(api_client, name=name, id=id)
return find_exact_match_by_name(networks, name) if name else networks[0]
def get_virtual_machine(api_client, name, network=None):
if network:
virtual_machines = list_virtual_machines(api_client, name=name, networkid=network.id, listall=True)
else:
virtual_machines = list_virtual_machines(api_client, name=name, listall=True)
return find_exact_match_by_name(virtual_machines, name)
def get_vpngateway(api_client, vpc=None):
vpngateways = list_vpngateways(api_client, vpcid=vpc.id, listall=True)
return next(iter(vpngateways or []), None)
def find_exact_match_by_name(items, name):
items = [item for item in items if item.name == name]
return next(iter(items or []), None)
| [
"marvin.cloudstackAPI.listPortForwardingRules.listPortForwardingRulesCmd",
"marvin.cloudstackAPI.listHosts.listHostsCmd",
"marvin.cloudstackAPI.listVlanIpRanges.listVlanIpRangesCmd",
"marvin.cloudstackAPI.listConfigurations.listConfigurationsCmd",
"marvin.cloudstackAPI.listNetworkACLLists.listNetworkACLList... | [((946, 970), 'marvin.cloudstackAPI.listZones.listZonesCmd', 'listZones.listZonesCmd', ([], {}), '()\n', (968, 970), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((1737, 1765), 'marvin.cloudstackAPI.listDomains.listDomainsCmd', 'listDomains.listDomainsCmd', ([], {}), '()\n', (1763, 1765), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((2586, 2618), 'marvin.cloudstackAPI.listTemplates.listTemplatesCmd', 'listTemplates.listTemplatesCmd', ([], {}), '()\n', (2616, 2618), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((3644, 3672), 'marvin.cloudstackAPI.listRouters.listRoutersCmd', 'listRouters.listRoutersCmd', ([], {}), '()\n', (3670, 3672), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((3952, 3976), 'marvin.cloudstackAPI.listZones.listZonesCmd', 'listZones.listZonesCmd', ([], {}), '()\n', (3974, 3976), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((4260, 4290), 'marvin.cloudstackAPI.listNetworks.listNetworksCmd', 'listNetworks.listNetworksCmd', ([], {}), '()\n', (4288, 4290), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((4569, 4591), 'marvin.cloudstackAPI.listVPCs.listVPCsCmd', 'listVPCs.listVPCsCmd', ([], {}), '()\n', (4589, 4591), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((4868, 4900), 'marvin.cloudstackAPI.listSystemVms.listSystemVmsCmd', 'listSystemVms.listSystemVmsCmd', ([], {}), '()\n', (4898, 4900), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((5191, 5235), 'marvin.cloudstackAPI.listVirtualMachines.listVirtualMachinesCmd', 'listVirtualMachines.listVirtualMachinesCmd', ([], {}), '()\n', (5233, 5235), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((5523, 5547), 'marvin.cloudstackAPI.listHosts.listHostsCmd', 'listHosts.listHostsCmd', ([], {}), '()\n', (5545, 5547), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((5840, 5882), 'marvin.cloudstackAPI.listConfigurations.listConfigurationsCmd', 'listConfigurations.listConfigurationsCmd', ([], {}), '()\n', (5880, 5882), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((6178, 6226), 'marvin.cloudstackAPI.listPublicIpAddresses.listPublicIpAddressesCmd', 'listPublicIpAddresses.listPublicIpAddressesCmd', ([], {}), '()\n', (6224, 6226), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((6524, 6576), 'marvin.cloudstackAPI.listPortForwardingRules.listPortForwardingRulesCmd', 'listPortForwardingRules.listPortForwardingRulesCmd', ([], {}), '()\n', (6574, 6576), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((6886, 6934), 'marvin.cloudstackAPI.listLoadBalancerRules.listLoadBalancerRulesCmd', 'listLoadBalancerRules.listLoadBalancerRulesCmd', ([], {}), '()\n', (6932, 6934), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((7250, 7314), 'marvin.cloudstackAPI.listLoadBalancerRuleInstances.listLoadBalancerRuleInstancesCmd', 'listLoadBalancerRuleInstances.listLoadBalancerRuleInstancesCmd', ([], {}), '()\n', (7312, 7314), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((7629, 7675), 'marvin.cloudstackAPI.listServiceOfferings.listServiceOfferingsCmd', 'listServiceOfferings.listServiceOfferingsCmd', ([], {}), '()\n', (7673, 7675), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((7965, 8003), 'marvin.cloudstackAPI.listVlanIpRanges.listVlanIpRangesCmd', 'listVlanIpRanges.listVlanIpRangesCmd', ([], {}), '()\n', (8001, 8003), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((8291, 8337), 'marvin.cloudstackAPI.listNetworkOfferings.listNetworkOfferingsCmd', 'listNetworkOfferings.listNetworkOfferingsCmd', ([], {}), '()\n', (8335, 8337), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((8620, 8656), 'marvin.cloudstackAPI.listVpnGateways.listVpnGatewaysCmd', 'listVpnGateways.listVpnGatewaysCmd', ([], {}), '()\n', (8654, 8656), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((8937, 8975), 'marvin.cloudstackAPI.listVPCOfferings.listVPCOfferingsCmd', 'listVPCOfferings.listVPCOfferingsCmd', ([], {}), '()\n', (8973, 8975), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((9262, 9306), 'marvin.cloudstackAPI.listNetworkACLLists.listNetworkACLListsCmd', 'listNetworkACLLists.listNetworkACLListsCmd', ([], {}), '()\n', (9304, 9306), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((9609, 9633), 'marvin.cloudstackAPI.listHosts.listHostsCmd', 'listHosts.listHostsCmd', ([], {}), '()\n', (9631, 9633), False, 'from marvin.cloudstackAPI import listConfigurations, listNetworkACLLists, listDomains, listZones, listTemplates, listRouters, listNetworks, listSystemVms, listVirtualMachines, listLoadBalancerRuleInstances, listVlanIpRanges, listHosts, listPublicIpAddresses, listPortForwardingRules, listLoadBalancerRules, listServiceOfferings, listNetworkOfferings, listVPCOfferings, listVPCs, listVpnGateways\n'), ((9755, 9775), 'utils.validate_list', 'validate_list', (['hosts'], {}), '(hosts)\n', (9768, 9775), False, 'from utils import validate_list\n'), ((1132, 1154), 'utils.validate_list', 'validate_list', (['cmd_out'], {}), '(cmd_out)\n', (1145, 1154), False, 'from utils import validate_list\n'), ((1936, 1958), 'utils.validate_list', 'validate_list', (['cmd_out'], {}), '(cmd_out)\n', (1949, 1958), False, 'from utils import validate_list\n'), ((3233, 3265), 'utils.validate_list', 'validate_list', (['list_templatesout'], {}), '(list_templatesout)\n', (3246, 3265), False, 'from utils import validate_list\n')] |
# !usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2017-06-12 18:18:54
# @Last modified by: <NAME>
# @Last modified time: 2017-07-31 12:07:88
from __future__ import absolute_import, division, print_function
import copy
import json
from imp import reload
import pandas as pd
import pytest
import six
import marvin
from marvin import config
from marvin.tools.cube import Cube
from marvin.tools.maps import Maps
from marvin.tools.modelcube import ModelCube
from marvin.tools.query import Query
from marvin.tools.results import Results, ResultSet, marvintuple
from marvin.tools.spaxel import Spaxel
from marvin.utils.datamodel.query.base import ParameterGroup
myplateifu = '8485-1901'
cols = ['cube.mangaid', 'cube.plateifu', 'nsa.z']
remotecols = [u'mangaid', u'plateifu', u'z']
@pytest.fixture(scope='function', autouse=True)
def allow_dap(monkeypatch):
monkeypatch.setattr(config, '_allow_DAP_queries', True)
# global Query, Results
# reload(marvin.tools.query)
# reload(marvin.tools.results)
# from marvin.tools.query import Query
# from marvin.tools.results import Results
@pytest.fixture()
def limits(results):
data = results.expdata['queries'][results.search_filter]
count = 10 if data['count'] >= 10 else data['count']
return (10, count)
@pytest.fixture()
def results(query, request):
searchfilter = request.param if hasattr(request, 'param') else 'nsa.z < 0.1'
q = Query(search_filter=searchfilter, mode=query.mode, limit=10, release=query.release)
if q.mode == 'remote':
pytest.xfail('cannot control for DAP spaxel queries on server side; failing all remotes until then')
r = q.run()
r.expdata = query.expdata
yield r
r = None
@pytest.fixture()
def columns(results):
''' returns the local or remote column syntax '''
return ParameterGroup('Columns', cols)
class TestResultsColumns(object):
def test_check_cols(self, results, columns):
assert set(results.columns.full) == set(columns.full)
assert set(results.columns.remote) == set(columns.remote)
@pytest.mark.parametrize('col, errmsg', [('cube', 'cube is too ambiguous. Did you mean one of')])
def test_fail(self, results, col, errmsg):
with pytest.raises(KeyError) as cm:
col in results.columns
assert cm.type == KeyError
assert errmsg in str(cm.value)
@pytest.mark.parametrize('results', [('nsa.z < 0.1 and emline_gflux_ha_6564 > 25')], indirect=True)
@pytest.mark.parametrize('colmns, pars', [(['spaxelprop.x', 'spaxelprop.y', 'emline_gflux_ha_6564', 'bintype.name', 'template.name'],
['x', 'y', 'emline_gflux_ha_6564', 'bintype_name', 'template_name'])])
def test_check_withadded(self, results, colmns, pars, columns):
newcols = cols + colmns
assert set(results._params) == set(newcols)
newcols = copy.copy(columns)
newcols.extend(ParameterGroup('Columns', colmns))
assert set(results.columns.full) == set(newcols.full)
assert set(results.columns.remote) == set(newcols.remote)
@pytest.mark.parametrize('results', [('nsa.z < 0.1 and emline_gflux_ha_6564 > 25')], indirect=True)
@pytest.mark.parametrize('full, name', [('nsa.z', 'z'), ('cube.plateifu', 'plateifu'),
('cube.mangaid', 'mangaid'),
('spaxelprop.emline_gflux_ha_6564', 'haflux')])
def test_colnames(self, results, full, name):
cols = results.columns
assert full in cols
assert name in cols
col = cols[name]
assert col.full == full
class TestMarvinTuple(object):
def test_create(self, results):
data = results.results[0]._asdict()
mt = marvintuple('ResultRow', data.keys())
assert mt is not None
assert hasattr(mt, 'mangaid')
assert hasattr(mt, 'plateifu')
row = mt(**data)
assert row.mangaid == data['mangaid']
assert row.plateifu == data['plateifu']
@pytest.mark.parametrize('params, msg',
[('plateifu, z', None),
('z', 'All rows must have a plateifu column to be able to add')],
ids=['pass', 'fail'])
def test_add(self, results, params, msg):
data = results.results[0]._asdict()
mt = marvintuple('ResultRow', 'mangaid, plateifu')
mt1 = marvintuple('ResultRow', params)
cols = [c.strip() for c in params.split(',')]
row = mt(**{k: v for k, v in data.items() if k in ['mangaid', 'plateifu']})
row1 = mt1(**{k: v for k, v in data.items() if k in cols})
if msg:
with pytest.raises(AssertionError) as cm:
new_row = row + row1
assert msg in str(cm)
else:
new_row = row + row1
assert new_row is not None
cols = ['mangaid', 'plateifu'] + cols
assert set(cols).issubset(set(new_row._asdict().keys()))
assert all(item in new_row._asdict().items() for item in row._asdict().items())
class TestResultSet(object):
def test_list(self, results):
reslist = results.results.to_list()
assert isinstance(reslist, list)
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
def test_sort(self, results):
redshift = results.expdata['queries']['nsa.z < 0.1']['sorted']['1'][-1]
results.getAll()
results.results.sort('z')
assert results.results['z'][0] == redshift
def test_add(self, results):
res = results.results
res1 = res
newres = res + res1
newres1 = res1 + res
assert res.columns.full == newres.columns.full
assert newres == newres1
class TestResultsMisc(object):
def test_showQuery(self, results):
x = results.showQuery()
assert isinstance(x, six.string_types)
class TestResultsOutput(object):
def test_tofits(self, results, temp_scratch):
file = temp_scratch.join('test_results.fits')
results.toFits(filename=str(file), overwrite=True)
assert file.check(file=1, exists=1) is True
def test_tocsv(self, results, temp_scratch):
file = temp_scratch.join('test_results.csv')
results.toCSV(filename=str(file), overwrite=True)
assert file.check(file=1, exists=1) is True
def test_topandas(self, results):
df = results.toDF()
assert isinstance(df, pd.core.frame.DataFrame)
def test_tojson(self, results):
res = results.toJson()
assert isinstance(res, six.string_types)
json_res = json.loads(res)
assert isinstance(json_res, list)
class TestResultsGetParams(object):
def test_get_attribute(self, results, columns):
res = results.results[0]
assert isinstance(results.results, ResultSet) is True
for i, name in enumerate(columns):
assert res[i] == res.__getattribute__(name.remote)
@pytest.mark.parametrize('col',
[(c) for c in cols],
ids=['cube.mangaid', 'cube.plateifu', 'nsa.z'])
def test_get_list(self, results, col):
assert col in results.columns
obj = results.getListOf(col)
assert obj is not None
assert isinstance(obj, list) is True
json_obj = results.getListOf(col, to_json=True)
assert isinstance(json_obj, six.string_types)
@pytest.mark.skip(reason="no spaxel queries causes this to fail since parameter counts are now off")
@pytest.mark.parametrize('results',
[('nsa.z < 0.1 and emline_gflux_ha_6564 > 25'),
('nsa.z < 0.1'),
('emline_gflux_ha_6564 > 25')], indirect=True)
def test_get_list_all(self, results):
q = Query(search_filter=results.search_filter, mode=results.mode, limit=1,
release=results.release, return_params=results.return_params)
r = q.run(start=0, end=1)
assert r.count == 1
mangaids = r.getListOf('mangaid', return_all=True)
assert len(mangaids) == r.totalcount
assert len(mangaids) == results.expdata['queries'][results.search_filter]['count']
@pytest.mark.parametrize('ftype', [('dictlist'), ('listdict')])
@pytest.mark.parametrize('name', [(None), ('mangaid'), ('z')], ids=['noname', 'mangaid', 'z'])
def test_get_dict(self, results, ftype, name):
output = results.getDictOf(name, format_type=ftype)
if ftype == 'listdict':
assert isinstance(output, list) is True
assert isinstance(output[0], dict) is True
if name is not None:
assert set([name]) == set(list(output[0]))
else:
assert set(remotecols) == set(output[0])
elif ftype == 'dictlist':
assert isinstance(output, dict) is True
assert isinstance(list(output.values())[0], list) is True
if name is not None:
assert set([name]) == set(list(output.keys()))
else:
assert set(remotecols) == set(output)
json_obj = results.getDictOf(name, format_type=ftype, to_json=True)
assert isinstance(json_obj, six.string_types)
def test_get_dict_all(self, results):
output = results.getDictOf('mangaid', return_all=True)
assert len(output) == results.totalcount
class TestResultsSort(object):
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
def test_sort(self, results, limits):
results.sort('z')
limit, count = limits
data = results.expdata['queries'][results.search_filter]['sorted']
assert tuple(data['1']) == results.results[0]
assert tuple(data[str(count)]) == results.results[count - 1]
class TestResultsPaging(object):
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
def test_check_counts(self, results, limits):
if results.mode == 'local':
pytest.skip('skipping now due to weird issue with local results not same as remote results')
results.sort('z')
limit, count = limits
data = results.expdata['queries'][results.search_filter]
assert results.totalcount == data['count']
assert results.count == count
assert len(results.results) == count
assert results.limit == limit
assert results.chunk == limit
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
@pytest.mark.parametrize('chunk, rows',
[(10, None),
(20, (10, 21))],
ids=['defaultchunk', 'chunk20'])
def test_get_next(self, results, chunk, rows, limits):
if results.mode == 'local':
pytest.skip('skipping now due to weird issue with local results not same as remote results')
limit, count = limits
results.sort('z')
results.getNext(chunk=chunk)
data = results.expdata['queries'][results.search_filter]['sorted']
if results.count == results.totalcount:
assert results.results[0] == tuple(data['1'])
assert len(results.results) == count
else:
assert results.results[0] == tuple(data['11'])
assert len(results.results) == chunk
if rows:
assert results.results[rows[0]] == tuple(data[str(rows[1])])
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
@pytest.mark.parametrize('index, chunk, rows',
[(30, 10, [(0, 21)]),
(45, 20, [(5, 31), (10, 36), (15, 41)])],
ids=['defaultchunk', 'chunk20'])
def test_get_prev(self, results, index, chunk, rows, limits):
if results.mode == 'local':
pytest.skip('skipping now due to weird issue with local results not same as remote results')
limit, count = limits
results.sort('z')
results.getSubset(index, limit=chunk)
results.getPrevious(chunk=chunk)
data = results.expdata['queries'][results.search_filter]['sorted']
if results.count == results.totalcount:
assert results.results[0] == tuple(data['1'])
assert len(results.results) == count
elif results.count == 0:
assert len(results.results) == 0
else:
assert len(results.results) == chunk
if rows:
for row in rows:
assert results.results[row[0]] == tuple(data[str(row[1])])
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
@pytest.mark.parametrize('index, chunk, rows',
[(35, 10, [(0, 36)]),
(30, 20, [(0, 31), (15, 46)])],
ids=['defaultchunk', 'chunk20'])
def test_get_set(self, results, index, chunk, rows, limits):
if results.mode == 'local':
pytest.skip('skipping now due to weird issue with local results not same as remote results')
limit, count = limits
results.sort('z')
results.getSubset(index, limit=chunk)
data = results.expdata['queries'][results.search_filter]['sorted']
if results.count == results.totalcount:
assert results.results[0] == tuple(data['1'])
assert len(results.results) == count
elif results.count == 0:
assert len(results.results) == 0
else:
assert len(results.results) == chunk
if rows:
for row in rows:
assert results.results[row[0]] == tuple(data[str(row[1])])
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
def test_extend_set(self, results):
res = results.getSubset(0, limit=1)
assert results.count == 1
assert len(results.results) == 1
results.extendSet(start=1, chunk=2)
setcount = 3 if results.count > 3 else results.count
assert results.count == setcount
assert len(results.results) == setcount
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
def test_loop(self, results):
res = results.getSubset(0, limit=1)
assert results.count == 1
results.loop(chunk=500)
assert results.count == results.expdata['queries'][results.search_filter]['count']
assert results.count == results.totalcount
@pytest.mark.parametrize('results', [('nsa.z < 0.1')], indirect=True)
def test_get_all(self, results):
res = results.getAll()
assert results.count == results.totalcount
class TestResultsPickling(object):
def test_pickle_save(self, results, temp_scratch):
file = temp_scratch.join('test_results.mpf')
path = results.save(str(file), overwrite=True)
assert file.check() is True
def test_pickle_restore(self, results, temp_scratch):
file = temp_scratch.join('test_results.mpf')
path = results.save(str(file), overwrite=True)
assert file.check() is True
r = Results.restore(str(file))
assert r.search_filter == results.search_filter
class TestResultsConvertTool(object):
@pytest.mark.skip(reason="no spaxel queries causes this to fail since parameter counts are now off")
@pytest.mark.parametrize('results', [('nsa.z < 0.1 and emline_gflux_ha_6564 > 25')], indirect=True)
@pytest.mark.parametrize('objtype, tool',
[('cube', Cube), ('maps', Maps), ('spaxel', Spaxel),
('modelcube', ModelCube)])
def test_convert_success(self, results, objtype, tool):
if config.release == 'MPL-4' and objtype == 'modelcube':
pytest.skip('no modelcubes in mpl-4')
results.convertToTool(objtype, limit=1, mode=results.mode)
assert results.objects is not None
assert isinstance(results.objects, list) is True
assert isinstance(results.objects[0], tool) is True
if objtype != 'spaxel':
assert results.mode == results.objects[0].mode
@pytest.mark.parametrize('objtype, error, errmsg',
[('modelcube', AssertionError, "ModelCubes require a release of MPL-5 and up"),
('spaxel', AssertionError, 'Parameters must include spaxelprop.x and y in order to convert to Marvin Spaxel')],
ids=['mcminrelease', 'nospaxinfo'])
def test_convert_failures(self, results, objtype, error, errmsg):
if config.release > 'MPL-4' and objtype == 'modelcube':
pytest.skip('modelcubes in post mpl-4')
with pytest.raises(error) as cm:
results.convertToTool(objtype, limit=1)
assert cm.type == error
assert errmsg in str(cm.value)
#
# Below here is beginnings of Results refactor
#
modes = ['local', 'remote']
@pytest.fixture(scope='session', params=modes)
def mode(request):
"""Yield a data mode."""
return request.param
@pytest.fixture(scope='class')
def newr(mode):
if mode == 'remote':
config.forceDbOff()
q = Query(search_filter='nsa.z < 0.1', release='MPL-4', mode=mode)
r = q.run()
yield r
q = None
r = None
if mode == 'remote':
config.forceDbOn()
@pytest.fixture(scope='function')
def fxnr(mode):
if mode == 'remote':
config.forceDbOff()
q = Query(search_filter='nsa.z < 0.1', release='MPL-4', mode=mode)
r = q.run()
yield r
q = None
r = None
if mode == 'remote':
config.forceDbOn()
class TestResultsPages(object):
sf = 'nsa.z < 0.1'
rel = 'MPL-4'
count = 1282
limit = 100
def page_asserts(self, res, chunk, useall=None):
assert res.totalcount == self.count
assert res.limit == self.limit
assert res.chunk == (chunk if chunk else self.limit)
assert res.count == self.count if useall else (chunk if chunk else self.limit)
assert len(res.results) == self.count if useall else (chunk if chunk else self.limit)
@pytest.mark.parametrize('chunk',
[(None), (100), (20), (5)],
ids=['none', 'chunk100', 'chunk20', 'chunk5'])
def test_next(self, newr, chunk):
assert newr.results is not None
newr.getNext(chunk=chunk)
self.page_asserts(newr, chunk)
@pytest.mark.parametrize('chunk',
[(None), (100), (20), (5)],
ids=['none', 'chunk100', 'chunk20', 'chunk5'])
def test_prev(self, newr, chunk):
assert newr.results is not None
newr.getNext(chunk=100)
newr.getPrevious(chunk=chunk)
self.page_asserts(newr, chunk)
def test_all(self, newr):
assert newr.results is not None
assert newr.totalcount == self.count
assert newr.count != self.count
newr.getAll()
self.page_asserts(newr, newr.chunk, useall=True)
@pytest.mark.parametrize('chunk, iters',
[(None, 12), (100, 12), (500, 3)],
ids=['none', 'chunk100', 'chunk500'])
def test_loop(self, fxnr, chunk, iters, capsys):
assert fxnr.results is not None
assert fxnr.totalcount == self.count
assert fxnr.count == self.limit
fxnr.loop(chunk=chunk)
self.page_asserts(fxnr, chunk, useall=True)
captured = capsys.readouterr()
out = captured.out
iterlines = len(out.split('\n')) - 1
assert iterlines == iters
| [
"marvin.utils.datamodel.query.base.ParameterGroup",
"marvin.config.forceDbOn",
"marvin.tools.query.Query",
"marvin.config.forceDbOff",
"marvin.tools.results.marvintuple"
] | [((857, 903), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'autouse': '(True)'}), "(scope='function', autouse=True)\n", (871, 903), False, 'import pytest\n'), ((1181, 1197), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1195, 1197), False, 'import pytest\n'), ((1363, 1379), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1377, 1379), False, 'import pytest\n'), ((1792, 1808), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1806, 1808), False, 'import pytest\n'), ((17171, 17216), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""', 'params': 'modes'}), "(scope='session', params=modes)\n", (17185, 17216), False, 'import pytest\n'), ((17293, 17322), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""class"""'}), "(scope='class')\n", (17307, 17322), False, 'import pytest\n'), ((17572, 17604), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (17586, 17604), False, 'import pytest\n'), ((1498, 1586), 'marvin.tools.query.Query', 'Query', ([], {'search_filter': 'searchfilter', 'mode': 'query.mode', 'limit': '(10)', 'release': 'query.release'}), '(search_filter=searchfilter, mode=query.mode, limit=10, release=query.\n release)\n', (1503, 1586), False, 'from marvin.tools.query import Query\n'), ((1896, 1927), 'marvin.utils.datamodel.query.base.ParameterGroup', 'ParameterGroup', (['"""Columns"""', 'cols'], {}), "('Columns', cols)\n", (1910, 1927), False, 'from marvin.utils.datamodel.query.base import ParameterGroup\n'), ((2148, 2249), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""col, errmsg"""', "[('cube', 'cube is too ambiguous. Did you mean one of')]"], {}), "('col, errmsg', [('cube',\n 'cube is too ambiguous. Did you mean one of')])\n", (2171, 2249), False, 'import pytest\n'), ((2452, 2553), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1 and emline_gflux_ha_6564 > 25']"], {'indirect': '(True)'}), "('results', [\n 'nsa.z < 0.1 and emline_gflux_ha_6564 > 25'], indirect=True)\n", (2475, 2553), False, 'import pytest\n'), ((2556, 2767), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""colmns, pars"""', "[(['spaxelprop.x', 'spaxelprop.y', 'emline_gflux_ha_6564', 'bintype.name',\n 'template.name'], ['x', 'y', 'emline_gflux_ha_6564', 'bintype_name',\n 'template_name'])]"], {}), "('colmns, pars', [(['spaxelprop.x', 'spaxelprop.y',\n 'emline_gflux_ha_6564', 'bintype.name', 'template.name'], ['x', 'y',\n 'emline_gflux_ha_6564', 'bintype_name', 'template_name'])])\n", (2579, 2767), False, 'import pytest\n'), ((3189, 3290), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1 and emline_gflux_ha_6564 > 25']"], {'indirect': '(True)'}), "('results', [\n 'nsa.z < 0.1 and emline_gflux_ha_6564 > 25'], indirect=True)\n", (3212, 3290), False, 'import pytest\n'), ((3293, 3464), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""full, name"""', "[('nsa.z', 'z'), ('cube.plateifu', 'plateifu'), ('cube.mangaid', 'mangaid'),\n ('spaxelprop.emline_gflux_ha_6564', 'haflux')]"], {}), "('full, name', [('nsa.z', 'z'), ('cube.plateifu',\n 'plateifu'), ('cube.mangaid', 'mangaid'), (\n 'spaxelprop.emline_gflux_ha_6564', 'haflux')])\n", (3316, 3464), False, 'import pytest\n'), ((4136, 4294), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params, msg"""', "[('plateifu, z', None), ('z',\n 'All rows must have a plateifu column to be able to add')]"], {'ids': "['pass', 'fail']"}), "('params, msg', [('plateifu, z', None), ('z',\n 'All rows must have a plateifu column to be able to add')], ids=['pass',\n 'fail'])\n", (4159, 4294), False, 'import pytest\n'), ((5372, 5438), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (5395, 5438), False, 'import pytest\n'), ((7123, 7224), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""col"""', '[c for c in cols]'], {'ids': "['cube.mangaid', 'cube.plateifu', 'nsa.z']"}), "('col', [c for c in cols], ids=['cube.mangaid',\n 'cube.plateifu', 'nsa.z'])\n", (7146, 7224), False, 'import pytest\n'), ((7591, 7695), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""no spaxel queries causes this to fail since parameter counts are now off"""'}), "(reason=\n 'no spaxel queries causes this to fail since parameter counts are now off')\n", (7607, 7695), False, 'import pytest\n'), ((7696, 7845), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1 and emline_gflux_ha_6564 > 25', 'nsa.z < 0.1',\n 'emline_gflux_ha_6564 > 25']"], {'indirect': '(True)'}), "('results', [\n 'nsa.z < 0.1 and emline_gflux_ha_6564 > 25', 'nsa.z < 0.1',\n 'emline_gflux_ha_6564 > 25'], indirect=True)\n", (7719, 7845), False, 'import pytest\n'), ((8400, 8458), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ftype"""', "['dictlist', 'listdict']"], {}), "('ftype', ['dictlist', 'listdict'])\n", (8423, 8458), False, 'import pytest\n'), ((8468, 8559), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""name"""', "[None, 'mangaid', 'z']"], {'ids': "['noname', 'mangaid', 'z']"}), "('name', [None, 'mangaid', 'z'], ids=['noname',\n 'mangaid', 'z'])\n", (8491, 8559), False, 'import pytest\n'), ((9629, 9695), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (9652, 9695), False, 'import pytest\n'), ((10035, 10101), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (10058, 10101), False, 'import pytest\n'), ((10632, 10698), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (10655, 10698), False, 'import pytest\n'), ((10706, 10812), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""chunk, rows"""', '[(10, None), (20, (10, 21))]'], {'ids': "['defaultchunk', 'chunk20']"}), "('chunk, rows', [(10, None), (20, (10, 21))], ids=[\n 'defaultchunk', 'chunk20'])\n", (10729, 10812), False, 'import pytest\n'), ((11645, 11711), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (11668, 11711), False, 'import pytest\n'), ((11719, 11865), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""index, chunk, rows"""', '[(30, 10, [(0, 21)]), (45, 20, [(5, 31), (10, 36), (15, 41)])]'], {'ids': "['defaultchunk', 'chunk20']"}), "('index, chunk, rows', [(30, 10, [(0, 21)]), (45, 20,\n [(5, 31), (10, 36), (15, 41)])], ids=['defaultchunk', 'chunk20'])\n", (11742, 11865), False, 'import pytest\n'), ((12810, 12876), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (12833, 12876), False, 'import pytest\n'), ((12884, 13020), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""index, chunk, rows"""', '[(35, 10, [(0, 36)]), (30, 20, [(0, 31), (15, 46)])]'], {'ids': "['defaultchunk', 'chunk20']"}), "('index, chunk, rows', [(35, 10, [(0, 36)]), (30, 20,\n [(0, 31), (15, 46)])], ids=['defaultchunk', 'chunk20'])\n", (12907, 13020), False, 'import pytest\n'), ((13923, 13989), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (13946, 13989), False, 'import pytest\n'), ((14351, 14417), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (14374, 14417), False, 'import pytest\n'), ((14712, 14778), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1']"], {'indirect': '(True)'}), "('results', ['nsa.z < 0.1'], indirect=True)\n", (14735, 14778), False, 'import pytest\n'), ((15481, 15585), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""no spaxel queries causes this to fail since parameter counts are now off"""'}), "(reason=\n 'no spaxel queries causes this to fail since parameter counts are now off')\n", (15497, 15585), False, 'import pytest\n'), ((15586, 15687), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""results"""', "['nsa.z < 0.1 and emline_gflux_ha_6564 > 25']"], {'indirect': '(True)'}), "('results', [\n 'nsa.z < 0.1 and emline_gflux_ha_6564 > 25'], indirect=True)\n", (15609, 15687), False, 'import pytest\n'), ((15690, 15815), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""objtype, tool"""', "[('cube', Cube), ('maps', Maps), ('spaxel', Spaxel), ('modelcube', ModelCube)]"], {}), "('objtype, tool', [('cube', Cube), ('maps', Maps), (\n 'spaxel', Spaxel), ('modelcube', ModelCube)])\n", (15713, 15815), False, 'import pytest\n'), ((16370, 16665), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""objtype, error, errmsg"""', "[('modelcube', AssertionError,\n 'ModelCubes require a release of MPL-5 and up'), ('spaxel',\n AssertionError,\n 'Parameters must include spaxelprop.x and y in order to convert to Marvin Spaxel'\n )]"], {'ids': "['mcminrelease', 'nospaxinfo']"}), "('objtype, error, errmsg', [('modelcube',\n AssertionError, 'ModelCubes require a release of MPL-5 and up'), (\n 'spaxel', AssertionError,\n 'Parameters must include spaxelprop.x and y in order to convert to Marvin Spaxel'\n )], ids=['mcminrelease', 'nospaxinfo'])\n", (16393, 16665), False, 'import pytest\n'), ((17400, 17462), 'marvin.tools.query.Query', 'Query', ([], {'search_filter': '"""nsa.z < 0.1"""', 'release': '"""MPL-4"""', 'mode': 'mode'}), "(search_filter='nsa.z < 0.1', release='MPL-4', mode=mode)\n", (17405, 17462), False, 'from marvin.tools.query import Query\n'), ((17682, 17744), 'marvin.tools.query.Query', 'Query', ([], {'search_filter': '"""nsa.z < 0.1"""', 'release': '"""MPL-4"""', 'mode': 'mode'}), "(search_filter='nsa.z < 0.1', release='MPL-4', mode=mode)\n", (17687, 17744), False, 'from marvin.tools.query import Query\n'), ((18344, 18447), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""chunk"""', '[None, 100, 20, 5]'], {'ids': "['none', 'chunk100', 'chunk20', 'chunk5']"}), "('chunk', [None, 100, 20, 5], ids=['none',\n 'chunk100', 'chunk20', 'chunk5'])\n", (18367, 18447), False, 'import pytest\n'), ((18667, 18770), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""chunk"""', '[None, 100, 20, 5]'], {'ids': "['none', 'chunk100', 'chunk20', 'chunk5']"}), "('chunk', [None, 100, 20, 5], ids=['none',\n 'chunk100', 'chunk20', 'chunk5'])\n", (18690, 18770), False, 'import pytest\n'), ((19262, 19378), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""chunk, iters"""', '[(None, 12), (100, 12), (500, 3)]'], {'ids': "['none', 'chunk100', 'chunk500']"}), "('chunk, iters', [(None, 12), (100, 12), (500, 3)],\n ids=['none', 'chunk100', 'chunk500'])\n", (19285, 19378), False, 'import pytest\n'), ((1617, 1727), 'pytest.xfail', 'pytest.xfail', (['"""cannot control for DAP spaxel queries on server side; failing all remotes until then"""'], {}), "(\n 'cannot control for DAP spaxel queries on server side; failing all remotes until then'\n )\n", (1629, 1727), False, 'import pytest\n'), ((2978, 2996), 'copy.copy', 'copy.copy', (['columns'], {}), '(columns)\n', (2987, 2996), False, 'import copy\n'), ((4478, 4523), 'marvin.tools.results.marvintuple', 'marvintuple', (['"""ResultRow"""', '"""mangaid, plateifu"""'], {}), "('ResultRow', 'mangaid, plateifu')\n", (4489, 4523), False, 'from marvin.tools.results import Results, ResultSet, marvintuple\n'), ((4538, 4570), 'marvin.tools.results.marvintuple', 'marvintuple', (['"""ResultRow"""', 'params'], {}), "('ResultRow', params)\n", (4549, 4570), False, 'from marvin.tools.results import Results, ResultSet, marvintuple\n'), ((6767, 6782), 'json.loads', 'json.loads', (['res'], {}), '(res)\n', (6777, 6782), False, 'import json\n'), ((7986, 8122), 'marvin.tools.query.Query', 'Query', ([], {'search_filter': 'results.search_filter', 'mode': 'results.mode', 'limit': '(1)', 'release': 'results.release', 'return_params': 'results.return_params'}), '(search_filter=results.search_filter, mode=results.mode, limit=1,\n release=results.release, return_params=results.return_params)\n', (7991, 8122), False, 'from marvin.tools.query import Query\n'), ((17372, 17391), 'marvin.config.forceDbOff', 'config.forceDbOff', ([], {}), '()\n', (17389, 17391), False, 'from marvin import config\n'), ((17550, 17568), 'marvin.config.forceDbOn', 'config.forceDbOn', ([], {}), '()\n', (17566, 17568), False, 'from marvin import config\n'), ((17654, 17673), 'marvin.config.forceDbOff', 'config.forceDbOff', ([], {}), '()\n', (17671, 17673), False, 'from marvin import config\n'), ((17832, 17850), 'marvin.config.forceDbOn', 'config.forceDbOn', ([], {}), '()\n', (17848, 17850), False, 'from marvin import config\n'), ((2306, 2329), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (2319, 2329), False, 'import pytest\n'), ((3020, 3053), 'marvin.utils.datamodel.query.base.ParameterGroup', 'ParameterGroup', (['"""Columns"""', 'colmns'], {}), "('Columns', colmns)\n", (3034, 3053), False, 'from marvin.utils.datamodel.query.base import ParameterGroup\n'), ((10202, 10304), 'pytest.skip', 'pytest.skip', (['"""skipping now due to weird issue with local results not same as remote results"""'], {}), "(\n 'skipping now due to weird issue with local results not same as remote results'\n )\n", (10213, 10304), False, 'import pytest\n'), ((11003, 11105), 'pytest.skip', 'pytest.skip', (['"""skipping now due to weird issue with local results not same as remote results"""'], {}), "(\n 'skipping now due to weird issue with local results not same as remote results'\n )\n", (11014, 11105), False, 'import pytest\n'), ((12064, 12166), 'pytest.skip', 'pytest.skip', (['"""skipping now due to weird issue with local results not same as remote results"""'], {}), "(\n 'skipping now due to weird issue with local results not same as remote results'\n )\n", (12075, 12166), False, 'import pytest\n'), ((13218, 13320), 'pytest.skip', 'pytest.skip', (['"""skipping now due to weird issue with local results not same as remote results"""'], {}), "(\n 'skipping now due to weird issue with local results not same as remote results'\n )\n", (13229, 13320), False, 'import pytest\n'), ((16007, 16044), 'pytest.skip', 'pytest.skip', (['"""no modelcubes in mpl-4"""'], {}), "('no modelcubes in mpl-4')\n", (16018, 16044), False, 'import pytest\n'), ((16882, 16921), 'pytest.skip', 'pytest.skip', (['"""modelcubes in post mpl-4"""'], {}), "('modelcubes in post mpl-4')\n", (16893, 16921), False, 'import pytest\n'), ((16936, 16956), 'pytest.raises', 'pytest.raises', (['error'], {}), '(error)\n', (16949, 16956), False, 'import pytest\n'), ((4810, 4839), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (4823, 4839), False, 'import pytest\n')] |
#!/usr/bin/env python
# encoding: utf-8
#
# @Author: <NAME>, <NAME>, <NAME>
# @Date: Oct 25, 2017
# @Filename: base.py
# @License: BSD 3-Clause
# @Copyright: <NAME>, <NAME>, <NAME>
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from astropy import units as u
from marvin.utils.datamodel.maskbit import get_maskbits
from .base import DRPDataModel, DataCube, Spectrum, DRPDataModelList
spaxel_unit = u.Unit('spaxel', represents=u.pixel, doc='A spectral pixel', parse_strict='silent')
MPL4_datacubes = [
DataCube('flux', 'FLUX', 'WAVE', extension_ivar='IVAR',
extension_mask='MASK', unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
scale=1e-17, formats={'string': 'Flux'},
description='3D rectified cube')
]
MPL4_spectra = [
Spectrum('spectral_resolution', 'SPECRES', extension_wave='WAVE', extension_std='SPECRESD',
unit=u.Angstrom, scale=1, formats={'string': 'Median spectral resolution'},
description='Median spectral resolution as a function of wavelength '
'for the fibers in this IFU'),
]
MPL6_datacubes = [
DataCube('dispersion', 'DISP', 'WAVE', extension_ivar=None,
extension_mask='MASK', unit=u.Angstrom,
scale=1, formats={'string': 'Dispersion'},
description='Broadened dispersion solution (1sigma LSF)'),
DataCube('dispersion_prepixel', 'PREDISP', 'WAVE', extension_ivar=None,
extension_mask='MASK', unit=u.Angstrom,
scale=1, formats={'string': 'Dispersion pre-pixel'},
description='Broadened pre-pixel dispersion solution (1sigma LSF)')
]
MPL6_spectra = [
Spectrum('spectral_resolution_prepixel', 'PRESPECRES', extension_wave='WAVE',
extension_std='PRESPECRESD', unit=u.Angstrom, scale=1,
formats={'string': 'Median spectral resolution pre-pixel'},
description='Median pre-pixel spectral resolution as a function of '
'wavelength for the fibers in this IFU'),
]
MPL4 = DRPDataModel('MPL-4', aliases=['MPL4'],
datacubes=MPL4_datacubes,
spectra=MPL4_spectra,
bitmasks=get_maskbits('MPL-4'))
MPL5 = DRPDataModel('MPL-5', aliases=['MPL5'],
datacubes=MPL4_datacubes,
spectra=MPL4_spectra,
bitmasks=get_maskbits('MPL-5'))
MPL6 = DRPDataModel('MPL-6', aliases=['MPL6'],
datacubes=MPL4_datacubes + MPL6_datacubes,
spectra=MPL4_spectra + MPL6_spectra,
bitmasks=get_maskbits('MPL-6'))
datamodel = DRPDataModelList([MPL4, MPL5, MPL6])
| [
"marvin.utils.datamodel.maskbit.get_maskbits"
] | [((466, 554), 'astropy.units.Unit', 'u.Unit', (['"""spaxel"""'], {'represents': 'u.pixel', 'doc': '"""A spectral pixel"""', 'parse_strict': '"""silent"""'}), "('spaxel', represents=u.pixel, doc='A spectral pixel', parse_strict=\n 'silent')\n", (472, 554), True, 'from astropy import units as u\n'), ((2274, 2295), 'marvin.utils.datamodel.maskbit.get_maskbits', 'get_maskbits', (['"""MPL-4"""'], {}), "('MPL-4')\n", (2286, 2295), False, 'from marvin.utils.datamodel.maskbit import get_maskbits\n'), ((2462, 2483), 'marvin.utils.datamodel.maskbit.get_maskbits', 'get_maskbits', (['"""MPL-5"""'], {}), "('MPL-5')\n", (2474, 2483), False, 'from marvin.utils.datamodel.maskbit import get_maskbits\n'), ((2682, 2703), 'marvin.utils.datamodel.maskbit.get_maskbits', 'get_maskbits', (['"""MPL-6"""'], {}), "('MPL-6')\n", (2694, 2703), False, 'from marvin.utils.datamodel.maskbit import get_maskbits\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Component tests VM deployment in VPC network functionality
"""
#Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.lib.base import (VirtualMachine,
NetworkOffering,
VpcOffering,
VPC,
NetworkACL,
PrivateGateway,
StaticRoute,
Router,
Network,
Account,
ServiceOffering,
PublicIPAddress,
NATRule,
StaticNATRule,
Configurations)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
wait_for_cleanup,
get_free_vlan)
from marvin.lib.utils import (cleanup_resources, validateList)
from marvin.codes import *
from marvin.cloudstackAPI import rebootRouter
from marvin.cloudstackAPI import updateResourceCount
class Services:
"""Test IP count inn VPC network
"""
def __init__(self):
self.services = {
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended for unique
# username
"password": "password",
},
"service_offering": {
"name": "Tiny Instance",
"displaytext": "Tiny Instance",
"cpunumber": 1,
"cpuspeed": 100,
"memory": 128,
},
"network_offering": {
"name": 'VPC Network offering',
"displaytext": 'VPC Network off',
"guestiptype": 'Isolated',
"supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL',
"traffictype": 'GUEST',
"availability": 'Optional',
"useVpc": 'on',
"serviceProviderList": {
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"Lb": 'VpcVirtualRouter',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
},
},
"network_offering_no_lb": {
"name": 'VPC Network offering',
"displaytext": 'VPC Network off',
"guestiptype": 'Isolated',
"supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,UserData,StaticNat,NetworkACL',
"traffictype": 'GUEST',
"availability": 'Optional',
"useVpc": 'on',
"serviceProviderList": {
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
},
},
"vpc_offering": {
"name": 'VPC off',
"displaytext": 'VPC off',
"supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat',
},
"vpc": {
"name": "TestVPC",
"displaytext": "TestVPC",
"cidr": '10.0.0.1/24'
},
"network": {
"name": "Test Network",
"displaytext": "Test Network",
"netmask": '255.255.255.0',
"limit": 5,
# Max networks allowed as per hypervisor
# Xenserver -> 5, VMWare -> 9
},
"virtual_machine": {
"displayname": "Test VM",
"username": "root",
"password": "password",
"ssh_port": 22,
"hypervisor": 'XenServer',
# Hypervisor type should be same as
# hypervisor type of cluster
"privateport": 22,
"publicport": 22,
"protocol": 'TCP',
},
"ostype": 'CentOS 5.3 (64-bit)',
# Cent OS 5.3 (64 bit)
"timeout": 10,
"mode": 'advanced'
}
class TestIPResourceCountVPC(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestIPResourceCountVPC, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.vpc_off = VpcOffering.create(
cls.api_client,
cls.services["vpc_offering"]
)
cls.vpc_off.update(cls.api_client, state='Enabled')
cls._cleanup = [
cls.service_offering,
cls.vpc_off
]
return
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account]
return
def tearDown(self):
try:
#Clean up, terminate the created network offerings
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def validate_vpc_offering(self, vpc_offering):
"""Validates the VPC offering"""
self.debug("Check if the VPC offering is created successfully?")
vpc_offs = VpcOffering.list(
self.apiclient,
id=vpc_offering.id
)
self.assertEqual(
isinstance(vpc_offs, list),
True,
"List VPC offerings should return a valid list"
)
self.assertEqual(
vpc_offering.name,
vpc_offs[0].name,
"Name of the VPC offering should match with listVPCOff data"
)
self.debug(
"VPC offering is created successfully - %s" %
vpc_offering.name)
return
def validate_vpc_network(self, network, state=None):
"""Validates the VPC network"""
self.debug("Check if the VPC network is created successfully?")
vpc_networks = VPC.list(
self.apiclient,
id=network.id
)
self.assertEqual(
isinstance(vpc_networks, list),
True,
"List VPC network should return a valid list"
)
self.assertEqual(
network.name,
vpc_networks[0].name,
"Name of the VPC network should match with listVPC data"
)
if state:
self.assertEqual(
vpc_networks[0].state,
state,
"VPC state should be '%s'" % state
)
self.debug("VPC network validated - %s" % network.name)
return
def updateIPCount(self):
cmd=updateResourceCount.updateResourceCountCmd()
cmd.account=self.account.name
cmd.domainid=self.domain.id
responce=self.apiclient.updateResourceCount(cmd)
def acquire_publicip(self, network, vpc):
self.debug("Associating public IP for network: %s" % network.name)
public_ip = PublicIPAddress.create(self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=vpc.id
)
self.debug("Associated {} with network {}".format(public_ip.ipaddress.ipaddress, network.id))
return public_ip
@attr(tags=["advanced", "intervlan"], required_hardware="false")
def test_01_ip_resouce_count_vpc_network(self):
""" Test IP count in VPC networks
"""
self.debug("Creating a VPC offering..")
vpc_off = VpcOffering.create(
self.apiclient,
self.services["vpc_offering"]
)
self.validate_vpc_offering(vpc_off)
self.debug("Enabling the VPC offering created")
vpc_off.update(self.apiclient, state='Enabled')
self.debug("creating a VPC network in the account: %s" %
self.account.name)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
nw_off = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
# Enable Network offering
nw_off.update(self.apiclient, state='Enabled')
self._cleanup.append(nw_off)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" % nw_off.id)
network_1 = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=nw_off.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Created network with ID: %s" % network_1.id)
account_list = Account.list(self.apiclient, id=self.account.id)
totalip_1 = account_list[0].iptotal
self.debug("Total IP: %s" % totalip_1)
public_ip_1 = self.acquire_publicip(network_1, vpc)
public_ip_2 = self.acquire_publicip(network_1, vpc)
public_ip_3 = self.acquire_publicip(network_1, vpc)
account_list = Account.list(self.apiclient, id=self.account.id)
totalip = account_list[0].iptotal
self.debug("Total IP: %s" % totalip)
self.assertTrue(totalip - totalip_1 == 3,"publicip count is 3")
self.updateIPCount()
account_list = Account.list(self.apiclient, id=self.account.id)
totalip = account_list[0].iptotal
self.assertTrue(totalip - totalip_1 == 3, "publicip count is 3")
| [
"marvin.lib.base.VpcOffering.create",
"marvin.lib.base.VpcOffering.list",
"marvin.lib.base.Network.create",
"marvin.lib.base.Account.create",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.common.get_domain",
"marvin.cloudstackAPI.updateResourceCount.updateResourceCountCmd",
"marvin.lib.base.Public... | [((10203, 10266), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'intervlan'], required_hardware='false')\n", (10207, 10266), False, 'from nose.plugins.attrib import attr\n'), ((6006, 6032), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (6016, 6032), False, 'from marvin.lib.common import get_domain, get_zone, get_template, wait_for_cleanup, get_free_vlan\n'), ((6134, 6199), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (6146, 6199), False, 'from marvin.lib.common import get_domain, get_zone, get_template, wait_for_cleanup, get_free_vlan\n'), ((6412, 6484), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (6434, 6484), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((6541, 6605), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['cls.api_client', "cls.services['vpc_offering']"], {}), "(cls.api_client, cls.services['vpc_offering'])\n", (6559, 6605), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((7242, 7339), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (7256, 7339), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((7914, 7966), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'id': 'vpc_offering.id'}), '(self.apiclient, id=vpc_offering.id)\n', (7930, 7966), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((8643, 8682), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'network.id'}), '(self.apiclient, id=network.id)\n', (8651, 8682), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((9335, 9379), 'marvin.cloudstackAPI.updateResourceCount.updateResourceCountCmd', 'updateResourceCount.updateResourceCountCmd', ([], {}), '()\n', (9377, 9379), False, 'from marvin.cloudstackAPI import updateResourceCount\n'), ((9654, 9819), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': 'vpc.id'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=vpc.id)\n', (9676, 9819), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((10439, 10504), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (10457, 10504), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((10868, 11031), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (10878, 11031), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((11163, 11260), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (11185, 11260), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((11589, 11800), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'nw_off.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=nw_off.\n id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (11603, 11800), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((11986, 12034), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'id': 'self.account.id'}), '(self.apiclient, id=self.account.id)\n', (11998, 12034), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((12331, 12379), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'id': 'self.account.id'}), '(self.apiclient, id=self.account.id)\n', (12343, 12379), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((12594, 12642), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'id': 'self.account.id'}), '(self.apiclient, id=self.account.id)\n', (12606, 12642), False, 'from marvin.lib.base import VirtualMachine, NetworkOffering, VpcOffering, VPC, NetworkACL, PrivateGateway, StaticRoute, Router, Network, Account, ServiceOffering, PublicIPAddress, NATRule, StaticNATRule, Configurations\n'), ((6915, 6962), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (6932, 6962), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((7560, 7607), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (7577, 7607), False, 'from marvin.lib.utils import cleanup_resources, validateList\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import time
from marvin.cloudstackAPI import updateConfiguration
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.sshClient import SshClient
from nose.plugins.attrib import attr
class TestHumanReadableLogs(cloudstackTestCase):
"""
Test correct output when logging byte size values.
"""
def setUp(self):
self.apiClient = self.testClient.getApiClient()
self.mgtSvrDetails = self.config.__dict__["mgtSvr"][0].__dict__
@attr(tags=["devcloud", "basic", "advanced"], required_hardware="false")
def test_01_disableHumanReadableLogs(self):
"""
Test log file output after disabling human readable sizes feature
"""
#create ssh client
sshClient = getSSHClient(self)
# Disable feature
updateConfig(self, "false")
# Restart service
command = "systemctl restart cloudstack-management"
sshClient.execute(command)
# CapacityChecker runs as soon as management server is up
# Check if "usedMem: (" is printed out within 60 seconds while server is starting
command = "timeout 60 tail -f /var/log/cloudstack/management/management-server.log | grep 'usedMem: ('"
sshClient.timeout = 60
result = sshClient.runCommand(command)
self.assertTrue(result['status'] == "FAILED")
@attr(tags=["devcloud", "basic", "advanced"], required_hardware="false")
def test_02_enableHumanReadableLogs(self):
"""
Test log file output after enabling human readable sizes feature
"""
# create ssh client
sshClient = getSSHClient(self)
# Enable feature
updateConfig(self, "true")
# Restart service
command = "systemctl restart cloudstack-management"
sshClient.execute(command)
# CapacityChecker runs as soon as management server is up
# Check if "usedMem: (" is printed out within 60 seconds while server is restarting
command = "timeout 120 tail -f /var/log/cloudstack/management/management-server.log | grep 'usedMem: ('"
sshClient.timeout = 120
result = sshClient.runCommand(command)
if result['status'] == "SUCCESS":
pass
else:
self.warn("We're not sure if test didn't pass due to timeout, so skipping failing the test")
def updateConfig(self, enableFeature):
updateConfigurationCmd = updateConfiguration.updateConfigurationCmd()
updateConfigurationCmd.name = "display.human.readable.sizes"
updateConfigurationCmd.value = enableFeature
updateConfigurationResponse = self.apiClient.updateConfiguration(updateConfigurationCmd)
self.debug("updated the parameter %s with value %s" % (
updateConfigurationResponse.name, updateConfigurationResponse.value))
def getSSHClient(self):
sshClient = SshClient(
self.mgtSvrDetails["mgtSvrIp"],
22,
self.mgtSvrDetails["user"],
self.mgtSvrDetails["passwd"]
)
return sshClient
| [
"marvin.sshClient.SshClient",
"marvin.cloudstackAPI.updateConfiguration.updateConfigurationCmd"
] | [((1263, 1334), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'basic', 'advanced']", 'required_hardware': '"""false"""'}), "(tags=['devcloud', 'basic', 'advanced'], required_hardware='false')\n", (1267, 1334), False, 'from nose.plugins.attrib import attr\n'), ((2139, 2210), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'basic', 'advanced']", 'required_hardware': '"""false"""'}), "(tags=['devcloud', 'basic', 'advanced'], required_hardware='false')\n", (2143, 2210), False, 'from nose.plugins.attrib import attr\n'), ((3203, 3247), 'marvin.cloudstackAPI.updateConfiguration.updateConfigurationCmd', 'updateConfiguration.updateConfigurationCmd', ([], {}), '()\n', (3245, 3247), False, 'from marvin.cloudstackAPI import updateConfiguration\n'), ((3635, 3742), 'marvin.sshClient.SshClient', 'SshClient', (["self.mgtSvrDetails['mgtSvrIp']", '(22)', "self.mgtSvrDetails['user']", "self.mgtSvrDetails['passwd']"], {}), "(self.mgtSvrDetails['mgtSvrIp'], 22, self.mgtSvrDetails['user'],\n self.mgtSvrDetails['passwd'])\n", (3644, 3742), False, 'from marvin.sshClient import SshClient\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for Persistent Networks without running VMs feature"""
from marvin.lib.utils import (cleanup_resources,
validateList,
get_hypervisor_type)
from marvin.lib.base import (Account,
VPC,
VirtualMachine,
LoadBalancerRule,
Network,
Domain,
Router,
NetworkACL,
PublicIPAddress,
VpcOffering,
ServiceOffering,
Project,
NetworkOffering,
NATRule,
FireWallRule,
Host,
StaticNATRule)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
verifyNetworkState,
add_netscaler,
wait_for_cleanup)
from nose.plugins.attrib import attr
from marvin.codes import PASS, FAIL, FAILED
from marvin.sshClient import SshClient
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from ddt import ddt, data
import time
@ddt
class TestPersistentNetworks(cloudstackTestCase):
'''
Test Persistent Networks without running VMs
'''
@classmethod
def setUpClass(cls):
cls.testClient = super(TestPersistentNetworks, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.isolated_persistent_network_offering = cls.createNetworkOffering("nw_off_isolated_persistent")
cls.isolated_persistent_network_offering_netscaler = cls.createNetworkOffering("nw_off_isolated_persistent_netscaler")
cls.isolated_persistent_network_offering_RVR = cls.createNetworkOffering("nw_off_persistent_RVR")
cls.isolated_network_offering = cls.createNetworkOffering("isolated_network_offering")
cls.isolated_network_offering_netscaler = cls.createNetworkOffering("nw_off_isolated_netscaler")
# Configure Netscaler device
# If configuration succeeds, set ns_configured to True so that Netscaler tests are executed
cls.ns_configured = False
try:
cls.netscaler = add_netscaler(cls.api_client, cls.zone.id, cls.services["netscaler_VPX"])
cls._cleanup.append(cls.netscaler)
cls.ns_configured = True
except Exception:
cls.ns_configured = False
# network will be deleted as part of account cleanup
cls._cleanup = [
cls.account, cls.service_offering, cls.isolated_persistent_network_offering, cls.isolated_network_offering,
cls.isolated_persistent_network_offering_RVR, cls.isolated_persistent_network_offering_netscaler,
cls.isolated_network_offering_netscaler
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def createNetworkOffering(cls, network_offering_type):
network_offering = NetworkOffering.create(
cls.api_client,
cls.services[network_offering_type],
conservemode=False
)
# Update network offering state from disabled to enabled.
NetworkOffering.update(network_offering, cls.api_client, id=network_offering.id,
state="enabled")
return network_offering
def checkRouterAccessibility(self, router):
"""Check if router is accessible through its linklocalip"""
hypervisor = str(get_hypervisor_type(self.api_client))
if hypervisor.lower() in ('vmware', 'hyperv'):
#SSH is done via management server for Vmware and Hyper-V
sourceip = self.api_client.connection.mgtSvr
else:
#For others, we will have to get the ipaddress of host connected to vm
hosts = Host.list(self.api_client,id=router.hostid)
self.assertEqual(validateList(hosts)[0], PASS, "hosts list validation failed, list is %s" % hosts)
host = hosts[0]
sourceip = host.ipaddress
# end else
try:
sshClient = SshClient(host=sourceip, port=22, user='root',passwd=self.services["host_password"])
res = sshClient.execute("ping -c 1 %s" % (
router.linklocalip
))
self.debug("SSH result: %s" % res)
except Exception as e:
self.fail("SSH Access failed for %s: %s" % \
(sourceip, e)
)
result = str(res)
self.assertEqual(
result.count("1 received"),
1,
"Ping to router should be successful"
)
return
def verifyVmExpungement(self, virtual_machine):
"""verify if vm is expunged"""
isVmExpunged = False
# Verify if it is expunged
retriesCount = 20
while True:
vms = VirtualMachine.list(self.api_client, id=virtual_machine.id)
# When vm is expunged, list will be None
if vms is None:
isVmExpunged = True
break
elif retriesCount == 0:
break
time.sleep(60)
retriesCount -= 1
# end while
if not isVmExpunged:
self.fail("Failed to expunge vm even after 20 minutes")
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = [ ]
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
self.cleanup[:] = []
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced"], required_hardware="false")
def test_network_state_after_destroying_vms(self):
# steps
# 1. Create an isolated persistent network
# 2. Deploy virtual machine in network
# 3. destroy created virtual machine
#
# validation
# 1. Persistent network state should be implemented before VM creation and have some vlan assigned
# 2. virtual machine should be created successfully
# 3. Network state should be implemented even after destroying all vms in network
# Creating isolated persistent network
network = Network.create(self.apiclient,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=self.account.name,domainid=self.domain.id,
zoneid=self.zone.id)
self.cleanup.append(network)
response = verifyNetworkState(self.apiclient, network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(network.vlan, "vlan must not be null for persistent network")
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[network.id],serviceofferingid=self.service_offering.id,
accountid=self.account.name,domainid=self.domain.id)
virtual_machine.delete(self.apiclient)
except Exception as e:
self.fail("vm creation failed: %s" % e)
# Verify VM is expunged
self.verifyVmExpungement(virtual_machine)
# wait for time such that, network is cleaned up
# assuming that it will change its state to allocated after this much period
wait_for_cleanup(self.api_client, ["network.gc.interval", "network.gc.wait"])
verifyNetworkState(self.api_client, network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
return
@attr(tags=["advanced"], required_hardware="false")
def test_shared_network_offering_with_persistent(self):
# steps
# 1. create shared network offering with persistent field enabled
#
# validation
# 1. network offering should throw an exception
try:
shared_persistent_network_offering = self.createNetworkOffering("nw_offering_shared_persistent")
shared_persistent_network_offering.delete(self.apiclient)
self.fail("Shared network got created with ispersistent flag True in the offering, it should have failed")
except Exception:
pass
@attr(tags=["advanced"])
def test_persistent_network_offering_with_VPCVR_services(self):
# steps
# 1. create network offering with persistent field enabled and all the services through VpcVirtualRouter
#
# validation
# 1. network offering should be created successfully
try:
persistent_network_offering_VPCVR = self.createNetworkOffering("nw_off_persistent_VPCVR_LB")
persistent_network_offering_VPCVR.delete(self.apiclient)
except Exception as e:
self.fail("Failed creating persistent network offering with VPCVR services: %s" % e)
@attr(tags=["advanced"])
def test_list_persistent_network_offering(self):
# steps
# 1. create isolated network offering with ispersistent True
# 2. List network offerings by id and check ispersistent flag
#
# validation
# 1. ispersistent flag should list as True
network_offering = self.createNetworkOffering("nw_off_isolated_persistent")
self.cleanup.append(network_offering)
nw_offering_list = NetworkOffering.list(self.api_client, id=network_offering.id)
self.assertEqual(validateList(nw_offering_list)[0], PASS, "network offerings' list validation failed, list is %s" %
nw_offering_list)
self.assertEqual(nw_offering_list[0].ispersistent, True, "ispersistent flag should be true for the network offering")
return
@data("LB-VR","LB-NS")
@attr(tags=["advanced","advancedns"])
def test_upgrade_to_persistent_services_VR(self, value):
# This test is run against two networks (one with LB as virtual router and other one is LB with Netscaler)
# All other services through VR
# steps
# 1. create isolated network with network offering which has ispersistent field disabled
# 2. upgrade isolated network offering to network offering which has ispersistent field enabled
# 3. Deploy VM ,acquire IP, create Firewall, NAT rules
# 4. Verify the working of NAT, Firewall rules
# 5. Delete VM
# 6. Verify network state after network cleanup interval
#
# validation
# 1. update of network should happen successfully
# 2. NAT and Firewall rule should work as expected
# 3. After network clenaup interval, network state should be implemented and have some vlan assigned
# Set network offering as required (either LB through VR or LB through Netscaler)
networkOffering = self.isolated_network_offering
changecidr = False # This will be true in case of Netscaler case, you have to change cidr while updating network
# In case Netscaler is used for LB
if value == "LB-NS":
if self.ns_configured:
networkOffering = self.isolated_network_offering_netscaler
changecidr = True
else:
self.skipTest("Skipping - this test required netscaler configured in the network")
# Create Account
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
# create network with the appropriate offering (not persistent)
isolated_network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=networkOffering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
response = verifyNetworkState(self.api_client, isolated_network.id, "allocated")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
# Update the network with persistent network offering
isolated_network.update(self.apiclient, networkofferingid=self.isolated_persistent_network_offering.id, changecidr=changecidr)
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[isolated_network.id],
serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
# Acquire public ip and open firewall for it
self.debug("Associating public IP for network: %s" % isolated_network.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_network.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
# Create NAT rule
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress.ipaddress.id,
networkid=isolated_network.id)
# Check if SSH works
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
# Delete VM
virtual_machine.delete(self.api_client)
# Verify VM is expunged
self.verifyVmExpungement(virtual_machine)
# wait for time such that, network is cleaned up
wait_for_cleanup(self.api_client, ["network.gc.interval", "network.gc.wait"])
# Check network state now, this will bolster that network updation has taken effect
response = verifyNetworkState(self.api_client, isolated_network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
return
@attr(tags=["advanced"])
def test_upgrade_network_VR_to_PersistentRVR(self):
# steps
# 1. create isolated network with network offering which has ispersistent field disabled (services through VR)
# 2. upgrade isolated network offering to network offering which has ispersistent field enabled (with RVR)
# 3. Deploy VM ,acquire IP, create Firewall, NAT rules
# 4. Verify the working of NAT, Firewall rules
# 5. Delete VM
# 6. Verify network state after network cleanup interval
#
# validation
# 1. update of network should happen successfully
# 2. NAT and Firewall rule should work as expected
# 3. After network clenaup interval, network state should be implemented and have some vlan assigned
# Create Account and isolated network in it
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
isolated_network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
response = verifyNetworkState(self.api_client, isolated_network.id, "allocated")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
# Update network with network offering which has RVR
isolated_network.update(self.apiclient, networkofferingid=self.isolated_persistent_network_offering_RVR.id)
# Deploy VM
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[isolated_network.id],
serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
# Acquire public IP and open firewall rule, create NAT rule
self.debug("Associating public IP for network: %s" % isolated_network.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_network.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress.ipaddress.id,
networkid=isolated_network.id)
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
virtual_machine.delete(self.api_client)
# Verify VM is expunged
self.verifyVmExpungement(virtual_machine)
# wait for time such that, network is cleaned up
wait_for_cleanup(self.api_client, ["network.gc.interval", "network.gc.wait"])
# Check network state now, this will bolster that network updation has taken effect
response = verifyNetworkState(self.api_client, isolated_network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
return
@attr(tags=["advanced", "advancedns"])
def test_upgrade_network_NS_to_persistent_NS(self):
# steps
# 1. create isolated network with network offering which has ispersistent field disabled
# and LB service through Netscaler
# 2. upgrade isolated network offering to network offering which has ispersistent field enabled
# and LB service through Netscaler
# 3. Deploy VM ,acquire IP, create Firewall, NAT rules
# 4. Verify the working of NAT, Firewall rules
# 5. Delete VM
# 6. Verify network state after network cleanup interval
#
# validation
# 1. update of network should happen successfully
# 2. NAT and Firewall rule should work as expected
# 3. After network clenaup interval, network state should be implemented and have some vlan assigned
# Skip test if Netscaler is not configured
if not self.ns_configured:
self.skipTest("Skipping - this test required netscaler configured in the network")
# Create Account and create isolated network in it
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
isolated_network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_network_offering_netscaler.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
response = verifyNetworkState(self.api_client, isolated_network.id, "allocated")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
isolated_network.update(self.apiclient, networkofferingid=self.isolated_persistent_network_offering_netscaler.id, changecidr=True)
# Deploy VM
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[isolated_network.id],
serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
self.debug("Associating public IP for network: %s" % isolated_network.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_network.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress.ipaddress.id,
networkid=isolated_network.id)
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
virtual_machine.delete(self.api_client)
# Verify VM is expunged
self.verifyVmExpungement(virtual_machine)
# wait for time such that, network is cleaned up
wait_for_cleanup(self.api_client, ["network.gc.interval", "network.gc.wait"])
# Check network state now, this will bolster that network updation has taken effect
response = verifyNetworkState(self.api_client, isolated_network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
return
@data("LB-VR","LB-Netscaler")
@attr(tags=["advanced", "advancedns"])
def test_pf_nat_rule_persistent_network(self, value):
# This test shall run with two scenarios, one with LB services through VR and other through LB service
# through Netscaler"""
# steps
# 1. create isolated network with network offering which has ispersistent field enabled
# and LB service through VR or Netscaler
# 2. Check routers belonging to network and verify that router is reachable through host using linklocalip
# 3. Deploy VM ,acquire IP, create Firewall, NAT rules
# 4. Verify the working of NAT, Firewall rules
#
# validation
# 1. Router should be reachable
# 2. NAT and Firewall rule should work as expected
# Set network offering according to data passed to test case
networkOffering = self.isolated_persistent_network_offering
if value == "LB-Netscaler":
if self.ns_configured:
networkOffering = self.isolated_persistent_network_offering_netscaler
else:
self.skipTest("Skipping - this test required netscaler configured in the network")
# Create account and network in it
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
isolated_persistent_network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=networkOffering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
self.assertEqual(str(isolated_persistent_network.state).lower(), "implemented", "network state should be implemented, it is %s" \
% isolated_persistent_network.state)
self.assertIsNotNone(isolated_persistent_network.vlan, "vlan must not be null for persistent network")
# Check if router is assigned to the persistent network
routers = Router.list(self.api_client, account=account.name,
domainid=account.domainid,
networkid=isolated_persistent_network.id)
self.assertEqual(validateList(routers)[0], PASS, "Routers list validation failed, list is %s" % routers)
router = routers[0]
# Check if router if reachable from the host
self.checkRouterAccessibility(router)
# Deploy VM in the network
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[isolated_persistent_network.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
# Acquire IP address, create Firewall, NAT rule
self.debug("Associating public IP for network: %s" % isolated_persistent_network.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_persistent_network.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress.ipaddress.id,
networkid=isolated_persistent_network.id)
# Check working of PF, NAT rules
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
return
@attr(tags=["advanced"])
def test_persistent_network_with_RVR(self):
# steps
# 1. create account and isolated network with network offering which has ispersistent field enabled
# and supporting Redundant Virtual Router in it
# 2. Check the Master and Backup Routers are present
# 3. Deploy VM ,acquire IP, create Firewall, NAT rules
# 4. Verify the working of NAT, Firewall rules
#
# validation
# 1. Two routers should belong to the network amd they should be reachable from host
# 2. NAT and Firewall rule should work as expected
# Create account and create isolated persistent network with RVR in it
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
# Create isolated persistent network with RVR
isolated_persistent_network_RVR = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering_RVR.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
self.assertEqual(str(isolated_persistent_network_RVR.state).lower(), "implemented", "network state should be implemented, it is %s" \
% isolated_persistent_network_RVR.state)
self.assertIsNotNone(isolated_persistent_network_RVR.vlan, "vlan must not be null for persistent network")
# Check if two routers belong to the network
self.debug("Listing routers for network: %s" % isolated_persistent_network_RVR.name)
routers = Router.list(self.api_client, listall=True,
networkid=isolated_persistent_network_RVR.id)
self.assertEqual(validateList(routers)[0], PASS, "Routers list validation failed, list is %s" % routers)
self.assertEqual(len(routers), 2, "Length of the list router should be 2 (Backup & master)")
# Check if routers are reachable from the host
for router in routers:
self.checkRouterAccessibility(router)
# Deploy VM
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[isolated_persistent_network_RVR.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
# Acquire public ip, create Firewall, NAT rule
self.debug("Associating public IP for network: %s" % isolated_persistent_network_RVR.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_persistent_network_RVR.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress.ipaddress.id,
networkid=isolated_persistent_network_RVR.id)
# Check if Firewall, NAT rule work as expected
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
return
@attr(tags=["advanced"])
def test_vm_deployment_two_persistent_networks(self):
# steps
# 1. Deploy VM in two persistent networks
# 2. Check working of NAT, Firewall rules in both the networks
#
# validation
# 1. VM should be deployed successfully in two networks
# 2. All network rules should work as expected
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
isolated_persistent_network_1 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
self.assertEqual(str(isolated_persistent_network_1.state).lower(), "implemented", "network state should be implemented, it is %s" \
% isolated_persistent_network_1.state)
self.assertIsNotNone(isolated_persistent_network_1.vlan, "vlan must not be null for persistent network")
isolated_persistent_network_2 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
self.assertEqual(str(isolated_persistent_network_2.state).lower(), "implemented", "network state should be implemented, it is %s" \
% isolated_persistent_network_2.state)
self.assertIsNotNone(isolated_persistent_network_2.vlan, "vlan must not be null for persistent network")
self.debug("Listing routers for network: %s" % isolated_persistent_network_1.name)
routers_nw_1 = Router.list(self.api_client, listall=True,
networkid=isolated_persistent_network_1.id)
self.assertEqual(validateList(routers_nw_1)[0], PASS, "Routers list validation failed, list is %s" % routers_nw_1)
# Check if router is reachable from the host
for router in routers_nw_1:
self.checkRouterAccessibility(router)
self.debug("Listing routers for network: %s" % isolated_persistent_network_2.name)
routers_nw_2 = Router.list(self.api_client, listall=True,
networkid=isolated_persistent_network_2.id)
self.assertEqual(validateList(routers_nw_2)[0], PASS, "Routers list validation failed, list is %s" % routers_nw_2)
# Check if router is reachable from the host
for router in routers_nw_2:
self.checkRouterAccessibility(router)
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[isolated_persistent_network_1.id, isolated_persistent_network_2.id],
serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
self.debug("Associating public IP for network: %s" % isolated_persistent_network_1.id)
ipaddress_nw_1 = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_persistent_network_1.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress_nw_1.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
self.debug("Associating public IP for network: %s" % isolated_persistent_network_2.id)
ipaddress_nw_2 = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_persistent_network_2.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress_nw_2.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress_nw_1.ipaddress.id,
networkid=isolated_persistent_network_1.id)
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress_nw_1.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress_nw_1.ipaddress.ipaddress))
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress_nw_2.ipaddress.id,
networkid=isolated_persistent_network_2.id)
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress_nw_2.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress_nw_2.ipaddress.ipaddress))
return
@attr(tags=["advanced"])
def test_vm_deployment_persistent_and_non_persistent_networks(self):
# steps
# 1. create account and create two networks in it (persistent and non persistent)
# 2. Deploy virtual machine in these two networks
# 3. Associate ip address with both the accounts and create firewall,port forwarding rule
# 4. Try to SSH to VM through both the IPs
#
# validation
# 1. Both persistent and non persistent networks should be created
# 2. virtual machine should be created successfully
# 3. SSH should be successful through both the IPs
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
network_1 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
self.assertEqual(str(network_1.state).lower(), "implemented", "network state should be implemented, it is %s" \
% network_1.state)
self.assertIsNotNone(network_1.vlan, "vlan must not be null for persistent network")
network_2 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[network_1.id, network_2.id],
serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
self.debug("Associating public IP for network: %s" % network_1.id)
ipaddress_nw_1 = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=network_1.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress_nw_1.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress_nw_1.ipaddress.id,
networkid=network_1.id)
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress_nw_1.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress_nw_1.ipaddress.ipaddress))
self.debug("Associating public IP for network: %s" % network_2.id)
ipaddress_nw_2 = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=network_2.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress_nw_2.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress_nw_2.ipaddress.id,
networkid=network_2.id)
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress_nw_2.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress_nw_2.ipaddress.ipaddress))
return
@attr(tags=["advanced"])
def test_change_persistent_network_to_non_persistent(self):
# steps
# 1. Create a persistent network and deploy VM in it
# 2. Update network with non persistent network offering
# 3. Acquire IP, create NAT, firewall rules
# 4. Test NAT, Firewall rules
# 5. Delete VM
# 6. Check the network state after network clenaup interval
#
# validation
# 1. Network updation should be successful
# 2. Network rules should work as expected
# 3. Network state should be allocated after network cleanup interval
# Create account and create persistent network in it
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
self.assertEqual(str(network.state).lower(), "implemented", "network state should be implemented, it is %s" \
% network.state)
self.assertIsNotNone(network.vlan, "vlan must not be null for persistent network")
# Update network with non persistent network offering
network.update(self.apiclient, networkofferingid=self.isolated_network_offering.id)
# Deploy VM, acquire IP, create NAT, firewall rules
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[network.id],
serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
self.debug("Associating public IP for network: %s" % network.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=network.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress.ipaddress.id,
networkid=network.id)
# Verify working of network rules
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
# Delete VM
virtual_machine.delete(self.api_client)
# Verify VM is expunged
self.verifyVmExpungement(virtual_machine)
# wait for time such that, network is cleaned up
wait_for_cleanup(self.api_client, ["network.gc.interval", "network.gc.wait"])
# Check network state now, this will bolster that network updation has taken effect
response = verifyNetworkState(self.api_client, network.id, "allocated")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
return
@attr(tags=["advanced"])
def test_delete_account(self):
# steps
# 1. create persistent network and deploy VM in it
# 2. Deploy VM in it and acquire IP address, create NAT, firewall rules
# 3. Delete the account in which network is created
#
# validation
# 1. Persistent network state should be implemented before VM creation and have some vlan assigned
# 2. Network rules should work as expected
# 3. Network and IPs should be freed after account is deleted
account = Account.create(self.api_client, self.services["account"],domainid=self.domain.id)
network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[network.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
self.debug("Associating public IP for network: %s" % network.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=network.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
NATRule.create(self.api_client, virtual_machine,
self.services["natrule"],ipaddressid=ipaddress.ipaddress.id,
networkid=network.id)
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
# Delete the account
account.delete(self.api_client)
# Verify the resources belonging to account have been cleaned up
networks = Network.list(self.apiclient, id=network.id)
self.assertEqual(validateList(networks)[0], FAIL, "network list should be enmpty, it is %s" % networks)
public_ips = PublicIPAddress.list(self.apiclient, id=ipaddress.ipaddress.id)
self.assertEqual(validateList(public_ips)[0], FAIL, "Public Ip list be empty, it is %s" % public_ips)
return
@ddt
class TestAssignVirtualMachine(cloudstackTestCase):
"""Test Persistent Network creation with assigning VM to different account/domain
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestAssignVirtualMachine, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.isolated_persistent_network_offering = cls.createNetworkOffering("nw_off_isolated_persistent")
cls.isolated_persistent_network_offering_RVR = cls.createNetworkOffering("nw_off_persistent_RVR")
cls.persistent_network_offering_netscaler = cls.createNetworkOffering("nw_off_isolated_persistent_netscaler")
# Configure Netscaler device
# If configuration succeeds, set ns_configured to True so that Netscaler tests are executed
cls.ns_configured = False
try:
cls.netscaler = add_netscaler(cls.api_client, cls.zone.id, cls.services["netscaler_VPX"])
cls._cleanup.append(cls.netscaler)
cls.ns_configured = True
except Exception:
cls.ns_configured = False
# network will be deleted as part of account cleanup
cls._cleanup = [
cls.service_offering, cls.isolated_persistent_network_offering,
cls.isolated_persistent_network_offering_RVR,
cls.persistent_network_offering_netscaler
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def createNetworkOffering(cls, network_offering_type):
network_offering = NetworkOffering.create(
cls.api_client,
cls.services[network_offering_type],
conservemode=False
)
# Update network offering state from disabled to enabled.
NetworkOffering.update(network_offering, cls.api_client, id=network_offering.id,
state="enabled")
return network_offering
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = [ ]
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
self.cleanup[:] = []
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@data("VR","RVR","LB-NS")
@attr(tags=["advanced", "advancedns"])
def test_assign_vm_different_account_VR(self, value):
# This test shall be run with three types of persistent networks
# a) All services through VR
# b) LB service through Netscaler
# c) with Redundant Virtual Router facility
# steps
# 1. create two accounts (account1 and account2)
# 2. Create a persistent network (with VR/RVR/Netscaler-LB with VR services) in account1 and deploy VM in it with this network
# 3. Stop the VM and assign the VM to account2
#
# validation
# 1. Assign VM operation should be successful
# 2. New network should be created in the other account
# Create Accounts
account_1 = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
self.cleanup.append(account_1)
account_2 = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
self.cleanup.append(account_2)
# Set the network offering according to the test scenario (data passed to the test case
if value == "VR":
network_offering = self.isolated_persistent_network_offering
elif value == "RVR":
network_offering = self.isolated_persistent_network_offering_RVR
elif value == "LB-NS":
if self.ns_configured:
network_offering = self.persistent_network_offering_netscaler
else:
self.skipTest("This test requires netscaler to be configured in the network")
network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=network_offering.id,
accountid=account_1.name,domainid=self.domain.id,
zoneid=self.zone.id)
response = verifyNetworkState(self.api_client, network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(network.vlan, "vlan must not be null for persistent network")
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[network.id],
serviceofferingid=self.service_offering.id,
accountid=account_1.name,domainid=self.domain.id)
virtual_machine.stop(self.apiclient)
# Assign virtual machine to different account
virtual_machine.assign_virtual_machine(self.apiclient, account=account_2.name, domainid=self.domain.id)
# Start VM
virtual_machine.start(self.apiclient)
# Verify that new network is created in other account
networks = Network.list(self.apiclient, account=account_2.name, domainid = account_2.domainid)
self.assertEqual(validateList(networks)[0], PASS, "networks list validation failed, list is %s" % networks)
except Exception as e:
self.fail("Exception occured: %s" % e)
return
@ddt
class TestProjectAccountOperations(cloudstackTestCase):
"""Test suspend/disable/lock account/project operations when they have persistent network
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestProjectAccountOperations, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.isolated_persistent_network_offering = NetworkOffering.create(
cls.api_client,
cls.services["nw_off_isolated_persistent"],
conservemode=False
)
# Update network offering state from disabled to enabled.
cls.isolated_persistent_network_offering.update(cls.api_client, state="enabled")
# network will be deleted as part of account cleanup
cls._cleanup = [
cls.service_offering, cls.isolated_persistent_network_offering
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = [ ]
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
self.cleanup[:] = []
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@data("locked","disabled")
@attr(tags=["advanced"])
def test_account_operations(self, value):
# steps
# 1. create account and create persistent network in it
# 2. Disable/lock the account
#
# validation
# 3. Wait for network cleanup interval and verify that network is not cleaned up and it is still in
# implemented state
account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
response = verifyNetworkState(self.api_client, network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(network.vlan, "vlan must not be null for persistent network")
if value == "disabled":
account.disable(self.apiclient)
elif value == "locked":
account.disable(self.apiclient, lock=True)
accounts = Account.list(self.apiclient, id=account.id)
self.assertEqual(validateList(accounts)[0], PASS, "accounts list validation failed, list id %s" % accounts)
self.assertEqual(str(accounts[0].state).lower(), value, "account state should be %s, it is %s" % (value, accounts[0].state))
# Wait for network cleanup interval
wait_for_cleanup(self.api_client, ["network.gc.interval", "network.gc.wait"])
networks = Network.list(self.apiclient, account=account.name, domainid = account.domainid)
self.assertEqual(validateList(networks)[0], PASS, "networks list validation failed, list is %s" % networks)
response = verifyNetworkState(self.api_client, networks[0].id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(networks[0].vlan, "vlan must not be null for persistent network")
return
@attr(tags=["advanced"])
def test_project_operations(self):
# steps
# 1. create account and create persistent network in it
# 2. Add account to project
# 3. Suspend the project
#
# validation
# 1. Verify that account has been added to the project
# 2. Wait for network cleanup interval and verify that network is not cleaned up and it is still in
# implemented state
# Create Account
account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
# Create Project
project = Project.create(self.apiclient, self.services["project"])
self.cleanup.append(project)
network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
# Add account to the project
project.addAccount(self.apiclient, account = account.name)
# Verify the account name in the list of accounts belonging to the project
projectAccounts = Project.listAccounts(self.apiclient, projectid = project.id)
self.assertEqual(validateList(projectAccounts)[0], PASS, "project accounts list validation failed, list is %s" % projectAccounts)
accountNames = [projectAccount.account for projectAccount in projectAccounts]
self.assertTrue(account.name in accountNames, "account %s is not present in account list %s of project %s" %
(account.name, accountNames, project.id))
# Suspend Project
project.suspend(self.apiclient)
# Verify the project is suspended
projects = Project.list(self.apiclient, id=project.id)
self.assertEqual(validateList(projects)[0], PASS, "projects list validation failed, list is %s" % projects)
self.assertEqual(str(projects[0].state).lower(), "suspended", "project state should be suspended, it is %s" % projects[0].state)
# Wait for network cleanup interval
wait_for_cleanup(self.api_client, ["network.gc.interval", "network.gc.wait"])
response = verifyNetworkState(self.apiclient, network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
return
@ddt
class TestRestartPersistentNetwork(cloudstackTestCase):
"""Test restart persistent network with cleanup parameter true and false
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestRestartPersistentNetwork, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.isolated_persistent_network_offering = NetworkOffering.create(cls.api_client,
cls.services["nw_off_isolated_persistent_lb"],
conservemode=False)
cls.isolated_persistent_network_offering_netscaler = NetworkOffering.create(cls.api_client,
cls.services["nw_off_isolated_persistent_netscaler"],
conservemode=False)
# Update network offering state from disabled to enabled.
cls.isolated_persistent_network_offering.update(cls.api_client, state="enabled")
cls.isolated_persistent_network_offering_netscaler.update(cls.api_client, state="enabled")
# Configure Netscaler device
# If configuration succeeds, set ns_configured to True so that Netscaler tests are executed
cls.ns_configured = False
try:
cls.netscaler = add_netscaler(cls.api_client, cls.zone.id, cls.services["netscaler_VPX"])
cls._cleanup.append(cls.netscaler)
cls.ns_configured = True
except Exception:
cls.ns_configured = False
# network will be deleted as part of account cleanup
cls._cleanup = [
cls.service_offering, cls.isolated_persistent_network_offering,
cls.isolated_persistent_network_offering_netscaler
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = [ ]
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
self.cleanup[:] = []
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def checkRouterAccessibility(self, router):
"""Check if router is accessible through its linklocalip"""
hypervisor = str(get_hypervisor_type(self.api_client))
if hypervisor.lower() in ('vmware', 'hyperv'):
#SSH is done via management server for Vmware and Hyper-V
sourceip = self.api_client.connection.mgtSvr
else:
#For others, we will have to get the ipaddress of host connected to vm
hosts = Host.list(self.api_client,id=router.hostid)
self.assertEqual(validateList(hosts)[0], PASS, "hosts list validation failed, list is %s" % hosts)
host = hosts[0]
sourceip = host.ipaddress
# end else
try:
sshClient = SshClient(host=sourceip, port=22, user='root',passwd=self.services["host_password"])
res = sshClient.execute("ping -c 1 %s" % (
router.linklocalip
))
except Exception as e:
self.fail("SSH Access failed for %s: %s" % \
(sourceip, e)
)
result = str(res)
self.assertEqual(
result.count("1 received"),
1,
"ping to router should be successful"
)
return
@data("true","false")
@attr(tags=["advanced"])
def test_cleanup_persistent_network(self, value):
# steps
# 1. Create account and create persistent network in it
# 2. Verify that router is reachable from the host
# 3. Acquire public IP, open firewall and create LB rule
# 4. Restart the network with clenup parameter true/false
# 5. Check network state after restart, it should be implemented
# 6. Deploy VM, assign LB rule to it, and verify the LB rule
account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
isolated_persistent_network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
response = verifyNetworkState(self.apiclient, isolated_persistent_network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(isolated_persistent_network.vlan, "vlan must not be null for persistent network")
self.debug("Listing routers for network: %s" % isolated_persistent_network.name)
routers = Router.list(self.api_client, listall=True,
networkid=isolated_persistent_network.id)
self.assertEqual(validateList(routers)[0], PASS, "Routers list validation failed, list is %s" % routers)
# Check if router is reachable from the host
for router in routers:
self.checkRouterAccessibility(router)
self.debug("Associating public IP for network: %s" % isolated_persistent_network.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_persistent_network.id)
FireWallRule.create(self.apiclient,ipaddressid=ipaddress.ipaddress.id,
protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])
# Create LB Rule
lb_rule = LoadBalancerRule.create(self.apiclient,self.services["lbrule"],
ipaddressid=ipaddress.ipaddress.id, accountid=account.name,
networkid=isolated_persistent_network.id, domainid=account.domainid)
# Restart Network
isolated_persistent_network.restart(self.apiclient, cleanup=value)
# List networks
networks = Network.list(self.apiclient, account=account.name, domainid = account.domainid)
self.assertEqual(validateList(networks)[0], PASS, "networks list validation failed, list is %s" % networks)
verifyNetworkState(self.apiclient, networks[0].id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(networks[0].vlan, "vlan must not be null for persistent network")
# Deploy VM
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[isolated_persistent_network.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
lb_rule.assign(self.api_client, [virtual_machine])
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
return
@data("true","false")
@attr(tags=["advanced", "advancedns"])
def test_cleanup_persistent_network_lb_netscaler(self, value):
# steps
# 1. Create account and create persistent network in it with LB service provided by netscaler
# 2. Verify that router is reachable from the host
# 3. Acquire public IP, open firewall and create LB rule
# 4. Restart the network with clenup parameter true/false
# 5. Check network state after restart, it should be implemented
# 6. Deploy VM, assign LB rule to it, and verify the LB rule
if not self.ns_configured:
self.skipTest("This test required netscaler to be configured in the network")
account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
isolated_persistent_network = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.isolated_persistent_network_offering_netscaler.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id)
response = verifyNetworkState(self.apiclient, isolated_persistent_network.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(isolated_persistent_network.vlan, "vlan must not be null for persistent network")
self.debug("Listing routers for network: %s" % isolated_persistent_network.name)
routers = Router.list(self.api_client, listall=True,
networkid=isolated_persistent_network.id)
self.assertEqual(validateList(routers)[0], PASS, "Routers list validation failed, list is %s" % routers)
# Check if router is reachable from the host
for router in routers:
self.checkRouterAccessibility(router)
self.debug("Associating public IP for network: %s" % isolated_persistent_network.id)
ipaddress = PublicIPAddress.create(self.api_client,accountid=account.name,
zoneid=self.zone.id,domainid=account.domainid,
networkid=isolated_persistent_network.id)
# Create LB Rule
lb_rule = LoadBalancerRule.create(self.apiclient,self.services["lbrule"],
ipaddressid=ipaddress.ipaddress.id, accountid=account.name,
networkid=isolated_persistent_network.id, domainid=account.domainid)
# Restart Network
isolated_persistent_network.restart(self.apiclient, cleanup=value)
# List networks
networks = Network.list(self.apiclient, account=account.name, domainid = account.domainid)
self.assertEqual(validateList(networks)[0], PASS, "networks list validation failed, list is %s" % networks)
response = verifyNetworkState(self.apiclient, networks[0].id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(networks[0].vlan, "vlan must not be null for persistent network")
# Deploy VM
try:
virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[isolated_persistent_network.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
lb_rule.assign(self.api_client, [virtual_machine])
try:
virtual_machine.get_ssh_client(ipaddress=ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail("Exception while SSHing to VM %s with IP %s" % (virtual_machine.id, ipaddress.ipaddress.ipaddress))
return
@ddt
class TestVPCNetworkOperations(cloudstackTestCase):
"""Test VPC network operations consisting persistent networks
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestVPCNetworkOperations, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offerings"]["small"]
)
cls.persistent_network_offering_NoLB = NetworkOffering.create(cls.api_client, cls.services["nw_off_persistent_VPCVR_NoLB"],
conservemode=False)
# Update network offering state from disabled to enabled.
cls.persistent_network_offering_NoLB.update(cls.api_client, state="enabled")
cls.persistent_network_offering_LB = NetworkOffering.create(cls.api_client, cls.services["nw_off_persistent_VPCVR_LB"],
conservemode=False)
# Update network offering state from disabled to enabled.
cls.persistent_network_offering_LB.update(cls.api_client, state="enabled")
cls.vpc_off = VpcOffering.create(cls.api_client, cls.services["vpc_offering"])
cls.vpc_off.update(cls.api_client, state='Enabled')
# network will be deleted as part of account cleanup
cls._cleanup = [
cls.service_offering, cls.persistent_network_offering_NoLB, cls.vpc_off,
cls.persistent_network_offering_LB
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
self.cleanup[:] = []
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def GetAssociatedIpForNetwork(self, networkid, vpcid, account):
""" Associate IP address with the network and open firewall for it
return associated IPaddress"""
ipaddress = PublicIPAddress.create(self.api_client,zoneid=self.zone.id,networkid=networkid, vpcid=vpcid,
accountid=account.name, domainid=account.domainid)
return ipaddress
def CreateIngressEgressNetworkACLForNetwork(self, networkid):
try:
ingressAcl = NetworkACL.create(self.apiclient, networkid=networkid, services=self.services["natrule"], traffictype='Ingress')
egressAcl = NetworkACL.create(self.apiclient, networkid=networkid, services=self.services["icmprule"], traffictype='Egress')
except Exception as e:
self.fail("Failed while creating Network ACL rule for network %s with error %s" % (networkid,e))
return ingressAcl,egressAcl
def CheckIngressEgressConnectivityofVM(self, virtual_machine, ipaddress):
try:
ssh = SshClient(
ipaddress,
22,
virtual_machine.username,
virtual_machine.password
)
# Ping to outsite world
res = ssh.execute("ping -c 1 www.google.com")
# res = 64 bytes from maa03s17-in-f20.1e100.net (192.168.127.12):
# icmp_req=1 ttl=57 time=25.9 ms
# --- www.l.google.com ping statistics ---
# 1 packets transmitted, 1 received, 0% packet loss, time 0ms
# rtt min/avg/max/mdev = 25.970/25.970/25.970/0.000 ms
except Exception as e:
self.fail("SSH Access failed for vm %s with IP address %s: %s" % \
(virtual_machine.id,ipaddress, e))
result = str(res)
self.assertEqual(result.count("1 received"),1, "Ping to outside world from VM should be successful")
return
def VerifyNetworkCleanup(self, networkid):
"""Verify that network is cleaned up"""
networks=Network.list(self.apiclient,id=networkid)
self.assertEqual(validateList(networks)[0], FAIL, "networks list should be empty, it is %s" % networks)
return
def VerifyVpcCleanup(self, vpcid):
"""Verify that VPC is cleaned up"""
vpcs = VPC.list(self.apiclient,id=vpcid)
self.assertEqual(validateList(vpcs)[0], FAIL, "VPC list should be empty, it is %s" % vpcs)
return
def VerifyVirtualMachineCleanup(self, vmid):
"""Verify that virtual machine is cleaned up"""
vms=VirtualMachine.list(self.apiclient,id=vmid)
self.assertEqual(validateList(vms)[0], FAIL, "vms list should be empty, it is %s" % vms)
return
def VerifyAclRuleCleanup(self, aclRuleId):
"""Verify that network ACL rule is cleaned up"""
networkAcls=NetworkACL.list(self.apiclient,id=aclRuleId)
self.assertEqual(validateList(networkAcls)[0], FAIL, "networkAcls list should be empty, it is %s" % networkAcls)
return
@data("delete", "restart")
@attr(tags=["advanced"])
def test_vpc_network_life_cycle(self, value):
# steps
# 1. Create account and create VPC network in the account
# 2. Create two persistent networks within this VPC
# 3. Restart/delete VPC network
# Validations
# 1. In case of Restart operation, restart should be successful and persistent networks should be back in persistent state
# 2. In case of Delete operation, VR servicing the VPC should get destroyed and sourceNAT ip should get released
account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
self.services["vpc"]["cidr"] = "10.1.1.1/16"
self.debug("creating a VPC network in the account: %s" %
account.name)
vpc = VPC.create(self.apiclient, self.services["vpc"],
vpcofferingid=self.vpc_off.id, zoneid=self.zone.id,
account=account.name, domainid=account.domainid)
vpcs = VPC.list(self.apiclient, id=vpc.id)
self.assertEqual(validateList(vpcs)[0], PASS, "VPC list validation failed, vpc list is %s" % vpcs)
VpcRouters = Router.list(self.apiclient, vpcid = vpc.id, listall=True)
self.assertEqual(validateList(VpcRouters)[0], PASS, "VpcRouters list validation failed, list is %s" % VpcRouters)
vpcrouter = VpcRouters[0]
publicipaddresses = PublicIPAddress.list(self.apiclient, vpcid=vpc.id, listall=True)
self.assertEqual(validateList(publicipaddresses)[0], PASS, "Public IP Addresses list validation failed, list is %s" % publicipaddresses)
persistent_network_1 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.persistent_network_offering_NoLB.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id, vpcid=vpc.id, gateway="10.1.1.1", netmask="255.255.255.0")
response = verifyNetworkState(self.apiclient, persistent_network_1.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(persistent_network_1.vlan, "vlan must not be null for persistent network %s" % persistent_network_1.id)
persistent_network_2 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.persistent_network_offering_NoLB.id,
accountid=account.name,domainid=self.domain.id,
zoneid=self.zone.id, vpcid=vpc.id, gateway="10.1.2.1", netmask="255.255.255.0")
response = verifyNetworkState(self.apiclient, persistent_network_2.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(persistent_network_2.vlan, "vlan must not be null for persistent network: %s" % persistent_network_2.id)
if value == "restart":
# Restart VPC
vpc.restart(self.apiclient)
response = verifyNetworkState(self.apiclient, persistent_network_1.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
response = verifyNetworkState(self.apiclient, persistent_network_2.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
elif value == "delete":
persistent_network_1.delete(self.apiclient)
persistent_network_2.delete(self.apiclient)
vpc.delete(self.apiclient)
vpcs = VPC.list(self.apiclient, id=vpc.id)
self.assertEqual(validateList(vpcs)[0], FAIL, "vpc list should be empty, list is %s" % vpcs)
# Check if router is deleted or not
routers = Router.list(self.apiclient, id=vpcrouter.id)
self.assertEqual(validateList(routers)[0], FAIL, "routers list should be empty, it is %s" % routers)
# Check if source nat IP address is released
ipaddresses = PublicIPAddress.list(self.apiclient, id=publicipaddresses[0].id)
self.assertEqual(validateList(ipaddresses)[0], FAIL, "public ip addresses list should be empty, list is %s" % ipaddresses)
return
@attr(tags=["advanced"])
def test_vpc_force_delete_domain(self):
# steps
# 1. Create account and create VPC network in the account
# 2. Create two persistent networks within this VPC
# 3. Restart/delete VPC network
# Validations
# 1. In case of Restart operation, restart should be successful
# and persistent networks should be back in persistent state
# 2. In case of Delete operation, VR servicing the VPC should
# get destroyed and sourceNAT ip should get released
child_domain = Domain.create(self.apiclient,
services=self.services["domain"],
parentdomainid=self.domain.id)
try:
account_1 = Account.create(
self.apiclient,self.services["account"],
domainid=child_domain.id
)
account_2 = Account.create(
self.apiclient,self.services["account"],
domainid=child_domain.id
)
self.services["vpc"]["cidr"] = "10.1.1.1/16"
vpc_1 = VPC.create(self.apiclient, self.services["vpc"],
vpcofferingid=self.vpc_off.id, zoneid=self.zone.id,
account=account_1.name, domainid=account_1.domainid)
vpcs = VPC.list(self.apiclient, id=vpc_1.id)
self.assertEqual(validateList(vpcs)[0], PASS,\
"VPC list validation failed, vpc list is %s" % vpcs)
vpc_2 = VPC.create(self.apiclient, self.services["vpc"],
vpcofferingid=self.vpc_off.id, zoneid=self.zone.id,
account=account_2.name, domainid=account_2.domainid)
vpcs = VPC.list(self.apiclient, id=vpc_2.id)
self.assertEqual(validateList(vpcs)[0], PASS,\
"VPC list validation failed, vpc list is %s" % vpcs)
persistent_network_1 = Network.create(
self.api_client,self.services["isolated_network"],
networkofferingid=self.persistent_network_offering_NoLB.id,
accountid=account_1.name,domainid=account_1.domainid,
zoneid=self.zone.id, vpcid=vpc_1.id, gateway="10.1.1.1",
netmask="255.255.255.0")
response = verifyNetworkState(self.apiclient,
persistent_network_1.id,
"implemented"
)
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
raise Exception(exceptionMessage)
self.assertIsNotNone(
persistent_network_1.vlan,\
"vlan must not be null for persistent network %s" %\
persistent_network_1.id)
persistent_network_2 = Network.create(
self.api_client,self.services["isolated_network"],
networkofferingid=self.persistent_network_offering_NoLB.id,
accountid=account_2.name,domainid=account_2.domainid,
zoneid=self.zone.id, vpcid=vpc_2.id, gateway="10.1.1.1",
netmask="255.255.255.0")
response = verifyNetworkState(self.apiclient, persistent_network_2.id,
"implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
raise Exception(exceptionMessage)
self.assertIsNotNone(persistent_network_2.vlan,\
"vlan must not be null for persistent network: %s" %\
persistent_network_2.id)
# Force delete domain
child_domain.delete(self.apiclient, cleanup=True)
except Exception as e:
self.cleanup.append(account_1)
self.cleanup.append(account_2)
self.cleanup.append(child_domain)
self.fail(e)
self.debug("Waiting for account.cleanup.interval" +
" to cleanup any remaining resouces")
# Sleep 3*account.gc to ensure that all resources are deleted
wait_for_cleanup(self.apiclient, ["account.cleanup.interval"]*3)
with self.assertRaises(Exception):
Domain.list(self.apiclient,id=child_domain.id)
with self.assertRaises(Exception):
Account.list(
self.apiclient,name=account_1.name,
domainid=account_1.domainid,listall=True
)
with self.assertRaises(Exception):
Account.list(
self.apiclient,name=account_2.name,
domainid=account_2.domainid,listall=True
)
self.VerifyVpcCleanup(vpc_1.id)
self.VerifyVpcCleanup(vpc_2.id)
self.VerifyNetworkCleanup(persistent_network_1.id)
self.VerifyNetworkCleanup(persistent_network_2.id)
return
@attr(tags=["advanced"])
def test_vpc_delete_account(self):
# steps
# 1. Create account and create VPC network in the account
# 2. Create two persistent networks within this VPC
# 3. Restart/delete VPC network
# Validations
# 1. In case of Restart operation, restart should be successful and persistent networks should be back in persistent state
# 2. In case of Delete operation, VR servicing the VPC should get destroyed and sourceNAT ip should get released
try:
# Create Account
account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
# Create VPC
self.services["vpc"]["cidr"] = "10.1.1.1/16"
vpc = VPC.create(self.apiclient, self.services["vpc"],
vpcofferingid=self.vpc_off.id, zoneid=self.zone.id,
account=account.name, domainid=account.domainid)
vpcs = VPC.list(self.apiclient, id=vpc.id)
self.assertEqual(validateList(vpcs)[0], PASS, "VPC list validation failed, vpc list is %s" % vpcs)
# Create Persistent Networks as tiers of VPC
persistent_network_1 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.persistent_network_offering_NoLB.id,
accountid=account.name,domainid=account.domainid,
zoneid=self.zone.id, vpcid=vpc.id, gateway="10.1.1.1", netmask="255.255.255.0")
response = verifyNetworkState(self.apiclient, persistent_network_1.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
raise Exception(exceptionMessage)
self.assertIsNotNone(persistent_network_1.vlan, "vlan must not be null for persistent network %s" % persistent_network_1.id)
persistent_network_2 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.persistent_network_offering_LB.id,
accountid=account.name,domainid=account.domainid,
zoneid=self.zone.id, vpcid=vpc.id, gateway="10.1.2.1", netmask="255.255.255.0")
response = verifyNetworkState(self.apiclient, persistent_network_2.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
raise Exception(exceptionMessage)
self.assertIsNotNone(persistent_network_2.vlan, "vlan must not be null for persistent network: %s" % persistent_network_2.id)
# Deploy VMs in above networks (VM1, VM2 in network1 and VM3, VM4 in network2)
virtual_machine_1 = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[persistent_network_1.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
virtual_machine_2 = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[persistent_network_1.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
virtual_machine_3 = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[persistent_network_2.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
virtual_machine_4 = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[persistent_network_2.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
# Associate IP addresses to persistent networks
ipaddress_1 = self.GetAssociatedIpForNetwork(persistent_network_1.id, vpcid=vpc.id, account=account)
ipaddress_2 = self.GetAssociatedIpForNetwork(persistent_network_1.id, vpcid=vpc.id, account=account)
ipaddress_3 = self.GetAssociatedIpForNetwork(persistent_network_2.id, vpcid=vpc.id, account=account)
# Create NAT rule for VM 1
NATRule.create(self.api_client, virtual_machine_1,
self.services["natrule"],ipaddressid=ipaddress_1.ipaddress.id,
networkid=persistent_network_1.id)
# Create Static NAT rule for VM 2
StaticNATRule.enable(self.apiclient, ipaddressid=ipaddress_2.ipaddress.id,
virtualmachineid=virtual_machine_2.id,
networkid=persistent_network_1.id)
# Create load balancer rule for ipaddress3 and assign to VM3 and VM4
lb_rule = LoadBalancerRule.create(self.apiclient,self.services["lbrule"],
ipaddressid=ipaddress_3.ipaddress.id, accountid=account.name,
networkid=persistent_network_2.id, domainid=account.domainid)
lb_rule.assign(self.api_client, [virtual_machine_3, virtual_machine_4])
# Create network ACL for both ther persistent networks (tiers of VPC)
ingressAclNetwork1, egressAclNetwork1 = self.CreateIngressEgressNetworkACLForNetwork(persistent_network_1.id)
ingressAclNetwork2, egressAclNetwork2 = self.CreateIngressEgressNetworkACLForNetwork(persistent_network_2.id)
self.CheckIngressEgressConnectivityofVM(virtual_machine_1, ipaddress_1.ipaddress.ipaddress)
self.CheckIngressEgressConnectivityofVM(virtual_machine_2, ipaddress_2.ipaddress.ipaddress)
self.CheckIngressEgressConnectivityofVM(virtual_machine_3, ipaddress_3.ipaddress.ipaddress)
self.CheckIngressEgressConnectivityofVM(virtual_machine_4, ipaddress_3.ipaddress.ipaddress)
except Exception as e:
self.cleanup.append(account)
self.fail(e)
# Delete account
account.delete(self.apiclient)
# Verify all the resources owned by the account are deleted
self.debug("Waiting for account.cleanup.interval" +
" to cleanup any remaining resouces")
# Sleep 3*account.gc to ensure that all resources are deleted
wait_for_cleanup(self.apiclient, ["account.cleanup.interval"]*3)
self.VerifyVpcCleanup(vpc.id)
self.VerifyNetworkCleanup(persistent_network_1.id)
self.VerifyNetworkCleanup(persistent_network_2.id)
self.VerifyVirtualMachineCleanup(virtual_machine_1.id)
self.VerifyVirtualMachineCleanup(virtual_machine_2.id)
self.VerifyVirtualMachineCleanup(virtual_machine_3.id)
self.VerifyVirtualMachineCleanup(virtual_machine_4.id)
self.VerifyAclRuleCleanup(ingressAclNetwork1.id)
self.VerifyAclRuleCleanup(egressAclNetwork1.id)
self.VerifyAclRuleCleanup(ingressAclNetwork2.id)
self.VerifyAclRuleCleanup(egressAclNetwork2.id)
return
@unittest.skip("WIP")
@attr(tags=["advanced"])
def test_vpc_private_gateway_static_route(self):
# steps
# 1. Create account and create VPC network in the account
# 2. Create two persistent networks within this VPC
# 3. Restart/delete VPC network
# Validations
# 1. In case of Restart operation, restart should be successful and persistent networks should be back in persistent state
# 2. In case of Delete operation, VR servicing the VPC should get destroyed and sourceNAT ip should get released
# Create Account
account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
self.cleanup.append(account)
# Create VPC
self.services["vpc"]["cidr"] = "10.1.1.1/16"
vpc = VPC.create(self.apiclient, self.services["vpc"],
vpcofferingid=self.vpc_off.id, zoneid=self.zone.id,
account=account.name, domainid=account.domainid)
vpcs = VPC.list(self.apiclient, id=vpc.id)
self.assertEqual(validateList(vpcs)[0], PASS, "VPC list validation failed, vpc list is %s" % vpcs)
# Create Persistent Networks as tiers of VPC
persistent_network_1 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.persistent_network_offering_NoLB.id,
accountid=account.name,domainid=account.domainid,
zoneid=self.zone.id, vpcid=vpc.id, gateway="10.1.1.1", netmask="255.255.255.0")
response = verifyNetworkState(self.apiclient, persistent_network_1.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(persistent_network_1.vlan, "vlan must not be null for persistent network %s" % persistent_network_1.id)
persistent_network_2 = Network.create(self.api_client,self.services["isolated_network"],
networkofferingid=self.persistent_network_offering_LB.id,
accountid=account.name,domainid=account.domainid,
zoneid=self.zone.id, vpcid=vpc.id, gateway="10.1.2.1", netmask="255.255.255.0")
response = verifyNetworkState(self.apiclient, persistent_network_2.id, "implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.assertIsNotNone(persistent_network_2.vlan, "vlan must not be null for persistent network: %s" % persistent_network_2.id)
# Deploy VMs in above networks (VM1, VM2 in network1 and VM3, VM4 in network2)
try:
virtual_machine_1 = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[persistent_network_1.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
virtual_machine_2 = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[persistent_network_1.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
virtual_machine_3 = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[persistent_network_2.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
virtual_machine_4 = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
networkids=[persistent_network_2.id],serviceofferingid=self.service_offering.id,
accountid=account.name,domainid=self.domain.id)
except Exception as e:
self.fail("vm creation failed: %s" % e)
# Associate IP addresses to persistent networks
ipaddress_1 = self.GetAssociatedIpForNetwork(persistent_network_1.id, vpcid=vpc.id, account=account)
ipaddress_2 = self.GetAssociatedIpForNetwork(persistent_network_1.id, vpcid=vpc.id, account=account)
ipaddress_3 = self.GetAssociatedIpForNetwork(persistent_network_2.id, vpcid=vpc.id, account=account)
# Create NAT rule for VM 1
NATRule.create(self.api_client, virtual_machine_1,
self.services["natrule"],ipaddressid=ipaddress_1.ipaddress.id,
networkid=persistent_network_1.id)
# Create Static NAT rule for VM 2
StaticNATRule.enable(self.apiclient, ipaddressid=ipaddress_2.ipaddress.id,
virtualmachineid=virtual_machine_2.id,
networkid=persistent_network_1.id)
# Create load balancer rule for ipaddress3 and assign to VM3 and VM4
lb_rule = LoadBalancerRule.create(self.apiclient,self.services["lbrule"],
ipaddressid=ipaddress_3.ipaddress.id, accountid=account.name,
networkid=persistent_network_2.id, domainid=account.domainid)
lb_rule.assign(self.api_client, [virtual_machine_3, virtual_machine_4])
# Create network ACL for both ther persistent networks (tiers of VPC)
ingressAclNetwork1, egressAclNetwork1 = self.CreateIngressEgressNetworkACLForNetwork(persistent_network_1.id)
ingressAclNetwork2, egressAclNetwork2 = self.CreateIngressEgressNetworkACLForNetwork(persistent_network_2.id)
"""private_gateway = PrivateGateway.create(self.apiclient,gateway='10.1.4.1',ipaddress='10.1.4.100',
netmask='255.255.255.0',vlan=679,vpcid=vpc.id)
gateways = PrivateGateway.list(self.apiclient,id=private_gateway.id, listall=True)
self.assertEqual(validateList(gateways)[0], PASS, "gateways list validation failed, list is %s" % gateways)
static_route = StaticRoute.create(self.apiclient, cidr='192.168.127.12/24',gatewayid=private_gateway.id)
static_routes = StaticRoute.list(self.apiclient,id=static_route.id,listall=True)
self.assertEqual(validateList(static_routes)[0], PASS, "static routes list validation failed, list is %s" % static_routes)"""
self.CheckIngressEgressConnectivityofVM(virtual_machine_1, ipaddress_1.ipaddress.ipaddress)
self.CheckIngressEgressConnectivityofVM(virtual_machine_2, ipaddress_2.ipaddress.ipaddress)
self.CheckIngressEgressConnectivityofVM(virtual_machine_3, ipaddress_3.ipaddress.ipaddress)
"""self.CheckIngressEgressConnectivityofVM(virtual_machine_4, ipaddress_3.ipaddress.ipaddress)"""
vpc.restart(self.apiclient)
self.CheckIngressEgressConnectivityofVM(virtual_machine_1, ipaddress_1.ipaddress.ipaddress)
self.CheckIngressEgressConnectivityofVM(virtual_machine_2, ipaddress_2.ipaddress.ipaddress)
self.CheckIngressEgressConnectivityofVM(virtual_machine_3, ipaddress_3.ipaddress.ipaddress)
"""self.CheckIngressEgressConnectivityofVM(virtual_machine_4, ipaddress_3.ipaddress.ipaddress)"""
return
| [
"marvin.lib.base.Domain.create",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.PublicIPAddress.create",
"marvin.lib.base.FireWallRule.create",
"marvin.lib.base.Host.list",
"marvin.lib.base.PublicIPAddress.list",
"marvin.lib.base.Domain.list",
"marvin.lib.base.Network.create",
"marvin.lib.c... | [((8483, 8533), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (8487, 8533), False, 'from nose.plugins.attrib import attr\n'), ((10985, 11035), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (10989, 11035), False, 'from nose.plugins.attrib import attr\n'), ((11633, 11656), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (11637, 11656), False, 'from nose.plugins.attrib import attr\n'), ((12267, 12290), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (12271, 12290), False, 'from nose.plugins.attrib import attr\n'), ((13114, 13136), 'ddt.data', 'data', (['"""LB-VR"""', '"""LB-NS"""'], {}), "('LB-VR', 'LB-NS')\n", (13118, 13136), False, 'from ddt import ddt, data\n'), ((13141, 13178), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']"}), "(tags=['advanced', 'advancedns'])\n", (13145, 13178), False, 'from nose.plugins.attrib import attr\n'), ((18168, 18191), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (18172, 18191), False, 'from nose.plugins.attrib import attr\n'), ((22391, 22428), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']"}), "(tags=['advanced', 'advancedns'])\n", (22395, 22428), False, 'from nose.plugins.attrib import attr\n'), ((26780, 26809), 'ddt.data', 'data', (['"""LB-VR"""', '"""LB-Netscaler"""'], {}), "('LB-VR', 'LB-Netscaler')\n", (26784, 26809), False, 'from ddt import ddt, data\n'), ((26814, 26851), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']"}), "(tags=['advanced', 'advancedns'])\n", (26818, 26851), False, 'from nose.plugins.attrib import attr\n'), ((31058, 31081), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (31062, 31081), False, 'from nose.plugins.attrib import attr\n'), ((35015, 35038), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (35019, 35038), False, 'from nose.plugins.attrib import attr\n'), ((40769, 40792), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (40773, 40792), False, 'from nose.plugins.attrib import attr\n'), ((45110, 45133), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (45114, 45133), False, 'from nose.plugins.attrib import attr\n'), ((49056, 49079), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (49060, 49079), False, 'from nose.plugins.attrib import attr\n'), ((55927, 55953), 'ddt.data', 'data', (['"""VR"""', '"""RVR"""', '"""LB-NS"""'], {}), "('VR', 'RVR', 'LB-NS')\n", (55931, 55953), False, 'from ddt import ddt, data\n'), ((55957, 55994), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']"}), "(tags=['advanced', 'advancedns'])\n", (55961, 55994), False, 'from nose.plugins.attrib import attr\n'), ((62222, 62248), 'ddt.data', 'data', (['"""locked"""', '"""disabled"""'], {}), "('locked', 'disabled')\n", (62226, 62248), False, 'from ddt import ddt, data\n'), ((62253, 62276), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (62257, 62276), False, 'from nose.plugins.attrib import attr\n'), ((64790, 64813), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (64794, 64813), False, 'from nose.plugins.attrib import attr\n'), ((72444, 72465), 'ddt.data', 'data', (['"""true"""', '"""false"""'], {}), "('true', 'false')\n", (72448, 72465), False, 'from ddt import ddt, data\n'), ((72470, 72493), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (72474, 72493), False, 'from nose.plugins.attrib import attr\n'), ((76926, 76947), 'ddt.data', 'data', (['"""true"""', '"""false"""'], {}), "('true', 'false')\n", (76930, 76947), False, 'from ddt import ddt, data\n'), ((76952, 76989), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']"}), "(tags=['advanced', 'advancedns'])\n", (76956, 76989), False, 'from nose.plugins.attrib import attr\n'), ((87683, 87708), 'ddt.data', 'data', (['"""delete"""', '"""restart"""'], {}), "('delete', 'restart')\n", (87687, 87708), False, 'from ddt import ddt, data\n'), ((87714, 87737), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (87718, 87737), False, 'from nose.plugins.attrib import attr\n'), ((92853, 92876), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (92857, 92876), False, 'from nose.plugins.attrib import attr\n'), ((98179, 98202), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (98183, 98202), False, 'from nose.plugins.attrib import attr\n'), ((105909, 105929), 'marvin.cloudstackTestCase.unittest.skip', 'unittest.skip', (['"""WIP"""'], {}), "('WIP')\n", (105922, 105929), False, 'from marvin.cloudstackTestCase import cloudstackTestCase, unittest\n'), ((105935, 105958), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (105939, 105958), False, 'from nose.plugins.attrib import attr\n'), ((2668, 2694), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2678, 2694), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((2796, 2861), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (2808, 2861), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((2998, 3077), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], domainid=cls.domain.id)\n", (3012, 3077), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((3357, 3429), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (3379, 3429), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((5366, 5465), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', 'cls.services[network_offering_type]'], {'conservemode': '(False)'}), '(cls.api_client, cls.services[network_offering_type],\n conservemode=False)\n', (5388, 5465), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((5734, 5836), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['network_offering', 'cls.api_client'], {'id': 'network_offering.id', 'state': '"""enabled"""'}), "(network_offering, cls.api_client, id=\n network_offering.id, state='enabled')\n", (5756, 5836), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((9102, 9314), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=self.account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (9116, 9314), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((9487, 9548), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'network.id', '"""implemented"""'], {}), "(self.apiclient, network.id, 'implemented')\n", (9505, 9548), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((10581, 10658), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.api_client, ['network.gc.interval', 'network.gc.wait'])\n", (10597, 10658), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((10668, 10730), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'network.id', '"""implemented"""'], {}), "(self.api_client, network.id, 'implemented')\n", (10686, 10730), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((12738, 12799), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'network_offering.id'}), '(self.api_client, id=network_offering.id)\n', (12758, 12799), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((14724, 14811), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (14738, 14811), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((14943, 15126), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'networkOffering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=networkOffering.id, accountid=account.name, domainid=\n self.domain.id, zoneid=self.zone.id)\n", (14957, 15126), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((15261, 15330), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'isolated_network.id', '"""allocated"""'], {}), "(self.api_client, isolated_network.id, 'allocated')\n", (15279, 15330), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((16398, 16545), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=isolated_network.id)\n', (16420, 16545), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((16634, 16871), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (16653, 16871), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((16967, 17112), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'networkid': 'isolated_network.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress.ipaddress.id, networkid=isolated_network.id)\n", (16981, 17112), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((17652, 17729), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.api_client, ['network.gc.interval', 'network.gc.wait'])\n", (17668, 17729), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((17842, 17913), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'isolated_network.id', '"""implemented"""'], {}), "(self.api_client, isolated_network.id, 'implemented')\n", (17860, 17913), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((19032, 19119), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (19046, 19119), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((19178, 19376), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_network_offering.id, accountid=account.\n name, domainid=self.domain.id, zoneid=self.zone.id)\n", (19192, 19376), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((19544, 19613), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'isolated_network.id', '"""allocated"""'], {}), "(self.api_client, isolated_network.id, 'allocated')\n", (19562, 19613), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((20696, 20843), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=isolated_network.id)\n', (20718, 20843), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((20932, 21169), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (20951, 21169), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((21239, 21384), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'networkid': 'isolated_network.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress.ipaddress.id, networkid=isolated_network.id)\n", (21253, 21384), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((21875, 21952), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.api_client, ['network.gc.interval', 'network.gc.wait'])\n", (21891, 21952), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((22065, 22136), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'isolated_network.id', '"""implemented"""'], {}), "(self.api_client, isolated_network.id, 'implemented')\n", (22083, 22136), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((23517, 23604), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (23531, 23604), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((23663, 23870), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_network_offering_netscaler.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_network_offering_netscaler.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (23677, 23870), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((24039, 24108), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'isolated_network.id', '"""allocated"""'], {}), "(self.api_client, isolated_network.id, 'allocated')\n", (24057, 24108), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((25085, 25232), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=isolated_network.id)\n', (25107, 25232), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((25321, 25558), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (25340, 25558), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((25628, 25773), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'networkid': 'isolated_network.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress.ipaddress.id, networkid=isolated_network.id)\n", (25642, 25773), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((26264, 26341), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.api_client, ['network.gc.interval', 'network.gc.wait'])\n", (26280, 26341), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((26454, 26525), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'isolated_network.id', '"""implemented"""'], {}), "(self.api_client, isolated_network.id, 'implemented')\n", (26472, 26525), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((28055, 28142), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (28069, 28142), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((28212, 28395), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'networkOffering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=networkOffering.id, accountid=account.name, domainid=\n self.domain.id, zoneid=self.zone.id)\n", (28226, 28395), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((28929, 29053), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'account': 'account.name', 'domainid': 'account.domainid', 'networkid': 'isolated_persistent_network.id'}), '(self.api_client, account=account.name, domainid=account.\n domainid, networkid=isolated_persistent_network.id)\n', (28940, 29053), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((29994, 30157), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_persistent_network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=\n isolated_persistent_network.id)\n', (30016, 30157), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((30241, 30478), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (30260, 30478), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((30547, 30708), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'networkid': 'isolated_persistent_network.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress.ipaddress.id, networkid=\n isolated_persistent_network.id)\n", (30561, 30708), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((31773, 31860), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (31787, 31860), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((31982, 32194), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering_RVR.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering_RVR.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (31996, 32194), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((32823, 32916), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'listall': '(True)', 'networkid': 'isolated_persistent_network_RVR.id'}), '(self.api_client, listall=True, networkid=\n isolated_persistent_network_RVR.id)\n', (32834, 32916), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((33929, 34096), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_persistent_network_RVR.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=\n isolated_persistent_network_RVR.id)\n', (33951, 34096), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((34180, 34417), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (34199, 34417), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((34486, 34651), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'networkid': 'isolated_persistent_network_RVR.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress.ipaddress.id, networkid=\n isolated_persistent_network_RVR.id)\n", (34500, 34651), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((35403, 35490), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (35417, 35490), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((35562, 35770), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (35576, 35770), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((36269, 36477), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (36283, 36477), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((37050, 37141), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'listall': '(True)', 'networkid': 'isolated_persistent_network_1.id'}), '(self.api_client, listall=True, networkid=\n isolated_persistent_network_1.id)\n', (37061, 37141), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((37546, 37637), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'listall': '(True)', 'networkid': 'isolated_persistent_network_2.id'}), '(self.api_client, listall=True, networkid=\n isolated_persistent_network_2.id)\n', (37557, 37637), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((38574, 38739), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_persistent_network_1.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=\n isolated_persistent_network_1.id)\n', (38596, 38739), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((38823, 39065), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress_nw_1.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress_nw_1.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (38842, 39065), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((39247, 39412), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_persistent_network_2.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=\n isolated_persistent_network_2.id)\n', (39269, 39412), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((39496, 39738), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress_nw_2.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress_nw_2.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (39515, 39738), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((39807, 39975), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress_nw_1.ipaddress.id', 'networkid': 'isolated_persistent_network_1.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress_nw_1.ipaddress.id, networkid=\n isolated_persistent_network_1.id)\n", (39821, 39975), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((40282, 40450), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress_nw_2.ipaddress.id', 'networkid': 'isolated_persistent_network_2.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress_nw_2.ipaddress.id, networkid=\n isolated_persistent_network_2.id)\n", (40296, 40450), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((41423, 41510), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (41437, 41510), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((41562, 41770), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (41576, 41770), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((42135, 42333), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_network_offering.id, accountid=account.\n name, domainid=self.domain.id, zoneid=self.zone.id)\n", (42149, 42333), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((43016, 43156), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'network_1.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=network_1.id)\n', (43038, 43156), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((43245, 43487), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress_nw_1.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress_nw_1.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (43264, 43487), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((43556, 43699), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress_nw_1.ipaddress.id', 'networkid': 'network_1.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress_nw_1.ipaddress.id, networkid=network_1.id)\n", (43570, 43699), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((44103, 44243), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'network_2.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=network_2.id)\n', (44125, 44243), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((44332, 44574), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress_nw_2.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress_nw_2.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (44351, 44574), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((44643, 44786), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress_nw_2.ipaddress.id', 'networkid': 'network_2.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress_nw_2.ipaddress.id, networkid=network_2.id)\n", (44657, 44786), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((45812, 45899), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (45826, 45899), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((45949, 46157), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (45963, 46157), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((47329, 47467), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=network.id)\n', (47351, 47467), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((47556, 47793), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (47575, 47793), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((47862, 47998), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'networkid': 'network.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress.ipaddress.id, networkid=network.id)\n", (47876, 47998), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((48551, 48628), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.api_client, ['network.gc.interval', 'network.gc.wait'])\n", (48567, 48628), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((48741, 48801), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'network.id', '"""allocated"""'], {}), "(self.api_client, network.id, 'allocated')\n", (48759, 48801), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((49608, 49695), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (49622, 49695), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((49708, 49916), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (49722, 49916), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((50577, 50715), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=network.id)\n', (50599, 50715), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((50804, 51041), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (50823, 51041), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((51110, 51246), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'networkid': 'network.id'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=ipaddress.ipaddress.id, networkid=network.id)\n", (51124, 51246), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((51702, 51745), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'network.id'}), '(self.apiclient, id=network.id)\n', (51714, 51745), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((51880, 51943), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.apiclient'], {'id': 'ipaddress.ipaddress.id'}), '(self.apiclient, id=ipaddress.ipaddress.id)\n', (51900, 51943), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((52583, 52609), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (52593, 52609), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((52711, 52776), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (52723, 52776), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((53205, 53277), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (53227, 53277), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((54907, 55006), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', 'cls.services[network_offering_type]'], {'conservemode': '(False)'}), '(cls.api_client, cls.services[network_offering_type],\n conservemode=False)\n', (54929, 55006), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((55275, 55377), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['network_offering', 'cls.api_client'], {'id': 'network_offering.id', 'state': '"""enabled"""'}), "(network_offering, cls.api_client, id=\n network_offering.id, state='enabled')\n", (55297, 55377), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((56718, 56804), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (56732, 56804), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((56858, 56944), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (56872, 56944), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((57554, 57739), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'network_offering.id', 'accountid': 'account_1.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=network_offering.id, accountid=account_1.name,\n domainid=self.domain.id, zoneid=self.zone.id)\n", (57568, 57739), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((57908, 57970), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'network.id', '"""implemented"""'], {}), "(self.api_client, network.id, 'implemented')\n", (57926, 57970), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((59904, 59930), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (59914, 59930), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((60032, 60097), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (60044, 60097), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((60526, 60598), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (60548, 60598), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((60784, 60891), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['nw_off_isolated_persistent']"], {'conservemode': '(False)'}), "(cls.api_client, cls.services[\n 'nw_off_isolated_persistent'], conservemode=False)\n", (60806, 60891), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((62630, 62716), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (62644, 62716), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((62766, 62974), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (62780, 62974), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((63143, 63205), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'network.id', '"""implemented"""'], {}), "(self.api_client, network.id, 'implemented')\n", (63161, 63205), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((63714, 63757), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'id': 'account.id'}), '(self.apiclient, id=account.id)\n', (63726, 63757), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((64060, 64137), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.api_client, ['network.gc.interval', 'network.gc.wait'])\n", (64076, 64137), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((64158, 64235), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'account': 'account.name', 'domainid': 'account.domainid'}), '(self.apiclient, account=account.name, domainid=account.domainid)\n', (64170, 64235), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((64374, 64440), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.api_client', 'networks[0].id', '"""implemented"""'], {}), "(self.api_client, networks[0].id, 'implemented')\n", (64392, 64440), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((65279, 65365), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (65293, 65365), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((65440, 65496), 'marvin.lib.base.Project.create', 'Project.create', (['self.apiclient', "self.services['project']"], {}), "(self.apiclient, self.services['project'])\n", (65454, 65496), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((65553, 65761), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (65567, 65761), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((66126, 66184), 'marvin.lib.base.Project.listAccounts', 'Project.listAccounts', (['self.apiclient'], {'projectid': 'project.id'}), '(self.apiclient, projectid=project.id)\n', (66146, 66184), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((66716, 66759), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'project.id'}), '(self.apiclient, id=project.id)\n', (66728, 66759), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((67066, 67143), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.api_client, ['network.gc.interval', 'network.gc.wait'])\n", (67082, 67143), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((67164, 67225), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'network.id', '"""implemented"""'], {}), "(self.apiclient, network.id, 'implemented')\n", (67182, 67225), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((67986, 68012), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (67996, 68012), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((68114, 68179), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (68126, 68179), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((68608, 68680), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (68630, 68680), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((68866, 68976), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['nw_off_isolated_persistent_lb']"], {'conservemode': '(False)'}), "(cls.api_client, cls.services[\n 'nw_off_isolated_persistent_lb'], conservemode=False)\n", (68888, 68976), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((69132, 69249), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['nw_off_isolated_persistent_netscaler']"], {'conservemode': '(False)'}), "(cls.api_client, cls.services[\n 'nw_off_isolated_persistent_netscaler'], conservemode=False)\n", (69154, 69249), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((72979, 73065), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (72993, 73065), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((73135, 73343), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering.id,\n accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (73149, 73343), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((73512, 73597), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'isolated_persistent_network.id', '"""implemented"""'], {}), "(self.apiclient, isolated_persistent_network.id,\n 'implemented')\n", (73530, 73597), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((74046, 74135), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'listall': '(True)', 'networkid': 'isolated_persistent_network.id'}), '(self.api_client, listall=True, networkid=\n isolated_persistent_network.id)\n', (74057, 74135), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((74524, 74687), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_persistent_network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=\n isolated_persistent_network.id)\n', (74546, 74687), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((74771, 75008), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddress.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddress.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (74790, 75008), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((75113, 75315), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'accountid': 'account.name', 'networkid': 'isolated_persistent_network.id', 'domainid': 'account.domainid'}), "(self.apiclient, self.services['lbrule'],\n ipaddressid=ipaddress.ipaddress.id, accountid=account.name, networkid=\n isolated_persistent_network.id, domainid=account.domainid)\n", (75136, 75315), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((75536, 75613), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'account': 'account.name', 'domainid': 'account.domainid'}), '(self.apiclient, account=account.name, domainid=account.domainid)\n', (75548, 75613), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((75741, 75806), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'networks[0].id', '"""implemented"""'], {}), "(self.apiclient, networks[0].id, 'implemented')\n", (75759, 75806), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((77652, 77738), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (77666, 77738), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((77808, 78027), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_persistent_network_offering_netscaler.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_persistent_network_offering_netscaler.\n id, accountid=account.name, domainid=self.domain.id, zoneid=self.zone.id)\n", (77822, 78027), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((78195, 78280), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'isolated_persistent_network.id', '"""implemented"""'], {}), "(self.apiclient, isolated_persistent_network.id,\n 'implemented')\n", (78213, 78280), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((78729, 78818), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'listall': '(True)', 'networkid': 'isolated_persistent_network.id'}), '(self.api_client, listall=True, networkid=\n isolated_persistent_network.id)\n', (78740, 78818), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((79207, 79370), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'isolated_persistent_network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=\n isolated_persistent_network.id)\n', (79229, 79370), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((79489, 79691), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']"], {'ipaddressid': 'ipaddress.ipaddress.id', 'accountid': 'account.name', 'networkid': 'isolated_persistent_network.id', 'domainid': 'account.domainid'}), "(self.apiclient, self.services['lbrule'],\n ipaddressid=ipaddress.ipaddress.id, accountid=account.name, networkid=\n isolated_persistent_network.id, domainid=account.domainid)\n", (79512, 79691), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((79912, 79989), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'account': 'account.name', 'domainid': 'account.domainid'}), '(self.apiclient, account=account.name, domainid=account.domainid)\n', (79924, 79989), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((80128, 80193), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'networks[0].id', '"""implemented"""'], {}), "(self.apiclient, networks[0].id, 'implemented')\n", (80146, 80193), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((81800, 81826), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (81810, 81826), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((81928, 81993), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (81940, 81993), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((82423, 82510), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offerings']['small']"], {}), "(cls.api_client, cls.services['service_offerings'][\n 'small'])\n", (82445, 82510), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((82687, 82796), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['nw_off_persistent_VPCVR_NoLB']"], {'conservemode': '(False)'}), "(cls.api_client, cls.services[\n 'nw_off_persistent_VPCVR_NoLB'], conservemode=False)\n", (82709, 82796), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((83060, 83167), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['nw_off_persistent_VPCVR_LB']"], {'conservemode': '(False)'}), "(cls.api_client, cls.services[\n 'nw_off_persistent_VPCVR_LB'], conservemode=False)\n", (83082, 83167), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((83406, 83470), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['cls.api_client', "cls.services['vpc_offering']"], {}), "(cls.api_client, cls.services['vpc_offering'])\n", (83424, 83470), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((84783, 84933), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'zoneid': 'self.zone.id', 'networkid': 'networkid', 'vpcid': 'vpcid', 'accountid': 'account.name', 'domainid': 'account.domainid'}), '(self.api_client, zoneid=self.zone.id, networkid=\n networkid, vpcid=vpcid, accountid=account.name, domainid=account.domainid)\n', (84805, 84933), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((86681, 86723), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'networkid'}), '(self.apiclient, id=networkid)\n', (86693, 86723), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((86949, 86983), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'vpcid'}), '(self.apiclient, id=vpcid)\n', (86957, 86983), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((87215, 87259), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'vmid'}), '(self.apiclient, id=vmid)\n', (87234, 87259), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((87496, 87541), 'marvin.lib.base.NetworkACL.list', 'NetworkACL.list', (['self.apiclient'], {'id': 'aclRuleId'}), '(self.apiclient, id=aclRuleId)\n', (87511, 87541), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((88264, 88350), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (88278, 88350), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((88580, 88734), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'account.name', 'domainid': 'account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=account.name, domainid=account.domainid)\n", (88590, 88734), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((88795, 88830), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'vpc.id'}), '(self.apiclient, id=vpc.id)\n', (88803, 88830), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((88961, 89016), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'vpcid': 'vpc.id', 'listall': '(True)'}), '(self.apiclient, vpcid=vpc.id, listall=True)\n', (88972, 89016), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((89204, 89268), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.apiclient'], {'vpcid': 'vpc.id', 'listall': '(True)'}), '(self.apiclient, vpcid=vpc.id, listall=True)\n', (89224, 89268), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((89446, 89715), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.persistent_network_offering_NoLB.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id', 'vpcid': 'vpc.id', 'gateway': '"""10.1.1.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.persistent_network_offering_NoLB.id, accountid=\n account.name, domainid=self.domain.id, zoneid=self.zone.id, vpcid=vpc.\n id, gateway='10.1.1.1', netmask='255.255.255.0')\n", (89460, 89715), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((89857, 89931), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_1.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_1.id, 'implemented')\n", (89875, 89931), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((90330, 90599), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.persistent_network_offering_NoLB.id', 'accountid': 'account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id', 'vpcid': 'vpc.id', 'gateway': '"""10.1.2.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.persistent_network_offering_NoLB.id, accountid=\n account.name, domainid=self.domain.id, zoneid=self.zone.id, vpcid=vpc.\n id, gateway='10.1.2.1', netmask='255.255.255.0')\n", (90344, 90599), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((90741, 90815), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_2.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_2.id, 'implemented')\n", (90759, 90815), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((93428, 93526), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.apiclient'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.apiclient, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (93441, 93526), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((97373, 97439), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.apiclient', "(['account.cleanup.interval'] * 3)"], {}), "(self.apiclient, ['account.cleanup.interval'] * 3)\n", (97389, 97439), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((105188, 105254), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.apiclient', "(['account.cleanup.interval'] * 3)"], {}), "(self.apiclient, ['account.cleanup.interval'] * 3)\n", (105204, 105254), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((106513, 106599), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (106527, 106599), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((106719, 106873), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'account.name', 'domainid': 'account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=account.name, domainid=account.domainid)\n", (106729, 106873), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((106934, 106969), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'vpc.id'}), '(self.apiclient, id=vpc.id)\n', (106942, 106969), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((107162, 107433), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.persistent_network_offering_NoLB.id', 'accountid': 'account.name', 'domainid': 'account.domainid', 'zoneid': 'self.zone.id', 'vpcid': 'vpc.id', 'gateway': '"""10.1.1.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.persistent_network_offering_NoLB.id, accountid=\n account.name, domainid=account.domainid, zoneid=self.zone.id, vpcid=vpc\n .id, gateway='10.1.1.1', netmask='255.255.255.0')\n", (107176, 107433), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((107575, 107649), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_1.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_1.id, 'implemented')\n", (107593, 107649), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((108048, 108317), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.persistent_network_offering_LB.id', 'accountid': 'account.name', 'domainid': 'account.domainid', 'zoneid': 'self.zone.id', 'vpcid': 'vpc.id', 'gateway': '"""10.1.2.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.persistent_network_offering_LB.id, accountid=\n account.name, domainid=account.domainid, zoneid=self.zone.id, vpcid=vpc\n .id, gateway='10.1.2.1', netmask='255.255.255.0')\n", (108062, 108317), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((108459, 108533), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_2.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_2.id, 'implemented')\n", (108477, 108533), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((110860, 111013), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine_1', "self.services['natrule']"], {'ipaddressid': 'ipaddress_1.ipaddress.id', 'networkid': 'persistent_network_1.id'}), "(self.api_client, virtual_machine_1, self.services['natrule'],\n ipaddressid=ipaddress_1.ipaddress.id, networkid=persistent_network_1.id)\n", (110874, 111013), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((111106, 111258), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient'], {'ipaddressid': 'ipaddress_2.ipaddress.id', 'virtualmachineid': 'virtual_machine_2.id', 'networkid': 'persistent_network_1.id'}), '(self.apiclient, ipaddressid=ipaddress_2.ipaddress.id,\n virtualmachineid=virtual_machine_2.id, networkid=persistent_network_1.id)\n', (111126, 111258), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((111411, 111608), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']"], {'ipaddressid': 'ipaddress_3.ipaddress.id', 'accountid': 'account.name', 'networkid': 'persistent_network_2.id', 'domainid': 'account.domainid'}), "(self.apiclient, self.services['lbrule'],\n ipaddressid=ipaddress_3.ipaddress.id, accountid=account.name, networkid\n =persistent_network_2.id, domainid=account.domainid)\n", (111434, 111608), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((4317, 4390), 'marvin.lib.common.add_netscaler', 'add_netscaler', (['cls.api_client', 'cls.zone.id', "cls.services['netscaler_VPX']"], {}), "(cls.api_client, cls.zone.id, cls.services['netscaler_VPX'])\n", (4330, 4390), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((5094, 5141), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (5111, 5141), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((6038, 6074), 'marvin.lib.utils.get_hypervisor_type', 'get_hypervisor_type', (['self.api_client'], {}), '(self.api_client)\n', (6057, 6074), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((6376, 6420), 'marvin.lib.base.Host.list', 'Host.list', (['self.api_client'], {'id': 'router.hostid'}), '(self.api_client, id=router.hostid)\n', (6385, 6420), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((6658, 6748), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'sourceip', 'port': '(22)', 'user': '"""root"""', 'passwd': "self.services['host_password']"}), "(host=sourceip, port=22, user='root', passwd=self.services[\n 'host_password'])\n", (6667, 6748), False, 'from marvin.sshClient import SshClient\n'), ((7541, 7600), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'virtual_machine.id'}), '(self.api_client, id=virtual_machine.id)\n', (7560, 7600), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((7810, 7824), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (7820, 7824), False, 'import time\n'), ((8276, 8323), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (8293, 8323), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((9917, 10119), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.domain.id)\n", (9938, 10119), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((15806, 16013), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[isolated_network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[isolated_network.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (15827, 16013), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((20089, 20296), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[isolated_network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[isolated_network.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (20110, 20296), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((24546, 24753), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[isolated_network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[isolated_network.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (24567, 24753), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((29430, 29648), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[isolated_persistent_network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[isolated_persistent_network.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (29451, 29648), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((33358, 33580), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[isolated_persistent_network_RVR.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[isolated_persistent_network_RVR.id], serviceofferingid=self\n .service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (33379, 33580), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((37970, 38228), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[isolated_persistent_network_1.id, isolated_persistent_network_2.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[isolated_persistent_network_1.id,\n isolated_persistent_network_2.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (37991, 38228), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((42472, 42686), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network_1.id, network_2.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network_1.id, network_2.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (42493, 42686), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((46808, 47005), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=account.name, domainid=self.domain.id)\n", (46829, 47005), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((50110, 50307), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=account.name, domainid=self.domain.id)\n", (50131, 50307), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((53955, 54028), 'marvin.lib.common.add_netscaler', 'add_netscaler', (['cls.api_client', 'cls.zone.id', "cls.services['netscaler_VPX']"], {}), "(cls.api_client, cls.zone.id, cls.services['netscaler_VPX'])\n", (53968, 54028), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((54635, 54682), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (54652, 54682), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((55720, 55767), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (55737, 55767), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((58339, 58538), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account_1.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=account_1.name, domainid=self.domain.id)\n", (58360, 58538), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((59074, 59160), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'account': 'account_2.name', 'domainid': 'account_2.domainid'}), '(self.apiclient, account=account_2.name, domainid=account_2.\n domainid)\n', (59086, 59160), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((61563, 61610), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (61580, 61610), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((62015, 62062), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (62032, 62062), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((69808, 69881), 'marvin.lib.common.add_netscaler', 'add_netscaler', (['cls.api_client', 'cls.zone.id', "cls.services['netscaler_VPX']"], {}), "(cls.api_client, cls.zone.id, cls.services['netscaler_VPX'])\n", (69821, 69881), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((70426, 70473), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (70443, 70473), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((70878, 70925), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (70895, 70925), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((71222, 71258), 'marvin.lib.utils.get_hypervisor_type', 'get_hypervisor_type', (['self.api_client'], {}), '(self.api_client)\n', (71241, 71258), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((71560, 71604), 'marvin.lib.base.Host.list', 'Host.list', (['self.api_client'], {'id': 'router.hostid'}), '(self.api_client, id=router.hostid)\n', (71569, 71604), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((71842, 71932), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'sourceip', 'port': '(22)', 'user': '"""root"""', 'passwd': "self.services['host_password']"}), "(host=sourceip, port=22, user='root', passwd=self.services[\n 'host_password'])\n", (71851, 71932), False, 'from marvin.sshClient import SshClient\n'), ((76199, 76417), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[isolated_persistent_network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[isolated_persistent_network.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (76220, 76417), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((80586, 80804), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[isolated_persistent_network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[isolated_persistent_network.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (80607, 80804), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((83923, 83970), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (83940, 83970), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((84374, 84421), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (84391, 84421), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((85102, 85219), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', (['self.apiclient'], {'networkid': 'networkid', 'services': "self.services['natrule']", 'traffictype': '"""Ingress"""'}), "(self.apiclient, networkid=networkid, services=self.\n services['natrule'], traffictype='Ingress')\n", (85119, 85219), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((85239, 85356), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', (['self.apiclient'], {'networkid': 'networkid', 'services': "self.services['icmprule']", 'traffictype': '"""Egress"""'}), "(self.apiclient, networkid=networkid, services=self.\n services['icmprule'], traffictype='Egress')\n", (85256, 85356), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((85638, 85714), 'marvin.sshClient.SshClient', 'SshClient', (['ipaddress', '(22)', 'virtual_machine.username', 'virtual_machine.password'], {}), '(ipaddress, 22, virtual_machine.username, virtual_machine.password)\n', (85647, 85714), False, 'from marvin.sshClient import SshClient\n'), ((91304, 91378), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_1.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_1.id, 'implemented')\n", (91322, 91378), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((91651, 91725), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_2.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_2.id, 'implemented')\n", (91669, 91725), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((93635, 93722), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'child_domain.id'}), "(self.apiclient, self.services['account'], domainid=\n child_domain.id)\n", (93649, 93722), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((93827, 93914), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'child_domain.id'}), "(self.apiclient, self.services['account'], domainid=\n child_domain.id)\n", (93841, 93914), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((94073, 94236), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'account_1.name', 'domainid': 'account_1.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=account_1.name, domainid=account_1.\n domainid)\n", (94083, 94236), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((94296, 94333), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'vpc_1.id'}), '(self.apiclient, id=vpc_1.id)\n', (94304, 94333), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((94487, 94650), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'account_2.name', 'domainid': 'account_2.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=account_2.name, domainid=account_2.\n domainid)\n", (94497, 94650), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((94710, 94747), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'vpc_2.id'}), '(self.apiclient, id=vpc_2.id)\n', (94718, 94747), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((94916, 95193), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.persistent_network_offering_NoLB.id', 'accountid': 'account_1.name', 'domainid': 'account_1.domainid', 'zoneid': 'self.zone.id', 'vpcid': 'vpc_1.id', 'gateway': '"""10.1.1.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.persistent_network_offering_NoLB.id, accountid=\n account_1.name, domainid=account_1.domainid, zoneid=self.zone.id, vpcid\n =vpc_1.id, gateway='10.1.1.1', netmask='255.255.255.0')\n", (94930, 95193), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((95283, 95357), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_1.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_1.id, 'implemented')\n", (95301, 95357), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((95976, 96253), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.persistent_network_offering_NoLB.id', 'accountid': 'account_2.name', 'domainid': 'account_2.domainid', 'zoneid': 'self.zone.id', 'vpcid': 'vpc_2.id', 'gateway': '"""10.1.1.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.persistent_network_offering_NoLB.id, accountid=\n account_2.name, domainid=account_2.domainid, zoneid=self.zone.id, vpcid\n =vpc_2.id, gateway='10.1.1.1', netmask='255.255.255.0')\n", (95990, 96253), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((96342, 96416), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_2.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_2.id, 'implemented')\n", (96360, 96416), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((97494, 97541), 'marvin.lib.base.Domain.list', 'Domain.list', (['self.apiclient'], {'id': 'child_domain.id'}), '(self.apiclient, id=child_domain.id)\n', (97505, 97541), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((97597, 97694), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'name': 'account_1.name', 'domainid': 'account_1.domainid', 'listall': '(True)'}), '(self.apiclient, name=account_1.name, domainid=account_1.\n domainid, listall=True)\n', (97609, 97694), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((97806, 97903), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'name': 'account_2.name', 'domainid': 'account_2.domainid', 'listall': '(True)'}), '(self.apiclient, name=account_2.name, domainid=account_2.\n domainid, listall=True)\n', (97818, 97903), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((98764, 98850), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (98778, 98850), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((98945, 99099), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'account.name', 'domainid': 'account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=account.name, domainid=account.domainid)\n", (98955, 99099), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((99164, 99199), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'vpc.id'}), '(self.apiclient, id=vpc.id)\n', (99172, 99199), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((99404, 99675), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.persistent_network_offering_NoLB.id', 'accountid': 'account.name', 'domainid': 'account.domainid', 'zoneid': 'self.zone.id', 'vpcid': 'vpc.id', 'gateway': '"""10.1.1.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.persistent_network_offering_NoLB.id, accountid=\n account.name, domainid=account.domainid, zoneid=self.zone.id, vpcid=vpc\n .id, gateway='10.1.1.1', netmask='255.255.255.0')\n", (99418, 99675), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((99821, 99895), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_1.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_1.id, 'implemented')\n", (99839, 99895), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((100324, 100593), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.persistent_network_offering_LB.id', 'accountid': 'account.name', 'domainid': 'account.domainid', 'zoneid': 'self.zone.id', 'vpcid': 'vpc.id', 'gateway': '"""10.1.2.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.persistent_network_offering_LB.id, accountid=\n account.name, domainid=account.domainid, zoneid=self.zone.id, vpcid=vpc\n .id, gateway='10.1.2.1', netmask='255.255.255.0')\n", (100338, 100593), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((100739, 100813), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'persistent_network_2.id', '"""implemented"""'], {}), "(self.apiclient, persistent_network_2.id, 'implemented')\n", (100757, 100813), False, 'from marvin.lib.common import get_domain, get_zone, get_template, verifyNetworkState, add_netscaler, wait_for_cleanup\n'), ((101331, 101542), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[persistent_network_1.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[persistent_network_1.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (101352, 101542), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((101668, 101879), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[persistent_network_1.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[persistent_network_1.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (101689, 101879), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((102005, 102216), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[persistent_network_2.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[persistent_network_2.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (102026, 102216), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((102342, 102553), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[persistent_network_2.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[persistent_network_2.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (102363, 102553), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((103098, 103251), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine_1', "self.services['natrule']"], {'ipaddressid': 'ipaddress_1.ipaddress.id', 'networkid': 'persistent_network_1.id'}), "(self.api_client, virtual_machine_1, self.services['natrule'],\n ipaddressid=ipaddress_1.ipaddress.id, networkid=persistent_network_1.id)\n", (103112, 103251), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((103352, 103504), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient'], {'ipaddressid': 'ipaddress_2.ipaddress.id', 'virtualmachineid': 'virtual_machine_2.id', 'networkid': 'persistent_network_1.id'}), '(self.apiclient, ipaddressid=ipaddress_2.ipaddress.id,\n virtualmachineid=virtual_machine_2.id, networkid=persistent_network_1.id)\n', (103372, 103504), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((103665, 103862), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']"], {'ipaddressid': 'ipaddress_3.ipaddress.id', 'accountid': 'account.name', 'networkid': 'persistent_network_2.id', 'domainid': 'account.domainid'}), "(self.apiclient, self.services['lbrule'],\n ipaddressid=ipaddress_3.ipaddress.id, accountid=account.name, networkid\n =persistent_network_2.id, domainid=account.domainid)\n", (103688, 103862), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((109034, 109245), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[persistent_network_1.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[persistent_network_1.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (109055, 109245), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((109371, 109582), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[persistent_network_1.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[persistent_network_1.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (109392, 109582), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((109708, 109919), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[persistent_network_2.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[persistent_network_2.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (109729, 109919), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((110045, 110256), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[persistent_network_2.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[persistent_network_2.id], serviceofferingid=self.\n service_offering.id, accountid=account.name, domainid=self.domain.id)\n", (110066, 110256), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((12825, 12855), 'marvin.lib.utils.validateList', 'validateList', (['nw_offering_list'], {}), '(nw_offering_list)\n', (12837, 12855), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((29135, 29156), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (29147, 29156), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((32968, 32989), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (32980, 32989), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((37193, 37219), 'marvin.lib.utils.validateList', 'validateList', (['routers_nw_1'], {}), '(routers_nw_1)\n', (37205, 37219), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((37689, 37715), 'marvin.lib.utils.validateList', 'validateList', (['routers_nw_2'], {}), '(routers_nw_2)\n', (37701, 37715), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((51771, 51793), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (51783, 51793), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((51969, 51993), 'marvin.lib.utils.validateList', 'validateList', (['public_ips'], {}), '(public_ips)\n', (51981, 51993), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((63783, 63805), 'marvin.lib.utils.validateList', 'validateList', (['accounts'], {}), '(accounts)\n', (63795, 63805), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((64263, 64285), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (64275, 64285), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((66212, 66241), 'marvin.lib.utils.validateList', 'validateList', (['projectAccounts'], {}), '(projectAccounts)\n', (66224, 66241), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((66785, 66807), 'marvin.lib.utils.validateList', 'validateList', (['projects'], {}), '(projects)\n', (66797, 66807), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((74187, 74208), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (74199, 74208), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((75641, 75663), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (75653, 75663), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((78870, 78891), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (78882, 78891), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((80017, 80039), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (80029, 80039), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((86748, 86770), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (86760, 86770), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((87008, 87026), 'marvin.lib.utils.validateList', 'validateList', (['vpcs'], {}), '(vpcs)\n', (87020, 87026), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((87284, 87301), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (87296, 87301), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((87566, 87591), 'marvin.lib.utils.validateList', 'validateList', (['networkAcls'], {}), '(networkAcls)\n', (87578, 87591), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((88856, 88874), 'marvin.lib.utils.validateList', 'validateList', (['vpcs'], {}), '(vpcs)\n', (88868, 88874), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((89044, 89068), 'marvin.lib.utils.validateList', 'validateList', (['VpcRouters'], {}), '(VpcRouters)\n', (89056, 89068), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((89294, 89325), 'marvin.lib.utils.validateList', 'validateList', (['publicipaddresses'], {}), '(publicipaddresses)\n', (89306, 89325), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((92178, 92213), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'vpc.id'}), '(self.apiclient, id=vpc.id)\n', (92186, 92213), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((92390, 92434), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'id': 'vpcrouter.id'}), '(self.apiclient, id=vpcrouter.id)\n', (92401, 92434), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((92632, 92696), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.apiclient'], {'id': 'publicipaddresses[0].id'}), '(self.apiclient, id=publicipaddresses[0].id)\n', (92652, 92696), False, 'from marvin.lib.base import Account, VPC, VirtualMachine, LoadBalancerRule, Network, Domain, Router, NetworkACL, PublicIPAddress, VpcOffering, ServiceOffering, Project, NetworkOffering, NATRule, FireWallRule, Host, StaticNATRule\n'), ((106995, 107013), 'marvin.lib.utils.validateList', 'validateList', (['vpcs'], {}), '(vpcs)\n', (107007, 107013), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((6449, 6468), 'marvin.lib.utils.validateList', 'validateList', (['hosts'], {}), '(hosts)\n', (6461, 6468), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((59187, 59209), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (59199, 59209), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((71633, 71652), 'marvin.lib.utils.validateList', 'validateList', (['hosts'], {}), '(hosts)\n', (71645, 71652), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((94363, 94381), 'marvin.lib.utils.validateList', 'validateList', (['vpcs'], {}), '(vpcs)\n', (94375, 94381), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((94777, 94795), 'marvin.lib.utils.validateList', 'validateList', (['vpcs'], {}), '(vpcs)\n', (94789, 94795), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((99229, 99247), 'marvin.lib.utils.validateList', 'validateList', (['vpcs'], {}), '(vpcs)\n', (99241, 99247), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((92243, 92261), 'marvin.lib.utils.validateList', 'validateList', (['vpcs'], {}), '(vpcs)\n', (92255, 92261), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((92464, 92485), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (92476, 92485), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n'), ((92726, 92751), 'marvin.lib.utils.validateList', 'validateList', (['ipaddresses'], {}), '(ipaddresses)\n', (92738, 92751), False, 'from marvin.lib.utils import cleanup_resources, validateList, get_hypervisor_type\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Test cases for validating global limit for concurrent snapshots
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (cleanup_resources,
validateList)
from marvin.lib.base import (Account,
ServiceOffering,
VirtualMachine,
Snapshot,
Volume,
Configurations
)
from marvin.lib.common import (get_domain,
get_zone,
get_template
)
from marvin.codes import PASS, BACKED_UP
from threading import Thread
class TestConcurrentSnapshotLimit(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestConcurrentSnapshotLimit, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
cls.hypervisor = cls.testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
cls._cleanup = []
cls.supportedHypervisor = True
if cls.hypervisor.lower() in [
"hyperv",
"lxc"]:
cls.supportedHypervisor = False
return
# Create Service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
)
cls._cleanup.append(cls.service_offering)
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
self.exceptionOccured = False
if not self.supportedHypervisor:
self.skipTest("Snapshot not supported on %s" % self.hypervisor)
def createSnapshot(self, volumeid):
try:
Snapshot.create(
self.apiclient,
volumeid
)
except Exception as e:
self.debug("Exception occured: %s" % e)
self.exceptionOccured = True
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "basic"], required_hardware="true")
def test_01_concurrent_snapshot_global_limit(self):
""" Test if global value concurrent.snapshots.threshold.perhost
value respected
This is positive test cases and tests if we are able to create
as many snapshots mentioned in global value
# 1. Create an account and a VM in it
# 2. Read the global value for concurrent.snapshots.threshold.perhost
# 3. If the value is Null, create at least 10 concurrent snapshots
and verify they are created successfully
# 4. Else, create as many snapshots specified in the global value, and
verify they are created successfully
"""
# Create an account
account = Account.create(
self.apiclient,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup.append(account)
# Create user api client of the account
userapiclient = self.testClient.getUserApiClient(
UserName=account.name,
DomainName=account.domain
)
# Create VM
virtual_machine = VirtualMachine.create(
userapiclient,
self.testdata["small"],
templateid=self.template.id,
accountid=account.name,
domainid=account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id
)
# Create 10 concurrent snapshots by default
# We can have any value, so keeping it 10 as it
# seems good enough to test
concurrentSnapshots = 10
# Step 1
# Get ROOT Volume Id
volumes = Volume.list(
self.apiclient,
virtualmachineid=virtual_machine.id,
type='ROOT',
listall=True
)
self.assertEqual(validateList(volumes)[0], PASS,
"Volumes list validation failed")
root_volume = volumes[0]
config = Configurations.list(
self.apiclient,
name="concurrent.snapshots.threshold.perhost"
)
self.assertEqual(
isinstance(
config,
list),
True,
"concurrent.snapshots.threshold.perhost should be present\
in global config")
if config[0].value:
concurrentSnapshots = int(config[0].value)
self.debug("concurrent Snapshots: %s" % concurrentSnapshots)
threads = []
for i in range(0, (concurrentSnapshots)):
thread = Thread(
target=Snapshot.create,
args=(
self.apiclient,
root_volume.id
))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
snapshots = Snapshot.list(self.apiclient,
volumeid=root_volume.id,
listall=True)
self.assertEqual(validateList(snapshots)[0], PASS,
"Snapshots list validation failed")
self.assertEqual(
len(snapshots),
concurrentSnapshots,
"There should be exactly %s snapshots present" %
concurrentSnapshots)
for snapshot in snapshots:
self.assertEqual(str(snapshot.state).lower(), BACKED_UP,
"Snapshot state should be backedUp but it is\
%s" % snapshot.state)
return
@attr(tags=["advanced", "basic"], required_hardware="true")
def test_02_concurrent_snapshot_global_limit(self):
""" Test if global value concurrent.snapshots.threshold.perhost
value is respected
This is negative test cases and tests no more concurrent
snapshots as specified in global value are created
# 1. Read the global value for concurrent.snapshots.threshold.perhost
# 2. If the value is Null, skip the test case
# 3. Create an account and a VM in it
# 4. Create more concurrent snapshots than specified in
global allowed limit
# 5. Verify that exception is raised while creating snapshots
"""
config = Configurations.list(
self.apiclient,
name="concurrent.snapshots.threshold.perhost"
)
self.assertEqual(
isinstance(
config,
list),
True,
"concurrent.snapshots.threshold.perhost should be present\
in global config")
if config[0].value:
concurrentSnapshots = int(config[0].value)
else:
self.skipTest("Skipping tests as the config value \
concurrent.snapshots.threshold.perhost is Null")
# Create an account
account = Account.create(
self.apiclient,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup.append(account)
# Create user api client of the account
userapiclient = self.testClient.getUserApiClient(
UserName=account.name,
DomainName=account.domain
)
# Create VM
virtual_machine = VirtualMachine.create(
userapiclient,
self.testdata["small"],
templateid=self.template.id,
accountid=account.name,
domainid=account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id
)
# Step 1
# Get ROOT Volume Id
volumes = Volume.list(
self.apiclient,
virtualmachineid=virtual_machine.id,
type='ROOT',
listall=True
)
self.assertEqual(validateList(volumes)[0], PASS,
"Volumes list validation failed")
root_volume = volumes[0]
threads = []
for i in range(0, (concurrentSnapshots + 1)):
thread = Thread(
target=self.createSnapshot,
args=(
self.apiclient,
root_volume.id
))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
self.assertTrue(self.exceptionOccured, "Concurrent snapshots\
more than concurrent.snapshots.threshold.perhost\
value successfully created")
return
| [
"marvin.lib.utils.validateList",
"marvin.lib.base.Account.create",
"marvin.lib.base.Configurations.list",
"marvin.lib.common.get_domain",
"marvin.lib.base.Volume.list",
"marvin.lib.base.Snapshot.list",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.Snapshot.create",
"marvin.lib.base.Servi... | [((3695, 3753), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (3699, 3753), False, 'from nose.plugins.attrib import attr\n'), ((7324, 7382), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (7328, 7382), False, 'from nose.plugins.attrib import attr\n'), ((1969, 1994), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (1979, 1994), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((2092, 2156), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.testdata['ostype'])\n", (2104, 2156), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((2479, 2550), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {}), "(cls.apiclient, cls.testdata['service_offering'])\n", (2501, 2550), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((4482, 4568), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testdata['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testdata['account'], domainid=self.\n domain.id)\n", (4496, 4568), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((4884, 5098), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['userapiclient', "self.testdata['small']"], {'templateid': 'self.template.id', 'accountid': 'account.name', 'domainid': 'account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id'}), "(userapiclient, self.testdata['small'], templateid=\n self.template.id, accountid=account.name, domainid=account.domainid,\n serviceofferingid=self.service_offering.id, zoneid=self.zone.id)\n", (4905, 5098), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((5427, 5523), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=virtual_machine.id, type=\n 'ROOT', listall=True)\n", (5438, 5523), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((5746, 5833), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""concurrent.snapshots.threshold.perhost"""'}), "(self.apiclient, name=\n 'concurrent.snapshots.threshold.perhost')\n", (5765, 5833), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((6634, 6702), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.apiclient'], {'volumeid': 'root_volume.id', 'listall': '(True)'}), '(self.apiclient, volumeid=root_volume.id, listall=True)\n', (6647, 6702), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((8050, 8137), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""concurrent.snapshots.threshold.perhost"""'}), "(self.apiclient, name=\n 'concurrent.snapshots.threshold.perhost')\n", (8069, 8137), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((8669, 8755), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testdata['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testdata['account'], domainid=self.\n domain.id)\n", (8683, 8755), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((9071, 9285), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['userapiclient', "self.testdata['small']"], {'templateid': 'self.template.id', 'accountid': 'account.name', 'domainid': 'account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id'}), "(userapiclient, self.testdata['small'], templateid=\n self.template.id, accountid=account.name, domainid=account.domainid,\n serviceofferingid=self.service_offering.id, zoneid=self.zone.id)\n", (9092, 9285), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((9436, 9532), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=virtual_machine.id, type=\n 'ROOT', listall=True)\n", (9447, 9532), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((2722, 2768), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (2739, 2768), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((3259, 3300), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'volumeid'], {}), '(self.apiclient, volumeid)\n', (3274, 3300), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Snapshot, Volume, Configurations\n'), ((3521, 3568), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (3538, 3568), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((6333, 6402), 'threading.Thread', 'Thread', ([], {'target': 'Snapshot.create', 'args': '(self.apiclient, root_volume.id)'}), '(target=Snapshot.create, args=(self.apiclient, root_volume.id))\n', (6339, 6402), False, 'from threading import Thread\n'), ((9834, 9907), 'threading.Thread', 'Thread', ([], {'target': 'self.createSnapshot', 'args': '(self.apiclient, root_volume.id)'}), '(target=self.createSnapshot, args=(self.apiclient, root_volume.id))\n', (9840, 9907), False, 'from threading import Thread\n'), ((5603, 5624), 'marvin.lib.utils.validateList', 'validateList', (['volumes'], {}), '(volumes)\n', (5615, 5624), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((6797, 6820), 'marvin.lib.utils.validateList', 'validateList', (['snapshots'], {}), '(snapshots)\n', (6809, 6820), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((9612, 9633), 'marvin.lib.utils.validateList', 'validateList', (['volumes'], {}), '(volumes)\n', (9624, 9633), False, 'from marvin.lib.utils import cleanup_resources, validateList\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for Kubernetes supported version """
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.cloudstackAPI import (listInfrastructure,
listKubernetesSupportedVersions,
addKubernetesSupportedVersion,
deleteKubernetesSupportedVersion)
from marvin.cloudstackException import CloudstackAPIException
from marvin.codes import FAILED
from marvin.lib.base import Configurations
from marvin.lib.utils import (cleanup_resources,
random_gen)
from marvin.lib.common import get_zone
from marvin.sshClient import SshClient
from nose.plugins.attrib import attr
import time
_multiprocess_shared_ = True
class TestKubernetesSupportedVersion(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestKubernetesSupportedVersion, cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
cls.kubernetes_version_iso_url = 'http://download.cloudstack.org/cks/setup-1.24.0.iso'
cls.initial_configuration_cks_enabled = Configurations.list(cls.apiclient,
name="cloud.kubernetes.service.enabled")[0].value
if cls.initial_configuration_cks_enabled not in ["true", True]:
cls.debug("Enabling CloudStack Kubernetes Service plugin and restarting management server")
Configurations.update(cls.apiclient,
"cloud.kubernetes.service.enabled",
"true")
cls.restartServer()
cls._cleanup = []
return
@classmethod
def tearDownClass(cls):
try:
# Restore CKS enabled
if cls.initial_configuration_cks_enabled not in ["true", True]:
cls.debug("Restoring Kubernetes Service enabled value")
Configurations.update(cls.apiclient,
"cloud.kubernetes.service.enabled",
"false")
cls.restartServer()
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def restartServer(cls):
"""Restart management server"""
cls.debug("Restarting management server")
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-management stop"
sshClient.execute(command)
command = "service cloudstack-management start"
sshClient.execute(command)
#Waits for management to come up in 5 mins, when it's up it will continue
timeout = time.time() + 300
while time.time() < timeout:
if cls.isManagementUp() is True:
time.sleep(30)
return
time.sleep(5)
return cls.fail("Management server did not come up, failing")
@classmethod
def isManagementUp(cls):
try:
cls.apiclient.listInfrastructure(listInfrastructure.listInfrastructureCmd())
return True
except Exception:
return False
def setUp(self):
self.services = self.testClient.getParsedTestDataConfig()
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_01_add_delete_kubernetes_supported_version(self):
"""Test to add a new Kubernetes supported version
# Validate the following:
# 1. addKubernetesSupportedVersion should return valid info for new version
# 2. The Cloud Database contains the valid information when listKubernetesSupportedVersions is called
"""
version = self.services["cks_kubernetes_versions"]["1.16.3"]
name = 'v' + version["semanticversion"] + '-' + random_gen()
self.debug("Adding Kubernetes supported version with name: %s" % name)
version_response = self.addKubernetesSupportedVersion(version["semanticversion"], name, self.zone.id, version["url"], version["mincpunumber"], version["minmemory"])
list_versions_response = self.listKubernetesSupportedVersion(version_response.id)
self.assertEqual(
list_versions_response.name,
name,
"Check KubernetesSupportedVersion name {}, {}".format(list_versions_response.name, name)
)
self.assertEqual(
list_versions_response.semanticversion,
version["semanticversion"],
"Check KubernetesSupportedVersion version {}, {}".format(list_versions_response.semanticversion, version["semanticversion"])
)
self.assertEqual(
list_versions_response.zoneid,
self.zone.id,
"Check KubernetesSupportedVersion zone {}, {}".format(list_versions_response.zoneid, self.zone.id)
)
db_version_name = self.dbclient.execute("select name from kubernetes_supported_version where uuid = '%s';" % version_response.id)[0][0]
self.assertEqual(
str(db_version_name),
name,
"Check KubernetesSupportedVersion name in DB {}, {}".format(db_version_name, name)
)
self.debug("Added Kubernetes supported version with ID: %s. Waiting for its ISO to be Ready" % version_response.id)
self.waitForKubernetesSupportedVersionIsoReadyState(version_response.id)
self.debug("Deleting Kubernetes supported version with ID: %s" % version_response.id)
delete_response = self.deleteKubernetesSupportedVersion(version_response.id, True)
self.assertEqual(
delete_response.success,
True,
"Check KubernetesSupportedVersion deletion in DB {}, {}".format(delete_response.success, True)
)
db_version_removed = self.dbclient.execute("select removed from kubernetes_supported_version where uuid = '%s';" % version_response.id)[0][0]
self.assertNotEqual(
db_version_removed,
None,
"KubernetesSupportedVersion not removed in DB"
)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_02_add_unsupported_kubernetes_supported_version(self):
"""Test to trying to add a new unsupported Kubernetes supported version
# Validate the following:
# 1. API should return an error
"""
version = '1.1.1'
name = 'v' + version + '-' + random_gen()
try:
version_response = self.addKubernetesSupportedVersion(version, name, self.zone.id, self.kubernetes_version_iso_url)
self.debug("Unsupported CKS Kubernetes supported added with ID: %s. Deleting it and failing test." % version_response.id)
self.waitForKubernetesSupportedVersionIsoReadyState(version_response.id)
self.deleteKubernetesSupportedVersion(version_response.id, True)
self.fail("Kubernetes supported version below version 1.11.0 been added. Must be an error.")
except CloudstackAPIException as e:
self.debug("Unsupported version error check successful, API failure: %s" % e)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_03_add_invalid_kubernetes_supported_version(self):
"""Test to trying to add a new unsupported Kubernetes supported version
# Validate the following:
# 1. API should return an error
"""
version = 'invalid'
name = 'v' + version + '-' + random_gen()
try:
version_response = self.addKubernetesSupportedVersion(version, name, self.zone.id, self.kubernetes_version_iso_url)
self.debug("Invalid Kubernetes supported added with ID: %s. Deleting it and failing test." % version_response.id)
self.waitForKubernetesSupportedVersionIsoReadyState(version_response.id)
self.deleteKubernetesSupportedVersion(version_response.id, True)
self.fail("Invalid Kubernetes supported version has been added. Must be an error.")
except CloudstackAPIException as e:
self.debug("Unsupported version error check successful, API failure: %s" % e)
return
def addKubernetesSupportedVersion(self, version, name, zoneId, isoUrl, mincpunumber=2, minmemory=2048):
addKubernetesSupportedVersionCmd = addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd()
addKubernetesSupportedVersionCmd.semanticversion = version
addKubernetesSupportedVersionCmd.name = name
addKubernetesSupportedVersionCmd.zoneid = zoneId
addKubernetesSupportedVersionCmd.url = isoUrl
addKubernetesSupportedVersionCmd.mincpunumber = mincpunumber
addKubernetesSupportedVersionCmd.minmemory = minmemory
versionResponse = self.apiclient.addKubernetesSupportedVersion(addKubernetesSupportedVersionCmd)
if not versionResponse:
self.cleanup.append(versionResponse)
return versionResponse
def listKubernetesSupportedVersion(self, versionId):
listKubernetesSupportedVersionsCmd = listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd()
listKubernetesSupportedVersionsCmd.id = versionId
versionResponse = self.apiclient.listKubernetesSupportedVersions(listKubernetesSupportedVersionsCmd)
return versionResponse[0]
def deleteKubernetesSupportedVersion(self, cmd):
response = self.apiclient.deleteKubernetesSupportedVersion(cmd)
return response
def deleteKubernetesSupportedVersion(self, versionId, deleteIso):
deleteKubernetesSupportedVersionCmd = deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd()
deleteKubernetesSupportedVersionCmd.id = versionId
deleteKubernetesSupportedVersionCmd.deleteiso = deleteIso
response = self.apiclient.deleteKubernetesSupportedVersion(deleteKubernetesSupportedVersionCmd)
return response
def waitForKubernetesSupportedVersionIsoReadyState(self, version_id, retries=30, interval=60):
"""Check if Kubernetes supported version ISO is in Ready state"""
while retries > 0:
time.sleep(interval)
list_versions_response = self.listKubernetesSupportedVersion(version_id)
if not hasattr(list_versions_response, 'isostate') or not list_versions_response or not list_versions_response.isostate:
retries = retries - 1
continue
if 'Ready' == list_versions_response.isostate:
return
elif 'Failed' == list_versions_response.isostate:
raise Exception( "Failed to download template: status - %s" % template.status)
retries = retries - 1
raise Exception("Kubernetes supported version Ready state timed out")
| [
"marvin.lib.utils.random_gen",
"marvin.cloudstackAPI.addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd",
"marvin.lib.base.Configurations.update",
"marvin.cloudstackAPI.deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd",
"marvin.lib.base.Configurations.list",
"marvin.lib.uti... | [((4964, 5022), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (4968, 5022), False, 'from nose.plugins.attrib import attr\n'), ((7792, 7850), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (7796, 7850), False, 'from nose.plugins.attrib import attr\n'), ((8860, 8918), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (8864, 8918), False, 'from nose.plugins.attrib import attr\n'), ((3517, 3622), 'marvin.sshClient.SshClient', 'SshClient', (["cls.mgtSvrDetails['mgtSvrIp']", '(22)', "cls.mgtSvrDetails['user']", "cls.mgtSvrDetails['passwd']"], {}), "(cls.mgtSvrDetails['mgtSvrIp'], 22, cls.mgtSvrDetails['user'], cls\n .mgtSvrDetails['passwd'])\n", (3526, 3622), False, 'from marvin.sshClient import SshClient\n'), ((10055, 10119), 'marvin.cloudstackAPI.addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd', 'addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd', ([], {}), '()\n', (10117, 10119), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion\n'), ((10803, 10871), 'marvin.cloudstackAPI.listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd', 'listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd', ([], {}), '()\n', (10869, 10871), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion\n'), ((11340, 11410), 'marvin.cloudstackAPI.deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd', 'deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd', ([], {}), '()\n', (11408, 11410), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion\n'), ((2507, 2592), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""cloud.kubernetes.service.enabled"""', '"""true"""'], {}), "(cls.apiclient, 'cloud.kubernetes.service.enabled', 'true'\n )\n", (2528, 2592), False, 'from marvin.lib.base import Configurations\n'), ((3193, 3239), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (3210, 3239), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((3967, 3978), 'time.time', 'time.time', ([], {}), '()\n', (3976, 3978), False, 'import time\n'), ((3999, 4010), 'time.time', 'time.time', ([], {}), '()\n', (4008, 4010), False, 'import time\n'), ((4133, 4146), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (4143, 4146), False, 'import time\n'), ((4789, 4836), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (4806, 4836), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((5511, 5523), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (5521, 5523), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((8150, 8162), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (8160, 8162), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((9216, 9228), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (9226, 9228), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((11878, 11898), 'time.sleep', 'time.sleep', (['interval'], {}), '(interval)\n', (11888, 11898), False, 'import time\n'), ((2166, 2241), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""cloud.kubernetes.service.enabled"""'}), "(cls.apiclient, name='cloud.kubernetes.service.enabled')\n", (2185, 2241), False, 'from marvin.lib.base import Configurations\n'), ((2987, 3072), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""cloud.kubernetes.service.enabled"""', '"""false"""'], {}), "(cls.apiclient, 'cloud.kubernetes.service.enabled',\n 'false')\n", (3008, 3072), False, 'from marvin.lib.base import Configurations\n'), ((4083, 4097), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (4093, 4097), False, 'import time\n'), ((4322, 4364), 'marvin.cloudstackAPI.listInfrastructure.listInfrastructureCmd', 'listInfrastructure.listInfrastructureCmd', ([], {}), '()\n', (4362, 4364), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Test cases for deploying Virtual Machine using impersonation (passing account and domainId parameters) for shared network
"""
# Import Local Modules
import marvin
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.lib.utils import *
from marvin.lib.base import *
from marvin.lib.common import *
from marvin.cloudstackException import CloudstackAclException
from nose.plugins.attrib import attr
# Import System modules
import time
_multiprocess_shared_ = True
class TestSharedNetworkImpersonation(cloudstackTestCase):
@classmethod
def setUpClass(cls):
"""
Create the following domain tree and accounts that are reqiured for executing impersonation test cases for shared networks:
Under ROOT - create 2 domaind D1 and D2
Under D1 - Create 2 subdomain D11 and D12
Under D11 - Create subdimain D111
Under each of the domain create 1 admin user and couple of regular users.
Create shared network with the following scope:
1. Network with scope="all"
2. Network with scope="domain" with no subdomain access
3. Network with scope="domain" with subdomain access
4. Network with scope="account"
"""
cls.testclient = super(TestSharedNetworkImpersonation, cls).getClsTestClient()
cls.apiclient = cls.testclient.getApiClient()
cls.testdata = cls.testClient.getParsedTestDataConfig()
cls.acldata = cls.testdata["acl"]
cls.domain_1 = None
cls.domain_2 = None
cleanup = []
try:
# backup default apikey and secretkey
cls.default_apikey = cls.apiclient.connection.apiKey
cls.default_secretkey = cls.apiclient.connection.securityKey
# Create domains
cls.domain_1 = Domain.create(
cls.apiclient,
cls.acldata["domain1"]
)
cls.domain_11 = Domain.create(
cls.apiclient,
cls.acldata["domain11"],
parentdomainid=cls.domain_1.id
)
cls.domain_111 = Domain.create(
cls.apiclient,
cls.acldata["domain111"],
parentdomainid=cls.domain_11.id,
)
cls.domain_12 = Domain.create(
cls.apiclient,
cls.acldata["domain12"],
parentdomainid=cls.domain_1.id
)
cls.domain_2 = Domain.create(
cls.apiclient,
cls.acldata["domain2"]
)
# Create 1 admin account and 2 user accounts for doamin_1
cls.account_d1 = Account.create(
cls.apiclient,
cls.acldata["accountD1"],
admin=True,
domainid=cls.domain_1.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d1)
cls.user_d1_apikey = user.apikey
cls.user_d1_secretkey = user.secretkey
cls.account_d1a = Account.create(
cls.apiclient,
cls.acldata["accountD1A"],
admin=False,
domainid=cls.domain_1.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d1a)
cls.user_d1a_apikey = user.apikey
cls.user_d1a_secretkey = user.secretkey
cls.account_d1b = Account.create(
cls.apiclient,
cls.acldata["accountD1B"],
admin=False,
domainid=cls.domain_1.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d1b)
cls.user_d1b_apikey = user.apikey
cls.user_d1b_secretkey = user.secretkey
# Create 1 admin and 2 user accounts for doamin_11
cls.account_d11 = Account.create(
cls.apiclient,
cls.acldata["accountD11"],
admin=True,
domainid=cls.domain_11.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d11)
cls.user_d11_apikey = user.apikey
cls.user_d11_secretkey = user.secretkey
cls.account_d11a = Account.create(
cls.apiclient,
cls.acldata["accountD11A"],
admin=False,
domainid=cls.domain_11.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d11a)
cls.user_d11a_apikey = user.apikey
cls.user_d11a_secretkey = user.secretkey
cls.account_d11b = Account.create(
cls.apiclient,
cls.acldata["accountD11B"],
admin=False,
domainid=cls.domain_11.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d11b)
cls.user_d11b_apikey = user.apikey
cls.user_d11b_secretkey = user.secretkey
# Create 2 user accounts and 1 admin account for doamin_111
cls.account_d111 = Account.create(
cls.apiclient,
cls.acldata["accountD111"],
admin=True,
domainid=cls.domain_111.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d111)
cls.user_d111_apikey = user.apikey
cls.user_d111_secretkey = user.secretkey
cls.account_d111a = Account.create(
cls.apiclient,
cls.acldata["accountD111A"],
admin=False,
domainid=cls.domain_111.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d111a)
cls.user_d111a_apikey = user.apikey
cls.user_d111a_secretkey = user.secretkey
cls.account_d111b = Account.create(
cls.apiclient,
cls.acldata["accountD111B"],
admin=False,
domainid=cls.domain_111.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d111b)
cls.user_d111b_apikey = user.apikey
cls.user_d111b_secretkey = user.secretkey
# Create 2 user accounts for doamin_12
cls.account_d12a = Account.create(
cls.apiclient,
cls.acldata["accountD12A"],
admin=False,
domainid=cls.domain_12.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d12a)
cls.user_d12a_apikey = user.apikey
cls.user_d12a_secretkey = user.secretkey
cls.account_d12b = Account.create(
cls.apiclient,
cls.acldata["accountD12B"],
admin=False,
domainid=cls.domain_12.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d12b)
cls.user_d12b_apikey = user.apikey
cls.user_d12b_secretkey = user.secretkey
# Create 1 user account for domain_2
cls.account_d2a = Account.create(
cls.apiclient,
cls.acldata["accountD2"],
admin=False,
domainid=cls.domain_2.id
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_d2a)
cls.user_d2a_apikey = user.apikey
cls.user_d2a_secretkey = user.secretkey
# Create 1 user account and admin account in "ROOT" domain
cls.account_roota = Account.create(
cls.apiclient,
cls.acldata["accountROOTA"],
admin=False,
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_roota)
cls.user_roota_apikey = user.apikey
cls.user_roota_secretkey = user.secretkey
cls.account_root = Account.create(
cls.apiclient,
cls.acldata["accountROOTA"],
admin=True,
)
user = cls.generateKeysForUser(cls.apiclient, cls.account_root)
cls.user_root_apikey = user.apikey
cls.user_root_secretkey = user.secretkey
# create service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.acldata["service_offering"]["small"]
)
cls.zone = get_zone(cls.apiclient, cls.testclient.getZoneForTests())
cls.acldata['mode'] = cls.zone.networktype
cls.template = get_template(cls.apiclient, cls.zone.id, cls.acldata["ostype"])
## As admin user , create shared network with scope "all","domain" with subdomain access , "domain" without subdomain access and "account"
cls.apiclient.connection.apiKey = cls.default_apikey
cls.apiclient.connection.securityKey = cls.default_secretkey
list_shared_network_offerings_response = NetworkOffering.list(
cls.apiclient,
name="DefaultSharedNetworkOffering",
displayText="Offering for Shared networks"
)
# Override name parameter so that there is no overlap with names being used in other shared network test suites
cls.acldata["network_all"]["name"] = cls.acldata["network_all"]["name"] + "-impersonation"
cls.acldata["network_domain_with_no_subdomain_access"]["name"] = cls.acldata["network_domain_with_no_subdomain_access"]["name"] + "-impersonation"
cls.acldata["network_domain_with_subdomain_access"]["name"] = cls.acldata["network_domain_with_subdomain_access"]["name"] + "-impersonation"
cls.acldata["network_account"]["name"] = cls.acldata["network_account"]["name"] + "-impersonation"
cls.shared_network_offering_id = list_shared_network_offerings_response[0].id
cls.shared_network_all = Network.create(
cls.apiclient,
cls.acldata["network_all"],
networkofferingid=cls.shared_network_offering_id,
zoneid=cls.zone.id
)
cls.shared_network_domain_d11 = Network.create(
cls.apiclient,
cls.acldata["network_domain_with_no_subdomain_access"],
networkofferingid=cls.shared_network_offering_id,
zoneid=cls.zone.id,
domainid=cls.domain_11.id,
subdomainaccess=False
)
cls.shared_network_domain_with_subdomain_d11 = Network.create(
cls.apiclient,
cls.acldata["network_domain_with_subdomain_access"],
networkofferingid=cls.shared_network_offering_id,
zoneid=cls.zone.id,
domainid=cls.domain_11.id,
subdomainaccess=True
)
cls.shared_network_account_d111a = Network.create(
cls.apiclient,
cls.acldata["network_account"],
networkofferingid=cls.shared_network_offering_id,
zoneid=cls.zone.id,
domainid=cls.domain_111.id,
accountid=cls.account_d111a.user[0].username
)
cls.vmdata = {"name": "test",
"displayname": "test"
}
cls.cleanup = [
cls.account_root,
cls.account_roota,
cls.shared_network_all,
cls.service_offering,
]
except Exception as e:
cls.domain_1.delete(cls.apiclient, cleanup="true")
cls.domain_2.delete(cls.apiclient, cleanup="true")
cleanup_resources(cls.apiclient, cls.cleanup)
raise Exception("Failed to create the setup required to execute the test cases: %s" % e)
@classmethod
def tearDownClass(cls):
cls.apiclient = super(TestSharedNetworkImpersonation, cls).getClsTestClient().getApiClient()
cls.apiclient.connection.apiKey = cls.default_apikey
cls.apiclient.connection.securityKey = cls.default_secretkey
cls.domain_1.delete(cls.apiclient, cleanup="true")
cls.domain_2.delete(cls.apiclient, cleanup="true")
cleanup_resources(cls.apiclient, cls.cleanup)
return
def setUp(cls):
cls.apiclient = cls.testClient.getApiClient()
cls.dbclient = cls.testClient.getDbConnection()
def tearDown(cls):
# restore back default apikey and secretkey
cls.apiclient.connection.apiKey = cls.default_apikey
cls.apiclient.connection.securityKey = cls.default_secretkey
return
## Test cases relating to deploying Virtual Machine as ROOT admin for other users in shared network with scope=all
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_all_domainuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for other users in a shared network with scope=all
"""
# Deploy VM for a user in a domain under ROOT as admin
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD1A"]["name"] + "-shared-scope-all-root-admin"
self.vmdata["displayname"] = self.acldata["vmD1A"]["displayname"] + "-shared-scope-all-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d1a.name,
domainid=self.account_d1a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d1a.name and vm.domainid == self.account_d1a.domainid,
True,
"ROOT admin is not able to deploy a VM for other users in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_all_domainadminuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for a domain admin users in a shared network with scope=all
"""
# Deploy VM for an admin user in a domain under ROOT as admin
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD1"]["name"] + "-shared-scope-all-root-admin"
self.vmdata["displayname"] = self.acldata["vmD1"]["displayname"] + "-shared-scope-all-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d1.name,
domainid=self.account_d1.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d1.name and vm.domainid == self.account_d1.domainid,
True,
"ROOT admin is not able to deploy a VM for a domain admin users in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_all_subdomainuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for any user in a subdomain in a shared network with scope=all
"""
# Deploy VM as user in a subdomain under ROOT
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD11A"]["name"] + "-shared-scope-all-root-admin"
self.vmdata["displayname"] = self.acldata["vmD11A"]["displayname"] + "-shared-scope-all-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d11a.name,
domainid=self.account_d11a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11a.name and vm.domainid == self.account_d11a.domainid,
True,
"ROOT admin is not able to deploy a VM for any user in a subdomain in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_all_subdomainadminuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for admin user in a domain in a shared network with scope=all
"""
# Deploy VM as an admin user in a subdomain under ROOT
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD11"]["name"] + "-shared-scope-all-root-admin"
self.vmdata["displayname"] = self.acldata["vmD11"]["displayname"] + "-shared-scope-all-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d11.name,
domainid=self.account_d11.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11.name and vm.domainid == self.account_d11.domainid,
True,
"ROOT admin is not able to deploy a VM for admin user in a domain in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_all_ROOTuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for user in ROOT domain in a shared network with scope=all
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-all-root-admin"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-all-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_roota.name,
domainid=self.account_roota.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_roota.name and vm.domainid == self.account_roota.domainid,
True,
"ROOT admin is not able to deploy a VM for user in ROOT domain in a shared network with scope=all")
## Test cases relating to deploying Virtual Machine as ROOT admin for other users in shared network with scope=Domain and no subdomain access
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_nosubdomainaccess_domainuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for domain user in a shared network with scope=domain with no subdomain access
"""
# Deploy VM as user in a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD11A"]["name"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD11A"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d11a.name,
domainid=self.account_d11a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11a.name and vm.domainid == self.account_d11a.domainid,
True,
"ROOT admin is not able to deploy a VM for domain user in a shared network with scope=domain with no subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_nosubdomainaccess_domainadminuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for domain admin user in a shared network with scope=domain with no subdomain access
"""
# Deploy VM as an admin user in a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD11"]["name"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD11"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d11.name,
domainid=self.account_d11.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11.name and vm.domainid == self.account_d11.domainid,
True,
"ROOT admin is not able to deploy a VM for domain admin user in a shared network with scope=domain with no subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_nosubdomainaccess_subdomainuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for sub domain user in a shared network with scope=domain with no subdomain access
"""
# Deploy VM as user in a subdomain under a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD111A"]["name"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD111A"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d111a.name,
domainid=self.account_d111a.domainid
)
self.fail("ROOT admin is able to deploy a VM for sub domain user in a shared network with scope=domain with no subdomain access")
except Exception as e:
self.debug("When a user from a subdomain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for sub domain user in a shared network with scope=domain with no subdomain access ")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_nosubdomainaccess_subdomainadminuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for sub domain admin user in a shared network with scope=domain with no subdomain access
"""
# Deploy VM as an admin user in a subdomain under a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD111"]["name"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD111"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d111.name,
domainid=self.account_d111.domainid
)
self.fail("ROOT admin is able to deploy a VM for sub domain admin user in a shared network with scope=domain with no subdomain access")
except Exception as e:
self.debug("When a admin user from a subdomain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for sub domain admin user in a shared network with scope=domain with no subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_nosubdomainaccess_parentdomainuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for parent domain user in a shared network with scope=domain with no subdomain access
"""
# Deploy VM as user in parentdomain of a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD1A"]["name"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD1A"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d1a.name,
domainid=self.account_d1a.domainid
)
self.fail(" ROOT admin is able to deploy a VM for parent domain user in a shared network with scope=domain with no subdomain access")
except Exception as e:
self.debug("When a user from parent domain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for parent domain user in a shared network with scope=domain with no subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_nosubdomainaccess_parentdomainadminuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for parent domain admin user in a shared network with scope=domain with no subdomain access
"""
# Deploy VM as an admin user in parentdomain of a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD1"]["name"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD1"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d1.name,
domainid=self.account_d1.domainid
)
self.fail("ROOT admin is able to deploy a VM for parent domain admin user in a shared network with scope=domain with no subdomain access")
except Exception as e:
self.debug("When an admin user from parent domain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for parent domain admin user in a shared network with scope=domain with no subdomain access ")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_nosubdomainaccess_ROOTuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for parent domain admin user in a shared network with scope=domain with no subdomain access
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_roota.name,
domainid=self.account_roota.domainid
)
self.fail("ROOT admin is able to deploy a VM for parent domain admin user in a shared network with scope=domain with no subdomain access")
except Exception as e:
self.debug("When a regular user from ROOT domain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for parent domain admin user in a shared network with scope=domain with no subdomain access")
## Test cases relating to deploying Virtual Machine as ROOT admin for other users in shared network with scope=Domain and with subdomain access
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_withsubdomainaccess_domainuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for domain user in a shared network with scope=domain with subdomain access
"""
# Deploy VM as user in a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD11A"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD11A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d11a.name,
domainid=self.account_d11a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11a.name and vm.domainid == self.account_d11a.domainid,
True,
"ROOT admin is NOT able to deploy a VM for domain user in a shared network with scope=domain with subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_withsubdomainaccess_domainadminuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for domain admin user in a shared network with scope=domain with subdomain access
"""
# Deploy VM as an admin user in a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD11"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD11"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d11.name,
domainid=self.account_d11.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11.name and vm.domainid == self.account_d11.domainid,
True,
"ROOT admin is not able to deploy a VM for domain admin user in a shared network with scope=domain with subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_withsubdomainaccess_subdomainuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for subdomain user in a shared network with scope=domain with subdomain access
"""
# Deploy VM as user in a subdomain under a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD111A"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD111A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d111a.name,
domainid=self.account_d111a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d111a.name and vm.domainid == self.account_d111a.domainid,
True,
"ROOT admin is not able to deploy a VM for subdomain user in a shared network with scope=domain with subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_withsubdomainaccess_subdomainadminuser(self):
"""
Valiate that ROOT admin is able to deploy a VM for subdomain admin user in a shared network with scope=domain with subdomain access
"""
# Deploy VM as an admin user in a subdomain under a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD111"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD111"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d111.name,
domainid=self.account_d111.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d111.name and vm.domainid == self.account_d111.domainid,
True,
"ROOT admin is not able to deploy a VM for subdomain admin user in a shared network with scope=domain with subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_withsubdomainaccess_parentdomainuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for parent domain user in a shared network with scope=domain with subdomain access
"""
# Deploy VM as user in parentdomain of a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD1A"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD1A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d1a.name,
domainid=self.account_d1a.domainid
)
self.fail("ROOT admin is NOT able to deploy a VM for parent domain user in a shared network with scope=domain with subdomain access")
except Exception as e:
self.debug("When a user from parent domain deploys a VM in a shared network with scope=domain with subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for parent domain user in a shared network with scope=domain with subdomain access ")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_withsubdomainaccess_parentdomainadminuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for parent domain admin user in a shared network with scope=domain with subdomain access
"""
# Deploy VM as an admin user in parentdomain of a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD1"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD1"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d1.name,
domainid=self.account_d1.domainid
)
self.fail("ROOT admin is able to deploy a VM for parent domain admin user in a shared network with scope=domain with subdomain access ")
except Exception as e:
self.debug("When an admin user from parent domain deploys a VM in a shared network with scope=domain with subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for parent domain admin user in a shared network with scope=domain with subdomain access ")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_domain_withsubdomainaccess_ROOTuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for user in ROOT domain in a shared network with scope=domain with subdomain access
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.user_roota_apikey
self.apiclient.connection.securityKey = self.user_roota_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_roota.name,
domainid=self.account_roota.domainid
)
self.fail("ROOT admin is able to deploy a VM for user in ROOT domain in a shared network with scope=domain with subdomain access")
except Exception as e:
self.debug("When a user from ROOT domain deploys a VM in a shared network with scope=domain with subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for user in ROOT domain in a shared network with scope=domain with subdomain access")
## Test cases relating to deploying Virtual Machine as ROOT admin for other users in shared network with scope=account
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_account_domainuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for user in the same domain but in a different account in a shared network with scope=account
"""
# Deploy VM as user in a domain under the same domain but different account from the account that has a shared network with scope=account
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD111B"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD111B"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_d111b.name,
domainid=self.account_d111b.domainid
)
self.fail("ROOT admin is able to deploy a VM for user in the same domain but in a different account in a shared network with scope=account")
except Exception as e:
self.debug("When a user from same domain but different account deploys a VM in a shared network with scope=account %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.UNABLE_TO_USE_NETWORK):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for user in the same domain but in a different account in a shared network with scope=account")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_account_domainadminuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for admin user in the same domain but in a different account in a shared network with scope=account
"""
# Deploy VM as admin user for a domain that has an account with shared network with scope=account
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD111"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD111"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_d111.name,
domainid=self.account_d111.domainid
)
self.fail("ROOT admin is able to deploy a VM for admin user in the same domain but in a different account in a shared network with scope=account")
except Exception as e:
self.debug("When a user from same domain but different account deploys a VM in a shared network with scope=account %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.UNABLE_TO_USE_NETWORK):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for admin user in the same domain but in a different account in a shared network with scope=account")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_account_user(self):
"""
Valiate that ROOT admin is able to deploy a VM for regular user in a shared network with scope=account
"""
# Deploy VM as account with shared network with scope=account
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD111A"]["name"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
self.vmdata["displayname"] = self.acldata["vmD111A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-root-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_d111a.name,
domainid=self.account_d111a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d111a.name and vm.domainid == self.account_d111a.domainid,
True,
"ROOT admin is not able to deploy a VM for regular user in a shared network with scope=account")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_account_differentdomain(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for a admin user in a shared network with scope=account which the admin user does not have access to
"""
# Deploy VM as an admin user in a subdomain under ROOT
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmD2A"]["name"] + "-shared-scope-account-root-admin"
self.vmdata["displayname"] = self.acldata["vmD2A"]["displayname"] + "-shared-scope-account-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_d2a.name,
domainid=self.account_d2a.domainid
)
self.fail("ROOT admin is able to deploy a VM for a admin user in a shared network with scope=account which the admin user does not have access to")
except Exception as e:
self.debug("account %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.UNABLE_TO_USE_NETWORK):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for a admin user in a shared network with scope=account which the admin user does not have access to ")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_admin_scope_account_ROOTuser(self):
"""
Valiate that ROOT admin is NOT able to deploy a VM for a user in ROOT domain in a shared network with scope=account which the user does not have access to
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.default_apikey
self.apiclient.connection.securityKey = self.default_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-account-root-admin"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-account-root-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_roota.name,
domainid=self.account_roota.domainid
)
self.fail("ROOT admin is able to deploy a VM for a user in ROOT domain in a shared network with scope=account which the user does not have access to")
except Exception as e:
self.debug("When a user from ROOT domain deploys a VM in a shared network with scope=account %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.UNABLE_TO_USE_NETWORK):
self.fail(
"Error message validation failed when ROOT admin tries to deploy a VM for a user in ROOT domain in a shared network with scope=account which the user does not have access to ")
## Test cases relating to deploying Virtual Machine as Domain admin for other users in shared network with scope=all
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_all_domainuser(self):
"""
Valiate that Domain admin is able to deploy a VM for a domain user in a shared network with scope=all
"""
# Deploy VM for a user in a domain under ROOT as admin
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD1A"]["name"] + "-shared-scope-all-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD1A"]["displayname"] + "-shared-scope-all-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d1a.name,
domainid=self.account_d1a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d1a.name and vm.domainid == self.account_d1a.domainid,
True,
"Domain admin is not able to deploy a VM for a domain user in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_all_domainadminuser(self):
"""
Valiate that Domain admin is able to deploy a VM for a domain admin user in a shared network with scope=all
"""
# Deploy VM for an admin user in a domain under ROOT as admin
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD1"]["name"] + "-shared-scope-all-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD1"]["displayname"] + "-shared-scope-all-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d1.name,
domainid=self.account_d1.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d1.name and vm.domainid == self.account_d1.domainid,
True,
"Domain admin is not able to deploy a VM for a domain admin user in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_all_subdomainuser(self):
"""
Valiate that Domain admin is able to deploy a VM for a sub domain user in a shared network with scope=all
"""
# Deploy VM as user in a subdomain under ROOT
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD11A"]["name"] + "-shared-scope-all-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD11A"]["displayname"] + "-shared-scope-all-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d11a.name,
domainid=self.account_d11a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11a.name and vm.domainid == self.account_d11a.domainid,
True,
"Domain admin is not able to deploy a VM for a sub domain user in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_all_subdomainadminuser(self):
"""
Valiate that Domain admin is able to deploy a VM for a sub domain admin user in a shared network with scope=all
"""
# Deploy VM as an admin user in a subdomain under ROOT
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD11"]["name"] + "-shared-scope-all-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD11"]["displayname"] + "-shared-scope-all-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d11.name,
domainid=self.account_d11.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11.name and vm.domainid == self.account_d11.domainid,
True,
"Domain admin is not able to deploy a VM for a sub domain admin user in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_all_ROOTuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for user in ROOT domain in a shared network with scope=all
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-all"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-all"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_roota.name,
domainid=self.account_roota.domainid
)
self.fail("Domain admin is NOT able to deploy a VM for user in ROOT domain in a shared network with scope=all")
except Exception as e:
self.debug("When a Domain admin user deploys a VM for ROOT user in a shared network with scope=all %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN):
self.fail("Error message validation failed when Domain admin is NOT able to deploy a VM for user in ROOT domain in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_all_crossdomainuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for user in other domain in a shared network with scope=all
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-all"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-all"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d2a.name,
domainid=self.account_d2a.domainid
)
self.fail("Domain admin user is able to Deploy VM for a domain user, but there is no access to in a shared network with scope=domain with no subdomain access ")
except Exception as e:
self.debug("When a Domain admin user deploys a VM for a domain user, but there is no access to in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN):
self.fail(
"Error mesage validation failed when Domain admin user tries to Deploy VM for a domain user, but there is no access to in a shared network with scope=domain with no subdomain access ")
## Test cases relating to deploying Virtual Machine as Domain admin for other users in shared network with scope=Domain and no subdomain access
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_nosubdomainaccess_domainuser(self):
"""
Valiate that Domain admin is able to deploy a VM for domain user in a shared network with scope=Domain and no subdomain access
"""
# Deploy VM as user in a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD11A"]["name"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD11A"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d11a.name,
domainid=self.account_d11a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11a.name and vm.domainid == self.account_d11a.domainid,
True,
"Domain admin is not able to deploy a VM for domain user in a shared network with scope=Domain and no subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_nosubdomainaccess_domainadminuser(self):
"""
Valiate that Domain admin is able to deploy a VM for domain admin user in a shared network with scope=Domain and no subdomain access
"""
# Deploy VM as an admin user in a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD11"]["name"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD11"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d11.name,
domainid=self.account_d11.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11.name and vm.domainid == self.account_d11.domainid,
True,
"Admin User in a domain that has a shared network with no subdomain access failed to Deploy VM in a shared network with scope=domain with no subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_nosubdomainaccess_subdomainuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for sub domain user in a shared network with scope=Domain and no subdomain access
"""
# Deploy VM as user in a subdomain under a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD111A"]["name"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD111A"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d111a.name,
domainid=self.account_d111a.domainid
)
self.fail("Domain admin is able to deploy a VM for sub domain user in a shared network with scope=Domain and no subdomain access")
except Exception as e:
self.debug("When a user from a subdomain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for sub domain user in a shared network with scope=Domain and no subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_nosubdomainaccess_subdomainadminuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for sub domain admin user in a shared network with scope=Domain and no subdomain access
"""
# Deploy VM as an admin user in a subdomain under a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD111"]["name"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD111"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d111.name,
domainid=self.account_d111.domainid
)
self.fail("Domain admin is able to deploy a VM for sub domain admin user in a shared network with scope=Domain and no subdomain access")
except Exception as e:
self.debug("When a admin user from a subdomain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for sub domain admin user in a shared network with scope=Domain and no subdomain access ")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_nosubdomainaccess_parentdomainuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for parent domain user in a shared network with scope=Domain and no subdomain access
"""
# Deploy VM as user in parentdomain of a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD1A"]["name"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD1A"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d1a.name,
domainid=self.account_d1a.domainid
)
self.fail("Domain admin is able to deploy a VM for parent domain user in a shared network with scope=Domain and no subdomain access")
except Exception as e:
self.debug("When a user from parent domain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for parent domain user in a shared network with scope=Domain and no subdomain access ")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_nosubdomainaccess_parentdomainadminuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for parent domain admin user in a shared network with scope=Domain and no subdomain access
"""
# Deploy VM as an admin user in parentdomain of a domain that has shared network with no subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD1"]["name"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD1"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_d1.name,
domainid=self.account_d1.domainid
)
self.fail("Domain admin is able to deploy a VM for parent domain admin user in a shared network with scope=Domain and no subdomain access")
except Exception as e:
self.debug("When an admin user from parent domain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for parent domain admin user in a shared network with scope=Domain and no subdomain access ")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_nosubdomainaccess_ROOTuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for user in ROOT domain in a shared network with scope=Domain and no subdomain access
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-domain-nosubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_d11.id,
accountid=self.account_roota.name,
domainid=self.account_roota.domainid
)
self.fail("Domain admin is able to deploy a VM for user in ROOT domain in a shared network with scope=Domain and no subdomain access")
except Exception as e:
self.debug("When a regular user from ROOT domain deploys a VM in a shared network with scope=domain with no subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for user in ROOT domain in a shared network with scope=Domain and no subdomain access")
## Test cases relating to deploying Virtual Machine as Domain admin for other users in shared network with scope=Domain and with subdomain access
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_withsubdomainaccess_domainuser(self):
"""
Valiate that Domain admin is able to deploy a VM for regular user in domain in a shared network with scope=Domain and subdomain access
"""
# Deploy VM as user in a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD11A"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD11A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d11a.name,
domainid=self.account_d11a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11a.name and vm.domainid == self.account_d11a.domainid,
True,
"Domain admin is not able to deploy a VM for regular user in domain in a shared network with scope=Domain and subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_withsubdomainaccess_domainadminuser(self):
"""
Valiate that Domain admin is able to deploy a VM for admin user in domain in a shared network with scope=Domain and subdomain access
"""
# Deploy VM as an admin user in a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD11"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD11"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d11.name,
domainid=self.account_d11.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d11.name and vm.domainid == self.account_d11.domainid,
True,
"Domain admin is not able to deploy a VM for admin user in domain in a shared network with scope=Domain and subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_withsubdomainaccess_subdomainuser(self):
"""
Valiate that Domain admin is able to deploy a VM for regular user in subdomain in a shared network with scope=Domain and subdomain access
"""
# Deploy VM as user in a subdomain under a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD111A"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD111A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d111a.name,
domainid=self.account_d111a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d111a.name and vm.domainid == self.account_d111a.domainid,
True,
"Domain admin is not able to deploy a VM for regular user in subdomain in a shared network with scope=Domain and subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_withsubdomainaccess_subdomainadminuser(self):
"""
Valiate that Domain admin is able to deploy a VM for admin user in subdomain in a shared network with scope=Domain and subdomain access
"""
# Deploy VM as an admin user in a subdomain under a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD111"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD111"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d111.name,
domainid=self.account_d111.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d111.name and vm.domainid == self.account_d111.domainid,
True,
"Domain admin is not able to deploy a VM for admin user in subdomain in a shared network with scope=Domain and subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_withsubdomainaccess_parentdomainuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for regular user in parent domain in a shared network with scope=Domain and subdomain access
"""
# Deploy VM as user in parentdomain of a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD1A"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD1A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d1a.name,
domainid=self.account_d1a.domainid
)
self.fail(" Domain admin is able to deploy a VM for regular user in parent domain in a shared network with scope=Domain and subdomain access")
except Exception as e:
self.debug("When a user from parent domain deploys a VM in a shared network with scope=domain with subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for regular user in parent domain in a shared network with scope=Domain and subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_withsubdomainaccess_parentdomainadminuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for admin user in parent domain in a shared network with scope=Domain and subdomain access
"""
# Deploy VM as an admin user in parentdomain of a domain that has shared network with subdomain access
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD1"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD1"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_d1.name,
domainid=self.account_d1.domainid
)
self.fail("Domain admin is able to deploy a VM for admin user in parent domain in a shared network with scope=Domain and subdomain access")
except Exception as e:
self.debug("When an admin user from parent domain deploys a VM in a shared network with scope=domain with subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for admin user in parent domain in a shared network with scope=Domain and subdomain access")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_domain_withsubdomainaccess_ROOTuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for user in ROOT domain in a shared network with scope=Domain and subdomain access
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_domain_with_subdomain_d11.id,
accountid=self.account_roota.name,
domainid=self.account_roota.domainid
)
self.fail("Domain admin is able to deploy a VM for user in ROOT domain in a shared network with scope=Domain and subdomain access")
except Exception as e:
self.debug("When a user from ROOT domain deploys a VM in a shared network with scope=domain with subdomain access %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for user in ROOT domain in a shared network with scope=Domain and subdomain access")
## Test cases relating to deploying Virtual Machine as Domain admin for other users in shared network with scope=account
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_account_domainuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for user in the same domain but belonging to a different account in a shared network with scope=account
"""
# Deploy VM as user in a domain under the same domain but different account from the acount that has a shared network with scope=account
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD111B"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD111B"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_d111b.name,
domainid=self.account_d111b.domainid
)
self.fail("Domain admin is able to deploy a VM for user in the same domain but belonging to a different account in a shared network with scope=account")
except Exception as e:
self.debug("When a user from same domain but different account deploys a VM in a shared network with scope=account %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.UNABLE_TO_USE_NETWORK):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for user in the same domain but belonging to a different account in a shared network with scope=account")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_account_domainadminuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for an admin user in the same domain but belonging to a different account in a shared network with scope=account
"""
# Deploy VM as admin user for a domain that has an account with shared network with scope=account
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD111"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD111"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_d111.name,
domainid=self.account_d111.domainid
)
self.fail("Domain admin is able to deploy a VM for user in the same domain but belonging to a different account in a shared network with scope=account")
except Exception as e:
self.debug("When a user from same domain but different account deploys a VM in a shared network with scope=account %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.UNABLE_TO_USE_NETWORK):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for user in the same domain but belonging to a different account in a shared network with scope=account")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_account_user(self):
"""
Valiate that Domain admin is able to deploy a VM for an regular user in a shared network with scope=account
"""
# Deploy VM as account with shared network with scope=account
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD111A"]["name"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD111A"]["displayname"] + "-shared-scope-domain-withsubdomainaccess-domain-admin"
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_d111a.name,
domainid=self.account_d111a.domainid
)
self.assertEqual(vm.state == "Running" and vm.account == self.account_d111a.name and vm.domainid == self.account_d111a.domainid,
True,
"Domain admin is not able to deploy a VM for an regular user in a shared network with scope=account")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_account_differentdomain(self):
"""
Valiate that Domain admin is able NOT able to deploy a VM for an regular user from a differnt domain in a shared network with scope=account
"""
# Deploy VM as an admin user in a subdomain under ROOT
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmD2A"]["name"] + "-shared-scope-account-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD2A"]["displayname"] + "-shared-scope-account-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_d2a.name,
domainid=self.account_d2a.domainid
)
self.fail("Domain admin is able able to deploy a VM for an regular user from a differnt domain in a shared network with scope=account")
except Exception as e:
self.debug("When a user from different domain deploys a VM in a shared network with scope=account %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN):
self.fail(
"Error message validation failed when Domain admin tries to deploy a VM for an regular user from a differnt domain in a shared network with scope=account")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_domainadmin_scope_account_ROOTuser(self):
"""
Valiate that Domain admin is NOT able to deploy a VM for an regular user in ROOT domain in a shared network with scope=account
"""
# Deploy VM as user in ROOT domain
self.apiclient.connection.apiKey = self.user_d1_apikey
self.apiclient.connection.securityKey = self.user_d1_secretkey
self.vmdata["name"] = self.acldata["vmROOTA"]["name"] + "-shared-scope-account-domain-admin"
self.vmdata["displayname"] = self.acldata["vmROOTA"]["displayname"] + "-shared-scope-account-domain-admin"
try:
vm = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_account_d111a.id,
accountid=self.account_roota.name,
domainid=self.account_roota.domainid
)
self.fail("Domain admin is able to deploy a VM for an regular user in ROOT domain in a shared network with scope=account")
except Exception as e:
self.debug("When a user from ROOT domain deploys a VM in a shared network with scope=account %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN):
self.fail("Error message validation failed when Domain admin tries to deploy a VM for an regular user in ROOT domain in a shared network with scope=account")
## Test cases relating to deploying Virtual Machine as Regular user for other users in shared network with scope=all
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_regularuser_scope_all_anotherusersamedomain(self):
"""
Valiate that regular user is able NOT able to deploy a VM for another user in the same domain in a shared network with scope=all
"""
# Deploy VM for a user in a domain under ROOT as admin
self.apiclient.connection.apiKey = self.user_d11a_apikey
self.apiclient.connection.securityKey = self.user_d11a_secretkey
self.vmdata["name"] = self.acldata["vmD11A"]["name"] + "-shared-scope-all-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD11A"]["displayname"] + "-shared-scope-all-domain-admin"
try:
vm_d1a = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d12a.name,
domainid=self.account_d12a.domainid
)
self.fail("Regular user is allowed to deploy a VM for another user in the same domain in a shared network with scope=all")
except Exception as e:
self.debug("When a regular user deploys a VM for another user in the same domain in a shared network with scope=all %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NO_PERMISSION_TO_OPERATE_ACCOUNT):
self.fail("Error message validation failed when Regular user tries to deploy a VM for another user in the same domain in a shared network with scope=all")
@attr("simulator_only", tags=["advanced"], required_hardware="false")
def test_deployVM_in_sharedNetwork_as_regularuser_scope_all_crossdomain(self):
"""
Valiate that regular user is able NOT able to deploy a VM for another user in a different domain in a shared network with scope=all
"""
# Deploy VM for a user in a domain under ROOT as admin
self.apiclient.connection.apiKey = self.user_d11a_apikey
self.apiclient.connection.securityKey = self.user_d11a_secretkey
self.vmdata["name"] = self.acldata["vmD11A"]["name"] + "-shared-scope-all-domain-admin"
self.vmdata["displayname"] = self.acldata["vmD11A"]["displayname"] + "-shared-scope-all-domain-admin"
try:
vm_d1a = VirtualMachine.create(
self.apiclient,
self.vmdata,
zoneid=self.zone.id,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
networkids=self.shared_network_all.id,
accountid=self.account_d2a.name,
domainid=self.account_d2a.domainid
)
self.fail("Regular user is allowed to deploy a VM for another user in the same domain in a shared network with scope=all")
except Exception as e:
self.debug("When a regular user deploys a VM for another user in the same domain in a shared network with scope=all %s" % e)
if not CloudstackAclException.verifyMsginException(e, CloudstackAclException.NO_PERMISSION_TO_OPERATE_ACCOUNT):
self.fail("Error message validation failed when Regular user tries to deploy a VM for another user in the same domain in a shared network with scope=all")
@staticmethod
def generateKeysForUser(apiclient, account):
user = User.list(
apiclient,
account=account.name,
domainid=account.domainid
)[0]
return (User.registerUserKeys(
apiclient,
user.id
))
| [
"marvin.cloudstackException.CloudstackAclException.verifyMsginException"
] | [((13628, 13696), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (13632, 13696), False, 'from nose.plugins.attrib import attr\n'), ((14963, 15031), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (14967, 15031), False, 'from nose.plugins.attrib import attr\n'), ((16322, 16390), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (16326, 16390), False, 'from nose.plugins.attrib import attr\n'), ((17679, 17747), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (17683, 17747), False, 'from nose.plugins.attrib import attr\n'), ((19043, 19111), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (19047, 19111), False, 'from nose.plugins.attrib import attr\n'), ((20530, 20598), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (20534, 20598), False, 'from nose.plugins.attrib import attr\n'), ((22023, 22091), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (22027, 22091), False, 'from nose.plugins.attrib import attr\n'), ((23536, 23604), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (23540, 23604), False, 'from nose.plugins.attrib import attr\n'), ((25434, 25502), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (25438, 25502), False, 'from nose.plugins.attrib import attr\n'), ((27363, 27431), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (27367, 27431), False, 'from nose.plugins.attrib import attr\n'), ((29263, 29331), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (29267, 29331), False, 'from nose.plugins.attrib import attr\n'), ((31198, 31266), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (31202, 31266), False, 'from nose.plugins.attrib import attr\n'), ((33207, 33275), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (33211, 33275), False, 'from nose.plugins.attrib import attr\n'), ((34712, 34780), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (34716, 34780), False, 'from nose.plugins.attrib import attr\n'), ((36237, 36305), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (36241, 36305), False, 'from nose.plugins.attrib import attr\n'), ((37775, 37843), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (37779, 37843), False, 'from nose.plugins.attrib import attr\n'), ((39333, 39401), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (39337, 39401), False, 'from nose.plugins.attrib import attr\n'), ((41242, 41310), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (41246, 41310), False, 'from nose.plugins.attrib import attr\n'), ((43185, 43253), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (43189, 43253), False, 'from nose.plugins.attrib import attr\n'), ((45161, 45229), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (45165, 45229), False, 'from nose.plugins.attrib import attr\n'), ((47110, 47178), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (47114, 47178), False, 'from nose.plugins.attrib import attr\n'), ((49038, 49106), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (49042, 49106), False, 'from nose.plugins.attrib import attr\n'), ((50456, 50524), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (50460, 50524), False, 'from nose.plugins.attrib import attr\n'), ((52208, 52276), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (52212, 52276), False, 'from nose.plugins.attrib import attr\n'), ((54145, 54213), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (54149, 54213), False, 'from nose.plugins.attrib import attr\n'), ((55497, 55565), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (55501, 55565), False, 'from nose.plugins.attrib import attr\n'), ((56867, 56935), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (56871, 56935), False, 'from nose.plugins.attrib import attr\n'), ((58226, 58294), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (58230, 58294), False, 'from nose.plugins.attrib import attr\n'), ((59605, 59673), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (59609, 59673), False, 'from nose.plugins.attrib import attr\n'), ((61256, 61324), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (61260, 61324), False, 'from nose.plugins.attrib import attr\n'), ((63237, 63305), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (63241, 63305), False, 'from nose.plugins.attrib import attr\n'), ((64741, 64809), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (64745, 64809), False, 'from nose.plugins.attrib import attr\n'), ((66300, 66368), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (66304, 66368), False, 'from nose.plugins.attrib import attr\n'), ((68208, 68276), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (68212, 68276), False, 'from nose.plugins.attrib import attr\n'), ((70151, 70219), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (70155, 70219), False, 'from nose.plugins.attrib import attr\n'), ((72063, 72131), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (72067, 72131), False, 'from nose.plugins.attrib import attr\n'), ((74011, 74079), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (74015, 74079), False, 'from nose.plugins.attrib import attr\n'), ((76027, 76095), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (76031, 76095), False, 'from nose.plugins.attrib import attr\n'), ((77565, 77633), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (77569, 77633), False, 'from nose.plugins.attrib import attr\n'), ((79107, 79175), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (79111, 79175), False, 'from nose.plugins.attrib import attr\n'), ((80678, 80746), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (80682, 80746), False, 'from nose.plugins.attrib import attr\n'), ((82253, 82321), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (82257, 82321), False, 'from nose.plugins.attrib import attr\n'), ((84203, 84271), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (84207, 84271), False, 'from nose.plugins.attrib import attr\n'), ((86166, 86234), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (86170, 86234), False, 'from nose.plugins.attrib import attr\n'), ((88158, 88226), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (88162, 88226), False, 'from nose.plugins.attrib import attr\n'), ((90151, 90219), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (90155, 90219), False, 'from nose.plugins.attrib import attr\n'), ((92115, 92183), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (92119, 92183), False, 'from nose.plugins.attrib import attr\n'), ((93552, 93620), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (93556, 93620), False, 'from nose.plugins.attrib import attr\n'), ((95359, 95427), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (95363, 95427), False, 'from nose.plugins.attrib import attr\n'), ((97209, 97277), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (97213, 97277), False, 'from nose.plugins.attrib import attr\n'), ((98976, 99044), 'nose.plugins.attrib.attr', 'attr', (['"""simulator_only"""'], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "('simulator_only', tags=['advanced'], required_hardware='false')\n", (98980, 99044), False, 'from nose.plugins.attrib import attr\n'), ((25129, 25228), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (25172, 25228), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((27053, 27152), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (27096, 27152), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((28955, 29054), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (28998, 29054), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((30884, 30983), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (30927, 30983), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((32745, 32844), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (32788, 32844), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((40937, 41036), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (40980, 41036), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((42874, 42973), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (42917, 42973), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((44732, 44831), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (44775, 44831), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((46797, 46894), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.UNABLE_TO_USE_NETWORK'], {}), '(e, CloudstackAclException.\n UNABLE_TO_USE_NETWORK)\n', (46840, 46894), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((48719, 48816), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.UNABLE_TO_USE_NETWORK'], {}), '(e, CloudstackAclException.\n UNABLE_TO_USE_NETWORK)\n', (48762, 48816), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((51887, 51984), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.UNABLE_TO_USE_NETWORK'], {}), '(e, CloudstackAclException.\n UNABLE_TO_USE_NETWORK)\n', (51930, 51984), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((53699, 53796), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.UNABLE_TO_USE_NETWORK'], {}), '(e, CloudstackAclException.\n UNABLE_TO_USE_NETWORK)\n', (53742, 53796), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((60981, 61088), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN'], {}), '(e, CloudstackAclException.\n NO_PERMISSION_TO_OPERATE_DOMAIN)\n', (61024, 61088), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((62746, 62853), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN'], {}), '(e, CloudstackAclException.\n NO_PERMISSION_TO_OPERATE_DOMAIN)\n', (62789, 62853), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((67903, 68002), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (67946, 68002), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((69839, 69938), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (69882, 69938), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((71754, 71853), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (71797, 71853), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((73696, 73795), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (73739, 73795), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((75559, 75666), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN'], {}), '(e, CloudstackAclException.\n NO_PERMISSION_TO_OPERATE_DOMAIN)\n', (75602, 75666), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((83887, 83986), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (83930, 83986), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((85852, 85951), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NOT_AVAILABLE_IN_DOMAIN'], {}), '(e, CloudstackAclException.\n NOT_AVAILABLE_IN_DOMAIN)\n', (85895, 85951), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((87718, 87825), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN'], {}), '(e, CloudstackAclException.\n NO_PERMISSION_TO_OPERATE_DOMAIN)\n', (87761, 87825), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((89826, 89923), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.UNABLE_TO_USE_NETWORK'], {}), '(e, CloudstackAclException.\n UNABLE_TO_USE_NETWORK)\n', (89869, 89923), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((91790, 91887), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.UNABLE_TO_USE_NETWORK'], {}), '(e, CloudstackAclException.\n UNABLE_TO_USE_NETWORK)\n', (91833, 91887), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((95046, 95153), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN'], {}), '(e, CloudstackAclException.\n NO_PERMISSION_TO_OPERATE_DOMAIN)\n', (95089, 95153), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((96803, 96910), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NO_PERMISSION_TO_OPERATE_DOMAIN'], {}), '(e, CloudstackAclException.\n NO_PERMISSION_TO_OPERATE_DOMAIN)\n', (96846, 96910), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((98694, 98802), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NO_PERMISSION_TO_OPERATE_ACCOUNT'], {}), '(e, CloudstackAclException.\n NO_PERMISSION_TO_OPERATE_ACCOUNT)\n', (98737, 98802), False, 'from marvin.cloudstackException import CloudstackAclException\n'), ((100451, 100559), 'marvin.cloudstackException.CloudstackAclException.verifyMsginException', 'CloudstackAclException.verifyMsginException', (['e', 'CloudstackAclException.NO_PERMISSION_TO_OPERATE_ACCOUNT'], {}), '(e, CloudstackAclException.\n NO_PERMISSION_TO_OPERATE_ACCOUNT)\n', (100494, 100559), False, 'from marvin.cloudstackException import CloudstackAclException\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#from marvin.cloudstackAPI import *
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import PhysicalNetwork
from marvin.lib.common import setNonContiguousVlanIds, get_zone
from nose.plugins.attrib import attr
class TestUpdatePhysicalNetwork(cloudstackTestCase):
"""
Test to extend physical network vlan range
"""
def setUp(self):
self.apiClient = self.testClient.getApiClient()
self.zone = get_zone(self.apiClient, self.testClient.getZoneForTests())
self.physicalnetwork, self.vlan = setNonContiguousVlanIds(self.apiClient, self.zone.id)
self.physicalnetworkid = self.physicalnetwork.id
self.existing_vlan = self.physicalnetwork.vlan
if self.vlan is None:
raise Exception("Failed to set non contiguous vlan ids to test. Free some ids from \
from existing physical networks at ends")
@attr(tags = ["advanced"], required_hardware="false")
def test_extendPhysicalNetworkVlan(self):
"""
Test to update a physical network and extend its vlan
"""
phy_networks = PhysicalNetwork.list(self.apiClient)
self.assertNotEqual(len(phy_networks), 0,
msg="There are no physical networks in the zone")
phy_network = None
for network in phy_networks:
if hasattr(network, 'vlan'):
phy_network = network
break
self.assert_(phy_network is not None, msg="No network with vlan found")
self.network = phy_network
self.networkid = phy_network.id
self.existing_vlan = phy_network.vlan
vlan1 = self.existing_vlan+","+self.vlan["partial_range"][0]
updatePhysicalNetworkResponse = self.network.update(self.apiClient, id = self.networkid, vlan = vlan1)
self.assert_(updatePhysicalNetworkResponse is not None,
msg="couldn't extend the physical network with vlan %s"%vlan1)
self.assert_(isinstance(self.network, PhysicalNetwork))
vlan2 = vlan1+","+self.vlan["partial_range"][1]
updatePhysicalNetworkResponse2 = self.network.update(self.apiClient, id = self.networkid, vlan = vlan2)
self.assert_(updatePhysicalNetworkResponse2 is not None,
msg="couldn't extend the physical network with vlan %s"%vlan2)
self.assert_(isinstance(self.network, PhysicalNetwork))
vlanranges= updatePhysicalNetworkResponse2.vlan
self.assert_(vlanranges is not None,
"No VLAN ranges found on the deployment")
def tearDown(self):
"""
Teardown to update a physical network and shrink its vlan
@return:
"""
phy_networks = PhysicalNetwork.list(self.apiClient)
self.assertNotEqual(len(phy_networks), 0,
msg="There are no physical networks in the zone")
self.network = phy_networks[0]
self.networkid = phy_networks[0].id
updateResponse = self.network.update(self.apiClient, id = self.networkid, vlan=self.existing_vlan)
self.assert_(updateResponse.vlan.find(self.vlan["full_range"]) < 0,
"VLAN was not removed successfully")
| [
"marvin.lib.base.PhysicalNetwork.list",
"marvin.lib.common.setNonContiguousVlanIds"
] | [((1708, 1758), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (1712, 1758), False, 'from nose.plugins.attrib import attr\n'), ((1341, 1394), 'marvin.lib.common.setNonContiguousVlanIds', 'setNonContiguousVlanIds', (['self.apiClient', 'self.zone.id'], {}), '(self.apiClient, self.zone.id)\n', (1364, 1394), False, 'from marvin.lib.common import setNonContiguousVlanIds, get_zone\n'), ((1916, 1952), 'marvin.lib.base.PhysicalNetwork.list', 'PhysicalNetwork.list', (['self.apiClient'], {}), '(self.apiClient)\n', (1936, 1952), False, 'from marvin.lib.base import PhysicalNetwork\n'), ((3502, 3538), 'marvin.lib.base.PhysicalNetwork.list', 'PhysicalNetwork.list', (['self.apiClient'], {}), '(self.apiClient)\n', (3522, 3538), False, 'from marvin.lib.base import PhysicalNetwork\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Component tests for extra dhcp options functionality with
Nuage VSP SDN plugin
"""
# Import Local Modules
from nuageTestCase import (nuageTestCase, gherkin)
from marvin.cloudstackAPI import updateVirtualMachine, updateZone
from marvin.lib.base import (Account,
Network,
VirtualMachine,
Configurations,
NetworkOffering)
# Import System Modules
from concurrent.futures import ThreadPoolExecutor, wait
from nose.plugins.attrib import attr
import copy
import time
class TestNuageExtraDhcp(nuageTestCase):
""" Test basic VPC Network functionality with Nuage VSP SDN plugin
"""
@classmethod
def setUpClass(cls, zone=None):
super(TestNuageExtraDhcp, cls).setUpClass()
cls.vmdata = cls.test_data["virtual_machine"]
cls.sharednetworkdata = cls.test_data["acl"]
# Create an account
cls.account = Account.create(cls.api_client,
cls.test_data["account"],
admin=True,
domainid=cls.domain.id
)
cmd = updateZone.updateZoneCmd()
cmd.id = cls.zone.id
cmd.domain = "testvpc.com"
cls.api_client.updateZone(cmd)
cls.vpc_offering = cls.create_VpcOffering(
cls.test_data["nuagevsp"]["vpc_offering_nuage_dhcp"])
cls.vpc1 = cls.create_Vpc(cls.vpc_offering, cidr="10.0.0.0/16",
networkDomain="testvpc.com")
cls.vpc_network_offering = cls.create_NetworkOffering(
cls.test_data["nuagevsp"]["vpc_network_offering_nuage_dhcp"])
cls.vpc_network = cls.create_Network(
cls.vpc_network_offering, gateway="10.0.0.1", vpc=cls.vpc1)
cmd.domain = "testisolated.com"
cls.api_client.updateZone(cmd)
# create the isolated network
cls.isolated_network_offering = cls.create_NetworkOffering(
cls.test_data["nuagevsp"]["isolated_network_offering"], True)
cls.isolated_network = cls.create_Network(
cls.isolated_network_offering, gateway="10.0.0.1",
netmask="255.255.255.0")
cmd.domain = "testshared.com"
cls.api_client.updateZone(cmd)
# Create Shared Network
cls.shared_network_offering = NetworkOffering.create(
cls.api_client,
cls.test_data["nuagevsp"]["shared_nuage_network_offering"],
conservemode=False
)
cls.shared_network_offering.update(cls.api_client, state='Enabled')
cls.shared_network_offering_id = cls.shared_network_offering.id
cls.shared_network_all = Network.create(
cls.api_client,
cls.test_data["nuagevsp"]["network_all"],
networkofferingid=cls.shared_network_offering_id,
zoneid=cls.zone.id
)
cls.dhcp_options_map = {}
cls.dhcp_options_to_verify_map = {}
cls.expected_dhcp_options_on_vm = {}
cls.dhcp_options_map_keys = [1, 16, 28, 41, 64, 93]
cls._cleanup.append(cls.account)
cls._cleanup.append(cls.shared_network_offering)
cls._cleanup.append(cls.shared_network_all)
def setUp(self):
self.vmdata["displayname"] = "vm"
self.vmdata["name"] = "vm"
self.update_NuageVspGlobalDomainTemplateName(name="")
self.dhcp_options_map.update({1: {"dhcp:1": "255.255.255.0",
"dhcp:2": "10",
"dhcp:4": "10.0.0.2,"
"10.0.0.3,"
"10.0.0.4",
"dhcp:7": "10.0.0.5,10.0.0.6",
"dhcp:9": "10.0.0.7",
"dhcp:13": "255",
}})
self.dhcp_options_map.update({16: {"dhcp:16": "10.0.0.8",
"dhcp:17": "/tmp/",
"dhcp:18": "/ext/",
"dhcp:19": "1",
"non-local-source-routing": "0",
"policy-filter": "10.1.2.12,"
"255.255.255.0",
"max-datagram-reassembly": "1000",
"default-ttl": "255",
"mtu": "1024",
"all-subnets-local": "1"}})
self.dhcp_options_map.update({28: {"broadcast": "10.1.2.255",
"router-discovery": "0",
"router-solicitation": "10.1.2.2",
"static-route": "10.0.0.1,10.0.0.2",
"trailer-encapsulation": "1",
"arp-timeout": "255",
"ethernet-encap": "1",
"tcp-ttl": "255",
"tcp-keepalive": "255",
"nis-domain": "www.test.com"}})
self.dhcp_options_map.update({41: {"nis-server": "10.1.1.1,10.1.1.2",
"ntp-server": "10.1.1.3,10.1.1.4",
"netbios-ns": "10.1.1.5,10.1.1.6",
"netbios-dd": "10.1.1.8,10.1.1.7",
"netbios-nodetype": "08",
"netbios-scope": "test2",
"x-windows-fs": "10.1.2.13,"
"10.1.2.16",
"x-windows-dm": "10.1.2.14,"
"10.1.2.15",
"requested-address": "10.1.2.16",
"vendor-class": "01"}})
self.dhcp_options_map.update({64: {"nis+-domain": "www.test3.com",
"nis+-server": "10.1.2.255,"
"10.1.2.254",
"tftp-server": "www.test4.com",
"bootfile-name": "file.txt",
"mobile-ip-home": "10.1.2.18,"
"10.1.2.19",
"smtp-server": "10.1.2.20,"
"10.1.2.21",
"pop3-server": "10.1.2.2,10.1.2.3",
"nntp-server": "10.1.2.5,10.1.2.4",
"irc-server": "10.1.2.1,10.1.2.4",
"user-class": "user-class"}})
self.dhcp_options_map.update({93: {"client-arch": "16",
"client-interface-id": "01",
"client-machine-id": "01",
"dhcp:114":
"http://www.testdhcpfeature."
"com/adfsgbfgtdhh125ki-23-fdh"
"-09",
"domain-search": "www.domain.com",
"sip-server": "www.sip.com",
"classless-static-route":
"10.1.0.0/16,10.1.0.1",
"vendor-id-encap":
"0000ACEF04CAFEBABE"
}})
self.dhcp_options_to_verify_map.update({1: {1: "255.255.255.0",
2: "10",
4: ["10.0.0.2",
"10.0.0.3",
"10.0.0.4"],
7: ["10.0.0.5",
"10.0.0.6"],
9: "10.0.0.7",
13: "255"}})
self.dhcp_options_to_verify_map.update({16: {16: "10.0.0.8",
17: "/tmp/",
18: "/ext/",
19: "1",
20: "0",
21: ["10.1.2.12",
"255.255.255.0"],
22: "1000",
23: "255",
26: "1024",
27: "1"}})
self.dhcp_options_to_verify_map.update({28: {28: "10.1.2.255",
31: "0",
32: "10.1.2.2",
33: ["10.0.0.1",
"10.0.0.2"],
34: "1",
35: "255",
36: "1",
37: "255",
38: "255",
40: "www.test.com"}})
self.dhcp_options_to_verify_map.update({41: {41: ["10.1.1.1",
"10.1.1.2"],
42: ["10.1.1.3",
"10.1.1.4"],
44: ["10.1.1.5",
"10.1.1.6"],
45: ["10.1.1.8",
"10.1.1.7"],
46: "H-node",
47: "test2",
48: ["10.1.2.13",
"10.1.2.16"],
49: ["10.1.2.14",
"10.1.2.15"],
50: "10.1.2.16",
60: "01"}})
self.dhcp_options_to_verify_map.update({64: {64: "www.test3.com",
65: ["10.1.2.255",
"10.1.2.254"],
66: "www.test4.com",
67: "file.txt",
68: ["10.1.2.18",
"10.1.2.19"],
69: ["10.1.2.20",
"10.1.2.21"],
70: ["10.1.2.2",
"10.1.2.3"],
71: ["10.1.2.5",
"10.1.2.4"],
74: ["10.1.2.1",
"10.1.2.4"],
77: "user-class"}})
self.dhcp_options_to_verify_map.update({93: {93: "16",
94: "01",
97: "01",
114: "http://www.testdhcp"
"feature.com/adfsgbf"
"gtdhh125ki-23-fdh-"
"09",
119: "www.domain.com",
120: "www.sip.com",
121: ["10.1.0.0/16",
"10.1.0.1"],
125: "0000acef04cafebabe"
}})
self.expected_dhcp_options_on_vm.update({46: "netbios-node-type 8",
60: "vendor-class-identifier"
" 1",
94: "unknown-94 1",
93: "unknown-93",
97: "unknown-97 1",
119: "unknown-119",
120: "unknown-120",
121: "unknown-121",
125: "0:0:ac:ef:4:ca:fe:ba:be"
})
self.cleanup = []
return
def tearDown(self):
super(TestNuageExtraDhcp, self).tearDown()
# Cleanup resources used
self.debug("Cleaning up the resources")
self.update_NuageVspGlobalDomainTemplateName(name="")
self.debug("Cleanup complete!")
return
def retrieve_dhcp_values_to_verify_on_vm_based_on(self, dhcp_map):
vm_dhcp_map = copy.deepcopy(dhcp_map)
for dhcpcode, dhcpval in self.expected_dhcp_options_on_vm.iteritems():
if dhcpcode in dhcp_map:
vm_dhcp_map[dhcpcode] = dhcpval
return vm_dhcp_map
def verify_vsd_dhcp_option_subnet(self, dhcp_type, value, subnet):
self.debug("Verifying the creation and value of DHCP option type -"
" %s in VSD" % dhcp_type)
found_dhcp_type = False
dhcp_options = self.vsd.get_subnet_dhcpoptions(
filter=self.get_externalID_filter(subnet.id))
for dhcp_option in dhcp_options:
self.debug("dhcptype option in vsd is : %s"
% dhcp_option.actual_type)
self.debug("dhcptype expected value is: %s" % value)
if dhcp_option.actual_type == dhcp_type:
found_dhcp_type = True
if isinstance(dhcp_option.actual_values, list):
self.debug("dhcptype actual value on vsd is %s:"
"" % dhcp_option.actual_values)
if value in dhcp_option.actual_values:
self.debug("Excepted DHCP option value found in"
" VSD")
else:
self.fail("Excepted DHCP option value not found"
" in VSD")
else:
self.debug("dhcptype actual value on vsd is %s:"
% dhcp_option.actual_values)
self.assertEqual(dhcp_option.actual_values, value,
"Expected DHCP option value is not same"
" in both CloudStack and VSD")
if not found_dhcp_type:
self.fail("Expected DHCP option type and value not found"
" in the VSD")
self.debug("Successfully verified the creation and value of DHCP"
" option type - %s in VSD" % dhcp_type)
def verify_vsd_dhcp_option(self, dhcp_type, value, vm_interface):
self.debug("Verifying the creation and value of DHCP option type -"
" %s in VSD" % dhcp_type)
self.debug("Expected value for this dhcp option is - %s in VSD"
% value)
found_dhcp_type = False
dhcp_options = self.vsd.get_vm_interface_dhcpoptions(
filter=self.get_externalID_filter(vm_interface.id))
for dhcp_option in dhcp_options:
self.debug("dhcptype on vsd is %s:" % dhcp_option.actual_type)
self.debug("dhcp value on vsd is: %s:" % dhcp_option.actual_values)
if dhcp_option.actual_type == dhcp_type:
found_dhcp_type = True
if isinstance(dhcp_option.actual_values, list):
self.debug("dhcptype actual value is %s:" %
dhcp_option.actual_values)
if type(value) is list:
for val in value:
self.is_value_in_options(dhcp_option.actual_values,
val)
else:
self.is_value_in_options(dhcp_option.actual_values,
value)
else:
self.assertEqual(dhcp_option.actual_values, value,
"Expected DHCP option value is not same"
" in both CloudStack and VSD")
if not found_dhcp_type:
self.fail("Expected DHCP option type and value not found in "
"the VSD for dhcp type %s " % dhcp_type)
self.debug("Successfully verified the creation and value of DHCP"
" option type - %s in VSD" % dhcp_type)
def is_value_in_options(self, actual_options, value):
if value in actual_options:
self.debug("Excepted DHCP option value found in VSD")
else:
self.fail("Excepted DHCP option value not found in VSD")
def verify_vsd_dhcp_option_empty(self, dhcp_type, vm_interface):
self.debug("Verifying the creation and value of DHCP option"
" type - %s in VSD" % dhcp_type)
self.debug("Expected value is empty string")
dhcp_options = self.vsd.get_vm_interface_dhcpoptions(
filter=self.get_externalID_filter(vm_interface.id))
for dhcp_option in dhcp_options:
self.debug("dhcptype on vsd is %s:" % dhcp_option.actual_type)
self.debug("dhcp value on vsd is: %s:" % dhcp_option.value)
if dhcp_option.actual_type == dhcp_type:
if dhcp_type == 15:
self.assertEqual(dhcp_option.value, "\x00",
"Expected DHCP option value is not"
" same in both CloudStack and VSD")
else:
self.assertEqual(dhcp_option.value, "00",
"Expected DHCP option value is not"
" same in both CloudStack and VSD")
self.debug("Successfully verified the creation and value of"
" DHCP option type - %s in VSD" % dhcp_type)
def verify_vsd_dhcp_value_notpresent(self, value, vm_interface):
self.debug("Verifying that on vminterface value is not present- %s"
% value)
dhcp_options = self.vsd.get_vm_interface_dhcpoptions(
filter=self.get_externalID_filter(vm_interface.id))
for dhcp_option in dhcp_options:
self.debug("dhcptype option is %s:" % dhcp_option.actual_type)
if isinstance(dhcp_option.actual_values, list):
self.debug("dhcptype actual value is %s:"
% dhcp_option.actual_values)
if value in dhcp_option.actual_values:
self.fail("This value is not expected on vminterface but "
"present as dhcp_type %s"
% dhcp_option.actual_type)
else:
self.debug("As Excepted DHCP value not found in VSD")
else:
try:
self.assertEqual(dhcp_option.actual_values, value,
"Expected DHCP option value is not same "
"in both CloudStack and VSD")
self.fail("This value is not expected on vm interface but "
"present as dhcp_type %s"
% dhcp_option.actual_type)
except Exception:
self.debug("As Expected DHCP value not found in VSD")
self.debug("Successfully verified dhcp value is not present - %s "
"in VSD" % value)
def verify_vsd_dhcp_type_notpresent(self, dhcp_types, vm_interface):
if type(dhcp_types) is not list:
dhcp_types = [dhcp_types]
for dhcp_type in dhcp_types:
self.debug("Verifying that DHCP option type - %s not present"
" in VSD" % dhcp_type)
dhcp_options = self.vsd.get_vm_interface_dhcpoptions(
filter=self.get_externalID_filter(vm_interface.id))
for dhcp_option in dhcp_options:
self.debug("dhcptype on vsd is %s:" % dhcp_option.actual_type)
if dhcp_option.actual_type == dhcp_type:
self.fail("Expected DHCP option type is not expected in "
"the VSD: %s" % dhcp_type)
self.debug("Successfully verified DHCP option type - %s "
"not present in the VSD" % dhcp_type)
def verify_dhcp_on_vm(
self, dhcpleasefile, dhcp_option_map, ssh_client, cleanlease=True):
if self.isSimulator:
self.debug("Simulator Environment: Skipping VM DHCP option verification")
return
cmd = 'cat /var/lib/dhclient/'+dhcpleasefile
self.debug("get content of dhcp lease file " + cmd)
outputlist = ssh_client.execute(cmd)
self.debug("command is executed properly " + cmd)
completeoutput = str(outputlist).strip('[]')
self.debug("complete output is " + completeoutput)
for key, value in dhcp_option_map.iteritems():
if type(value) is list:
for val in value:
self.check_if_value_contains(completeoutput, val)
else:
self.check_if_value_contains(completeoutput, value)
if cleanlease:
self.remove_lease_file(ssh_client, dhcpleasefile)
def check_if_value_contains(self, completeoutput, value):
if value in completeoutput:
self.debug("excepted value found in vm: " + value)
else:
self.fail("excepted value not found in vm: " + value)
def remove_lease_file(self, ssh_client, dhcpleasefile):
cmd = 'rm -rf /var/lib/dhclient/'+dhcpleasefile
outputlist = ssh_client.execute(cmd)
completeoutput = str(outputlist).strip('[]')
self.debug("clear lease is done properly:" + completeoutput)
def update_zone_details(self, value):
"""Updates the VM data"""
# update Network Domain at zone level
cmd = updateZone.updateZoneCmd()
cmd.id = self.zone.id
cmd.domain = value
self.api_client.updateZone(cmd)
def update_NuageVspGlobalDomainTemplateName(self, name):
self.debug("Updating global setting nuagevsp.vpc.domaintemplate.name "
"with value - %s" % name)
Configurations.update(self.api_client,
name="nuagevsp.vpc.domaintemplate.name",
value=name)
self.debug("Successfully updated global setting "
"nuagevsp.vpc.domaintemplate.name with value - %s" % name)
def create_isolated_network(
self, network_offering=None, gateway="10.1.1.1",
netmask="255.255.255.0"):
# create a isolated network
self.debug("Creating an Isolated network...")
if not network_offering:
network_offering = self.create_isolated_network_offering()
network = self.create_Network(network_offering, gateway, netmask)
return network
def validate_isolated_network(
self, network_offering, network):
self.debug("Validating network...")
self.validate_NetworkOffering(network_offering, state="Enabled")
self.validate_Network(network)
def validate_vpc(self, vpc, vpc_offering):
self.debug("Validating vpc...")
self.validate_Vpc(vpc)
self.validate_VpcOffering(vpc_offering)
def verify_dhcp_options_on_vm(
self, vm, network, vpc, dhcp_options, remove_lease_file=True,
lease_file="dhclient-eth0.leases", verify_on_vsd=True):
# Adding Ingress Firewall/Network ACL rule
self.debug("Adding Ingress Firewall/Network ACL rule to make the "
"created Static NAT rule (wget) accessible...")
public_ip = self.acquire_PublicIPAddress(network, vpc=vpc)
self.create_StaticNatRule_For_VM(
vm, public_ip, network)
if vpc:
public_http_rule = self.create_NetworkAclRule(
self.test_data["ingress_rule"], network=network)
else:
public_http_rule = self.create_FirewallRule(public_ip)
# VSD verification
if verify_on_vsd:
self.verify_vsd_firewall_rule(public_http_rule)
ssh_client = self.ssh_into_VM(vm, public_ip)
dhcp_options_to_verify_on_vm =\
self.retrieve_dhcp_values_to_verify_on_vm_based_on(
dhcp_options)
self.verify_dhcp_on_vm(
lease_file, dhcp_options_to_verify_on_vm,
ssh_client, remove_lease_file)
# Removing Ingress Firewall/Network ACL rule
self.debug("Removing the created Ingress Firewall/Network ACL "
"rule in the network...")
public_http_rule.delete(self.api_client)
public_ip.delete(self.api_client)
with self.assertRaises(Exception):
self.validate_PublicIPAddress(public_ip, network)
def verify_dhcp_options_on_vsd(
self, vm, dhcp_options,
networks_with_options=None,
verify_vm_on_vsd=True):
if verify_vm_on_vsd:
self.verify_vsd_vm(vm)
if networks_with_options:
for nic in vm.nic:
if self.is_nic_in_network_list(nic, networks_with_options):
for key, value in dhcp_options.iteritems():
self.verify_vsd_dhcp_option(key, value, nic)
else:
for nic in vm.nic:
for key, value in dhcp_options.iteritems():
self.verify_vsd_dhcp_option(key, value, nic)
@staticmethod
def is_nic_in_network_list(nic, network_list):
if type(network_list) is list:
for network in network_list:
if network.id == nic.networkid:
return True
return False
elif network_list.id == nic.networkid:
return True
return False
def validate_network_on_vsd_based_on_networktype(
self, network, vpc=None, is_shared_network=False):
if is_shared_network:
self.verify_vsd_shared_network(
self.domain.id, network,
gateway=self.test_data["nuagevsp"]["network_all"]["gateway"])
else:
self.verify_vsd_network(self.domain.id, network, vpc)
def create_vpc_offering_with_nuage_dhcp(self):
# Creating a VPC offering
self.debug("Creating Nuage VSP VPC offering without dhcp...")
vpc_offering = self.create_VpcOffering(
self.test_data["nuagevsp"]["vpc_offering_nuage_dhcp"])
self.validate_VpcOffering(vpc_offering, state="Enabled")
return vpc_offering
def create_isolated_network_offering(self):
network_offering = self.create_NetworkOffering(
self.test_data["nuagevsp"]["isolated_network_offering"])
self.validate_NetworkOffering(network_offering, state="Enabled")
return network_offering
def create_vpc_network_offering(self):
network_offering = self.create_NetworkOffering(
self.test_data["nuagevsp"]["vpc_network_offering_nuage_dhcp"])
self.validate_NetworkOffering(network_offering, state="Enabled")
return network_offering
def create_vpc(self, vpc_offering, cidr="10.0.0.0/16"):
# Creating a VPC
self.debug("Creating a VPC with Nuage VSP VPC offering...")
vpc = self.create_Vpc(vpc_offering, cidr=cidr,
networkDomain="testvpc.com")
self.validate_Vpc(vpc, state="Enabled")
return vpc
def create_vpc_with_tier(self, domain_name="testvpc.com"):
vpc_offering = self.create_vpc_offering_with_nuage_dhcp()
vpc = self.create_vpc(vpc_offering)
vpc_network_offering = self.create_vpc_network_offering()
acl_list = self.create_acl_list_with_item(vpc)
vpc_first_tier = \
self.when_i_create_a_first_vpc_network_with_nuage_dhcp(
vpc, vpc_network_offering, acl_list)
self.verify_vsd_dhcp_option_subnet(15, domain_name, vpc_first_tier)
return {"vpc": vpc, "tier": vpc_first_tier}
def create_acl_list_with_item(self, vpc):
# Creating an ACL list
acl_list = self.create_NetworkAclList(name="acl", description="acl",
vpc=vpc)
# Creating an ACL item
self.create_NetworkAclRule(self.test_data["ingress_rule"],
acl_list=acl_list)
return acl_list
@staticmethod
def add_extra_dhcp_options_to_check(dhcp_options_to_verify, domain_name,
remove_dns_options=False):
if not remove_dns_options:
dhcp_options_to_verify[12] = "vm1"
dhcp_options_to_verify[15] = domain_name
return dhcp_options_to_verify
def get_extra_dhcp_options_starting_with(self, dhcp_option_code,
network=None):
dhcp_options =\
copy.deepcopy(self.dhcp_options_map.get(dhcp_option_code))
if network:
dhcp_options["networkid"] = network.id
return dhcp_options
def get_extra_dhcp_options_to_verify_starting_with(
self, number, domain_name, remove_dns_options=False):
dhcp_options_to_verify = copy.deepcopy(
self.dhcp_options_to_verify_map.get(number))
self.add_extra_dhcp_options_to_check(
dhcp_options_to_verify, domain_name, remove_dns_options)
return dhcp_options_to_verify
@gherkin
def when_i_update_the_zone_details_and_restart_a_vpc(self, vpc):
self.update_zone_details("testvpc.com")
vpc.restart(self.api_client)
@gherkin
def when_i_create_a_first_vpc_network_with_nuage_dhcp(
self, vpc, network_offering, acl_list, gateway="10.0.0.1"):
# Creating a VPC network in the VPC
self.debug(
"Creating a VPC network with Nuage VSP VPC Network offering...")
vpc_network = self.create_Network(network_offering, gateway=gateway,
vpc=vpc, acl_list=acl_list)
self.validate_Network(vpc_network, state="Implemented")
return vpc_network
@gherkin
def when_i_create_a_second_vpc_network_with_nuage_dhcp(
self, vpc, network_offering, acl_list):
vpc_network_1 = self.create_Network(
network_offering, gateway='10.1.2.1', vpc=vpc, acl_list=acl_list)
self.validate_Network(vpc_network_1, state="Implemented")
return vpc_network_1
@gherkin
def when_i_stop_and_start_a_vm(self, vm):
vm.stop(self.api_client)
vm.start(self.api_client)
@gherkin
def when_i_add_an_extra_nic_to_a_vm(self, vm, network, dhcp_options=None):
dhcp_options_list = None
if dhcp_options:
if type(dhcp_options) is list:
dhcp_options_list = []
for item in dhcp_options:
dhcp_options_list.extend([item])
else:
dhcp_options_list = [dhcp_options]
return vm.add_nic(self.api_client, network.id,
dhcpoptions=dhcp_options_list)
@gherkin
def when_i_restart_a_network(self, network):
network.restart(self.api_client, cleanup=True)
@gherkin
def when_i_create_a_vm(
self, network, vpc, vm_name, dhcp_options,
start_vm=True, is_shared_network=False,
ip_address=None):
vm_data = copy.deepcopy(self.vmdata)
if dhcp_options:
if type(dhcp_options) is list:
dhcp_options_list = []
for item in dhcp_options:
dhcp_options_list.extend([item])
else:
dhcp_options_list = [dhcp_options]
vm_data["dhcpoptionsnetworklist"] = dhcp_options_list
elif "dhcpoptionsnetworklist" in vm_data:
del vm_data["dhcpoptionsnetworklist"]
if ip_address:
vm_data["ipaddress"] = ip_address
if vm_name:
vm_data["displayname"] = vm_name
vm_data["name"] = vm_name
vm = self.create_VM(network, start_vm=start_vm, testdata=vm_data)
if start_vm:
self.check_VM_state(vm, state="Running")
else:
self.check_VM_state(vm, state="Stopped")
# VSD verification
if type(network) is not list:
self.validate_network_on_vsd_based_on_networktype(
network, vpc, is_shared_network)
return vm
@gherkin
def when_i_update_extra_dhcp_options_on_a_vm(self, vm, dhcp_options):
"""Updates the VM data"""
if type(dhcp_options) is list:
dhcp_options_list = []
for item in dhcp_options:
dhcp_options_list.extend([item])
else:
dhcp_options_list = [dhcp_options]
cmd = updateVirtualMachine.updateVirtualMachineCmd()
cmd.id = vm.id
cmd.dhcpoptionsnetworklist = dhcp_options_list
self.api_client.updateVirtualMachine(cmd)
@gherkin
def then_verify_domain_name_and_router_options_multi_nic_set(
self, multinic_vm, primary_network, domain_name="testvpc.com"):
for nic in multinic_vm.nic:
if nic.networkid != primary_network.id:
self.verify_vsd_dhcp_option(3, "0.0.0.0", nic)
self.verify_vsd_dhcp_option(15, "\x00", nic)
else:
self.verify_vsd_dhcp_option(15, domain_name, nic)
@gherkin
def then_verify_dhcp_options_on_vsd_and_vm(self, vm, network,
dhcp_options_to_verify,
network_with_options=None,
is_shared_network=False,
verify_on_vm=False,
default_network=None,
vpc=None,
remove_lease_file=False,
verify_on_vsd=True):
if verify_on_vsd:
self.verify_dhcp_options_on_vsd(
vm, dhcp_options_to_verify, network_with_options,
not is_shared_network)
if verify_on_vm and not self.isSimulator and not is_shared_network:
if default_network:
network = default_network
lease_file = "dhclient-eth1.leases"
else:
lease_file = "dhclient-eth0.leases"
self.verify_dhcp_options_on_vm(
vm=vm,
network=network,
vpc=vpc,
dhcp_options=dhcp_options_to_verify,
lease_file=lease_file,
remove_lease_file=remove_lease_file,
verify_on_vsd=verify_on_vsd)
@gherkin
def then_no_dhcp_options_present_on_vsd(self, dhcp_options_map, vm,
excluded_nics=None):
for nic in vm.nic:
if not excluded_nics or nic not in excluded_nics:
self.verify_vsd_dhcp_type_notpresent(
dhcp_options_map.keys(), nic)
self.verify_vsd_dhcp_value_notpresent(
dhcp_options_map.values(), nic)
def validate_all_extra_dhcp_for_add_remove_nic_after_migrate(
self, network, domain_name="testisolated.com",
is_shared_network=False, verify_all_options=False):
# 1 - create an extra isolated network
# 2 - for each extra dhc option:
# a - deploy a vm
# b - migrate vm
# c - plug nic
# d - verify the dhcp options are correctly set on the nic
# e - remove nic
# f - verify the dhcp options are no longer present on the vsd
# and vm
# 3 - try to remove the default nic which has extra dhcp options set
# (this should fail)
isolated_network2 =\
self.create_isolated_network(gateway="10.0.1.1")
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
vm1 = self.when_i_create_a_vm(
isolated_network2, None, "vm1",
dhcp_options=None,
is_shared_network=False)
if not self.isSimulator:
self.migrate_VM(vm1)
result = self.when_i_add_an_extra_nic_to_a_vm(vm1, network, None)
dhcp_options_network = self.get_extra_dhcp_options_starting_with(
number, network)
self.when_i_update_extra_dhcp_options_on_a_vm(
vm1, dhcp_options_network)
self.when_i_stop_and_start_a_vm(vm1)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, remove_dns_options=True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
network_with_options=network,
is_shared_network=is_shared_network,
verify_on_vm=True,
default_network=isolated_network2,
vpc=None)
vm1.remove_nic(
self.api_client,
[nic for nic in result.nic
if nic.networkid == network.id][0].id)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, remove_dns_options=True)
self.then_no_dhcp_options_present_on_vsd(dhcp_options_to_verify,
vm1)
self.delete_VM(vm1)
def validate_vm_deploy_concurrency(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False):
old_dhcp_options =\
self.get_extra_dhcp_options_starting_with(1, network)
old_dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
1, domain_name, True)
new_dhcp_options =\
self.get_extra_dhcp_options_starting_with(16, network)
new_dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
16, domain_name, True)
def deploy_update_validate_vm(number):
vm = self.when_i_create_a_vm(
[network], vpc, "vm-%02d" % number,
old_dhcp_options,
is_shared_network=is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm, network, old_dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc,
verify_on_vsd=False)
self.when_i_update_extra_dhcp_options_on_a_vm(vm, new_dhcp_options)
self.when_i_stop_and_start_a_vm(vm)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm, network, new_dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc,
verify_on_vsd=False)
self.delete_VM(vm)
try:
executor = ThreadPoolExecutor(max_workers=10)
vm_futures = [executor.submit(
deploy_update_validate_vm, i)
for i in range(10)]
wait(vm_futures)
[f.result()
for f in vm_futures]
finally:
executor.shutdown(wait=True)
def validate_all_extra_dhcp_for_network_actions_in_network(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False,
verify_all_options=False):
# 1 - for each extra dhcp option:
# a - deploy a vm with dhcp options
# b - restart the network
# c - check if the extra dhcp options are still correct
# d - restart the network with clean up = false
# e - check if the extra dhcp options are still correct
# f - if the network is a vpc, restart the vpc
# g - check if the extra dhcp options are still correct
# h - delete the vm
# i - create a vm
# j - stop the vm
# k - start the vm in a seperate thread
# l - add an extra nic while the vn is still in starting state
# m - delete the the vm
# 2 - deploy a vm
# 3 - wait for the network to go into allocated state
# 4 - deploy a new vm in the network
# 5 - check if all options are set correctly
# 6 - delete the network
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
dhcp_options_network =\
self.get_extra_dhcp_options_starting_with(number, network)
vm1 = self.when_i_create_a_vm(
network, vpc, "vm1", dhcp_options_network,
is_shared_network=is_shared_network)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True,
vpc=vpc, remove_lease_file=False)
network.restart(self.api_client, True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True,
vpc=vpc, remove_lease_file=False)
network.restart(self.api_client, False)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True,
vpc=vpc, remove_lease_file=False)
if vpc:
self.restart_Vpc(vpc)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True,
vpc=vpc, remove_lease_file=False)
self.restart_Vpc(vpc, True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True,
vpc=vpc)
self.delete_VM(vm1)
dhcp_options_network = \
self.get_extra_dhcp_options_starting_with(number, network)
vm2 = self.when_i_create_a_vm(
network, vpc, "vm2", dhcp_options_network,
is_shared_network=is_shared_network)
isolated_network2 =\
self.create_isolated_network(gateway="10.0.1.1")
dhcp_options_network =\
self.get_extra_dhcp_options_starting_with(
number, None)
vm_nic = self.when_i_add_an_extra_nic_to_a_vm(
vm2, isolated_network2, dhcp_options=dhcp_options_network)
dhcp_options_to_verify = \
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, remove_dns_options=True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm2, isolated_network2, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=False)
if not is_shared_network:
self.then_verify_domain_name_and_router_options_multi_nic_set(
vm2, network, domain_name)
vm2.update_default_nic(
self.api_client,
[nic
for nic in vm_nic.nic
if not nic.isdefault][0].id)
self.when_i_stop_and_start_a_vm(vm2)
if not is_shared_network:
self.then_verify_domain_name_and_router_options_multi_nic_set(
vm2, isolated_network2, domain_name)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm2, isolated_network2, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True)
self.delete_VM(vm2)
def validate_all_extra_dhcp_for_network_in_allocated(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False):
dhcp_options_network =\
self.get_extra_dhcp_options_starting_with(1, network)
vm3 = self.when_i_create_a_vm(
network, vpc, "vm3", dhcp_options_network,
is_shared_network=is_shared_network)
vm3.stop(self.api_client)
# wait 1 min for network to go into allocated state
time.sleep(60)
dhcp_options_network =\
self.get_extra_dhcp_options_starting_with(64, network)
vm4 = self.when_i_create_a_vm(
network, vpc, "vm1", dhcp_options_network,
is_shared_network=is_shared_network)
dhcp_options_to_verify = \
self.get_extra_dhcp_options_to_verify_starting_with(
64, domain_name, is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm4, network, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True, vpc=vpc)
self.delete_VM(vm4)
self.delete_VM(vm3)
def validate_all_extra_dhcp_for_vm_actions_in_network(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False,
verify_all_options=False):
# 1 - for each extra dhcp options:
# a - create a vm with dhcp options
# b - start and stop the vm
# c - check if the dhcp options are set correctly
# d - reboot the vm
# e - check if the dhcp options are set correctly
# f - delete a vm without expunging it
# g - recover the vm
# h - start the vm
# i - check if the dhcp options are set correctly
# j - delete the vm
# 2 - create a vm with extra dhcp options set
# 3 - check if the dhcp options are set correctly
# 4 - update the vm with new extra dhcp options
# 5 - reboot the vm
# 6 - verify the dhcp options on the vm and the vsd are not updated
# 7 - delete the vm
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
dhcp_options_network =\
self.get_extra_dhcp_options_starting_with(number, network)
vm1 = self.when_i_create_a_vm(
network, vpc, "vm1", dhcp_options_network,
is_shared_network=is_shared_network)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
self.when_i_stop_and_start_a_vm(vm1)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
vm1.reboot(self.api_client)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
vm1.delete(self.api_client, False)
vm1.recover(self.api_client)
vm1.start(self.api_client)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
vm1.restore(self.api_client)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
if not self.isSimulator:
self.migrate_VM(vm1)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True,
vpc=vpc)
vm1.delete(self.api_client, True)
dhcp_options_network = self.get_extra_dhcp_options_starting_with(
1, network)
vm1 = self.when_i_create_a_vm(
network, vpc, "vm1", dhcp_options_network,
is_shared_network=is_shared_network)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
1, domain_name, is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
dhcp_options_network_not_present =\
self.get_extra_dhcp_options_starting_with(93, network)
dhcp_options_to_verify_network_not_present =\
self.get_extra_dhcp_options_to_verify_starting_with(
93, domain_name, True)
self.when_i_update_extra_dhcp_options_on_a_vm(
vm1, dhcp_options_network_not_present)
vm1.reboot(self.api_client)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
self.then_no_dhcp_options_present_on_vsd(
dhcp_options_to_verify_network_not_present, vm1)
if not self.isSimulator:
self.migrate_VM(vm1)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
dhcp_options_network = self.get_extra_dhcp_options_starting_with(
64, network)
dhcp_options_to_verify = \
self.get_extra_dhcp_options_to_verify_starting_with(
64, domain_name, is_shared_network)
self.when_i_update_extra_dhcp_options_on_a_vm(
vm1, dhcp_options_network)
vm1.restore(self.api_client)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
self.delete_VM(vm1)
def validate_all_extra_dhcp_for_remove_nic_from_vm(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False,
verify_all_options=False):
# 1 - create an extra isolated network
# 2 - for each extra dhc option:
# a - deploy a vm
# b - plug nic
# c - verify the dhcp options are correctly set on the nic
# d - remove nic
# e - verify the dhcp options are no longer present on the vsd
# and vm
# 3 - try to remove the default nic which has extra dhcp options set
# (this should fail)
isolated_network2 =\
self.create_isolated_network(gateway="10.0.1.1")
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
vm1 = self.when_i_create_a_vm(
isolated_network2, None, "vm1", dhcp_options=None,
is_shared_network=False)
result = self.when_i_add_an_extra_nic_to_a_vm(vm1, network, None)
dhcp_options_network = self.get_extra_dhcp_options_starting_with(
number, network)
self.when_i_update_extra_dhcp_options_on_a_vm(
vm1, dhcp_options_network)
self.when_i_stop_and_start_a_vm(vm1)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify=dhcp_options_to_verify,
network_with_options=network,
is_shared_network=is_shared_network, verify_on_vm=True,
default_network=isolated_network2, vpc=None)
vm1.remove_nic(
self.api_client,
[nic for nic in result.nic
if nic.networkid == network.id][0].id)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, True)
self.then_no_dhcp_options_present_on_vsd(dhcp_options_to_verify,
vm1)
self.delete_VM(vm1)
# invalid remove option
vm1 = self.when_i_create_a_vm(
network, vpc, "vm1", None, is_shared_network=is_shared_network)
result = self.when_i_add_an_extra_nic_to_a_vm(
vm1, isolated_network2, None)
self.when_i_update_extra_dhcp_options_on_a_vm(
vm1, dhcp_options_network)
self.when_i_stop_and_start_a_vm(vm1)
with self.assertRaises(Exception):
vm1.remove_nic(
self.api_client, [nic for nic in result.nic
if nic.networkid == network.id][0])
def validate_all_extra_dhcp_for_update_multinic(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False,
verify_all_options=False):
# 1 - create an extra isolated network
# 2 - for each extra dhcp option:
# a - deploy a vm and ad an extra nic
# b - update the dhcp options on both nics
# c - verify the dhcp options are not yet set on the vsd and vm
# d - start and stop the vm
# e - verify the new dhcp options are set on the vsd and vm
# 3 - try to update a multi nic vm with invalid options
# (this should fail)
isolated_network2 =\
self.create_isolated_network(gateway="10.0.1.1")
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
vm1 = self.when_i_create_a_vm(
isolated_network2, None, "vm1",
dhcp_options=None,
is_shared_network=False)
self.when_i_add_an_extra_nic_to_a_vm(vm1, network, None)
dhcp_options_network = self.get_extra_dhcp_options_starting_with(
number, network)
dhcp_options_network2 = self.get_extra_dhcp_options_starting_with(
number, isolated_network2)
dhcp_options_list = [dhcp_options_network, dhcp_options_network2]
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, True)
self.when_i_update_extra_dhcp_options_on_a_vm(vm1,
dhcp_options_list)
self.then_no_dhcp_options_present_on_vsd(dhcp_options_to_verify,
vm1)
self.when_i_stop_and_start_a_vm(vm1)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify=dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True,
default_network=isolated_network2, vpc=None)
self.delete_VM(vm1)
invalid_dhcp_options_list = [{"networkid": network.id,
"dhcp:":
"http://www.testdhcpfeature.com/"
"adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": network.id,
"dhcp:241":
"http://www.testdhcpfeature.com/"
"adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": network.id,
"unknownvalue":
"http://www.testdhcpfeature.com/"
"adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": "invalidnetworkid",
"dhcp:114":
"http://www.testdhcpfeature.com/"
"adfsgbfgtdhh125ki-23-fdh-09"}]
valid_dhcp_option = {"networkid": isolated_network2.id,
"dhcp:124":
"http://www.testdhcpfeature.com/"
"adfsgbfgtdhh125ki-23-fdh-09"}
for invalid_dhcp_option in invalid_dhcp_options_list:
vm1 = self.when_i_create_a_vm(
isolated_network2, vpc, "vm1",
dhcp_options=None,
is_shared_network=False)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
93, domain_name, True)
self.then_no_dhcp_options_present_on_vsd(dhcp_options_to_verify,
vm1)
combined_options = [invalid_dhcp_option, valid_dhcp_option]
with self.assertRaises(Exception):
self.when_i_update_extra_dhcp_options_on_a_vm(
vm1, combined_options)
self.delete_VM(vm1)
def validate_all_extra_dhcp_for_multi_nic(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False,
verify_all_options=False):
# 1 - create an extra isolated network
# 2 - for each extra dhcp option:
# a - deploy a vm with a nic in two networks
# b - verify that the dhcp options are correctly set on the vsd
# and vn
# c - deploy a vm with a nic in two networks but now, let the other
# network be the default network of the vm
# d - verify that the dhcp options are correctly set on the vsd
# and vm
# 3 - try to deploy a multi nic vm with invalid dhcp options
# (should fail)
isolated_network2 =\
self.create_isolated_network(gateway="10.0.1.1")
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
dhcp_options_network = self.get_extra_dhcp_options_starting_with(
number, network)
dhcp_options_network2 = self.get_extra_dhcp_options_starting_with(
number, isolated_network2)
dhcp_options = [dhcp_options_network, dhcp_options_network2]
# default nic is the network provided
multinic_vm = self.when_i_create_a_vm(
[network, isolated_network2], vpc, "vm1", dhcp_options,
is_shared_network=is_shared_network)
if not is_shared_network:
self.then_verify_domain_name_and_router_options_multi_nic_set(
multinic_vm, network, domain_name)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
multinic_vm, network, dhcp_options_to_verify,
network_with_options=network,
is_shared_network=is_shared_network, verify_on_vm=True,
vpc=vpc)
# is not primary nic so no option 12
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, remove_dns_options=True)
self.then_verify_dhcp_options_on_vsd_and_vm(
multinic_vm, network, dhcp_options_to_verify,
network_with_options=isolated_network2,
is_shared_network=is_shared_network, verify_on_vm=False,
default_network=network, vpc=vpc)
self.delete_VM(multinic_vm)
# default nic is isolated_network2
multinic_vm = self.when_i_create_a_vm(
[isolated_network2, network], vpc, "vm1", dhcp_options,
is_shared_network=is_shared_network)
if not is_shared_network:
self.then_verify_domain_name_and_router_options_multi_nic_set(
multinic_vm, isolated_network2, domain_name)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
multinic_vm, network, dhcp_options_to_verify,
network_with_options=isolated_network2,
is_shared_network=is_shared_network, verify_on_vm=False,
vpc=vpc)
# is not primary nic so no option 12
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, True)
self.then_verify_dhcp_options_on_vsd_and_vm(
multinic_vm, network,
dhcp_options_to_verify=dhcp_options_to_verify,
network_with_options=network,
is_shared_network=is_shared_network, verify_on_vm=True,
default_network=isolated_network2, vpc=None)
self.delete_VM(multinic_vm)
invalid_dhcp_options_list = [{"networkid": network.id,
"dhcp:":
"http://www.testdhcpfeature.com"
"/adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": network.id,
"dhcp:241":
"http://www.testdhcpfeature.com"
"/adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": network.id,
"unknownvalue":
"http://www.testdhcpfeature.com"
"/adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": "invalidnetworkid",
"dhcp:114":
"http://www.testdhcpfeature.com"
"/adfsgbfgtdhh125ki-23-fdh-09"}]
for invalid_dhcp_option in invalid_dhcp_options_list:
with self.assertRaises(Exception):
self.when_i_create_a_vm(
[isolated_network2, network], vpc, "vm1",
dhcp_options=invalid_dhcp_option,
is_shared_network=is_shared_network)
def validate_all_extra_dhcp_after_plug_nic(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False,
verify_all_options=False):
# 1 - create an extra isolated network
# 2 - for each extra dchp options:
# a - deploy a vm in the created isolated network
# b - add an extra nic
# c - verify if the dhcp options are correctly set
# 3 - try to add a nic with invalid dhcp options (this should fail)
isolated_network2 =\
self.create_isolated_network(gateway="10.0.1.1")
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, True)
vm1 = self.when_i_create_a_vm(
isolated_network2, vpc, "vm1", None,
is_shared_network=False)
self.then_no_dhcp_options_present_on_vsd(
dhcp_options_to_verify, vm1)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, True)
dhcp_options = self.get_extra_dhcp_options_starting_with(number)
self.when_i_add_an_extra_nic_to_a_vm(vm1, network,
dhcp_options=dhcp_options)
vm1.reboot(self.api_client)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify=dhcp_options_to_verify,
network_with_options=network,
is_shared_network=is_shared_network, verify_on_vm=True,
default_network=isolated_network2, vpc=None)
self.delete_VM(vm1)
invalid_dhcp_options_list = [
{"dhcp:": "http://www.testdhcpfeature.com/"
"adfsgbfgtdhh125ki-23-fdh-09"},
{"dhcp:241": "http://www.testdhcpfeature.com/"
"adfsgbfgtdhh125ki-23-fdh-09"},
{"unknownvalue": "http://www.testdhcpfeature.com/"
"adfsgbfgtdhh125ki-23-fdh-09"}]
for invalid_dhcp_option in invalid_dhcp_options_list:
vm1 = self.when_i_create_a_vm(
isolated_network2, vpc, "vm1", None,
is_shared_network=False)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
93, domain_name, remove_dns_options=True)
self.then_no_dhcp_options_present_on_vsd(dhcp_options_to_verify,
vm1)
with self.assertRaises(Exception):
self.when_i_add_an_extra_nic_to_a_vm(
vm1, network, dhcp_options=invalid_dhcp_option)
self.delete_VM(vm1)
def validate_all_extra_dhcp_after_vm_update(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False,
verify_all_options=False):
# 1 - deploy a vm without extra dhcp options
# 2 - verify no dhcp options are present
# 3 - For each extra dhcp options
# a - update the vm with extra dhcp options
# b - check that the vm options are yet not updated on the vsd
# and vm
# c - stop and start the vm
# d - check that the dhcp options are set on the vsd an vm
# 4 - update a vm zith invalid dhcp options (this should fail)
# option 1 to 13 is special because we start a vm here
# instead of update
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(1, domain_name,
True)
vm1 = self.when_i_create_a_vm(
network, vpc, "vm1", None,
is_shared_network=is_shared_network)
self.then_no_dhcp_options_present_on_vsd(dhcp_options_to_verify, vm1)
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
dhcp_options = self.get_extra_dhcp_options_starting_with(number,
network)
self.when_i_update_extra_dhcp_options_on_a_vm(vm1, dhcp_options)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, True)
self.then_no_dhcp_options_present_on_vsd(dhcp_options_to_verify,
vm1)
# dhcp options get applied after start stop vm
self.when_i_stop_and_start_a_vm(vm1)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network, verify_on_vm=True,
vpc=vpc)
invalid_dhcp_options_list = [{"networkid": network.id,
"dhcp:": "http://www.testdhcpfeature.com"
"/adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": network.id,
"dhcp:241": "http://www.testdhcpfeature"
".com/adfsgbfgtdhh125ki-23"
"-fdh-09"},
{"networkid": network.id,
"unknownvalue": "http://www.testdhcp"
"feature.com/"
"adfsgbfgtdhh125ki-23-"
"fdh-09"},
{"networkid": "invalidnetworkid",
"dhcp:114": "http://www.testdhcpfeature"
".com/adfsgbfgtdhh125ki-23-"
"fdh-09"}]
for invalid_dhcp_option in invalid_dhcp_options_list:
with self.assertRaises(Exception):
self.when_i_update_extra_dhcp_options_on_a_vm(
vm1, invalid_dhcp_option)
def validate_all_extra_dhcp_deploy_vm(
self, network,
vpc=None,
domain_name="testisolated.com",
is_shared_network=False,
verify_all_options=False):
# 1 - For each extra dhcp option:
# a - deploy a vm with extra dhcp options
# b - verify if the options are present on the vsd and vm
# c - delete the VM
# 2 - create a vm with different invalid dhcp options
# (this should fail)
if verify_all_options:
options_to_verify = self.dhcp_options_map_keys
else:
options_to_verify = [1]
for number in options_to_verify:
dhcp_options = self.get_extra_dhcp_options_starting_with(
number, network)
dhcp_options_to_verify =\
self.get_extra_dhcp_options_to_verify_starting_with(
number, domain_name, is_shared_network)
vm1 = self.when_i_create_a_vm(
network, vpc, "vm1", dhcp_options,
is_shared_network=is_shared_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
is_shared_network=is_shared_network,
verify_on_vm=True,
vpc=vpc)
self.delete_VM(vm1)
invalid_dhcp_options_list = [{"networkid": network.id,
"dhcp:": "http://www.testdhcpfeature.com"
"/adfsgbfgtdhh125ki-23-fdh"
"-09"},
{"networkid": network.id,
"dhcp:241":
"http://www.testdhcpfeature.com"
"/adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": network.id,
"unknownvalue":
"http://www.testdhcpfeature"
".com/adfsgbfgtdhh125ki-23-fdh-09"},
{"networkid": "invalidnetworkid",
"dhcp:114":
"http://www.testdhcpfeature.com"
"/adfsgbfgtdhh125ki-23-fdh-09"}]
for invalid_dhcp_option in invalid_dhcp_options_list:
with self.assertRaises(Exception):
self.when_i_create_a_vm(
network, vpc, "vm2", invalid_dhcp_option,
is_shared_network=is_shared_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_01_nuage_extra_dhcp_single_nic_in_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_deploy_vm(self.isolated_network,
verify_all_options=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_02_nuage_extra_dhcp_single_nic_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_deploy_vm(
self.vpc_network,
self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_03_nuage_extra_dhcp_single_nic_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_deploy_vm(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_04_nuage_extra_dhcp_update_vm_in_isoltated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_after_vm_update(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_05_nuage_extra_dhcp_update_vm_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_after_vm_update(
self.vpc_network, self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_06_nuage_extra_dhcp_update_vm_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_after_vm_update(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_07_nuage_extra_dhcp_add_nic_in_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_after_plug_nic(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_08_nuage_extra_dhcp_add_nic_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_after_plug_nic(
self.vpc_network, self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_09_nuage_extra_dhcp_add_nic_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_after_plug_nic(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_10_nuage_extra_dhcp_deploy_multi_nic_vm_in_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_for_multi_nic(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_11_nuage_extra_dhcp_deploy_multi_nic_vm_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_for_multi_nic(
self.vpc_network, self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_12_nuage_extra_dhcp_deploy_multi_nic_vm_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_for_multi_nic(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_13_nuage_extra_dhcp_update_multi_nic_in_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_for_update_multinic(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_14_nuage_extra_dhcp_update_multi_nic_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_for_update_multinic(
self.vpc_network, self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_15_nuage_extra_dhcp_update_multi_nic_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_for_update_multinic(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_16_nuage_extra_dhcp_remove_nic_in_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_for_remove_nic_from_vm(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_17_nuage_extra_dhcp_remove_nic_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_for_remove_nic_from_vm(
network=self.vpc_network,
vpc=self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_18_nuage_extra_dhcp_remove_nic_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_for_remove_nic_from_vm(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_19_nuage_extra_dhcp_vm_actions_in_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_for_vm_actions_in_network(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_20_nuage_nuage_extra_dhcp_vm_actions_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_for_vm_actions_in_network(
network=self.vpc_network,
vpc=self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_21_nuage_extra_dhcp_vm_actions_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_for_vm_actions_in_network(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_22_nuage_extra_dhcp_network_actions_in_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_for_network_actions_in_network(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_23_nuage_nuage_extra_dhcp_network_actions_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_for_network_actions_in_network(
self.vpc_network,
vpc=self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_24_nuage_extra_dhcp_network_actions_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_for_network_actions_in_network(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_25_nuage_extra_dhcp_nic_after_migrate_in_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network)
self.validate_all_extra_dhcp_for_add_remove_nic_after_migrate(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_26_nuage_nuage_extra_dhcp_nic_after_migrate_in_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_for_add_remove_nic_after_migrate(
self.vpc_network,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_27_nuage_extra_dhcp_nic_after_migrate_in_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_for_add_remove_nic_after_migrate(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_28_nuage_extra_dhcp_deploy_multiple_vms(self):
self.update_zone_details("testisolated.com")
isolated_network =\
self.create_isolated_network(gateway="10.0.0.1")
self.validate_vm_deploy_concurrency(
isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_29_nuage_extra_dhcp_allocated_isolated_network(self):
self.update_zone_details("testisolated.com")
self.validate_isolated_network(
self.isolated_network_offering, self.isolated_network,)
self.validate_all_extra_dhcp_for_network_in_allocated(
self.isolated_network)
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_30_nuage_extra_dhcp_allocated_vpc(self):
self.update_zone_details("testvpc.com")
self.validate_vpc(self.vpc1, self.vpc_offering)
self.validate_Network(self.vpc_network)
self.validate_all_extra_dhcp_for_network_in_allocated(
self.vpc_network, self.vpc1,
domain_name="testvpc.com")
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_31_nuage_extra_dhcp_allocated_shared_network(self):
self.update_zone_details("testshared.com")
self.validate_all_extra_dhcp_for_network_in_allocated(
self.shared_network_all,
domain_name="testshared.com",
is_shared_network=True)
@attr(tags=["advanced", "nuagevsp", "smoke"], required_hardware="false")
def smoke_test(self):
# This test does basic sanity checks to see if basic
# DHCP options still work.
# 1 - deploy vm in an isolated network
# 2 - verify dhcp options
# 3 - update dhcp options
# 4 - add nic to a vpc_network with different dhcp options
# 5 - restart the vm
# 6 - check if dhcp options are on the extra nic and the default nic
# 7 - restart the network
# 8 - verify if the dhcp options are set correctly
# 9 - remove the vm
network = self.isolated_network
domain_name = "testisolated.com"
self.update_zone_details(domain_name)
dhcp_options_isolated_network =\
self.get_extra_dhcp_options_starting_with(1, network)
dhcp_options_to_verify = \
self.get_extra_dhcp_options_to_verify_starting_with(
1, domain_name, remove_dns_options=False)
vm1 = self.when_i_create_a_vm(
network,
vpc=None,
vm_name="vm1",
dhcp_options=dhcp_options_isolated_network)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify,
verify_on_vm=True)
dhcp_options_isolated_network =\
self.get_extra_dhcp_options_starting_with(16, network)
self.when_i_update_extra_dhcp_options_on_a_vm(
vm1, dhcp_options_isolated_network)
dhcp_options_vpc_network = self.get_extra_dhcp_options_starting_with(
28, None)
self.when_i_add_an_extra_nic_to_a_vm(
vm1, self.vpc_network, dhcp_options_vpc_network)
self.when_i_stop_and_start_a_vm(vm1)
dhcp_options_to_verify_on_default_nic = \
self.get_extra_dhcp_options_to_verify_starting_with(
16, domain_name, False)
dhcp_options_to_verify_on_second_nic = \
self.get_extra_dhcp_options_to_verify_starting_with(
28, domain_name, remove_dns_options=True)
# dhcp options get applied after start stop vm
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify_on_default_nic,
verify_on_vm=True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify_on_second_nic,
network_with_options=self.vpc_network,
verify_on_vm=True,
default_network=network,
vpc=None)
network.restart(self.api_client, True)
self.vpc_network.restart(self.api_client, True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify_on_default_nic,
verify_on_vm=True)
self.then_verify_dhcp_options_on_vsd_and_vm(
vm1, network, dhcp_options_to_verify_on_second_nic,
network_with_options=self.vpc_network,
verify_on_vm=True,
default_network=network,
vpc=None)
self.delete_VM(vm1)
| [
"marvin.cloudstackAPI.updateZone.updateZoneCmd",
"marvin.lib.base.Configurations.update",
"marvin.lib.base.Network.create",
"marvin.lib.base.Account.create",
"marvin.lib.base.NetworkOffering.create",
"marvin.cloudstackAPI.updateVirtualMachine.updateVirtualMachineCmd"
] | [((77127, 77189), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (77131, 77189), False, 'from nose.plugins.attrib import attr\n'), ((77569, 77631), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (77573, 77631), False, 'from nose.plugins.attrib import attr\n'), ((77989, 78051), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (77993, 78051), False, 'from nose.plugins.attrib import attr\n'), ((78341, 78403), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (78345, 78403), False, 'from nose.plugins.attrib import attr\n'), ((78730, 78792), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (78734, 78792), False, 'from nose.plugins.attrib import attr\n'), ((79143, 79205), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (79147, 79205), False, 'from nose.plugins.attrib import attr\n'), ((79500, 79562), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (79504, 79562), False, 'from nose.plugins.attrib import attr\n'), ((79885, 79947), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (79889, 79947), False, 'from nose.plugins.attrib import attr\n'), ((80295, 80357), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (80299, 80357), False, 'from nose.plugins.attrib import attr\n'), ((80649, 80711), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (80653, 80711), False, 'from nose.plugins.attrib import attr\n'), ((81045, 81107), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (81049, 81107), False, 'from nose.plugins.attrib import attr\n'), ((81466, 81528), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (81470, 81528), False, 'from nose.plugins.attrib import attr\n'), ((81831, 81893), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (81835, 81893), False, 'from nose.plugins.attrib import attr\n'), ((82230, 82292), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (82234, 82292), False, 'from nose.plugins.attrib import attr\n'), ((82654, 82716), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (82658, 82716), False, 'from nose.plugins.attrib import attr\n'), ((83022, 83084), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (83026, 83084), False, 'from nose.plugins.attrib import attr\n'), ((83418, 83480), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (83422, 83480), False, 'from nose.plugins.attrib import attr\n'), ((83863, 83925), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (83867, 83925), False, 'from nose.plugins.attrib import attr\n'), ((84228, 84290), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (84232, 84290), False, 'from nose.plugins.attrib import attr\n'), ((84627, 84689), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (84631, 84689), False, 'from nose.plugins.attrib import attr\n'), ((85081, 85143), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (85085, 85143), False, 'from nose.plugins.attrib import attr\n'), ((85449, 85511), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (85453, 85511), False, 'from nose.plugins.attrib import attr\n'), ((85858, 85920), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (85862, 85920), False, 'from nose.plugins.attrib import attr\n'), ((86314, 86376), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (86318, 86376), False, 'from nose.plugins.attrib import attr\n'), ((86692, 86754), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (86696, 86754), False, 'from nose.plugins.attrib import attr\n'), ((87105, 87167), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (87109, 87167), False, 'from nose.plugins.attrib import attr\n'), ((87538, 87600), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (87542, 87600), False, 'from nose.plugins.attrib import attr\n'), ((87920, 87982), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (87924, 87982), False, 'from nose.plugins.attrib import attr\n'), ((88266, 88328), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (88270, 88328), False, 'from nose.plugins.attrib import attr\n'), ((88661, 88723), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (88665, 88723), False, 'from nose.plugins.attrib import attr\n'), ((89080, 89142), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (89084, 89142), False, 'from nose.plugins.attrib import attr\n'), ((89443, 89514), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp', 'smoke'], required_hardware='false')\n", (89447, 89514), False, 'from nose.plugins.attrib import attr\n'), ((1752, 1848), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.test_data['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.api_client, cls.test_data['account'], admin=True,\n domainid=cls.domain.id)\n", (1766, 1848), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Configurations, NetworkOffering\n'), ((2009, 2035), 'marvin.cloudstackAPI.updateZone.updateZoneCmd', 'updateZone.updateZoneCmd', ([], {}), '()\n', (2033, 2035), False, 'from marvin.cloudstackAPI import updateVirtualMachine, updateZone\n'), ((3208, 3331), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.test_data['nuagevsp']['shared_nuage_network_offering']"], {'conservemode': '(False)'}), "(cls.api_client, cls.test_data['nuagevsp'][\n 'shared_nuage_network_offering'], conservemode=False)\n", (3230, 3331), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Configurations, NetworkOffering\n'), ((3556, 3702), 'marvin.lib.base.Network.create', 'Network.create', (['cls.api_client', "cls.test_data['nuagevsp']['network_all']"], {'networkofferingid': 'cls.shared_network_offering_id', 'zoneid': 'cls.zone.id'}), "(cls.api_client, cls.test_data['nuagevsp']['network_all'],\n networkofferingid=cls.shared_network_offering_id, zoneid=cls.zone.id)\n", (3570, 3702), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Configurations, NetworkOffering\n'), ((15441, 15464), 'copy.deepcopy', 'copy.deepcopy', (['dhcp_map'], {}), '(dhcp_map)\n', (15454, 15464), False, 'import copy\n'), ((24861, 24887), 'marvin.cloudstackAPI.updateZone.updateZoneCmd', 'updateZone.updateZoneCmd', ([], {}), '()\n', (24885, 24887), False, 'from marvin.cloudstackAPI import updateVirtualMachine, updateZone\n'), ((25179, 25275), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.api_client'], {'name': '"""nuagevsp.vpc.domaintemplate.name"""', 'value': 'name'}), "(self.api_client, name=\n 'nuagevsp.vpc.domaintemplate.name', value=name)\n", (25200, 25275), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Configurations, NetworkOffering\n'), ((34490, 34516), 'copy.deepcopy', 'copy.deepcopy', (['self.vmdata'], {}), '(self.vmdata)\n', (34503, 34516), False, 'import copy\n'), ((35899, 35945), 'marvin.cloudstackAPI.updateVirtualMachine.updateVirtualMachineCmd', 'updateVirtualMachine.updateVirtualMachineCmd', ([], {}), '()\n', (35943, 35945), False, 'from marvin.cloudstackAPI import updateVirtualMachine, updateZone\n'), ((48326, 48340), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (48336, 48340), False, 'import time\n'), ((42496, 42530), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': '(10)'}), '(max_workers=10)\n', (42514, 42530), False, 'from concurrent.futures import ThreadPoolExecutor, wait\n'), ((42674, 42690), 'concurrent.futures.wait', 'wait', (['vm_futures'], {}), '(vm_futures)\n', (42678, 42690), False, 'from concurrent.futures import ThreadPoolExecutor, wait\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#Test from the Marvin - Testing in Python wiki
#All tests inherit from cloudstackTestCase
from marvin.cloudstackTestCase import cloudstackTestCase
#Import Integration Libraries
#base - contains all resources as entities and defines create, delete, list operations on them
from marvin.lib.base import (
Account,
VirtualMachine,
Volume,
ServiceOffering,
Configurations,
DiskOffering,
Template)
#utils - utility classes for common cleanup, external library wrappers etc
from marvin.lib.utils import cleanup_resources, validateList
#common - commonly used methods for all tests are listed here
from marvin.lib.common import get_zone, get_domain, get_template
from marvin.codes import PASS
from nose.plugins.attrib import attr
import time
class TestTemplates(cloudstackTestCase):
@classmethod
def setUpClass(cls):
try:
cls._cleanup = []
cls.testClient = super(TestTemplates, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Domain, Zone, Template
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(
cls.api_client,
cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["template"]["ostypeid"] = cls.template.ostypeid
cls.services["template"]["isextractable"] = 'True'
if cls.zone.localstorageenabled:
cls.storagetype = 'local'
cls.services["service_offerings"][
"tiny"]["storagetype"] = 'local'
cls.services["disk_offering"]["storagetype"] = 'local'
else:
cls.storagetype = 'shared'
cls.services["service_offerings"][
"tiny"]["storagetype"] = 'shared'
cls.services["disk_offering"]["storagetype"] = 'shared'
cls.services['mode'] = cls.zone.networktype
cls.services["virtual_machine"][
"hypervisor"] = cls.testClient.getHypervisorInfo()
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.services["custom_volume"]["zoneid"] = cls.zone.id
# Creating Disk offering, Service Offering and Account
cls.disk_offering = DiskOffering.create(
cls.api_client,
cls.services["disk_offering"]
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offerings"]["tiny"]
)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
# Getting authentication for user in newly created Account
cls.user = cls.account.user[0]
cls.userapiclient = cls.testClient.getUserApiClient(cls.user.username, cls.domain.name)
cls._cleanup.append(cls.disk_offering)
cls._cleanup.append(cls.service_offering)
cls._cleanup.append(cls.account)
except Exception as e:
cls.tearDownClass()
raise Exception("Warning: Exception in setup : %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiClient = self.testClient.getApiClient()
self.cleanup = []
return
def tearDown(self):
#Clean up, terminate the created volumes
cleanup_resources(self.apiClient, self.cleanup)
return
@attr(tags=["advanced", "advancedsg", "sg"], required_hardware='true')
def test01_template_download_URL_expire(self):
"""
@Desc:Template files are deleted from secondary storage after download URL expires
Step1:Deploy vm with default cent os template
Step2:Stop the vm
Step3:Create template from the vm's root volume
Step4:Extract Template and wait for the download url to expire
Step5:Deploy another vm with the template created at Step3
Step6:Verify that vm deployment succeeds
"""
params = ['extract.url.expiration.interval', 'extract.url.cleanup.interval']
wait_time = 0
for param in params:
config = Configurations.list(
self.apiClient,
name=param,
)
self.assertEqual(validateList(config)[0], PASS, "Config list returned invalid response")
wait_time = wait_time+int(config[0].value)
self.debug("Total wait time for url expiry: %s" % wait_time)
# Creating Virtual Machine
self.virtual_machine = VirtualMachine.create(
self.userapiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
)
self.assertIsNotNone(self.virtual_machine, "Virtual Machine creation failed")
self.cleanup.append(self.virtual_machine)
#Stop virtual machine
self.virtual_machine.stop(self.userapiclient)
list_volume = Volume.list(
self.userapiclient,
virtualmachineid=self.virtual_machine.id,
type='ROOT',
listall=True
)
self.assertEqual(validateList(list_volume)[0],
PASS,
"list volumes with type ROOT returned invalid list"
)
self.volume = list_volume[0]
self.create_template = Template.create(
self.userapiclient,
self.services["template"],
volumeid=self.volume.id,
account=self.account.name,
domainid=self.account.domainid
)
self.assertIsNotNone(self.create_template, "Failed to create template from root volume")
self.cleanup.append(self.create_template)
"""
Extract template
"""
try:
Template.extract(
self.userapiclient,
self.create_template.id,
'HTTP_DOWNLOAD',
self.zone.id
)
except Exception as e:
self.fail("Extract template failed with error %s" % e)
self.debug("Waiting for %s seconds for url to expire" % repr(wait_time+20))
time.sleep(wait_time+20)
self.debug("Waited for %s seconds for url to expire" % repr(wait_time+20))
"""
Deploy vm with the template created from the volume. After url expiration interval only
url should be deleted not the template. To validate this deploy vm with the template
"""
try:
self.vm = VirtualMachine.create(
self.userapiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.create_template.id
)
self.cleanup.append(self.vm)
except Exception as e:
self.fail("Template is automatically deleted after URL expired.\
So vm deployment failed with error: %s" % e)
return
| [
"marvin.lib.utils.validateList",
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.Template.create",
"marvin.lib.base.Volume.list",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.DiskOffering.create",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.b... | [((4982, 5051), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg', 'sg']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedsg', 'sg'], required_hardware='true')\n", (4986, 5051), False, 'from nose.plugins.attrib import attr\n'), ((4913, 4960), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiClient', 'self.cleanup'], {}), '(self.apiClient, self.cleanup)\n', (4930, 4960), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((6088, 6276), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.userapiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.userapiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id)\n", (6109, 6276), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((6586, 6690), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.userapiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.userapiclient, virtualmachineid=self.virtual_machine.id,\n type='ROOT', listall=True)\n", (6597, 6690), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((6986, 7137), 'marvin.lib.base.Template.create', 'Template.create', (['self.userapiclient', "self.services['template']"], {'volumeid': 'self.volume.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.userapiclient, self.services['template'], volumeid=\n self.volume.id, account=self.account.name, domainid=self.account.domainid)\n", (7001, 7137), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((7785, 7811), 'time.sleep', 'time.sleep', (['(wait_time + 20)'], {}), '(wait_time + 20)\n', (7795, 7811), False, 'import time\n'), ((2125, 2151), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2135, 2151), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((2294, 2359), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (2306, 2359), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((3534, 3600), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.api_client', "cls.services['disk_offering']"], {}), "(cls.api_client, cls.services['disk_offering'])\n", (3553, 3600), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((3682, 3768), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offerings']['tiny']"], {}), "(cls.api_client, cls.services['service_offerings'][\n 'tiny'])\n", (3704, 3768), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((3836, 3915), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], domainid=cls.domain.id)\n", (3850, 3915), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((4559, 4606), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (4576, 4606), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((5698, 5745), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiClient'], {'name': 'param'}), '(self.apiClient, name=param)\n', (5717, 5745), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((7424, 7520), 'marvin.lib.base.Template.extract', 'Template.extract', (['self.userapiclient', 'self.create_template.id', '"""HTTP_DOWNLOAD"""', 'self.zone.id'], {}), "(self.userapiclient, self.create_template.id,\n 'HTTP_DOWNLOAD', self.zone.id)\n", (7440, 7520), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((8141, 8370), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.userapiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.create_template.id'}), "(self.userapiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, templateid=self.\n create_template.id)\n", (8162, 8370), False, 'from marvin.lib.base import Account, VirtualMachine, Volume, ServiceOffering, Configurations, DiskOffering, Template\n'), ((6770, 6795), 'marvin.lib.utils.validateList', 'validateList', (['list_volume'], {}), '(list_volume)\n', (6782, 6795), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((5826, 5846), 'marvin.lib.utils.validateList', 'validateList', (['config'], {}), '(config)\n', (5838, 5846), False, 'from marvin.lib.utils import cleanup_resources, validateList\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for elastic load balancing and elastic IP
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.cloudstackAPI import (authorizeSecurityGroupIngress,
disassociateIpAddress,
deleteLoadBalancerRule)
from marvin.lib.utils import cleanup_resources
from marvin.lib.base import (Account,
PublicIPAddress,
VirtualMachine,
Network,
LoadBalancerRule,
SecurityGroup,
ServiceOffering,
StaticNATRule,
PublicIpRange)
from marvin.lib.common import (get_zone,
get_domain,
get_template)
from marvin.sshClient import SshClient
import time
class Services:
"""Test elastic load balancing and elastic IP
"""
def __init__(self):
self.services = {
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended for unique
# username
"password": "password",
},
"service_offering": {
"name": "Tiny Instance",
"displaytext": "Tiny Instance",
"cpunumber": 1,
"cpuspeed": 100, # in MHz
"memory": 128, # In MBs
},
"lbrule": {
"name": "SSH",
"alg": "roundrobin",
# Algorithm used for load balancing
"privateport": 22,
"publicport": 22,
"openfirewall": False,
},
"natrule": {
"privateport": 22,
"publicport": 22,
"protocol": "TCP"
},
"virtual_machine": {
"displayname": "Test VM",
"username": "root",
"password": "password",
"ssh_port": 22,
"hypervisor": 'XenServer',
# Hypervisor type should be same as
# hypervisor type of cluster
"privateport": 22,
"publicport": 22,
"protocol": 'TCP',
},
"ostype": 'CentOS 5.3 (64-bit)',
# Cent OS 5.3 (64 bit)
"sleep": 60,
"timeout": 10,
}
class TestEIP(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestEIP, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
try:
cls.services["netscaler"] = cls.config.__dict__[
"netscalerDevice"].__dict__
except KeyError:
raise unittest.SkipTest("Please make sure you have included netscalerDevice\
dict in your config file (keys - ipaddress, username,\
password")
except Exception as e:
raise unittest.SkipTest(e)
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
# Spawn an instance
cls.virtual_machine = VirtualMachine.create(
cls.api_client,
cls.services["virtual_machine"],
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id
)
networks = Network.list(
cls.api_client,
zoneid=cls.zone.id,
listall=True
)
if isinstance(networks, list):
# Basic zone has only one network i.e Basic network
cls.guest_network = networks[0]
else:
raise Exception(
"List networks returned empty response for zone: %s" %
cls.zone.id)
ip_addrs = PublicIPAddress.list(
cls.api_client,
associatednetworkid=cls.guest_network.id,
isstaticnat=True,
account=cls.account.name,
domainid=cls.account.domainid,
listall=True
)
if isinstance(ip_addrs, list):
cls.source_nat = ip_addrs[0]
print("source_nat ipaddress : ", cls.source_nat.ipaddress)
else:
raise Exception(
"No Source NAT IP found for guest network: %s" %
cls.guest_network.id)
cls._cleanup = [
cls.account,
cls.service_offering,
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
# Clean up, terminate the created network offerings
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["eip"])
def test_01_eip_by_deploying_instance(self):
"""Test EIP by deploying an instance
"""
# Validate the following
# 1. Instance gets an IP from GUEST IP range.
# 2. One IP from EIP pool is taken and configured on NS
# commands to verify on NS:
# show ip, show inat- make sure that output says USIP : ON
# 3. After allowing ingress rule based on source CIDR to the
# respective port, verify that you are able to reach guest with EIP
# 4. user_ip_address.is_system=1, user_ip_address.one_to_one_nat=1
self.debug("Fetching public network IP range for public network")
ip_ranges = PublicIpRange.list(
self.apiclient,
zoneid=self.zone.id,
forvirtualnetwork=True
)
self.assertEqual(
isinstance(ip_ranges, list),
True,
"Public IP range should return a valid range"
)
# Guest network can have multiple IP ranges. In that case, split IP
# address and then compare the values
for ip_range in ip_ranges:
self.debug("IP range: %s - %s" % (
ip_range.startip,
ip_range.endip
))
start_ip_list = ip_range.startip.split(".")
end_ip_list = ip_range.endip.split(".")
source_nat_list = self.source_nat.ipaddress.split(".")
self.assertGreaterEqual(
int(source_nat_list[3]),
int(start_ip_list[3]),
"The NAT should be greater/equal to start IP of guest network"
)
self.assertLessEqual(
int(source_nat_list[3]),
int(end_ip_list[3]),
"The NAT should be less/equal to start IP of guest network"
)
# Verify listSecurity groups response
security_groups = SecurityGroup.list(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(security_groups, list),
True,
"Check for list security groups response"
)
self.assertEqual(
len(security_groups),
1,
"Check List Security groups response"
)
self.debug("List Security groups response: %s" %
str(security_groups))
security_group = security_groups[0]
self.debug(
"Creating Ingress rule to allow SSH on default security group")
cmd = authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd()
cmd.domainid = self.account.domainid
cmd.account = self.account.name
cmd.securitygroupid = security_group.id
cmd.protocol = 'TCP'
cmd.startport = 22
cmd.endport = 22
cmd.cidrlist = '0.0.0.0/0'
self.apiclient.authorizeSecurityGroupIngress(cmd)
# COMMENTED:
# try:
# self.debug("SSH into VM: %s" % self.virtual_machine.ssh_ip)
# ssh = self.virtual_machine.get_ssh_client(
# ipaddress=self.source_nat.ipaddress)
# except Exception as e:
# self.fail("SSH Access failed for %s: %s" % \
# (self.virtual_machine.ipaddress, e)
# )
# Fetch details from user_ip_address table in database
self.debug(
"select is_system, one_to_one_nat from user_ip_address\
where public_ip_address='%s';" %
self.source_nat.ipaddress)
qresultset = self.dbclient.execute(
"select is_system, one_to_one_nat from user_ip_address\
where public_ip_address='%s';" %
self.source_nat.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
1,
"user_ip_address.is_system value should be 1 for static NAT"
)
self.assertEqual(
qresult[1],
1,
"user_ip_address.one_to_one_nat value should be 1 for static NAT"
)
self.debug("SSH into netscaler: %s" %
self.services["netscaler"]["ipaddress"])
ssh_client = SshClient(
self.services["netscaler"]["ipaddress"],
22,
self.services["netscaler"]["username"],
self.services["netscaler"]["password"],
)
self.debug("command: show ip")
res = ssh_client.execute("show ip")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(self.source_nat.ipaddress),
1,
"One IP from EIP pool should be taken and configured on NS"
)
self.debug("Command:show inat")
res = ssh_client.execute("show inat")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(
"NAME: Cloud-Inat-%s" %
self.source_nat.ipaddress),
1,
"User source IP should be enabled for INAT service")
return
@attr(tags=["eip"])
def test_02_acquire_ip_enable_static_nat(self):
"""Test associate new IP and enable static NAT for new IP and the VM
"""
# Validate the following
# 1. user_ip_address.is_system = 0 & user_ip_address.one_to_one_nat=1
# 2. releases default EIP whose user_ip_address.is_system=1
# 3. After allowing ingress rule based on source CIDR to the
# respective port, verify that you are able to reach guest with EIP
# 4. check configuration changes for EIP reflects on NS
# commands to verify on NS :
# * "show ip"
# * "show inat" - make sure that output says USIP : ON
self.debug("Acquiring new IP for network: %s" % self.guest_network.id)
public_ip = PublicIPAddress.create(
self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
services=self.services["virtual_machine"]
)
self.debug("IP address: %s is acquired by network: %s" % (
public_ip.ipaddress.ipaddress,
self.guest_network.id))
self.debug("Enabling static NAT for IP Address: %s" %
public_ip.ipaddress.ipaddress)
StaticNATRule.enable(
self.apiclient,
ipaddressid=public_ip.ipaddress.id,
virtualmachineid=self.virtual_machine.id
)
# Fetch details from user_ip_address table in database
self.debug(
"select is_system, one_to_one_nat from user_ip_address\
where public_ip_address='%s';" %
public_ip.ipaddress.ipaddress)
qresultset = self.dbclient.execute(
"select is_system, one_to_one_nat from user_ip_address\
where public_ip_address='%s';" %
public_ip.ipaddress.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
0,
"user_ip_address.is_system value should be 0 for new IP"
)
self.assertEqual(
qresult[1],
1,
"user_ip_address.one_to_one_nat value should be 1 for static NAT"
)
self.debug(
"select is_system, one_to_one_nat from user_ip_address\
where public_ip_address='%s';" %
self.source_nat.ipaddress)
qresultset = self.dbclient.execute(
"select is_system, one_to_one_nat from user_ip_address\
where public_ip_address='%s';" %
self.source_nat.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
0,
"user_ip_address.is_system value should be 0 old source NAT"
)
# try:
# self.debug("SSH into VM: %s" % public_ip.ipaddress)
# ssh = self.virtual_machine.get_ssh_client(
# ipaddress=public_ip.ipaddress)
# except Exception as e:
# self.fail("SSH Access failed for %s: %s" % \
# (public_ip.ipaddress, e)
# )
self.debug("SSH into netscaler: %s" %
self.services["netscaler"]["ipaddress"])
try:
ssh_client = SshClient(
self.services["netscaler"]["ipaddress"],
22,
self.services["netscaler"]["username"],
self.services["netscaler"]["password"],
)
self.debug("command: show ip")
res = ssh_client.execute("show ip")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(public_ip.ipaddress.ipaddress),
1,
"One IP from EIP pool should be taken and configured on NS"
)
self.debug("Command:show inat")
res = ssh_client.execute("show inat")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(
"NAME: Cloud-Inat-%s" %
public_ip.ipaddress.ipaddress),
1,
"User source IP should be enabled for INAT service")
except Exception as e:
self.fail("SSH Access failed for %s: %s" %
(self.services["netscaler"]["ipaddress"], e))
return
@attr(tags=["eip"])
def test_03_disable_static_nat(self):
"""Test disable static NAT and release EIP acquired
"""
# Validate the following
# 1. Disable static NAT. Disables one-to-one NAT and releases EIP
# whose user_ip_address.is_system=0
# 2. Gets a new ip from EIP pool whose user_ip_address.is_system=1
# and user_ip_address.one_to_one_nat=1
# 3. DisassicateIP should mark this EIP whose is_system=0 as free.
# commands to verify on NS :
# * "show ip"
# * "show inat"-make sure that output says USIP : ON
self.debug(
"Fetching static NAT for VM: %s" % self.virtual_machine.name)
ip_addrs = PublicIPAddress.list(
self.api_client,
associatednetworkid=self.guest_network.id,
isstaticnat=True,
account=self.account.name,
domainid=self.account.domainid,
listall=True
)
self.assertEqual(
isinstance(ip_addrs, list),
True,
"List Public IP address should return valid IP address for network"
)
static_nat = ip_addrs[0]
self.debug("Static NAT for VM: %s is: %s" % (
self.virtual_machine.name,
static_nat.ipaddress
))
# Fetch details from user_ip_address table in database
self.debug(
"select is_system from user_ip_address where\
public_ip_address='%s';" %
static_nat.ipaddress)
qresultset = self.dbclient.execute(
"select is_system from user_ip_address where\
public_ip_address='%s';" %
static_nat.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
0,
"user_ip_address.is_system value should be 0"
)
self.debug(
"Disassociate Static NAT: %s" %
static_nat.ipaddress)
cmd = disassociateIpAddress.disassociateIpAddressCmd()
cmd.id = static_nat.id
self.apiclient.disassociateIpAddress(cmd)
self.debug("Sleeping - after disassociating static NAT")
time.sleep(self.services["sleep"])
# Fetch details from user_ip_address table in database
self.debug(
"select state from user_ip_address where public_ip_address='%s';"
% static_nat.ipaddress)
qresultset = self.dbclient.execute(
"select state from user_ip_address where public_ip_address='%s';"
% static_nat.ipaddress
)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
"Free",
"Ip should be marked as Free after disassociate IP"
)
self.debug(
"Fetching static NAT for VM: %s" % self.virtual_machine.name)
ip_addrs = PublicIPAddress.list(
self.api_client,
associatednetworkid=self.guest_network.id,
isstaticnat=True,
account=self.account.name,
domainid=self.account.domainid,
listall=True
)
self.assertEqual(
isinstance(ip_addrs, list),
True,
"List Public IP address should return valid IP address for network"
)
static_nat = ip_addrs[0]
self.debug("Static NAT for VM: %s is: %s" % (
self.virtual_machine.name,
static_nat.ipaddress
))
# Fetch details from user_ip_address table in database
self.debug(
"select is_system, one_to_one_nat from user_ip_address\
where public_ip_address='%s';" %
static_nat.ipaddress)
qresultset = self.dbclient.execute(
"select is_system, one_to_one_nat from user_ip_address\
where public_ip_address='%s';" %
static_nat.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
1,
"is_system value should be 1 for automatically assigned IP"
)
self.assertEqual(
qresult[1],
1,
"one_to_one_nat value should be 1 for automatically assigned IP"
)
# try:
# self.debug("SSH into VM: %s" % static_nat.ipaddress)
# ssh = self.virtual_machine.get_ssh_client(
# ipaddress=static_nat.ipaddress)
# except Exception as e:
# self.fail("SSH Access failed for %s: %s" % \
# (static_nat.ipaddress, e))
self.debug("SSH into netscaler: %s" %
self.services["netscaler"]["ipaddress"])
ssh_client = SshClient(
self.services["netscaler"]["ipaddress"],
22,
self.services["netscaler"]["username"],
self.services["netscaler"]["password"],
)
self.debug("command: show ip")
res = ssh_client.execute("show ip")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(static_nat.ipaddress),
1,
"One IP from EIP pool should be taken and configured on NS"
)
self.debug("Command:show inat")
res = ssh_client.execute("show inat")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count("USIP: ON"),
2,
"User source IP should be enabled for INAT service"
)
return
@attr(tags=["eip"])
def test_04_disable_static_nat_system(self):
"""Test disable static NAT with system = True
"""
# Validate the following
# 1. Try to disassociate/disable static NAT on EIP where is_system=1
# 2. This operation should fail with proper error message.
self.debug(
"Fetching static NAT for VM: %s" % self.virtual_machine.name)
ip_addrs = PublicIPAddress.list(
self.api_client,
associatednetworkid=self.guest_network.id,
isstaticnat=True,
account=self.account.name,
domainid=self.account.domainid,
listall=True
)
self.assertEqual(
isinstance(ip_addrs, list),
True,
"List Public IP address should return valid IP address for network"
)
static_nat = ip_addrs[0]
self.debug("Static NAT for VM: %s is: %s" % (
self.virtual_machine.name,
static_nat.ipaddress
))
# Fetch details from user_ip_address table in database
self.debug(
"select is_system from user_ip_address where\
public_ip_address='%s';" %
static_nat.ipaddress)
qresultset = self.dbclient.execute(
"select is_system from user_ip_address where\
public_ip_address='%s';" %
static_nat.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
1,
"user_ip_address.is_system value should be 1"
)
self.debug(
"Disassociate Static NAT: %s" %
static_nat.ipaddress)
with self.assertRaises(Exception):
cmd = disassociateIpAddress.disassociateIpAddressCmd()
cmd.id = static_nat.id
self.api_client.disassociateIpAddress(cmd)
self.debug("Disassociate system IP failed")
return
@attr(tags=["eip"])
def test_05_destroy_instance(self):
"""Test EIO after destroying instance
"""
# Validate the following
# 1. Destroy instance. Destroy should result in is_system=0 for EIP
# and EIP should also be marked as free.
# 2. Commands to verify on NS :
# * "show ip"
# * "show inat" - make sure that output says USIP: ON
self.debug(
"Fetching static NAT for VM: %s" % self.virtual_machine.name)
ip_addrs = PublicIPAddress.list(
self.api_client,
associatednetworkid=self.guest_network.id,
isstaticnat=True,
account=self.account.name,
domainid=self.account.domainid,
listall=True
)
self.assertEqual(
isinstance(ip_addrs, list),
True,
"List Public IP address should return valid IP address for network"
)
static_nat = ip_addrs[0]
self.debug("Static NAT for VM: %s is: %s" % (
self.virtual_machine.name,
static_nat.ipaddress
))
self.debug("Destroying an instance: %s" % self.virtual_machine.name)
self.virtual_machine.delete(self.apiclient, expunge=True)
self.debug("Destroy instance complete!")
vms = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
vms,
None,
"list VM should not return anything after destroy"
)
# Fetch details from user_ip_address table in database
self.debug(
"select is_system, state from user_ip_address where\
public_ip_address='%s';" %
static_nat.ipaddress)
qresultset = self.dbclient.execute(
"select is_system, state from user_ip_address where\
public_ip_address='%s';" %
static_nat.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
0,
"user_ip_address.is_system value should be 0"
)
self.assertEqual(
qresult[1],
"Free",
"IP should be marked as Free after destroying VM"
)
self.debug("SSH into netscaler: %s" %
self.services["netscaler"]["ipaddress"])
ssh_client = SshClient(
self.services["netscaler"]["ipaddress"],
22,
self.services["netscaler"]["username"],
self.services["netscaler"]["password"],
)
self.debug("command: show ip")
res = ssh_client.execute("show ip")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(static_nat.ipaddress),
0,
"show ip should return nothing after VM destroy"
)
self.debug("Command:show inat")
res = ssh_client.execute("show inat")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(static_nat.ipaddress),
0,
"show inat should return nothing after VM destroy"
)
return
class TestELB(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestELB, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
try:
cls.services["netscaler"] = cls.config.__dict__[
"netscalerDevice"].__dict__
except KeyError:
raise unittest.SkipTest("Please make sure you have included netscalerDevice\
dict in your config file (keys - ipaddress, username,\
password")
except Exception as e:
raise unittest.SkipTest(e)
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
# Spawn an instance
cls.vm_1 = VirtualMachine.create(
cls.api_client,
cls.services["virtual_machine"],
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id
)
cls.vm_2 = VirtualMachine.create(
cls.api_client,
cls.services["virtual_machine"],
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id
)
networks = Network.list(
cls.api_client,
zoneid=cls.zone.id,
listall=True
)
if isinstance(networks, list):
# Basic zone has only one network i.e Basic network
cls.guest_network = networks[0]
else:
raise Exception(
"List networks returned empty response for zone: %s" %
cls.zone.id)
cls.lb_rule = LoadBalancerRule.create(
cls.api_client,
cls.services["lbrule"],
accountid=cls.account.name,
networkid=cls.guest_network.id,
domainid=cls.account.domainid
)
cls.lb_rule.assign(cls.api_client, [cls.vm_1, cls.vm_2])
cls._cleanup = [
cls.account,
cls.service_offering,
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
# Clean up, terminate the created network offerings
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["eip"])
def test_01_elb_create(self):
"""Test ELB by creating a LB rule
"""
# Validate the following
# 1. Deploy 2 instances
# 2. Create LB rule to port 22 for the VMs and try to access VMs with
# EIP:port. Make sure that ingress rule is created to allow access
# with universal CIDR (0.0.0.0/0)
# 3. For LB rule IP user_ip_address.is_system=1
# 4. check configuration changes for EIP reflects on NS
# commands to verify on NS :
# * "show ip"
# * "show lb vserer"-make sure that output says they are all up
# and running and USNIP : ON
# Verify listSecurity groups response
security_groups = SecurityGroup.list(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(security_groups, list),
True,
"Check for list security groups response"
)
self.assertEqual(
len(security_groups),
1,
"Check List Security groups response"
)
self.debug("List Security groups response: %s" %
str(security_groups))
security_group = security_groups[0]
self.debug(
"Creating Ingress rule to allow SSH on default security group")
cmd = authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd()
cmd.domainid = self.account.domainid
cmd.account = self.account.name
cmd.securitygroupid = security_group.id
cmd.protocol = 'TCP'
cmd.startport = 22
cmd.endport = 22
cmd.cidrlist = '0.0.0.0/0'
self.apiclient.authorizeSecurityGroupIngress(cmd)
self.debug(
"Fetching LB IP for account: %s" % self.account.name)
ip_addrs = PublicIPAddress.list(
self.api_client,
associatednetworkid=self.guest_network.id,
account=self.account.name,
domainid=self.account.domainid,
forloadbalancing=True,
listall=True
)
self.assertEqual(
isinstance(ip_addrs, list),
True,
"List Public IP address should return valid IP address for network"
)
lb_ip = ip_addrs[0]
self.debug("LB IP generated for account: %s is: %s" % (
self.account.name,
lb_ip.ipaddress
))
# TODO: uncomment this after ssh issue is resolved
# self.debug("SSHing into VMs using ELB IP: %s" % lb_ip.ipaddress)
# try:
# ssh_1 = self.vm_1.get_ssh_client(ipaddress=lb_ip.ipaddress)
# self.debug("Command: hostname")
# result = ssh_1.execute("hostname")
# self.debug("Result: %s" % result)
#
# if isinstance(result, list):
# res = result[0]
# else:
# self.fail("hostname retrieval failed!")
#
# self.assertIn(
# res,
# [self.vm_1.name, self.vm_2.name],
# "SSH should return hostname of one of the VM"
# )
#
# ssh_2 = self.vm_2.get_ssh_client(ipaddress=lb_ip.ipaddress)
# self.debug("Command: hostname")
# result = ssh_2.execute("hostname")
# self.debug("Result: %s" % result)
#
# if isinstance(result, list):
# res = result[0]
# else:
# self.fail("hostname retrieval failed!")
# self.assertIn(
# res,
# [self.vm_1.name, self.vm_2.name],
# "SSH should return hostname of one of the VM"
# )
# except Exception as e:
# self.fail(
# "SSH Access failed for %s: %s" % (self.vm_1.ipaddress, e))
# Fetch details from user_ip_address table in database
self.debug(
"select is_system from user_ip_address where\
public_ip_address='%s';" %
lb_ip.ipaddress)
qresultset = self.dbclient.execute(
"select is_system from user_ip_address where\
public_ip_address='%s';" %
lb_ip.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
1,
"is_system value should be 1 for system generated LB rule"
)
self.debug("SSH into netscaler: %s" %
self.services["netscaler"]["ipaddress"])
try:
ssh_client = SshClient(
self.services["netscaler"]["ipaddress"],
22,
self.services["netscaler"]["username"],
self.services["netscaler"]["password"],
)
self.debug("command: show ip")
res = ssh_client.execute("show ip")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(lb_ip.ipaddress),
1,
"One IP from EIP pool should be taken and configured on NS"
)
self.debug("Command:show lb vserver")
res = ssh_client.execute("show lb vserver")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(
"Cloud-VirtualServer-%s-22 (%s:22) - TCP" %
(lb_ip.ipaddress,
lb_ip.ipaddress)),
1,
"User subnet IP should be enabled for LB service")
except Exception as e:
self.fail("SSH Access failed for %s: %s" %
(self.services["netscaler"]["ipaddress"], e))
return
@attr(tags=["eip"])
def test_02_elb_acquire_and_create(self):
"""Test ELB by acquiring IP and then creating a LB rule
"""
# Validate the following
# 1. Deploy 2 instances
# 2. Create LB rule to port 22 for the VMs and try to access VMs with
# EIP:port. Make sure that ingress rule is created to allow access
# with universal CIDR (0.0.0.0/0)
# 3. For LB rule IP user_ip_address.is_system=0
# 4. check configuration changes for EIP reflects on NS
# commands to verify on NS :
# * "show ip"
# * "show lb vserer" - make sure that output says they are all up
# and running and USNIP : ON
self.debug("Acquiring new IP for network: %s" % self.guest_network.id)
public_ip = PublicIPAddress.create(
self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
services=self.services["virtual_machine"]
)
self.debug("IP address: %s is acquired by network: %s" % (
public_ip.ipaddress.ipaddress,
self.guest_network.id))
self.debug("Creating LB rule for public IP: %s" %
public_ip.ipaddress.ipaddress)
lb_rule = LoadBalancerRule.create(
self.apiclient,
self.services["lbrule"],
accountid=self.account.name,
ipaddressid=public_ip.ipaddress.id,
networkid=self.guest_network.id,
domainid=self.account.domainid
)
self.debug("Assigning VMs (%s, %s) to LB rule: %s" % (self.vm_1.name,
self.vm_2.name,
lb_rule.name))
lb_rule.assign(self.apiclient, [self.vm_1, self.vm_2])
# TODO: workaround : add route in the guest VM for SNIP
#
# self.debug("SSHing into VMs using ELB IP: %s" %
# public_ip.ipaddress)
# try:
# ssh_1 = self.vm_1.get_ssh_client(
# ipaddress=public_ip.ipaddress)
# self.debug("Command: hostname")
# result = ssh_1.execute("hostname")
# self.debug("Result: %s" % result)
#
# if isinstance(result, list):
# res = result[0]
# else:
# self.fail("hostname retrieval failed!")
# self.assertIn(
# res,
# [self.vm_1.name, self.vm_2.name],
# "SSH should return hostname of one of the VM"
# )
#
# ssh_2 = self.vm_2.get_ssh_client(
# ipaddress=public_ip.ipaddress)
# self.debug("Command: hostname")
# result = ssh_2.execute("hostname")
# self.debug("Result: %s" % result)
#
# if isinstance(result, list):
# res = result[0]
# else:
# self.fail("hostname retrieval failed!")
# self.assertIn(
# res,
# [self.vm_1.name, self.vm_2.name],
# "SSH should return hostname of one of the VM"
# )
# except Exception as e:
# self.fail(
# "SSH Access failed for %s: %s" % (self.vm_1.ipaddress, e))
#
# Fetch details from user_ip_address table in database
self.debug(
"select is_system from user_ip_address where\
public_ip_address='%s';" %
public_ip.ipaddress.ipaddress)
qresultset = self.dbclient.execute(
"select is_system from user_ip_address where\
public_ip_address='%s';" %
public_ip.ipaddress.ipaddress)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"Check DB Query result set"
)
qresult = qresultset[0]
self.assertEqual(
qresult[0],
0,
"is_system value should be 0 for non-system generated LB rule"
)
self.debug("SSH into netscaler: %s" %
self.services["netscaler"]["ipaddress"])
try:
ssh_client = SshClient(
self.services["netscaler"]["ipaddress"],
22,
self.services["netscaler"]["username"],
self.services["netscaler"]["password"],
)
self.debug("command: show ip")
res = ssh_client.execute("show ip")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(public_ip.ipaddress.ipaddress),
1,
"One IP from EIP pool should be taken and configured on NS"
)
self.debug("Command:show lb vserver")
res = ssh_client.execute("show lb vserver")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(
"Cloud-VirtualServer-%s-22 (%s:22) - TCP" %
(public_ip.ipaddress.ipaddress,
public_ip.ipaddress.ipaddress)),
1,
"User subnet IP should be enabled for LB service")
except Exception as e:
self.fail("SSH Access failed for %s: %s" %
(self.services["netscaler"]["ipaddress"], e))
return
@attr(tags=["eip"])
def test_03_elb_delete_lb_system(self):
"""Test delete LB rule generated with public IP with is_system = 1
"""
# Validate the following
# 1. Deleting LB rule should release EIP where is_system=1
# 2. check configuration changes for EIP reflects on NS
# commands to verify on NS:
# * "show ip"
# * "show lb vserer"-make sure that output says they are all up and
# running and USNIP : ON
self.debug(
"Fetching LB IP for account: %s" % self.account.name)
ip_addrs = PublicIPAddress.list(
self.api_client,
associatednetworkid=self.guest_network.id,
account=self.account.name,
domainid=self.account.domainid,
forloadbalancing=True,
listall=True
)
self.assertEqual(
isinstance(ip_addrs, list),
True,
"List Public IP address should return valid IP address for network"
)
lb_ip = ip_addrs[0]
self.debug("LB IP generated for account: %s is: %s" % (
self.account.name,
lb_ip.ipaddress
))
self.debug("Deleting LB rule: %s" % self.lb_rule.id)
self.lb_rule.delete(self.apiclient)
time.sleep(60)
self.debug("SSH into netscaler: %s" %
self.services["netscaler"]["ipaddress"])
ssh_client = SshClient(
self.services["netscaler"]["ipaddress"],
22,
self.services["netscaler"]["username"],
self.services["netscaler"]["password"],
)
self.debug("command: show ip")
res = ssh_client.execute("show ip")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(lb_ip.ipaddress),
1,
"One IP from EIP pool should be taken and configured on NS"
)
self.debug("Command:show lb vserver")
res = ssh_client.execute("show lb vserver")
result = str(res)
self.debug("Output: %s" % result)
self.assertEqual(
result.count(
"Cloud-VirtualServer-%s-22 (%s:22) - TCP" %
(lb_ip.ipaddress,
lb_ip.ipaddress)),
1,
"User subnet IP should be enabled for LB service")
return
@attr(tags=["eip"])
def test_04_delete_lb_on_eip(self):
"""Test delete LB rule generated on EIP
"""
# Validate the following
# 1. Deleting LB rule won't release EIP where is_system=0
# 2. disassociateIP must release the above IP
# 3. check configuration changes for EIP reflects on NS
# commands to verify on NS :
# * "show ip"
# * "show lb vserer"-make sure that output says they are all up and
# running and USNIP : ON
# Fetch details from account_id table in database
self.debug(
"select id from account where account_name='%s';"
% self.account.name)
qresultset = self.dbclient.execute(
"select id from account where account_name='%s';"
% self.account.name)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"DB query should return a valid public IP address"
)
qresult = qresultset[0]
account_id = qresult[0]
# Fetch details from user_ip_address table in database
self.debug(
"select public_ip_address from user_ip_address where\
is_system=0 and account_id=%s;" %
account_id)
qresultset = self.dbclient.execute(
"select public_ip_address from user_ip_address where\
is_system=0 and account_id=%s;" %
account_id)
self.assertEqual(
isinstance(qresultset, list),
True,
"Check DB query result set for valid data"
)
self.assertNotEqual(
len(qresultset),
0,
"DB query should return a valid public IP address"
)
qresult = qresultset[0]
public_ip = qresult[0]
self.debug(
"Fetching public IP for account: %s" % self.account.name)
ip_addrs = PublicIPAddress.list(
self.api_client,
ipaddress=public_ip,
listall=True
)
self.debug("ip address list: %s" % ip_addrs)
self.assertEqual(
isinstance(ip_addrs, list),
True,
"List Public IP address should return valid IP address for network"
)
lb_ip = ip_addrs[0]
lb_rules = LoadBalancerRule.list(
self.apiclient,
publicipid=lb_ip.id,
listall=True
)
self.assertEqual(
isinstance(lb_rules, list),
True,
"Atleast one LB rule must be present for public IP address"
)
lb_rule = lb_rules[0]
self.debug("Deleting LB rule associated with IP: %s" % public_ip)
try:
cmd = deleteLoadBalancerRule.deleteLoadBalancerRuleCmd()
cmd.id = lb_rule.id
self.apiclient.deleteLoadBalancerRule(cmd)
except Exception as e:
self.fail("Deleting LB rule failed for IP: %s-%s" % (public_ip, e))
# TODO:check the lb rule list and then confirm that lb rule is deleted
self.debug("LB rule deleted!")
ip_addrs = PublicIPAddress.list(
self.api_client,
ipaddress=public_ip,
listall=True
)
self.assertEqual(
isinstance(ip_addrs, list),
True,
"Deleting LB rule should not delete public IP"
)
self.debug("SSH into netscaler: %s" %
self.services["netscaler"]["ipaddress"])
try:
ssh_client = SshClient(
self.services["netscaler"]["ipaddress"],
22,
self.services["netscaler"]["username"],
self.services["netscaler"]["password"],
)
self.debug("command: show ip")
res = ssh_client.execute("show ip")
result = str(res)
self.debug("Output: %s" % result)
self.assertNotEqual(
result.count(public_ip),
1,
"One IP from EIP pool should be taken and configured on NS"
)
self.debug("Command:show lb vserver")
res = ssh_client.execute("show lb vserver")
result = str(res)
self.debug("Output: %s" % result)
self.assertNotEqual(
result.count(
"Cloud-VirtualServer-%s-22 (%s:22) - TCP" %
(lb_ip.ipaddress,
lb_ip.ipaddress)),
1,
"User subnet IP should be enabled for LB service")
except Exception as e:
self.fail("SSH Access failed for %s: %s" %
(self.services["netscaler"]["ipaddress"], e))
return
| [
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.PublicIPAddress.create",
"marvin.lib.base.SecurityGroup.list",
"marvin.lib.base.LoadBalancerRule.list",
"marvin.lib.base.PublicIPAddress.list",
"marvin.cloudstackAPI.authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd",
"marvin.lib.commo... | [((7053, 7071), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (7057, 7071), False, 'from nose.plugins.attrib import attr\n'), ((12550, 12568), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (12554, 12568), False, 'from nose.plugins.attrib import attr\n'), ((17588, 17606), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (17592, 17606), False, 'from nose.plugins.attrib import attr\n'), ((24029, 24047), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (24033, 24047), False, 'from nose.plugins.attrib import attr\n'), ((26275, 26293), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (26279, 26293), False, 'from nose.plugins.attrib import attr\n'), ((33393, 33411), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (33397, 33411), False, 'from nose.plugins.attrib import attr\n'), ((39564, 39582), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (39568, 39582), False, 'from nose.plugins.attrib import attr\n'), ((45330, 45348), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (45334, 45348), False, 'from nose.plugins.attrib import attr\n'), ((47746, 47764), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['eip']"}), "(tags=['eip'])\n", (47750, 47764), False, 'from nose.plugins.attrib import attr\n'), ((4180, 4206), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (4190, 4206), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((4360, 4425), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (4372, 4425), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((4638, 4710), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (4660, 4710), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((4767, 4862), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], admin=True,\n domainid=cls.domain.id)\n", (4781, 4862), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((4975, 5155), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.api_client', "cls.services['virtual_machine']"], {'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.api_client, cls.services['virtual_machine'],\n accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering.id)\n", (4996, 5155), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((5237, 5299), 'marvin.lib.base.Network.list', 'Network.list', (['cls.api_client'], {'zoneid': 'cls.zone.id', 'listall': '(True)'}), '(cls.api_client, zoneid=cls.zone.id, listall=True)\n', (5249, 5299), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((5656, 5833), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['cls.api_client'], {'associatednetworkid': 'cls.guest_network.id', 'isstaticnat': '(True)', 'account': 'cls.account.name', 'domainid': 'cls.account.domainid', 'listall': '(True)'}), '(cls.api_client, associatednetworkid=cls.guest_network.\n id, isstaticnat=True, account=cls.account.name, domainid=cls.account.\n domainid, listall=True)\n', (5676, 5833), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((7757, 7836), 'marvin.lib.base.PublicIpRange.list', 'PublicIpRange.list', (['self.apiclient'], {'zoneid': 'self.zone.id', 'forvirtualnetwork': '(True)'}), '(self.apiclient, zoneid=self.zone.id, forvirtualnetwork=True)\n', (7775, 7836), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((8983, 9081), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self\n .account.domainid)\n', (9001, 9081), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((9668, 9732), 'marvin.cloudstackAPI.authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd', 'authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd', ([], {}), '()\n', (9730, 9732), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, disassociateIpAddress, deleteLoadBalancerRule\n'), ((11634, 11773), 'marvin.sshClient.SshClient', 'SshClient', (["self.services['netscaler']['ipaddress']", '(22)', "self.services['netscaler']['username']", "self.services['netscaler']['password']"], {}), "(self.services['netscaler']['ipaddress'], 22, self.services[\n 'netscaler']['username'], self.services['netscaler']['password'])\n", (11643, 11773), False, 'from marvin.sshClient import SshClient\n'), ((13334, 13507), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'services': "self.services['virtual_machine']"}), "(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, services=self.services[\n 'virtual_machine'])\n", (13356, 13507), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((13835, 13953), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient'], {'ipaddressid': 'public_ip.ipaddress.id', 'virtualmachineid': 'self.virtual_machine.id'}), '(self.apiclient, ipaddressid=public_ip.ipaddress.id,\n virtualmachineid=self.virtual_machine.id)\n', (13855, 13953), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((18319, 18500), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'associatednetworkid': 'self.guest_network.id', 'isstaticnat': '(True)', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'listall': '(True)'}), '(self.api_client, associatednetworkid=self.\n guest_network.id, isstaticnat=True, account=self.account.name, domainid\n =self.account.domainid, listall=True)\n', (18339, 18500), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((19878, 19926), 'marvin.cloudstackAPI.disassociateIpAddress.disassociateIpAddressCmd', 'disassociateIpAddress.disassociateIpAddressCmd', ([], {}), '()\n', (19924, 19926), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, disassociateIpAddress, deleteLoadBalancerRule\n'), ((20082, 20116), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (20092, 20116), False, 'import time\n'), ((21049, 21230), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'associatednetworkid': 'self.guest_network.id', 'isstaticnat': '(True)', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'listall': '(True)'}), '(self.api_client, associatednetworkid=self.\n guest_network.id, isstaticnat=True, account=self.account.name, domainid\n =self.account.domainid, listall=True)\n', (21069, 21230), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((23181, 23320), 'marvin.sshClient.SshClient', 'SshClient', (["self.services['netscaler']['ipaddress']", '(22)', "self.services['netscaler']['username']", "self.services['netscaler']['password']"], {}), "(self.services['netscaler']['ipaddress'], 22, self.services[\n 'netscaler']['username'], self.services['netscaler']['password'])\n", (23190, 23320), False, 'from marvin.sshClient import SshClient\n'), ((24455, 24636), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'associatednetworkid': 'self.guest_network.id', 'isstaticnat': '(True)', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'listall': '(True)'}), '(self.api_client, associatednetworkid=self.\n guest_network.id, isstaticnat=True, account=self.account.name, domainid\n =self.account.domainid, listall=True)\n', (24475, 24636), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((26798, 26979), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'associatednetworkid': 'self.guest_network.id', 'isstaticnat': '(True)', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'listall': '(True)'}), '(self.api_client, associatednetworkid=self.\n guest_network.id, isstaticnat=True, account=self.account.name, domainid\n =self.account.domainid, listall=True)\n', (26818, 26979), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((27604, 27667), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (27623, 27667), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((28968, 29107), 'marvin.sshClient.SshClient', 'SshClient', (["self.services['netscaler']['ipaddress']", '(22)', "self.services['netscaler']['username']", "self.services['netscaler']['password']"], {}), "(self.services['netscaler']['ipaddress'], 22, self.services[\n 'netscaler']['username'], self.services['netscaler']['password'])\n", (28977, 29107), False, 'from marvin.sshClient import SshClient\n'), ((30113, 30139), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (30123, 30139), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((30703, 30768), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (30715, 30768), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((30981, 31053), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (31003, 31053), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((31110, 31205), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], admin=True,\n domainid=cls.domain.id)\n", (31124, 31205), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((31307, 31487), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.api_client', "cls.services['virtual_machine']"], {'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.api_client, cls.services['virtual_machine'],\n accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering.id)\n", (31328, 31487), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((31569, 31749), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.api_client', "cls.services['virtual_machine']"], {'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.api_client, cls.services['virtual_machine'],\n accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering.id)\n", (31590, 31749), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((31831, 31893), 'marvin.lib.base.Network.list', 'Network.list', (['cls.api_client'], {'zoneid': 'cls.zone.id', 'listall': '(True)'}), '(cls.api_client, zoneid=cls.zone.id, listall=True)\n', (31843, 31893), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((32252, 32416), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['cls.api_client', "cls.services['lbrule']"], {'accountid': 'cls.account.name', 'networkid': 'cls.guest_network.id', 'domainid': 'cls.account.domainid'}), "(cls.api_client, cls.services['lbrule'], accountid=\n cls.account.name, networkid=cls.guest_network.id, domainid=cls.account.\n domainid)\n", (32275, 32416), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((34140, 34238), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self\n .account.domainid)\n', (34158, 34238), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((34825, 34889), 'marvin.cloudstackAPI.authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd', 'authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd', ([], {}), '()\n', (34887, 34889), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, disassociateIpAddress, deleteLoadBalancerRule\n'), ((35303, 35489), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'associatednetworkid': 'self.guest_network.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'forloadbalancing': '(True)', 'listall': '(True)'}), '(self.api_client, associatednetworkid=self.\n guest_network.id, account=self.account.name, domainid=self.account.\n domainid, forloadbalancing=True, listall=True)\n', (35323, 35489), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((40375, 40548), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'services': "self.services['virtual_machine']"}), "(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, services=self.services[\n 'virtual_machine'])\n", (40397, 40548), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((40882, 41086), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']"], {'accountid': 'self.account.name', 'ipaddressid': 'public_ip.ipaddress.id', 'networkid': 'self.guest_network.id', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['lbrule'], accountid=\n self.account.name, ipaddressid=public_ip.ipaddress.id, networkid=self.\n guest_network.id, domainid=self.account.domainid)\n", (40905, 41086), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((45930, 46116), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'associatednetworkid': 'self.guest_network.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'forloadbalancing': '(True)', 'listall': '(True)'}), '(self.api_client, associatednetworkid=self.\n guest_network.id, account=self.account.name, domainid=self.account.\n domainid, forloadbalancing=True, listall=True)\n', (45950, 46116), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((46641, 46655), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (46651, 46655), False, 'import time\n'), ((46784, 46923), 'marvin.sshClient.SshClient', 'SshClient', (["self.services['netscaler']['ipaddress']", '(22)', "self.services['netscaler']['username']", "self.services['netscaler']['password']"], {}), "(self.services['netscaler']['ipaddress'], 22, self.services[\n 'netscaler']['username'], self.services['netscaler']['password'])\n", (46793, 46923), False, 'from marvin.sshClient import SshClient\n'), ((49828, 49900), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'ipaddress': 'public_ip', 'listall': '(True)'}), '(self.api_client, ipaddress=public_ip, listall=True)\n', (49848, 49900), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((50223, 50295), 'marvin.lib.base.LoadBalancerRule.list', 'LoadBalancerRule.list', (['self.apiclient'], {'publicipid': 'lb_ip.id', 'listall': '(True)'}), '(self.apiclient, publicipid=lb_ip.id, listall=True)\n', (50244, 50295), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((51024, 51096), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'ipaddress': 'public_ip', 'listall': '(True)'}), '(self.api_client, ipaddress=public_ip, listall=True)\n', (51044, 51096), False, 'from marvin.lib.base import Account, PublicIPAddress, VirtualMachine, Network, LoadBalancerRule, SecurityGroup, ServiceOffering, StaticNATRule, PublicIpRange\n'), ((6420, 6467), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (6437, 6467), False, 'from marvin.lib.utils import cleanup_resources\n'), ((6879, 6926), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (6896, 6926), False, 'from marvin.lib.utils import cleanup_resources\n'), ((16413, 16552), 'marvin.sshClient.SshClient', 'SshClient', (["self.services['netscaler']['ipaddress']", '(22)', "self.services['netscaler']['username']", "self.services['netscaler']['password']"], {}), "(self.services['netscaler']['ipaddress'], 22, self.services[\n 'netscaler']['username'], self.services['netscaler']['password'])\n", (16422, 16552), False, 'from marvin.sshClient import SshClient\n'), ((26062, 26110), 'marvin.cloudstackAPI.disassociateIpAddress.disassociateIpAddressCmd', 'disassociateIpAddress.disassociateIpAddressCmd', ([], {}), '()\n', (26108, 26110), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, disassociateIpAddress, deleteLoadBalancerRule\n'), ((32760, 32807), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (32777, 32807), False, 'from marvin.lib.utils import cleanup_resources\n'), ((33219, 33266), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (33236, 33266), False, 'from marvin.lib.utils import cleanup_resources\n'), ((38347, 38486), 'marvin.sshClient.SshClient', 'SshClient', (["self.services['netscaler']['ipaddress']", '(22)', "self.services['netscaler']['username']", "self.services['netscaler']['password']"], {}), "(self.services['netscaler']['ipaddress'], 22, self.services[\n 'netscaler']['username'], self.services['netscaler']['password'])\n", (38356, 38486), False, 'from marvin.sshClient import SshClient\n'), ((44071, 44210), 'marvin.sshClient.SshClient', 'SshClient', (["self.services['netscaler']['ipaddress']", '(22)', "self.services['netscaler']['username']", "self.services['netscaler']['password']"], {}), "(self.services['netscaler']['ipaddress'], 22, self.services[\n 'netscaler']['username'], self.services['netscaler']['password'])\n", (44080, 44210), False, 'from marvin.sshClient import SshClient\n'), ((50644, 50694), 'marvin.cloudstackAPI.deleteLoadBalancerRule.deleteLoadBalancerRuleCmd', 'deleteLoadBalancerRule.deleteLoadBalancerRuleCmd', ([], {}), '()\n', (50692, 50694), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, disassociateIpAddress, deleteLoadBalancerRule\n'), ((51440, 51579), 'marvin.sshClient.SshClient', 'SshClient', (["self.services['netscaler']['ipaddress']", '(22)', "self.services['netscaler']['username']", "self.services['netscaler']['password']"], {}), "(self.services['netscaler']['ipaddress'], 22, self.services[\n 'netscaler']['username'], self.services['netscaler']['password'])\n", (51449, 51579), False, 'from marvin.sshClient import SshClient\n'), ((3870, 4052), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Please make sure you have included netscalerDevice dict in your config file (keys - ipaddress, username, password"""'], {}), "(\n 'Please make sure you have included netscalerDevice dict in your config file (keys - ipaddress, username, password'\n )\n", (3887, 4052), False, 'import unittest\n'), ((4096, 4116), 'unittest.SkipTest', 'unittest.SkipTest', (['e'], {}), '(e)\n', (4113, 4116), False, 'import unittest\n'), ((30432, 30614), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Please make sure you have included netscalerDevice dict in your config file (keys - ipaddress, username, password"""'], {}), "(\n 'Please make sure you have included netscalerDevice dict in your config file (keys - ipaddress, username, password'\n )\n", (30449, 30614), False, 'import unittest\n'), ((30658, 30678), 'unittest.SkipTest', 'unittest.SkipTest', (['e'], {}), '(e)\n', (30675, 30678), False, 'import unittest\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Test from the Marvin - Testing in Python wiki
# All tests inherit from cloudstackTestCase
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.cloudstackAPI import changeServiceForVirtualMachine, startVirtualMachine
# Import Integration Libraries
# base - contains all resources as entities and defines create, delete,
# list operations on them
from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot
# utils - utility classes for common cleanup, external library wrappers etc
from marvin.lib.utils import cleanup_resources
# common - commonly used methods for all tests are listed here
from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines
from marvin.sshClient import SshClient
from marvin.codes import FAILED
from nose.plugins.attrib import attr
import time
class TestvGPUWindowsVm(cloudstackTestCase):
"""
Testing vGPU VM with All vGPU service offerings
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestvGPUWindowsVm, cls).getClsTestClient()
cls.testdata = cls.testClient.getParsedTestDataConfig()
cls.apiclient = cls.testClient.getApiClient()
cls._cleanup = []
cls.cleanup = []
hosts = list_hosts(
cls.apiclient,
hypervisor="XenServer"
)
if hosts is None:
raise unittest.SkipTest(
"There are no XenServers available. GPU feature is supported only on XenServer.Check listhosts response")
else:
cls.k140qgpuhosts = 0
cls.k120qgpuhosts = 0
cls.k100gpuhosts = 0
cls.k260qgpuhosts = 0
cls.k240qgpuhosts = 0
cls.k220qgpuhosts = 0
cls.k200gpuhosts = 0
cls.k1passthroughgpuhosts = 0
cls.k2passthroughgpuhosts = 0
cls.nongpuhosts = []
cls.k2hosts = 0
cls.k1hosts = 0
cls.k100_vgpu_service_offering = []
cls.k200_vgpu_service_offering = []
cls.nonvgpu_service_offering = []
cls.vm_k1_card = []
cls.vm_k2_card = []
cls.vm2_k2_card = []
cls.nonvgpu = []
cls.vmlifecycletest = 0
cls.vmsnapwomemory = 0
cls.vmsnapwithmemory = 0
for ghost in hosts:
if ghost.hypervisorversion >= "6.2.0":
sshClient = SshClient(
host=ghost.ipaddress,
port=cls.testdata['configurableData']['host']["publicport"],
user=cls.testdata['configurableData']['host']["username"],
passwd=cls.testdata['configurableData']['host']["password"])
if ghost.hypervisorversion == "6.2.0":
res = len(
sshClient.execute("xe patch-list uuid=0850b186-4d47-11e3-a720-001b2151a503"))
if res == 0:
continue
k1card = len(sshClient.execute("lspci | grep \"GRID K1\""))
k2card = len(sshClient.execute("lspci | grep \"GRID K2\""))
cls.debug(
"k1 card and k2 card details are :%s %s " %
(k1card, k2card))
if (k2card == 0) and (k1card == 0):
cls.nongpuhosts.append(ghost.ipaddress)
if k2card != 0:
cls.k2hosts = cls.k2hosts + 1
k260q = len(
sshClient.execute("xe vgpu-type-list model-name=\"GRID K260Q\""))
k240q = len(
sshClient.execute("xe vgpu-type-list model-name=\"GRID K240Q\""))
k220q = len(
sshClient.execute("xe vgpu-type-list model-name=\"GRID K220Q\""))
k200 = len(
sshClient.execute("xe vgpu-type-list model-name=\"GRID K200\""))
k2passthrough = len(
sshClient.execute("xe vgpu-type-list model-name='passthrough'"))
if ((k260q == 0) and (k240q == 0) and (k220q == 0)
and (k200 == 0) and (k2passthrough == 0)):
continue
else:
if k260q != 0:
cls.k260qgpuhosts = cls.k260qgpuhosts + 1
if k240q != 0:
cls.k240qgpuhosts = cls.k240qgpuhosts + 1
if k220q != 0:
cls.k220qgpuhosts = cls.k220qgpuhosts + 1
if k200 != 0:
cls.k200gpuhosts = cls.k200gpuhosts + 1
if k2passthrough != 0:
cls.k2passthroughgpuhosts = cls.k2passthroughgpuhosts + \
1
if k1card != 0:
cls.k1hosts = cls.k1hosts + 1
k100 = len(
sshClient.execute("xe vgpu-type-list model-name=\"GRID K100\""))
k120q = len(
sshClient.execute("xe vgpu-type-list model-name=\"GRID K120Q\""))
k140q = len(
sshClient.execute("xe vgpu-type-list model-name=\"GRID K140Q\""))
k1passthrough = len(
sshClient.execute("xe vgpu-type-list model-name='passthrough'"))
if ((k100 == 0) and (k120q == 0) and (
k140q == 0) and (k1passthrough == 0)):
continue
else:
if k140q != 0:
cls.k140qgpuhosts = cls.k140qgpuhosts + 1
if k120q != 0:
cls.k120qgpuhosts = cls.k120qgpuhosts + 1
if k100 != 0:
cls.k100gpuhosts = cls.k100gpuhosts + 1
if k1passthrough != 0:
cls.k1passthroughgpuhosts = cls.k1passthroughgpuhosts + \
1
if (cls.k2hosts == 0) and (cls.k1hosts == 0):
raise unittest.SkipTest(
"No XenServer available with GPU Drivers installed")
cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.domain = get_domain(cls.apiclient)
cls.pod = get_pod(cls.apiclient, cls.zone.id)
cls.account = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
cls.template = get_windows_template(
cls.apiclient,
cls.zone.id,
ostype_desc="Windows 8 (64-bit)")
#cls.template = get_windows_template(cls.apiclient, cls.zone.id ,ostype_desc="Windows Server 2012 (64-bit)")
if cls.template == FAILED:
if "http://pleaseupdateURL/dummy.vhd" in cls.testdata[
"vgpu"]["templateregister1"]["url"]:
raise unittest.SkipTest(
"Check Test Data file if it has the valid template URL")
cls.template = Template.register(
cls.apiclient,
cls.testdata["vgpu"]["templateregister1"],
hypervisor="XenServer",
zoneid=cls.zone.id,
domainid=cls.account.domainid,
account=cls.account.name
)
timeout = cls.testdata["vgpu"]["timeout"]
while True:
time.sleep(cls.testdata["vgpu"]["sleep"])
list_template_response = Template.list(
cls.apiclient,
templatefilter=cls.testdata["templatefilter"],
id=cls.template.id
)
if (isinstance(list_template_response, list)) is not True:
raise unittest.SkipTest(
"Check list template api response returns a valid list")
if len(list_template_response) is None:
raise unittest.SkipTest(
"Check template registered is in List Templates")
template_response = list_template_response[0]
if template_response.isready:
break
if timeout == 0:
raise unittest.SkipTest(
"Failed to download template(ID: %s). " %
template_response.id)
timeout = timeout - 1
cls._cleanup = [
cls.account,
# cls.k100_vgpu_service_offering,
# cls.k200_vgpu_service_offering
]
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def setUp(self):
self.testdata = self.testClient.getParsedTestDataConfig()
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
return
def check_host_vgpu_capacity(self, gpucard, gtype):
gputhosts = list_hosts(
self.apiclient,
hypervisor="XenServer"
)
vgpucapacity = 0
for ghost in gputhosts:
if ghost.gpugroup is not None:
for gp in ghost.gpugroup:
if gp.gpugroupname == gpucard:
for gptype in gp.vgpu:
if gptype.vgputype == gtype:
vgpucapacity = vgpucapacity + \
gptype.remainingcapacity
return(vgpucapacity)
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def vgpu_serviceoffering_creation(self, gtype, nvidiamodel):
if gtype == "nonvgpuoffering" and nvidiamodel == "None":
self.service_offering = ServiceOffering.create(
self.apiclient,
self.testdata["vgpu"]["service_offerings"][gtype]
)
self.debug(
"service offering details are:%s" %
self.service_offering)
list_service_response = ServiceOffering.list(
self.apiclient,
id=self.service_offering.id
)
if list_service_response is None:
raise unittest.SkipTest(
"Check Service Offering list for %s service offering" %
(gtype))
self.assertEqual(
list_service_response[0].displaytext,
self.testdata["vgpu"]["service_offerings"][gtype]["displaytext"],
"Check server display text in createServiceOfferings")
self.assertEqual(
list_service_response[0].name,
self.testdata["vgpu"]["service_offerings"][gtype]["name"],
"Check name in createServiceOffering"
)
else:
self.testdata["vgpu"]["service_offerings"][gtype]["serviceofferingdetails"] = [
{'pciDevice': nvidiamodel}, {'vgpuType': gtype}]
self.service_offering = ServiceOffering.create(
self.apiclient,
self.testdata["vgpu"]["service_offerings"][gtype]
)
list_service_response = ServiceOffering.list(
self.apiclient,
id=self.service_offering.id
)
if list_service_response is None:
raise unittest.SkipTest(
"Check Service Offering list for %s service offering" %
(gtype))
self.assertEqual(
list_service_response[0].serviceofferingdetails.vgpuType,
gtype,
"Failed To Create Service Offering . Check vGPU Service Offering list")
self.assertEqual(
list_service_response[0].displaytext,
self.testdata["vgpu"]["service_offerings"][gtype]["displaytext"],
"Check server displaytext in createServiceOfferings")
self.assertEqual(
list_service_response[0].name,
self.testdata["vgpu"]["service_offerings"][gtype]["name"],
"Check name in createServiceOffering"
)
return(self.service_offering)
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def check_for_vGPU_resource(
self,
hostid,
vminstancename,
serviceofferingid,
vgputype):
"""
Validate the VM for VGPU resources
"""
"""Create SSH Client for Host Connection
"""
vgpu_host = list_hosts(
self.apiclient,
id=hostid
)
ssh_client = SshClient(
host=vgpu_host[0].ipaddress,
port=self.testdata['configurableData']['host']["publicport"],
user=self.testdata['configurableData']['host']["username"],
passwd=self.testdata['configurableData']['host']["password"])
"""
Get vGPU type model
"""
vgpu_type_model = ssh_client.execute(
"xe vgpu-list vm-name-label=" +
vminstancename +
" params=type-model-name --minimal")
self.debug(
"vgpu type model is %s and value is %s and length is %s" %
(vgpu_type_model, vgpu_type_model[0], len(
vgpu_type_model[0])))
if vgputype is None:
if len(vgpu_type_model[0]) == 0:
self.debug("This is non GPU instance")
return
else:
self.fail(
"Non vGPU VM has GPU cards @ host:%s" %
vminstancename)
self.assertNotEqual(
len(vgpu_type_model),
0,
"The VM is NOT deployed with vGPU cards"
)
"""
List service offering from which VM is deployed
"""
list_service_offering_response = ServiceOffering.list(
self.apiclient,
id=serviceofferingid
)
""" Check whether the vgputype in the service offering is same as the one obtained by listing the vgpu type model
"""
self.debug(
"VM vGPU type is: %s and vGPU type on XenServer is : %s" %
(list_service_offering_response[0].serviceofferingdetails.vgpuType,
vgpu_type_model[0]))
self.assertEqual(
list_service_offering_response[0].serviceofferingdetails.vgpuType,
vgpu_type_model[0],
"VM does not have the correct GPU resources, verified on the host"
)
"""
Check whether the VM is deployed with the card which was mentioned in the service offering
"""
self.assertEqual(
vgputype,
list_service_offering_response[0].serviceofferingdetails.vgpuType,
"The VM is NOT deployed with correct cards, verified from CS"
)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def deploy_vGPU_windows_vm(self, vgpuofferingid, vgput):
"""
Validate vGPU K1 windows instances
"""
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.testdata["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=vgpuofferingid,
templateid=self.template.id
)
time.sleep(self.testdata["vgpu"]["sleep"])
list_vms = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s"
% self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vms, list),
True,
"List VM response was not a valid list"
)
self.assertNotEqual(
len(list_vms),
0,
"List VM response was empty"
)
vm = list_vms[0]
self.assertEqual(
vm.id,
self.virtual_machine.id,
"Virtual Machine ids do not match"
)
self.assertEqual(
vm.name,
self.virtual_machine.name,
"Virtual Machine names do not match"
)
self.assertEqual(
vm.state,
"Running",
msg="VM is not in Running state"
)
if vgput != "nonvgpuoffering":
self.assertEqual(
vm.vgpu,
vgput,
msg="Failed to deploy VM with vGPU card"
)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def delete_vgpu_service_offering(self, serviceoffering):
"""
delete vGPU Service Offering
"""
serviceoffering.delete(self.apiclient)
list_service_response = list_service_offering(
self.apiclient,
id=serviceoffering.id
)
self.assertEqual(
list_service_response,
None,
"Check if service offering exists in listServiceOfferings"
)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def check_for_vm(self, vgpucard, vgpuofferingid, vmid):
list_vm_response = list_virtual_machines(
self.apiclient,
id=vmid
)
if isinstance(list_vm_response, list):
vm = list_vm_response[0]
if vm.state == 'Running':
self.debug("VM state: %s" % vm.state)
else:
self.fail("Failed to start VM (ID: %s)" % vm.id)
if vm.serviceofferingid == vgpuofferingid:
self.debug(
"VM service offering id : %s" %
vm.serviceofferingid)
else:
self.fail("Service Offering is not matching " % vm.id)
if vgpucard != "nonvgpuoffering":
if vm.vgpu == vgpucard:
self.debug("VM vGPU card is : %s" % vm.vgpu)
else:
self.fail(
"Failed to start VM (ID: %s) with %s vGPU card " %
(vm.id, vgpucard))
return(list_vm_response[0])
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def destroy_vm(self):
"""Destroy Virtual Machine
"""
self.virtual_machine.delete(self.apiclient)
list_vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vm_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_vm_response),
0,
"Check VM avaliable in List Virtual Machines"
)
self.assertEqual(
list_vm_response[0].state,
"Destroyed",
"Check virtual machine is in destroyed state"
)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def stop_vm(self):
"""Stop Virtual Machine
"""
try:
self.virtual_machine.stop(self.apiclient)
except Exception as e:
self.fail("Failed to stop VM: %s" % e)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def start_vm(self):
"""Start Virtual Machine
"""
self.debug("Starting VM - ID: %s" % self.virtual_machine.id)
self.virtual_machine.start(self.apiclient)
list_vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vm_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_vm_response),
0,
"Check VM available in List Virtual Machines"
)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s"
% self.virtual_machine.id
)
self.assertEqual(
list_vm_response[0].state,
"Running",
"Check virtual machine is in running state"
)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def serviceoffering_upgrade(
self,
sourcetype,
sourcemodel,
desttype,
destmodel):
self.sourcevgpuoffering = self.vgpu_serviceoffering_creation(
sourcetype,
sourcemodel)
self.deploy_vGPU_windows_vm(self.sourcevgpuoffering.id, sourcetype)
time.sleep(self.testdata["vgpu"]["sleep"])
vm = self.check_for_vm(
sourcetype,
self.sourcevgpuoffering.id,
self.virtual_machine.id)
self.check_for_vGPU_resource(
vm.hostid,
vm.instancename,
vm.serviceofferingid,
vm.vgpu)
self.stop_vm()
self.destvgpuoffering = self.vgpu_serviceoffering_creation(
desttype,
destmodel)
cmd = changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd()
cmd.id = vm.id
cmd.serviceofferingid = self.destvgpuoffering.id
self.apiclient.changeServiceForVirtualMachine(cmd)
self.debug("Starting VM - ID: %s" % vm.id)
self.start_vm()
time.sleep(self.testdata["vgpu"]["sleep"])
# Ensure that VM is in running state
vm = self.check_for_vm(desttype, self.destvgpuoffering.id, vm.id)
self.check_for_vGPU_resource(
vm.hostid,
vm.instancename,
vm.serviceofferingid,
vm.vgpu)
self.delete_vgpu_service_offering(self.destvgpuoffering)
self.delete_vgpu_service_offering(self.sourcevgpuoffering)
self.destroy_vm()
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def vm_snapshot_serviceoffering_upgrade(
self,
sourcetype,
sourcemodel,
desttype,
destmodel):
self.sourcevgpuoffering = self.vgpu_serviceoffering_creation(
sourcetype,
sourcemodel)
self.deploy_vGPU_windows_vm(self.sourcevgpuoffering.id, sourcetype)
time.sleep(self.testdata["vgpu"]["sleep"])
vm = self.check_for_vm(
sourcetype,
self.sourcevgpuoffering.id,
self.virtual_machine.id)
self.check_for_vGPU_resource(
vm.hostid,
vm.instancename,
vm.serviceofferingid,
vm.vgpu)
self.stop_vm()
self.destvgpuoffering = self.vgpu_serviceoffering_creation(
desttype,
destmodel)
cmd = changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd()
cmd.id = vm.id
cmd.serviceofferingid = self.destvgpuoffering.id
self.apiclient.changeServiceForVirtualMachine(cmd)
self.debug("Starting VM - ID: %s" % vm.id)
self.start_vm()
time.sleep(self.testdata["vgpu"]["sleep"])
# Ensure that VM is in running state
vm = self.check_for_vm(desttype, self.destvgpuoffering.id, vm.id)
self.check_for_vGPU_resource(
vm.hostid,
vm.instancename,
vm.serviceofferingid,
vm.vgpu)
self.delete_vgpu_service_offering(self.destvgpuoffering)
self.delete_vgpu_service_offering(self.sourcevgpuoffering)
self.destroy_vm()
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def deploy_vm(self, type, model):
self.vgpuoffering = self.vgpu_serviceoffering_creation(type, model)
if self.vgpuoffering is not None:
self.deploy_vGPU_windows_vm(self.vgpuoffering.id, type)
time.sleep(self.testdata["vgpu"]["sleep"])
vm = self.check_for_vm(
type,
self.vgpuoffering.id,
self.virtual_machine.id)
self.check_for_vGPU_resource(
vm.hostid,
vm.instancename,
vm.serviceofferingid,
vm.vgpu)
self.destroy_vm()
self.delete_vgpu_service_offering(self.vgpuoffering)
return
def new_template_register(self, guestostype):
template1 = get_windows_template(
self.apiclient,
self.zone.id,
ostype_desc=guestostype)
if template1 == FAILED:
if "http://pleaseupdateURL/dummy.vhd" in self.testdata[
"vgpu"][guestostype]["url"]:
raise unittest.SkipTest(
"Check Test Data file if it has the valid template URL")
template1 = Template.register(
self.apiclient,
self.testdata["vgpu"][guestostype],
hypervisor="XenServer",
zoneid=self.zone.id,
domainid=self.account.domainid,
account=self.account.name
)
timeout = self.testdata["vgpu"]["timeout"]
while True:
time.sleep(self.testdata["vgpu"]["sleep"])
list_template_response = Template.list(
self.apiclient,
templatefilter=self.testdata["templatefilter"],
id=template1.id
)
if (isinstance(list_template_response, list)) is not True:
raise unittest.SkipTest(
"Check list template api response returns a valid list")
if len(list_template_response) is None:
raise unittest.SkipTest(
"Check template registered is in List Templates")
template_response = list_template_response[0]
if template_response.isready:
break
if timeout == 0:
raise unittest.SkipTest(
"Failed to download template(ID: %s)" %
template_response.id)
timeout = timeout - 1
return(template1.id)
def deploy_vm_lifecycle(self):
"""
Create Service Offerings for Both K1 and K2 cards to be used for VM life cycle tests
"""
if(self.k1hosts != 0):
if(self.k140qgpuhosts != 0):
gtype = "GRID K140Q"
elif(self.k120qgpuhosts != 0):
gtype = "GRID K120Q"
elif(self.k100gpuhosts != 0):
gtype = "GRID K100"
else:
gtype = "passthrough"
self.testdata["vgpu"]["service_offerings"][gtype]["serviceofferingdetails"] = [
{'pciDevice': 'Group of NVIDIA Corporation GK107GL [GRID K1] GPUs'}, {'vgpuType': gtype}]
try:
self.__class__.k100_vgpu_service_offering = ServiceOffering.create(
self.apiclient,
self.testdata["vgpu"]["service_offerings"][gtype]
)
except Exception as e:
self.fail("Failed to create the service offering, %s" % e)
if(self.k2hosts != 0):
if(self.k240qgpuhosts != 0):
gtype = "GRID K240Q"
elif(self.k220qgpuhosts != 0):
gtype = "GRID K220Q"
elif(self.k200gpuhosts != 0):
gtype = "GRID K200"
else:
gtype = "passthrough"
self.testdata["vgpu"]["service_offerings"][gtype]["serviceofferingdetails"] = [
{'pciDevice': 'Group of NVIDIA Corporation GK104GL [GRID K2] GPUs'}, {'vgpuType': gtype}]
try:
self.__class__.k200_vgpu_service_offering = ServiceOffering.create(
self.apiclient,
self.testdata["vgpu"]["service_offerings"][gtype]
)
except Exception as e:
self.fail("Failed to create the service offering, %s" % e)
win8templateid = self.new_template_register("Windows 8 (64-bit)")
win2012templateid = self.new_template_register(
"Windows Server 2012 (64-bit)")
win7templateid = self.new_template_register("Windows 7 (64-bit)")
self.__class__.nonvgpu_service_offering = ServiceOffering.create(
self.apiclient,
self.testdata["vgpu"]["service_offerings"]["nonvgpuoffering"]
)
"""
Create Virtual Machines for Both K1 and K2 cards to be used for VM life cycle tests
"""
if(self.k1hosts != 0):
self.__class__.vm_k1_card = VirtualMachine.create(
self.apiclient,
self.testdata["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.k100_vgpu_service_offering.id,
templateid=win8templateid
)
if(self.k2hosts != 0):
self.__class__.vm_k2_card = VirtualMachine.create(
self.apiclient,
self.testdata["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.k200_vgpu_service_offering.id,
templateid=win2012templateid
)
if(self.k2hosts != 0):
self.__class__.vm2_k2_card = VirtualMachine.create(
self.apiclient,
self.testdata["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.k200_vgpu_service_offering.id,
templateid=win7templateid
)
self.__class__.nonvgpu = VirtualMachine.create(
self.apiclient,
self.testdata["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.__class__.nonvgpu_service_offering.id,
templateid=win7templateid
)
return
def check_gpu_resources_released_vm(
self,
gpuhostid,
vm_vgpu_type,
rcapacity):
hhosts = list_hosts(
self.apiclient,
hypervisor="XenServer",
id=gpuhostid
)
self.assertEqual(
isinstance(hhosts, list),
True,
"Check list hosts response returns a valid list"
)
self.assertNotEqual(
len(hhosts),
0,
"Check Host details are available in List Hosts"
)
for ggroup in hhosts:
if ggroup.ipaddress not in self.nongpuhosts:
for gp in ggroup.gpugroup:
# if gp.gpugroupname == "Group of NVIDIA Corporation
# GK104GL [GRID K2] GPUs":
for gptype in gp.vgpu:
if gptype.vgputype == vm_vgpu_type:
self.debug(
"Latest remainingcapacity is %s and before remainingcapacity is %s" %
(gptype.remainingcapacity, rcapacity))
if gptype.remainingcapacity != rcapacity + 1:
self.fail(
"Host capacity is not updated .GPU resources should be released when VM is stopped/Destroyed ")
return
def check_vm_state(self, vmid):
list_vm_response = list_virtual_machines(
self.apiclient,
id=vmid
)
if list_vm_response is None:
return("Expunge")
return(list_vm_response[0].state)
def check_host_vgpu_remaining_capacity(self, gpuhostid, gtype):
gputhosts = list_hosts(
self.apiclient,
hypervisor="XenServer",
id=gpuhostid
)
vgpucapacity = 0
for ghost in gputhosts:
if ghost.gpugroup is not None:
for gp in ghost.gpugroup:
# if gp.gpugroupname == gpucard:
for gptype in gp.vgpu:
if gptype.vgputype == gtype:
vgpucapacity = vgpucapacity + \
gptype.remainingcapacity
return(vgpucapacity)
def verify_vm(self, vm_gpu_card):
if(vm_gpu_card):
vm_gpu_card.getState(
self.apiclient,
"Running")
time.sleep(self.testdata["vgpu"]["sleep"] * 3)
self.check_for_vGPU_resource(
vm_gpu_card.hostid,
vm_gpu_card.instancename,
vm_gpu_card.serviceofferingid,
vm_gpu_card.vgpu)
def stop_life_cycle_vm(self, vm_gpu_card):
if(vm_gpu_card):
vm_gpu_card.stop(self.apiclient)
time.sleep(self.testdata["vgpu"]["sleep"])
vm_gpu_card.getState(
self.apiclient,
"Stopped")
def start_life_cycle_vm(self, vm_gpu_card):
if(vm_gpu_card):
vm_gpu_card.start(self.apiclient)
time.sleep(self.testdata["vgpu"]["sleep"])
vm_gpu_card.getState(
self.apiclient,
"Running")
def restore_life_cycle_vm(self, vm_gpu_card):
if(vm_gpu_card):
vm_gpu_card.restore(self.apiclient)
time.sleep(self.testdata["vgpu"]["sleep"])
def reboot_life_cycle_vm(self, vm_gpu_card):
if(vm_gpu_card):
vm_gpu_card.reboot(self.apiclient)
time.sleep(self.testdata["vgpu"]["sleep"])
def delete_vm_life_cycle_vm(self, vm_gpu_card):
if(vm_gpu_card):
vm_gpu_card.delete(self.apiclient)
time.sleep(self.testdata["vgpu"]["sleep"])
vm_gpu_card.getState(
self.apiclient,
"Destroyed")
def recover_vm_life_cycle_vm(self, vm_gpu_card):
if(vm_gpu_card):
vm_gpu_card.recover(self.apiclient)
vm_gpu_card.getState(
self.apiclient,
"Stopped")
def recovervm(self, vm_gpu_card):
if self.check_vm_state(vm_gpu_card.id) == "Expunge":
raise unittest.SkipTest("VM is already deleted hence skipping")
self.recover_vm_life_cycle_vm(vm_gpu_card)
self.start_life_cycle_vm(vm_gpu_card)
self.verify_vm(vm_gpu_card)
return
def startvm(self, vm_gpu_card):
self.start_life_cycle_vm(vm_gpu_card)
self.verify_vm(vm_gpu_card)
return
def stopvm(self, vm_gpu_card):
rcapacity = self.check_host_vgpu_remaining_capacity(
vm_gpu_card.hostid,
vm_gpu_card.vgpu)
self.stop_life_cycle_vm(vm_gpu_card)
time.sleep(self.testdata["vgpu"]["sleep"] * 3)
self.check_gpu_resources_released_vm(
vm_gpu_card.hostid,
vm_gpu_card.vgpu,
rcapacity)
return
def deletevm(self, vm_gpu_card):
rcapacity = self.check_host_vgpu_remaining_capacity(
vm_gpu_card.hostid,
vm_gpu_card.vgpu)
hostid = vm_gpu_card.hostid
vgputype = vm_gpu_card.vgpu
self.delete_vm_life_cycle_vm(vm_gpu_card)
time.sleep(self.testdata["vgpu"]["sleep"] * 3)
self.check_gpu_resources_released_vm(hostid, vgputype, rcapacity)
return
def restorevm(self, vm_gpu_card):
self.restore_life_cycle_vm(vm_gpu_card)
self.verify_vm(vm_gpu_card)
return
def create_vm_snapshot(self, vmcard):
self.debug("Check if deployed VMs are in running state?")
if(vmcard):
vmcard.getState(
self.apiclient,
"Running")
if hasattr(vmcard, "vgpu"):
self.check_for_vGPU_resource(
vmcard.hostid,
vmcard.instancename,
vmcard.serviceofferingid,
vmcard.vgpu)
VmSnapshot.create(
self.apiclient,
vmcard.id,
"false",
"TestSnapshot",
"Display Text"
)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=vmcard.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
self.assertEqual(
list_snapshot_response[0].state,
"Ready",
"Check the snapshot of vm is ready!"
)
vgpu_host = list_hosts(
self.apiclient,
id=vmcard.hostid
)
ssh_client = SshClient(
host=vgpu_host[0].ipaddress,
port=self.testdata['configurableData']['host']["publicport"],
user=self.testdata['configurableData']['host']["username"],
passwd=self.testdata['configurableData']['host']["password"])
"""
Get vGPU type model
"""
vgpu_snapshot = ssh_client.execute(
"xe snapshot-list name-label=" +
list_snapshot_response[0].name +
" --minimal")
#vgpu_snapshot = ssh_client.execute("xe snapshot-param-get param-name=name-label uuid="+vgpu_snapshot_uuid[0]+ " params=type-model-name --minimal")
# self.debug("vgpu type model is %s and value is %s and length is %s"%(vgpu_type_model,vgpu_type_model[0],len(vgpu_type_model[0])))
self.assertNotEqual(
len(vgpu_snapshot[0]),
0,
"VM Snapshot is not created"
)
self.__class__.vmsnapwomemory = 1
return
def revert_vm_snapshot(self, vmcard):
self.debug("Check if deployed VMs are in running state?")
# if(vmcard):
# vmcard.getState(
# self.apiclient,
# "Running")
if hasattr(vmcard, "vgpu"):
self.check_for_vGPU_resource(
vmcard.hostid,
vmcard.instancename,
vmcard.serviceofferingid,
vmcard.vgpu)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=vmcard.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
self.assertEqual(
list_snapshot_response[0].state,
"Ready",
"Check the snapshot of vm is ready!"
)
VmSnapshot.revertToSnapshot(
self.apiclient,
list_snapshot_response[0].id)
time.sleep(self.testdata["vgpu"]["sleep"])
list_vm_response = list_virtual_machines(
self.apiclient,
id=vmcard.id
)
vm = list_vm_response[0]
self.assertEqual(
list_vm_response[0].state,
"Stopped",
"Check the state of vm is Stopped"
)
cmd = startVirtualMachine.startVirtualMachineCmd()
cmd.id = vm.id
self.apiclient.startVirtualMachine(cmd)
time.sleep(self.testdata["vgpu"]["sleep"])
list_vm_response = list_virtual_machines(
self.apiclient,
id=vm.id
)
vm = list_vm_response[0]
if vm is None:
self.fail("Failed to list VM details after Vm Snapshot")
self.assertEqual(
vm.state,
"Running",
"Check the state of vm is Running"
)
if hasattr(vmcard, "vgpu"):
self.check_for_vGPU_resource(
vmcard.hostid,
vmcard.instancename,
vmcard.serviceofferingid,
vmcard.vgpu)
def delete_vm_snapshot(self, vmcard):
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=vmcard.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
Tobedeletedsnapname = list_snapshot_response[0].name
VmSnapshot.deleteVMSnapshot(
self.apiclient,
list_snapshot_response[0].id)
time.sleep(self.testdata["vgpu"]["sleep"])
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=vmcard.id,
listall=True)
self.debug(
"List Snapshot response after snapshot deletion %s" %
list_snapshot_response)
self.assertEqual(
list_snapshot_response,
None,
"Check if vm snapshot is deleted"
)
vgpu_host = list_hosts(
self.apiclient,
id=vmcard.hostid
)
ssh_client = SshClient(
host=vgpu_host[0].ipaddress,
port=self.testdata['configurableData']['host']["publicport"],
user=self.testdata['configurableData']['host']["username"],
passwd=self.testdata['configurableData']['host']["password"])
vgpu_snapshot = ssh_client.execute(
"xe snapshot-list name-label=" +
Tobedeletedsnapname +
" --minimal")
#vgpu_snapshot = ssh_client.execute("xe snapshot-param-get param-name=name-label uuid="+vgpu_snapshot_uuid[0]+ " params=type-model-name --minimal")
# self.debug("vgpu type model is %s and value is %s and length is %s"%(vgpu_type_model,vgpu_type_model[0],len(vgpu_type_model[0])))
self.debug(
"List Snapshot response after snapshot deletion is %s %s" %
(vgpu_snapshot, vgpu_snapshot[0]))
self.assertEqual(
len(vgpu_snapshot[0]),
0,
"check if VM Snapshot is not deleted"
)
return
def create_vm_snapshot_with_memory(self, vmcard):
self.debug("Check if deployed VMs are in running state?")
if(vmcard):
vmcard.getState(
self.apiclient,
"Running")
self.check_for_vGPU_resource(
vmcard.hostid,
vmcard.instancename,
vmcard.serviceofferingid,
vmcard.vgpu)
VmSnapshot.create(
self.apiclient,
vmcard.id,
"true",
"TestSnapshotwithmemory",
"Display Text"
)
time.sleep(self.testdata["vgpu"]["sleep"] * 3)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=vmcard.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
self.assertEqual(
list_snapshot_response[0].state,
"Ready",
"Check the snapshot of vm is ready!"
)
vgpu_host = list_hosts(
self.apiclient,
id=vmcard.hostid
)
ssh_client = SshClient(
host=vgpu_host[0].ipaddress,
port=self.testdata['configurableData']['host']["publicport"],
user=self.testdata['configurableData']['host']["username"],
passwd=self.testdata['configurableData']['host']["password"])
vgpu_snapshot = ssh_client.execute(
"xe snapshot-list name-label=" +
list_snapshot_response[0].name +
" --minimal")
#vgpu_snapshot = ssh_client.execute("xe snapshot-param-get param-name=name-label uuid="+vgpu_snapshot_uuid[0]+ " params=type-model-name --minimal")
# self.debug("vgpu type model is %s and value is %s and length is %s"%(vgpu_type_model,vgpu_type_model[0],len(vgpu_type_model[0])))
self.assertNotEqual(
len(vgpu_snapshot[0]),
0,
"VM Snapshot is not created"
)
self.__class__.vmsnapwithmemory = 1
return
def revert_vm_snapshot_with_memory(self, vmcard):
self.debug("Check if deployed VMs are in running state?")
if(vmcard):
vmcard.getState(
self.apiclient,
"Running")
self.check_for_vGPU_resource(
vmcard.hostid,
vmcard.instancename,
vmcard.serviceofferingid,
vmcard.vgpu)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=vmcard.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
self.assertEqual(
list_snapshot_response[0].state,
"Ready",
"Check the snapshot of vm is ready!"
)
VmSnapshot.revertToSnapshot(
self.apiclient,
list_snapshot_response[0].id)
list_vm_response = list_virtual_machines(
self.apiclient,
id=vmcard.id
)
vm = list_vm_response[0]
if vm is None:
self.fail("Failed to list VM details after Vm Snapshot")
self.assertEqual(
vm.state,
"Running",
"Check the state of vm is Running"
)
self.check_for_vGPU_resource(
vmcard.hostid,
vmcard.instancename,
vmcard.serviceofferingid,
vmcard.vgpu)
return
def rebootvm(self, vm_vgpu_card):
self.reboot_life_cycle_vm(vm_vgpu_card)
self.verify_vm(vm_vgpu_card)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def vm_snapshot_vgpu(
self,
vmcard,
sourcetype,
sourcemodel,
desttype,
destmodel):
self.create_vm_snapshot(vmcard)
self.start_life_cycle_vm(vmcard)
self.destvgpuoffering = self.vgpu_serviceoffering_creation(
desttype,
destmodel)
self.stop_life_cycle_vm(vmcard)
cmd = changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd()
cmd.id = vmcard.id
cmd.serviceofferingid = self.destvgpuoffering.id
self.apiclient.changeServiceForVirtualMachine(cmd)
self.debug("Starting VM - ID: %s" % vmcard.id)
self.start_life_cycle_vm(vmcard)
time.sleep(self.testdata["vgpu"]["sleep"])
vm = self.check_for_vm(desttype, self.destvgpuoffering.id, vmcard.id)
# Ensure that VM is in running state
if destmodel != "None":
self.check_for_vGPU_resource(
vm.hostid,
vm.instancename,
vm.serviceofferingid,
vm.vgpu)
self.revert_vm_snapshot(vm)
self.delete_vm_snapshot(vm)
def test_01_list_vgpu_host_details(self):
""" list vGPU host details """
hhosts = list_hosts(
self.apiclient,
hypervisor="XenServer",
)
self.assertEqual(
isinstance(hhosts, list),
True,
"Check list hosts response returns a valid list"
)
self.assertNotEqual(
len(hhosts),
0,
"Check Host details are available in List Hosts"
)
k260q = 0
k240q = 0
k220q = 0
k200 = 0
k2pass = 0
k140q = 0
k120q = 0
k100 = 0
k1pass = 0
for ggroup in hhosts:
if ggroup.ipaddress not in self.nongpuhosts:
for gp in ggroup.gpugroup:
if gp.gpugroupname == "Group of NVIDIA Corporation GK104GL [GRID K2] GPUs":
for gptype in gp.vgpu:
if gptype.vgputype == "GRID K260Q":
k260q = k260q + 1
if gptype.vgputype == "GRID K220Q":
k220q = k220q + 1
if gptype.vgputype == "GRID K240Q":
k240q = k240q + 1
if gptype.vgputype == "GRID K200":
k200 = k200 + 1
if gptype.vgputype != "passthrough":
k2pass = k2pass + 1
if gp.gpugroupname == "Group of NVIDIA Corporation GK107GL [GRID K1] GPUs":
for gptype in gp.vgpu:
if gptype.vgputype == "GRID K140Q":
k140q = k140q + 1
if gptype.vgputype == "GRID K120Q":
k120q = k120q + 1
if gptype.vgputype == "GRID K100":
k100 = k100 + 1
if gptype.vgputype == "passthrough":
k1pass = k1pass + 1
else:
self.debug("This is nongpuhost:%s" % (ggroup.ipaddress))
if self.k260qgpuhosts > 0:
if not k260q:
self.fail("list host details with K260Q vgpu are not correct")
if self.k240qgpuhosts > 0:
if not k240q:
self.fail("list host details with K240Q vgpu are not correct")
if self.k220qgpuhosts > 0:
if not k220q:
self.fail("list host details with K220Q vgpu are not correct")
if self.k200gpuhosts > 0:
if not k200:
self.fail("list host details with K200 vgpu are not correct")
if self.k2passthroughgpuhosts > 0:
if not k2pass:
self.fail(
"list host details with K2 passthrough vgpu are not correct")
if self.k140qgpuhosts > 0:
if not k140q:
self.fail("list host details with K140Q vgpu are not correct")
if self.k120qgpuhosts > 0:
if not k120q:
self.fail("list host details with K120Q vgpu are not correct")
if self.k100gpuhosts > 0:
if not k100:
self.fail("list host details with K100 vgpu are not correct")
if self.k1passthroughgpuhosts > 0:
if not k1pass:
self.fail(
"list host details with K1 Passthrough vgpu are not correct")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_02_create_deploy_windows_vm_with_k100_vgpu_service_offering(self):
"""Test to create and deploy vm with K100 vGPU service offering"""
k100capacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K100")
if (self.k100gpuhosts == 0) or (k100capacity == 0):
raise unittest.SkipTest(
"No XenServer available with K100 vGPU Drivers installed")
self.deploy_vm(
"GRID K100",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_03_create_deploy_windows_vm_with_k120q_vgpu_service_offering(
self):
"""Test to create and deploy vm with K120Q vGPU service offering"""
k120qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K120Q")
if (self.k120qgpuhosts == 0) or (k120qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K120Q vGPU Drivers installed")
self.deploy_vm(
"GRID K120Q",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_04_create_deploy_windows_vm_with_k140q_vgpu_service_offering(
self):
"""Test to create and deploy vm with K140Q vGPU service offering"""
k140qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K140Q")
if (self.k140qgpuhosts == 0) or (k140qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K140Q vGPU Drivers installed")
self.deploy_vm(
"GRID K140Q",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_05_create_deploy_windows_vm_with_k1_passthrough_vgpu_service_offering(
self):
"""Test to create and deploy vm with K1 passthrough vGPU service offering"""
k1passcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"passthrough")
if (self.k1passthroughgpuhosts == 0) or (k1passcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K1 passthrough installed")
self.deploy_vm(
"passthrough",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_06_create_deploy_windows_vm_with_k2_passthrough_vgpu_service_offering(
self):
"""Test to create and deploy vm with K2 pasthrough vGPU service offering"""
k2passcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"passthrough")
if (self.k2passthroughgpuhosts == 0) or (k2passcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K2 passthrough installed")
self.deploy_vm(
"passthrough",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_07_create_deploy_windows_vm_with_k260q_vgpu_service_offering(
self):
"""Test to create and deploy vm with K260Q vGPU service offering"""
k260qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K260Q")
if (self.k260qgpuhosts == 0) or (k260qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K260Q vGPU Drivers installed")
self.deploy_vm(
"GRID K260Q",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_08_create_deploy_windows_vm_with_k240q_vgpu_service_offering(
self):
""" Test to create and deploy vm with K240Q vGPU service offering """
k240qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K240Q")
if (self.k240qgpuhosts == 0) or (k240qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K240Q vGPU Drivers installed")
self.deploy_vm(
"GRID K240Q",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_09_create_deploy_windows_vm_with_k220q_vgpu_service_offering(
self):
""" Test to create and deploy vm with K220Q vGPU service offering """
k220qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K220Q")
if (self.k220qgpuhosts == 0) or (k220qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K220Q vGPU Drivers installed")
self.deploy_vm(
"GRID K220Q",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_10_create_deploy_windows_vm_with_k200_vgpu_service_offering(self):
""" Test to create and deploy vm with K200 vGPU service offering """
k200capacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K200")
if (self.k200gpuhosts == 0) or (k200capacity == 0):
raise unittest.SkipTest(
"No XenServer available with K200 vGPU Drivers installed")
self.deploy_vm(
"GRID K200",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs")
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_11_add_nonvgpu_host_to_vgpucluster(self):
""" Test to add non vGPU host to an existing cluster """
countx = 0
# hostuuids=[]
huuids = []
lhosts = list_hosts(
self.apiclient,
hypervisor="XenServer"
)
sshClient1 = SshClient(
host=lhosts[0].ipaddress,
port=self.testdata['configurableData']['host']["publicport"],
user=self.testdata['configurableData']['host']["username"],
passwd=self.testdata['configurableData']['host']["password"])
totalxenhosts = len(sshClient1.execute("xe host-list | grep uuid"))
for hostlist in lhosts:
countx = countx + 1
if totalxenhosts <= countx:
raise unittest.SkipTest(
"No additional Host is available in the XS pool to add host")
huuids.append(sshClient1.execute("xe host-list --minimal"))
self.debug("host uuids are:%s" % huuids)
hostuuids = huuids[0][0].split(',')
addhost = "FAIL"
for hid in hostuuids:
self.debug("host id: %s" % (hid))
haddress = sshClient1.execute(
"xe host-param-get param-name=address --minimal uuid=" +
hid)
self.debug("host address is %s" % (haddress[0]))
if haddress[0] == self.testdata["vgpu"]["nongpu_host_ip"]:
addhost = "PASS"
break
if addhost != "PASS":
raise unittest.SkipTest(
"XS Pool new host ip is not matching with test data host ip. Skipping the test.Please update test data file with hostip added to XS pool")
list_cluster_response = list_clusters(
self.apiclient,
hypervisor="XenServer",
allocationstate="Enabled"
)
self.assertEqual(
isinstance(list_cluster_response, list),
True,
"Check list clusters response returns a valid list"
)
self.assertNotEqual(
len(list_cluster_response),
0,
"Check list clusters response"
)
cluster_response = list_cluster_response[0]
self.assertEqual(
cluster_response.allocationstate,
'Enabled',
"Check whether allocation state of cluster is enabled"
)
self.debug("Cluster response is:%s" % (cluster_response))
self.assertEqual(
cluster_response.hypervisortype,
"XenServer",
"Check hypervisor type is XenServer or not"
)
nongpuhost = Host.create(
self.apiclient,
cluster_response,
self.testdata["vgpu"]["hosts"]["nonvgpuxenserver"],
zoneid=self.zone.id,
podid=self.pod.id,
hypervisor="XenServer"
)
if nongpuhost == FAILED:
self.fail("Host Creation Failed")
self.debug(
"Created host (ID: %s) in cluster ID %s" % (
nongpuhost.id,
cluster_response.id
))
listhosts = list_hosts(
self.apiclient,
hypervisor="XenServer",
id=nongpuhost.id
)
self.assertEqual(
isinstance(listhosts, list),
True,
"Check list hosts response returns a valid list"
)
self.assertNotEqual(
len(listhosts),
0,
"Check Host details are available in List Hosts"
)
for ggroup in listhosts:
if ggroup.gpugroup is not None:
self.fail("This is not a non vGPU host")
# Cleanup Host
self.cleanup.append(nongpuhost)
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_12_validate_deployed_vGPU_windows_vm(self):
""" Test deploy virtual machine
"""
self.deploy_vm_lifecycle()
self.debug("Check if deployed VMs are in running state?")
if self.__class__.vm_k1_card is not None:
self.verify_vm(self.__class__.vm_k1_card)
if self.__class__.vm_k2_card is not None:
self.verify_vm(self.__class__.vm_k2_card)
if self.__class__.vm2_k2_card is not None:
self.verify_vm(self.__class__.vm2_k2_card)
self.__class__.vmlifecycletest = 1
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_13_stop_vGPU_windows_vm(self):
""" Test stop virtual machine
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vm_k1_card:
self.stopvm(self.__class__.vm_k1_card)
if self.__class__.vm_k2_card:
self.stopvm(self.__class__.vm_k2_card)
if self.__class__.vm2_k2_card:
self.stopvm(self.__class__.vm2_k2_card)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_14_start_vGPU_windows_vm(self):
""" Test start virtual machine
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vm_k1_card:
self.startvm(self.__class__.vm_k1_card)
if self.__class__.vm_k2_card:
self.startvm(self.__class__.vm_k2_card)
if self.__class__.vm2_k2_card:
self.startvm(self.__class__.vm2_k2_card)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_15_restore_vGPU_windows_vm(self):
"""Test restore Virtual Machine
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vm_k1_card:
self.restorevm(self.__class__.vm_k1_card)
if self.__class__.vm_k2_card:
self.restorevm(self.__class__.vm_k2_card)
if self.__class__.vm2_k2_card:
self.restorevm(self.__class__.vm2_k2_card)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_16_reboot_vGPU_windows_vm(self):
""" Test reboot virtual machine
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vm_k1_card:
self.rebootvm(self.__class__.vm_k1_card)
if self.__class__.vm_k2_card:
self.rebootvm(self.__class__.vm_k2_card)
if self.__class__.vm2_k2_card:
self.rebootvm(self.__class__.vm2_k2_card)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_17_create_k1_vm_snapshot_wo_memory(self):
"""Test to create VM snapshots
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if not (self.__class__.vm_k1_card):
raise unittest.SkipTest(" No VM available.Hence skipping")
self.create_vm_snapshot(self.__class__.vm_k1_card)
# self.create_vm_snapshot(self.__class__.vm_k2_card)
# self.create_vm_snapshot(self.__class__.vm_k2_card)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_18_revert_k1_vm_snapshot_wo_memory(self):
"""Test to revert VM snapshots
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vmsnapwomemory == 0:
raise unittest.SkipTest(
"VM Snapshot creation test failed hence skipping")
if not self.__class__.vm_k1_card:
raise unittest.SkipTest("No VM available.Hence skipping")
self.revert_vm_snapshot(self.__class__.vm_k1_card)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_19_delete_k1_vm_snapshot_wo_memory(self):
"""Test to delete vm snapshots
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vmsnapwomemory == 0:
raise unittest.SkipTest(
"VM Snapshot creation test failed hence skipping")
if not (self.__class__.vm_k1_card):
raise unittest.SkipTest("No VM available.Hence skipping")
self.delete_vm_snapshot(self.__class__.vm_k1_card)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_20_create_k2_vm_snapshot_with_memory(self):
"""Test to create VM snapshots
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if not (self.__class__.vm_k2_card):
raise unittest.SkipTest("No VM available.Hence skipping")
self.create_vm_snapshot_with_memory(self.__class__.vm_k2_card)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_21_revert_k2_vm_snapshot_with_memory(self):
"""Test to revert VM snapshots
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vmsnapwithmemory == 0:
raise unittest.SkipTest(
"VM Snapshot creation with memory test failed hence skipping")
if not (self.__class__.vm_k2_card):
raise unittest.SkipTest("No VM available.Hence skipping")
self.revert_vm_snapshot_with_memory(self.__class__.vm_k2_card)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_22_delete_k2_vm_snapshot_with_memory(self):
"""Test to delete vm snapshots
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vmsnapwithmemory == 0:
raise unittest.SkipTest(
"VM Snapshot creation with memory test failed hence skipping")
if not(self.__class__.vm_k2_card):
raise unittest.SkipTest("No VM available.Hence skipping")
self.delete_vm_snapshot(self.__class__.vm_k2_card)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_23_vm_snapshot_without_memory_from_k1_vgpu_nonvgpu_vgpu(self):
"""Test to verify VM snapshot from vGPU to non vgpu to vGPU snap
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
k1qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
self.__class__.vm_k1_card.vgpu)
if (k1qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K1 vGPU Drivers installed. Skipping ")
if not(self.__class__.vm_k1_card):
raise unittest.SkipTest("No VM available.Hence skipping")
self.vm_snapshot_vgpu(
self.__class__.vm_k1_card,
self.__class__.vm_k1_card.vgpu,
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"nonvgpuoffering",
"None")
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_24_vm_snapshot_without_memory_from_nonvgpu_k1vgpu_nonvgpu(self):
"""Test to verify VM snapshot from non vGPU snap to vGPU snap to non vGPU snap
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
k1qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
self.__class__.vm_k1_card.vgpu)
if (k1qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with vGPU Drivers installed. Skipping ")
if not(self.__class__.vm_k1_card):
raise unittest.SkipTest("No VM available.Hence skipping")
self.vm_snapshot_vgpu(
self.__class__.nonvgpu,
"nonvgpuoffering",
"None",
self.__class__.vm_k1_card.vgpu,
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_25_vm_snapshot_without_memory_from_k2vgpu_k1vgpu_k2vgpu(self):
"""Test to verify VM snapshot from K2 vGPU snap to K1 vGPU snap to K2 vGPU snap
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
k1qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
self.__class__.vm_k1_card.vgpu)
if (k1qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with vGPU Drivers installed. Skipping ")
if not(self.__class__.vm_k2_card):
raise unittest.SkipTest("No VM available.Hence skipping")
self.vm_snapshot_vgpu(
self.__class__.vm_k2_card,
self.__class__.vm_k2_card.vgpu,
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
self.__class__.vm_k1_card.vgpu,
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_26_destroy_vGPU_windows_vm(self):
"""Test destroy Virtual Machine
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vm_k2_card:
self.deletevm(self.__class__.vm_k2_card)
if self.__class__.vm_k1_card:
self.deletevm(self.__class__.vm_k1_card)
if self.__class__.vm2_k2_card:
self.deletevm(self.__class__.vm2_k2_card)
if self.__class__.nonvgpu:
self.deletevm(self.__class__.nonvgpu)
self.cleanup.append(self.__class__.nonvgpu_service_offerin)
self.cleanup.append(self.__class__.k100_vgpu_service_offering)
self.cleanup.append(self.__class__.k200_vgpu_service_offering)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_27_recover_vGPU_windows_vm(self):
"""Test recover Virtual Machine
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vm_k2_card is not None:
self.recovervm(self.__class__.vm_k2_card)
if self.__class__.vm_k1_card is not None:
self.recovervm(self.__class__.vm_k1_card)
if self.__class__.vm2_k2_card is not None:
self.recovervm(self.__class__.vm2_k2_card)
return
def test_28_destroy_vGPU_windows_vm_after_recover(self):
"""Test destroy Virtual Machine
"""
if self.__class__.vmlifecycletest == 0:
raise unittest.SkipTest(
"VM Life Cycle Deploy VM test failed hence skipping")
if self.__class__.vm_k1_card:
if self.check_vm_state(self.__class__.vm_k1_card.id) == "Expunge":
raise unittest.SkipTest("VM is already deleted hence skipping")
self.deletevm(self.__class__.vm_k1_card)
if self.__class__.vm_k2_card:
if self.check_vm_state(self.__class__.vm_k2_card.id) == "Expunge":
raise unittest.SkipTest("VM is already deleted hence skipping")
self.deletevm(self.__class__.vm_k2_card)
if self.__class__.vm2_k2_card:
if self.check_vm_state(self.__class__.vm2_k2_card.id) == "Expunge":
raise unittest.SkipTest("VM is already deleted hence skipping")
self.deletevm(self.__class__.vm2_k2_card)
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_29_nonvgpuvm_k2vgpuvm_offline(self):
"""Test to change service from non vgpu to vgpu K200"""
k200capacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K200")
if (self.k200gpuhosts == 0) or (k200capacity == 0):
raise unittest.SkipTest(
"No XenServer available with K200 vGPU Drivers installed. Skipping non gpu to K200 Offering Upgrade")
self.serviceoffering_upgrade(
"nonvgpuoffering",
"None",
"GRID K200",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs")
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_30_K2_vgpuvm_vgpuvm_offline(self):
"""Test to change service from vgpu K200 to vgpu K240Q"""
k240qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K240Q")
k200capacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K200")
if (self.k240qgpuhosts == 0) or (self.k200gpuhosts == 0) or (
k240qcapacity == 0) or (k200capacity == 0):
raise unittest.SkipTest(
"No XenServer available with K240Q,K200Q vGPU Drivers installed. Skipping K200 to K240Q Offering Upgrade")
self.serviceoffering_upgrade(
"GRID K200",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K240Q",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs")
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_31_K1_vgpuvm_vgpuvm_offline(self):
"""Test to change service from K1 vgpu K120Q to K1 vgpu K140Q"""
k140qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K140Q")
k120qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K120Q")
if (self.k140qgpuhosts == 0) or (self.k120qgpuhosts == 0) or (
k140qcapacity == 0) or (k120qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K140Q,K120Q vGPU Drivers installed. Skipping K200 to K240Q Offering Upgrade")
self.serviceoffering_upgrade(
"GRID K120Q",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K140Q",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_32_nonvgpuvm_k1vgpuvm_offline(self):
"""Test to change service from non vgpu to vgpu K100"""
k100capacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K100")
if (self.k100gpuhosts == 0) or (k100capacity == 0):
raise unittest.SkipTest(
"No XenServer available with K100 vGPU Drivers installed. Skipping non gpu to K100 Offering Upgrade")
self.serviceoffering_upgrade(
"nonvgpuoffering",
"None",
"GRID K100",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_33_K2_vgpuvm_nonvgpuvm_offline(self):
"""Test to change service from non vgpu to vgpu K240Q"""
k240qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K240Q")
if (self.k240qgpuhosts == 0) or (k240qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K240Q vGPU Drivers installed. Skipping K2 vgpu 240Q to nonvgpu Offering Upgrade")
self.serviceoffering_upgrade(
"GRID K240Q",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"nonvgpuoffering",
"None")
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_34_K1_vgpuvm_nonvgpuvm_offline(self):
"""Test to change service from non vgpu to vgpu K140Q"""
k140qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K140Q")
if (self.k140qgpuhosts == 0) or (k140qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K140Q vGPU Drivers installed. Skipping K1 vgpu 140Q to nonvgpu Offering Upgrade")
self.serviceoffering_upgrade(
"GRID K140Q",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"nonvgpuoffering",
"None")
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_35_K140Q_vgpuvm_K240Q_vgpuvm_offline(self):
"""Test to change service from K1 vgpu K140Q to K2 vgpu K240Q"""
k140qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K140Q")
k240qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K240Q")
if (self.k140qgpuhosts == 0) or (self.k240qgpuhosts == 0) or (
k140qcapacity == 0) or (k240qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K140Q,K240Q vGPU Drivers installed. Skipping K140Q to K240Q Offering Upgrade")
self.serviceoffering_upgrade(
"GRID K140Q",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K240Q",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs")
return
@attr(tags=['advanced', 'basic', 'vgpu'], required_hardware="true")
def test_36_K240Q_vgpuvm_K140Q_vgpuvm_offline(self):
"""Test to change service from K2 vgpu K240Q to K1 vgpu K140Q"""
k140qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs",
"GRID K140Q")
k240qcapacity = self.check_host_vgpu_capacity(
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K240Q")
if (self.k140qgpuhosts == 0) or (self.k240qgpuhosts == 0) or (
k140qcapacity == 0) or (k240qcapacity == 0):
raise unittest.SkipTest(
"No XenServer available with K140Q,K240Q vGPU Drivers installed. Skipping K140Q to K240Q Offering Upgrade")
self.serviceoffering_upgrade(
"GRID K240Q",
"Group of NVIDIA Corporation GK104GL [GRID K2] GPUs",
"GRID K140Q",
"Group of NVIDIA Corporation GK107GL [GRID K1] GPUs")
return
@classmethod
def tearDownClass(self):
try:
self.apiclient = super(
TestvGPUWindowsVm,
self).getClsTestClient().getApiClient()
cleanup_resources(self.apiclient, self._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
self.debug("Warning! Exception in tearDown: %s" % e)
| [
"marvin.lib.base.Host.create",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.common.get_pod",
"marvin.lib.base.Template.register",
"marvin.cloudstackAPI.startVirtualMachine.startVirtualMachineCmd",
"marvin.lib.common.list_virtual_machines",
"marvin.lib.base.VmSnapshot.list",
"marvin.lib.base.VmSn... | [((9887, 9953), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (9891, 9953), False, 'from nose.plugins.attrib import attr\n'), ((10758, 10824), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (10762, 10824), False, 'from nose.plugins.attrib import attr\n'), ((13441, 13507), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (13445, 13507), False, 'from nose.plugins.attrib import attr\n'), ((16147, 16213), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (16151, 16213), False, 'from nose.plugins.attrib import attr\n'), ((17900, 17966), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (17904, 17966), False, 'from nose.plugins.attrib import attr\n'), ((18446, 18512), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (18450, 18512), False, 'from nose.plugins.attrib import attr\n'), ((19571, 19637), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (19575, 19637), False, 'from nose.plugins.attrib import attr\n'), ((20375, 20441), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (20379, 20441), False, 'from nose.plugins.attrib import attr\n'), ((20680, 20746), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (20684, 20746), False, 'from nose.plugins.attrib import attr\n'), ((21686, 21752), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (21690, 21752), False, 'from nose.plugins.attrib import attr\n'), ((23354, 23420), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (23358, 23420), False, 'from nose.plugins.attrib import attr\n'), ((25034, 25100), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (25038, 25100), False, 'from nose.plugins.attrib import attr\n'), ((48255, 48327), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (48259, 48327), False, 'from nose.plugins.attrib import attr\n'), ((53009, 53075), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (53013, 53075), False, 'from nose.plugins.attrib import attr\n'), ((53672, 53738), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (53676, 53738), False, 'from nose.plugins.attrib import attr\n'), ((54356, 54422), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (54360, 54422), False, 'from nose.plugins.attrib import attr\n'), ((55040, 55106), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (55044, 55106), False, 'from nose.plugins.attrib import attr\n'), ((55750, 55816), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (55754, 55816), False, 'from nose.plugins.attrib import attr\n'), ((56459, 56525), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (56463, 56525), False, 'from nose.plugins.attrib import attr\n'), ((57143, 57209), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (57147, 57209), False, 'from nose.plugins.attrib import attr\n'), ((57831, 57897), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (57835, 57897), False, 'from nose.plugins.attrib import attr\n'), ((58518, 58584), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (58522, 58584), False, 'from nose.plugins.attrib import attr\n'), ((59186, 59252), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (59190, 59252), False, 'from nose.plugins.attrib import attr\n'), ((63006, 63072), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (63010, 63072), False, 'from nose.plugins.attrib import attr\n'), ((63667, 63733), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (63671, 63733), False, 'from nose.plugins.attrib import attr\n'), ((64277, 64343), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (64281, 64343), False, 'from nose.plugins.attrib import attr\n'), ((64892, 64958), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (64896, 64958), False, 'from nose.plugins.attrib import attr\n'), ((65515, 65581), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (65519, 65581), False, 'from nose.plugins.attrib import attr\n'), ((66134, 66206), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (66138, 66206), False, 'from nose.plugins.attrib import attr\n'), ((66787, 66859), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (66791, 66859), False, 'from nose.plugins.attrib import attr\n'), ((67469, 67541), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (67473, 67541), False, 'from nose.plugins.attrib import attr\n'), ((68153, 68225), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (68157, 68225), False, 'from nose.plugins.attrib import attr\n'), ((68699, 68771), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (68703, 68771), False, 'from nose.plugins.attrib import attr\n'), ((69411, 69483), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (69415, 69483), False, 'from nose.plugins.attrib import attr\n'), ((70110, 70182), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (70114, 70182), False, 'from nose.plugins.attrib import attr\n'), ((71185, 71257), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (71189, 71257), False, 'from nose.plugins.attrib import attr\n'), ((72270, 72342), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (72274, 72342), False, 'from nose.plugins.attrib import attr\n'), ((73416, 73482), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (73420, 73482), False, 'from nose.plugins.attrib import attr\n'), ((74335, 74401), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (74339, 74401), False, 'from nose.plugins.attrib import attr\n'), ((76038, 76104), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (76042, 76104), False, 'from nose.plugins.attrib import attr\n'), ((76782, 76848), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (76786, 76848), False, 'from nose.plugins.attrib import attr\n'), ((77789, 77855), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (77793, 77855), False, 'from nose.plugins.attrib import attr\n'), ((78810, 78876), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (78814, 78876), False, 'from nose.plugins.attrib import attr\n'), ((79554, 79620), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (79558, 79620), False, 'from nose.plugins.attrib import attr\n'), ((80315, 80381), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (80319, 80381), False, 'from nose.plugins.attrib import attr\n'), ((81077, 81143), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (81081, 81143), False, 'from nose.plugins.attrib import attr\n'), ((82107, 82173), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'vgpu']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'vgpu'], required_hardware='true')\n", (82111, 82173), False, 'from nose.plugins.attrib import attr\n'), ((2142, 2191), 'marvin.lib.common.list_hosts', 'list_hosts', (['cls.apiclient'], {'hypervisor': '"""XenServer"""'}), "(cls.apiclient, hypervisor='XenServer')\n", (2152, 2191), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((7555, 7580), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (7565, 7580), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((7599, 7634), 'marvin.lib.common.get_pod', 'get_pod', (['cls.apiclient', 'cls.zone.id'], {}), '(cls.apiclient, cls.zone.id)\n', (7606, 7634), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((7657, 7735), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.testdata['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.testdata['account'], domainid=cls.domain.id)\n", (7671, 7735), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((7806, 7893), 'marvin.lib.common.get_windows_template', 'get_windows_template', (['cls.apiclient', 'cls.zone.id'], {'ostype_desc': '"""Windows 8 (64-bit)"""'}), "(cls.apiclient, cls.zone.id, ostype_desc=\n 'Windows 8 (64-bit)')\n", (7826, 7893), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((10215, 10265), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'hypervisor': '"""XenServer"""'}), "(self.apiclient, hypervisor='XenServer')\n", (10225, 10265), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((13809, 13846), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'hostid'}), '(self.apiclient, id=hostid)\n', (13819, 13846), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((13902, 14139), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'vgpu_host[0].ipaddress', 'port': "self.testdata['configurableData']['host']['publicport']", 'user': "self.testdata['configurableData']['host']['username']", 'passwd': "self.testdata['configurableData']['host']['password']"}), "(host=vgpu_host[0].ipaddress, port=self.testdata[\n 'configurableData']['host']['publicport'], user=self.testdata[\n 'configurableData']['host']['username'], passwd=self.testdata[\n 'configurableData']['host']['password'])\n", (13911, 14139), False, 'from marvin.sshClient import SshClient\n'), ((15133, 15191), 'marvin.lib.base.ServiceOffering.list', 'ServiceOffering.list', (['self.apiclient'], {'id': 'serviceofferingid'}), '(self.apiclient, id=serviceofferingid)\n', (15153, 15191), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((16373, 16598), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'vgpuofferingid', 'templateid': 'self.template.id'}), "(self.apiclient, self.testdata['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=vgpuofferingid, templateid=self.template.id)\n", (16394, 16598), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((16692, 16734), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (16702, 16734), False, 'import time\n'), ((16754, 16817), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (16773, 16817), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((18169, 18229), 'marvin.lib.common.list_service_offering', 'list_service_offering', (['self.apiclient'], {'id': 'serviceoffering.id'}), '(self.apiclient, id=serviceoffering.id)\n', (18190, 18229), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((18600, 18646), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'id': 'vmid'}), '(self.apiclient, id=vmid)\n', (18621, 18646), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((19792, 19855), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (19811, 19855), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((20965, 21028), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (20984, 21028), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((22103, 22145), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (22113, 22145), False, 'import time\n'), ((22577, 22643), 'marvin.cloudstackAPI.changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd', 'changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd', ([], {}), '()\n', (22641, 22643), False, 'from marvin.cloudstackAPI import changeServiceForVirtualMachine, startVirtualMachine\n'), ((22867, 22909), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (22877, 22909), False, 'import time\n'), ((23783, 23825), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (23793, 23825), False, 'import time\n'), ((24257, 24323), 'marvin.cloudstackAPI.changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd', 'changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd', ([], {}), '()\n', (24321, 24323), False, 'from marvin.cloudstackAPI import changeServiceForVirtualMachine, startVirtualMachine\n'), ((24547, 24589), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (24557, 24589), False, 'import time\n'), ((25865, 25940), 'marvin.lib.common.get_windows_template', 'get_windows_template', (['self.apiclient', 'self.zone.id'], {'ostype_desc': 'guestostype'}), '(self.apiclient, self.zone.id, ostype_desc=guestostype)\n', (25885, 25940), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((29844, 29950), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.testdata['vgpu']['service_offerings']['nonvgpuoffering']"], {}), "(self.apiclient, self.testdata['vgpu'][\n 'service_offerings']['nonvgpuoffering'])\n", (29866, 29950), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((31432, 31687), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.__class__.nonvgpu_service_offering.id', 'templateid': 'win7templateid'}), "(self.apiclient, self.testdata['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.__class__.nonvgpu_service_offering.id,\n templateid=win7templateid)\n", (31453, 31687), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((31935, 31999), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'hypervisor': '"""XenServer"""', 'id': 'gpuhostid'}), "(self.apiclient, hypervisor='XenServer', id=gpuhostid)\n", (31945, 31999), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((33234, 33280), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'id': 'vmid'}), '(self.apiclient, id=vmid)\n', (33255, 33280), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((33514, 33578), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'hypervisor': '"""XenServer"""', 'id': 'gpuhostid'}), "(self.apiclient, hypervisor='XenServer', id=gpuhostid)\n", (33524, 33578), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((36540, 36586), 'time.sleep', 'time.sleep', (["(self.testdata['vgpu']['sleep'] * 3)"], {}), "(self.testdata['vgpu']['sleep'] * 3)\n", (36550, 36586), False, 'import time\n'), ((37025, 37071), 'time.sleep', 'time.sleep', (["(self.testdata['vgpu']['sleep'] * 3)"], {}), "(self.testdata['vgpu']['sleep'] * 3)\n", (37035, 37071), False, 'import time\n'), ((37745, 37834), 'marvin.lib.base.VmSnapshot.create', 'VmSnapshot.create', (['self.apiclient', 'vmcard.id', '"""false"""', '"""TestSnapshot"""', '"""Display Text"""'], {}), "(self.apiclient, vmcard.id, 'false', 'TestSnapshot',\n 'Display Text')\n", (37762, 37834), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((37935, 38008), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'vmcard.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=vmcard.id, listall=True)\n', (37950, 38008), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((38531, 38575), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'vmcard.hostid'}), '(self.apiclient, id=vmcard.hostid)\n', (38541, 38575), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((38631, 38868), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'vgpu_host[0].ipaddress', 'port': "self.testdata['configurableData']['host']['publicport']", 'user': "self.testdata['configurableData']['host']['username']", 'passwd': "self.testdata['configurableData']['host']['password']"}), "(host=vgpu_host[0].ipaddress, port=self.testdata[\n 'configurableData']['host']['publicport'], user=self.testdata[\n 'configurableData']['host']['username'], passwd=self.testdata[\n 'configurableData']['host']['password'])\n", (38640, 38868), False, 'from marvin.sshClient import SshClient\n'), ((40105, 40178), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'vmcard.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=vmcard.id, listall=True)\n', (40120, 40178), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((40689, 40762), 'marvin.lib.base.VmSnapshot.revertToSnapshot', 'VmSnapshot.revertToSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (40716, 40762), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((40796, 40838), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (40806, 40838), False, 'import time\n'), ((40866, 40917), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'id': 'vmcard.id'}), '(self.apiclient, id=vmcard.id)\n', (40887, 40917), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((41145, 41189), 'marvin.cloudstackAPI.startVirtualMachine.startVirtualMachineCmd', 'startVirtualMachine.startVirtualMachineCmd', ([], {}), '()\n', (41187, 41189), False, 'from marvin.cloudstackAPI import changeServiceForVirtualMachine, startVirtualMachine\n'), ((41269, 41311), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (41279, 41311), False, 'import time\n'), ((41340, 41387), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'id': 'vm.id'}), '(self.apiclient, id=vm.id)\n', (41361, 41387), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((41970, 42043), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'vmcard.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=vmcard.id, listall=True)\n', (41985, 42043), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((42462, 42535), 'marvin.lib.base.VmSnapshot.deleteVMSnapshot', 'VmSnapshot.deleteVMSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (42489, 42535), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((42570, 42612), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (42580, 42612), False, 'import time\n'), ((42647, 42720), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'vmcard.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=vmcard.id, listall=True)\n', (42662, 42720), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((43037, 43081), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'vmcard.hostid'}), '(self.apiclient, id=vmcard.hostid)\n', (43047, 43081), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((43137, 43374), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'vgpu_host[0].ipaddress', 'port': "self.testdata['configurableData']['host']['publicport']", 'user': "self.testdata['configurableData']['host']['username']", 'passwd': "self.testdata['configurableData']['host']['password']"}), "(host=vgpu_host[0].ipaddress, port=self.testdata[\n 'configurableData']['host']['publicport'], user=self.testdata[\n 'configurableData']['host']['username'], passwd=self.testdata[\n 'configurableData']['host']['password'])\n", (43146, 43374), False, 'from marvin.sshClient import SshClient\n'), ((44566, 44664), 'marvin.lib.base.VmSnapshot.create', 'VmSnapshot.create', (['self.apiclient', 'vmcard.id', '"""true"""', '"""TestSnapshotwithmemory"""', '"""Display Text"""'], {}), "(self.apiclient, vmcard.id, 'true',\n 'TestSnapshotwithmemory', 'Display Text')\n", (44583, 44664), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((44740, 44786), 'time.sleep', 'time.sleep', (["(self.testdata['vgpu']['sleep'] * 3)"], {}), "(self.testdata['vgpu']['sleep'] * 3)\n", (44750, 44786), False, 'import time\n'), ((44821, 44894), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'vmcard.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=vmcard.id, listall=True)\n', (44836, 44894), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((45417, 45461), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'vmcard.hostid'}), '(self.apiclient, id=vmcard.hostid)\n', (45427, 45461), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((45517, 45754), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'vgpu_host[0].ipaddress', 'port': "self.testdata['configurableData']['host']['publicport']", 'user': "self.testdata['configurableData']['host']['username']", 'passwd': "self.testdata['configurableData']['host']['password']"}), "(host=vgpu_host[0].ipaddress, port=self.testdata[\n 'configurableData']['host']['publicport'], user=self.testdata[\n 'configurableData']['host']['username'], passwd=self.testdata[\n 'configurableData']['host']['password'])\n", (45526, 45754), False, 'from marvin.sshClient import SshClient\n'), ((46881, 46954), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'vmcard.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=vmcard.id, listall=True)\n', (46896, 46954), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((47465, 47538), 'marvin.lib.base.VmSnapshot.revertToSnapshot', 'VmSnapshot.revertToSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (47492, 47538), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((47592, 47643), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'id': 'vmcard.id'}), '(self.apiclient, id=vmcard.id)\n', (47613, 47643), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((48736, 48802), 'marvin.cloudstackAPI.changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd', 'changeServiceForVirtualMachine.changeServiceForVirtualMachineCmd', ([], {}), '()\n', (48800, 48802), False, 'from marvin.cloudstackAPI import changeServiceForVirtualMachine, startVirtualMachine\n'), ((49051, 49093), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (49061, 49093), False, 'import time\n'), ((49594, 49644), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'hypervisor': '"""XenServer"""'}), "(self.apiclient, hypervisor='XenServer')\n", (49604, 49644), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((59455, 59505), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'hypervisor': '"""XenServer"""'}), "(self.apiclient, hypervisor='XenServer')\n", (59465, 59505), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((59562, 59791), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'lhosts[0].ipaddress', 'port': "self.testdata['configurableData']['host']['publicport']", 'user': "self.testdata['configurableData']['host']['username']", 'passwd': "self.testdata['configurableData']['host']['password']"}), "(host=lhosts[0].ipaddress, port=self.testdata['configurableData'][\n 'host']['publicport'], user=self.testdata['configurableData']['host'][\n 'username'], passwd=self.testdata['configurableData']['host']['password'])\n", (59571, 59791), False, 'from marvin.sshClient import SshClient\n'), ((60967, 61052), 'marvin.lib.common.list_clusters', 'list_clusters', (['self.apiclient'], {'hypervisor': '"""XenServer"""', 'allocationstate': '"""Enabled"""'}), "(self.apiclient, hypervisor='XenServer', allocationstate='Enabled'\n )\n", (60980, 61052), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((61877, 62047), 'marvin.lib.base.Host.create', 'Host.create', (['self.apiclient', 'cluster_response', "self.testdata['vgpu']['hosts']['nonvgpuxenserver']"], {'zoneid': 'self.zone.id', 'podid': 'self.pod.id', 'hypervisor': '"""XenServer"""'}), "(self.apiclient, cluster_response, self.testdata['vgpu']['hosts'\n ]['nonvgpuxenserver'], zoneid=self.zone.id, podid=self.pod.id,\n hypervisor='XenServer')\n", (61888, 62047), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((62379, 62447), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'hypervisor': '"""XenServer"""', 'id': 'nongpuhost.id'}), "(self.apiclient, hypervisor='XenServer', id=nongpuhost.id)\n", (62389, 62447), False, 'from marvin.lib.common import get_zone, get_domain, list_hosts, list_service_offering, get_windows_template, get_pod, list_clusters, list_virtual_machines\n'), ((2270, 2403), 'unittest.SkipTest', 'unittest.SkipTest', (['"""There are no XenServers available. GPU feature is supported only on XenServer.Check listhosts response"""'], {}), "(\n 'There are no XenServers available. GPU feature is supported only on XenServer.Check listhosts response'\n )\n", (2287, 2403), False, 'import unittest\n'), ((7368, 7438), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with GPU Drivers installed"""'], {}), "('No XenServer available with GPU Drivers installed')\n", (7385, 7438), False, 'import unittest\n'), ((8348, 8533), 'marvin.lib.base.Template.register', 'Template.register', (['cls.apiclient', "cls.testdata['vgpu']['templateregister1']"], {'hypervisor': '"""XenServer"""', 'zoneid': 'cls.zone.id', 'domainid': 'cls.account.domainid', 'account': 'cls.account.name'}), "(cls.apiclient, cls.testdata['vgpu']['templateregister1'],\n hypervisor='XenServer', zoneid=cls.zone.id, domainid=cls.account.\n domainid, account=cls.account.name)\n", (8365, 8533), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((10991, 11085), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.testdata['vgpu']['service_offerings'][gtype]"], {}), "(self.apiclient, self.testdata['vgpu'][\n 'service_offerings'][gtype])\n", (11013, 11085), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((11278, 11343), 'marvin.lib.base.ServiceOffering.list', 'ServiceOffering.list', (['self.apiclient'], {'id': 'self.service_offering.id'}), '(self.apiclient, id=self.service_offering.id)\n', (11298, 11343), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((12248, 12342), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.testdata['vgpu']['service_offerings'][gtype]"], {}), "(self.apiclient, self.testdata['vgpu'][\n 'service_offerings'][gtype])\n", (12270, 12342), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((12420, 12485), 'marvin.lib.base.ServiceOffering.list', 'ServiceOffering.list', (['self.apiclient'], {'id': 'self.service_offering.id'}), '(self.apiclient, id=self.service_offering.id)\n', (12440, 12485), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((25338, 25380), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (25348, 25380), False, 'import time\n'), ((26270, 26452), 'marvin.lib.base.Template.register', 'Template.register', (['self.apiclient', "self.testdata['vgpu'][guestostype]"], {'hypervisor': '"""XenServer"""', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'account': 'self.account.name'}), "(self.apiclient, self.testdata['vgpu'][guestostype],\n hypervisor='XenServer', zoneid=self.zone.id, domainid=self.account.\n domainid, account=self.account.name)\n", (26287, 26452), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((30168, 30415), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.k100_vgpu_service_offering.id', 'templateid': 'win8templateid'}), "(self.apiclient, self.testdata['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.k100_vgpu_service_offering.id,\n templateid=win8templateid)\n", (30189, 30415), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((30601, 30851), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.k200_vgpu_service_offering.id', 'templateid': 'win2012templateid'}), "(self.apiclient, self.testdata['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.k200_vgpu_service_offering.id,\n templateid=win2012templateid)\n", (30622, 30851), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((31037, 31284), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.k200_vgpu_service_offering.id', 'templateid': 'win7templateid'}), "(self.apiclient, self.testdata['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.k200_vgpu_service_offering.id,\n templateid=win7templateid)\n", (31058, 31284), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((34232, 34278), 'time.sleep', 'time.sleep', (["(self.testdata['vgpu']['sleep'] * 3)"], {}), "(self.testdata['vgpu']['sleep'] * 3)\n", (34242, 34278), False, 'import time\n'), ((34611, 34653), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (34621, 34653), False, 'import time\n'), ((34880, 34922), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (34890, 34922), False, 'import time\n'), ((35152, 35194), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (35162, 35194), False, 'import time\n'), ((35330, 35372), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (35340, 35372), False, 'import time\n'), ((35510, 35552), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (35520, 35552), False, 'import time\n'), ((35986, 36043), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM is already deleted hence skipping"""'], {}), "('VM is already deleted hence skipping')\n", (36003, 36043), False, 'import unittest\n'), ((53456, 53532), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K100 vGPU Drivers installed"""'], {}), "('No XenServer available with K100 vGPU Drivers installed')\n", (53473, 53532), False, 'import unittest\n'), ((54138, 54215), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K120Q vGPU Drivers installed"""'], {}), "('No XenServer available with K120Q vGPU Drivers installed')\n", (54155, 54215), False, 'import unittest\n'), ((54822, 54899), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K140Q vGPU Drivers installed"""'], {}), "('No XenServer available with K140Q vGPU Drivers installed')\n", (54839, 54899), False, 'import unittest\n'), ((55535, 55608), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K1 passthrough installed"""'], {}), "('No XenServer available with K1 passthrough installed')\n", (55552, 55608), False, 'import unittest\n'), ((56244, 56317), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K2 passthrough installed"""'], {}), "('No XenServer available with K2 passthrough installed')\n", (56261, 56317), False, 'import unittest\n'), ((56925, 57002), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K260Q vGPU Drivers installed"""'], {}), "('No XenServer available with K260Q vGPU Drivers installed')\n", (56942, 57002), False, 'import unittest\n'), ((57613, 57690), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K240Q vGPU Drivers installed"""'], {}), "('No XenServer available with K240Q vGPU Drivers installed')\n", (57630, 57690), False, 'import unittest\n'), ((58300, 58377), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K220Q vGPU Drivers installed"""'], {}), "('No XenServer available with K220Q vGPU Drivers installed')\n", (58317, 58377), False, 'import unittest\n'), ((58970, 59046), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K200 vGPU Drivers installed"""'], {}), "('No XenServer available with K200 vGPU Drivers installed')\n", (58987, 59046), False, 'import unittest\n'), ((60027, 60106), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No additional Host is available in the XS pool to add host"""'], {}), "('No additional Host is available in the XS pool to add host')\n", (60044, 60106), False, 'import unittest\n'), ((60761, 60927), 'unittest.SkipTest', 'unittest.SkipTest', (['"""XS Pool new host ip is not matching with test data host ip. Skipping the test.Please update test data file with hostip added to XS pool"""'], {}), "(\n 'XS Pool new host ip is not matching with test data host ip. Skipping the test.Please update test data file with hostip added to XS pool'\n )\n", (60778, 60927), False, 'import unittest\n'), ((63894, 63965), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (63911, 63965), False, 'import unittest\n'), ((64506, 64577), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (64523, 64577), False, 'import unittest\n'), ((65125, 65196), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (65142, 65196), False, 'import unittest\n'), ((65747, 65818), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (65764, 65818), False, 'import unittest\n'), ((66380, 66451), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (66397, 66451), False, 'import unittest\n'), ((66532, 66584), 'unittest.SkipTest', 'unittest.SkipTest', (['""" No VM available.Hence skipping"""'], {}), "(' No VM available.Hence skipping')\n", (66549, 66584), False, 'import unittest\n'), ((67033, 67104), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (67050, 67104), False, 'import unittest\n'), ((67188, 67256), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Snapshot creation test failed hence skipping"""'], {}), "('VM Snapshot creation test failed hence skipping')\n", (67205, 67256), False, 'import unittest\n'), ((67335, 67386), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No VM available.Hence skipping"""'], {}), "('No VM available.Hence skipping')\n", (67352, 67386), False, 'import unittest\n'), ((67715, 67786), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (67732, 67786), False, 'import unittest\n'), ((67870, 67938), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Snapshot creation test failed hence skipping"""'], {}), "('VM Snapshot creation test failed hence skipping')\n", (67887, 67938), False, 'import unittest\n'), ((68019, 68070), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No VM available.Hence skipping"""'], {}), "('No VM available.Hence skipping')\n", (68036, 68070), False, 'import unittest\n'), ((68401, 68472), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (68418, 68472), False, 'import unittest\n'), ((68553, 68604), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No VM available.Hence skipping"""'], {}), "('No VM available.Hence skipping')\n", (68570, 68604), False, 'import unittest\n'), ((68947, 69018), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (68964, 69018), False, 'import unittest\n'), ((69104, 69189), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Snapshot creation with memory test failed hence skipping"""'], {}), "('VM Snapshot creation with memory test failed hence skipping'\n )\n", (69121, 69189), False, 'import unittest\n'), ((69265, 69316), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No VM available.Hence skipping"""'], {}), "('No VM available.Hence skipping')\n", (69282, 69316), False, 'import unittest\n'), ((69659, 69730), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (69676, 69730), False, 'import unittest\n'), ((69816, 69901), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Snapshot creation with memory test failed hence skipping"""'], {}), "('VM Snapshot creation with memory test failed hence skipping'\n )\n", (69833, 69901), False, 'import unittest\n'), ((69976, 70027), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No VM available.Hence skipping"""'], {}), "('No VM available.Hence skipping')\n", (69993, 70027), False, 'import unittest\n'), ((70411, 70482), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (70428, 70482), False, 'import unittest\n'), ((70714, 70804), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K1 vGPU Drivers installed. Skipping """'], {}), "(\n 'No XenServer available with K1 vGPU Drivers installed. Skipping ')\n", (70731, 70804), False, 'import unittest\n'), ((70879, 70930), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No VM available.Hence skipping"""'], {}), "('No VM available.Hence skipping')\n", (70896, 70930), False, 'import unittest\n'), ((71502, 71573), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (71519, 71573), False, 'import unittest\n'), ((71805, 71892), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with vGPU Drivers installed. Skipping """'], {}), "(\n 'No XenServer available with vGPU Drivers installed. Skipping ')\n", (71822, 71892), False, 'import unittest\n'), ((71967, 72018), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No VM available.Hence skipping"""'], {}), "('No VM available.Hence skipping')\n", (71984, 72018), False, 'import unittest\n'), ((72586, 72657), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (72603, 72657), False, 'import unittest\n'), ((72889, 72976), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with vGPU Drivers installed. Skipping """'], {}), "(\n 'No XenServer available with vGPU Drivers installed. Skipping ')\n", (72906, 72976), False, 'import unittest\n'), ((73051, 73102), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No VM available.Hence skipping"""'], {}), "('No VM available.Hence skipping')\n", (73068, 73102), False, 'import unittest\n'), ((73649, 73720), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (73666, 73720), False, 'import unittest\n'), ((74568, 74639), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (74585, 74639), False, 'import unittest\n'), ((75171, 75242), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM Life Cycle Deploy VM test failed hence skipping"""'], {}), "('VM Life Cycle Deploy VM test failed hence skipping')\n", (75188, 75242), False, 'import unittest\n'), ((76442, 76571), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K200 vGPU Drivers installed. Skipping non gpu to K200 Offering Upgrade"""'], {}), "(\n 'No XenServer available with K200 vGPU Drivers installed. Skipping non gpu to K200 Offering Upgrade'\n )\n", (76459, 76571), False, 'import unittest\n'), ((77403, 77537), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K240Q,K200Q vGPU Drivers installed. Skipping K200 to K240Q Offering Upgrade"""'], {}), "(\n 'No XenServer available with K240Q,K200Q vGPU Drivers installed. Skipping K200 to K240Q Offering Upgrade'\n )\n", (77420, 77537), False, 'import unittest\n'), ((78423, 78557), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K140Q,K120Q vGPU Drivers installed. Skipping K200 to K240Q Offering Upgrade"""'], {}), "(\n 'No XenServer available with K140Q,K120Q vGPU Drivers installed. Skipping K200 to K240Q Offering Upgrade'\n )\n", (78440, 78557), False, 'import unittest\n'), ((79215, 79344), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K100 vGPU Drivers installed. Skipping non gpu to K100 Offering Upgrade"""'], {}), "(\n 'No XenServer available with K100 vGPU Drivers installed. Skipping non gpu to K100 Offering Upgrade'\n )\n", (79232, 79344), False, 'import unittest\n'), ((79965, 80103), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K240Q vGPU Drivers installed. Skipping K2 vgpu 240Q to nonvgpu Offering Upgrade"""'], {}), "(\n 'No XenServer available with K240Q vGPU Drivers installed. Skipping K2 vgpu 240Q to nonvgpu Offering Upgrade'\n )\n", (79982, 80103), False, 'import unittest\n'), ((80727, 80865), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K140Q vGPU Drivers installed. Skipping K1 vgpu 140Q to nonvgpu Offering Upgrade"""'], {}), "(\n 'No XenServer available with K140Q vGPU Drivers installed. Skipping K1 vgpu 140Q to nonvgpu Offering Upgrade'\n )\n", (80744, 80865), False, 'import unittest\n'), ((81720, 81855), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K140Q,K240Q vGPU Drivers installed. Skipping K140Q to K240Q Offering Upgrade"""'], {}), "(\n 'No XenServer available with K140Q,K240Q vGPU Drivers installed. Skipping K140Q to K240Q Offering Upgrade'\n )\n", (81737, 81855), False, 'import unittest\n'), ((82750, 82885), 'unittest.SkipTest', 'unittest.SkipTest', (['"""No XenServer available with K140Q,K240Q vGPU Drivers installed. Skipping K140Q to K240Q Offering Upgrade"""'], {}), "(\n 'No XenServer available with K140Q,K240Q vGPU Drivers installed. Skipping K140Q to K240Q Offering Upgrade'\n )\n", (82767, 82885), False, 'import unittest\n'), ((83330, 83378), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self._cleanup'], {}), '(self.apiclient, self._cleanup)\n', (83347, 83378), False, 'from marvin.lib.utils import cleanup_resources\n'), ((83549, 83596), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (83566, 83596), False, 'from marvin.lib.utils import cleanup_resources\n'), ((8225, 8299), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Check Test Data file if it has the valid template URL"""'], {}), "('Check Test Data file if it has the valid template URL')\n", (8242, 8299), False, 'import unittest\n'), ((8730, 8771), 'time.sleep', 'time.sleep', (["cls.testdata['vgpu']['sleep']"], {}), "(cls.testdata['vgpu']['sleep'])\n", (8740, 8771), False, 'import time\n'), ((8813, 8912), 'marvin.lib.base.Template.list', 'Template.list', (['cls.apiclient'], {'templatefilter': "cls.testdata['templatefilter']", 'id': 'cls.template.id'}), "(cls.apiclient, templatefilter=cls.testdata['templatefilter'],\n id=cls.template.id)\n", (8826, 8912), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((11459, 11544), 'unittest.SkipTest', 'unittest.SkipTest', (["('Check Service Offering list for %s service offering' % gtype)"], {}), "('Check Service Offering list for %s service offering' % gtype\n )\n", (11476, 11544), False, 'import unittest\n'), ((12601, 12686), 'unittest.SkipTest', 'unittest.SkipTest', (["('Check Service Offering list for %s service offering' % gtype)"], {}), "('Check Service Offering list for %s service offering' % gtype\n )\n", (12618, 12686), False, 'import unittest\n'), ((26150, 26224), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Check Test Data file if it has the valid template URL"""'], {}), "('Check Test Data file if it has the valid template URL')\n", (26167, 26224), False, 'import unittest\n'), ((26650, 26692), 'time.sleep', 'time.sleep', (["self.testdata['vgpu']['sleep']"], {}), "(self.testdata['vgpu']['sleep'])\n", (26660, 26692), False, 'import time\n'), ((26734, 26833), 'marvin.lib.base.Template.list', 'Template.list', (['self.apiclient'], {'templatefilter': "self.testdata['templatefilter']", 'id': 'template1.id'}), "(self.apiclient, templatefilter=self.testdata['templatefilter'\n ], id=template1.id)\n", (26747, 26833), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((28428, 28522), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.testdata['vgpu']['service_offerings'][gtype]"], {}), "(self.apiclient, self.testdata['vgpu'][\n 'service_offerings'][gtype])\n", (28450, 28522), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((29286, 29380), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.testdata['vgpu']['service_offerings'][gtype]"], {}), "(self.apiclient, self.testdata['vgpu'][\n 'service_offerings'][gtype])\n", (29308, 29380), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, Template, Host, VmSnapshot\n'), ((75400, 75457), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM is already deleted hence skipping"""'], {}), "('VM is already deleted hence skipping')\n", (75417, 75457), False, 'import unittest\n'), ((75651, 75708), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM is already deleted hence skipping"""'], {}), "('VM is already deleted hence skipping')\n", (75668, 75708), False, 'import unittest\n'), ((75904, 75961), 'unittest.SkipTest', 'unittest.SkipTest', (['"""VM is already deleted hence skipping"""'], {}), "('VM is already deleted hence skipping')\n", (75921, 75961), False, 'import unittest\n'), ((3331, 3553), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'ghost.ipaddress', 'port': "cls.testdata['configurableData']['host']['publicport']", 'user': "cls.testdata['configurableData']['host']['username']", 'passwd': "cls.testdata['configurableData']['host']['password']"}), "(host=ghost.ipaddress, port=cls.testdata['configurableData'][\n 'host']['publicport'], user=cls.testdata['configurableData']['host'][\n 'username'], passwd=cls.testdata['configurableData']['host']['password'])\n", (3340, 3553), False, 'from marvin.sshClient import SshClient\n'), ((9088, 9162), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Check list template api response returns a valid list"""'], {}), "('Check list template api response returns a valid list')\n", (9105, 9162), False, 'import unittest\n'), ((9271, 9338), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Check template registered is in List Templates"""'], {}), "('Check template registered is in List Templates')\n", (9288, 9338), False, 'import unittest\n'), ((9559, 9644), 'unittest.SkipTest', 'unittest.SkipTest', (["('Failed to download template(ID: %s). ' % template_response.id)"], {}), "('Failed to download template(ID: %s). ' %\n template_response.id)\n", (9576, 9644), False, 'import unittest\n'), ((27008, 27082), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Check list template api response returns a valid list"""'], {}), "('Check list template api response returns a valid list')\n", (27025, 27082), False, 'import unittest\n'), ((27191, 27258), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Check template registered is in List Templates"""'], {}), "('Check template registered is in List Templates')\n", (27208, 27258), False, 'import unittest\n'), ((27478, 27557), 'unittest.SkipTest', 'unittest.SkipTest', (["('Failed to download template(ID: %s)' % template_response.id)"], {}), "('Failed to download template(ID: %s)' % template_response.id)\n", (27495, 27557), False, 'import unittest\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Tests of network permissions
"""
import logging
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import (Account,
Configurations,
Domain,
Project,
ServiceOffering,
VirtualMachine,
Zone,
Network,
NetworkOffering,
NetworkPermission,
NIC,
PublicIPAddress,
LoadBalancerRule,
NATRule,
StaticNATRule,
SSHKeyPair)
from marvin.lib.common import (get_domain,
get_zone,
get_template)
NETWORK_FILTER_ACCOUNT = 'account'
NETWORK_FILTER_DOMAIN = 'domain'
NETWORK_FILTER_ACCOUNT_DOMAIN = 'accountdomain'
NETWORK_FILTER_SHARED = 'shared'
NETWORK_FILTER_ALL = 'all'
class TestNetworkPermissions(cloudstackTestCase):
"""
Test user-shared networks
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(
TestNetworkPermissions,
cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.zone = Zone(zone.__dict__)
cls.template = get_template(cls.apiclient, cls.zone.id)
cls._cleanup = []
cls.logger = logging.getLogger("TestNetworkPermissions")
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
cls.domain = get_domain(cls.apiclient)
# Create small service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["small"]
)
cls._cleanup.append(cls.service_offering)
# Create network offering for isolated networks
cls.network_offering_isolated = NetworkOffering.create(
cls.apiclient,
cls.services["isolated_network_offering"]
)
cls.network_offering_isolated.update(cls.apiclient, state='Enabled')
cls._cleanup.append(cls.network_offering_isolated)
# Create sub-domain
cls.sub_domain = Domain.create(
cls.apiclient,
cls.services["acl"]["domain1"]
)
cls._cleanup.append(cls.sub_domain)
# Create domain admin and normal user
cls.domain_admin = Account.create(
cls.apiclient,
cls.services["acl"]["accountD1A"],
admin=True,
domainid=cls.sub_domain.id
)
cls._cleanup.append(cls.domain_admin)
cls.network_owner = Account.create(
cls.apiclient,
cls.services["acl"]["accountD11A"],
domainid=cls.sub_domain.id
)
cls._cleanup.append(cls.network_owner)
cls.other_user = Account.create(
cls.apiclient,
cls.services["acl"]["accountD11B"],
domainid=cls.sub_domain.id
)
cls._cleanup.append(cls.other_user)
# Create project
cls.project = Project.create(
cls.apiclient,
cls.services["project"],
account=cls.domain_admin.name,
domainid=cls.domain_admin.domainid
)
cls._cleanup.append(cls.project)
# Create api clients for domain admin and normal user
cls.domainadmin_user = cls.domain_admin.user[0]
cls.domainadmin_apiclient = cls.testClient.getUserApiClient(
cls.domainadmin_user.username, cls.sub_domain.name
)
cls.networkowner_user = cls.network_owner.user[0]
cls.user_apiclient = cls.testClient.getUserApiClient(
cls.networkowner_user.username, cls.sub_domain.name
)
cls.otheruser_user = cls.other_user.user[0]
cls.otheruser_apiclient = cls.testClient.getUserApiClient(
cls.otheruser_user.username, cls.sub_domain.name
)
# Create networks for domain admin, normal user and project
cls.services["network"]["name"] = "Test Network Isolated - Project"
cls.project_network = Network.create(
cls.apiclient,
cls.services["network"],
networkofferingid=cls.network_offering_isolated.id,
domainid=cls.sub_domain.id,
projectid=cls.project.id,
zoneid=cls.zone.id
)
cls._cleanup.append(cls.project_network)
cls.services["network"]["name"] = "Test Network Isolated - Domain admin"
cls.domainadmin_network = Network.create(
cls.apiclient,
cls.services["network"],
networkofferingid=cls.network_offering_isolated.id,
domainid=cls.sub_domain.id,
accountid=cls.domain_admin.name,
zoneid=cls.zone.id
)
cls._cleanup.append(cls.domainadmin_network)
cls.services["network"]["name"] = "Test Network Isolated - Normal user"
cls.user_network = Network.create(
cls.apiclient,
cls.services["network"],
networkofferingid=cls.network_offering_isolated.id,
domainid=cls.sub_domain.id,
accountid=cls.network_owner.name,
zoneid=cls.zone.id
)
cls._cleanup.append(cls.user_network)
@classmethod
def tearDownClass(cls):
super(TestNetworkPermissions, cls).tearDownClass()
def setUp(self):
self.cleanup = []
self.virtual_machine = None
def tearDown(self):
super(TestNetworkPermissions, self).tearDown()
def list_network(self, apiclient, account, network, project, network_filter=None, expected=True):
# List networks by apiclient, account, network, project and network network_filter
# If account is specified, list the networks which can be used by the domain (canusefordeploy=true,listall=false)
# otherwise canusefordeploy is None and listall is True.
domain_id = None
account_name = None
project_id = None
canusefordeploy = None
list_all = True
if account:
domain_id = account.domainid
account_name = account.name
canusefordeploy = True
list_all = False
if project:
project_id = project.id
networks = None
try:
networks = Network.list(
apiclient,
canusefordeploy=canusefordeploy,
listall=list_all,
networkfilter= network_filter,
domainid=domain_id,
account=account_name,
projectid=project_id,
id=network.id
)
if isinstance(networks, list) and len(networks) > 0:
if not expected:
self.fail("Found the network, but expected to fail")
elif expected:
self.fail("Failed to find the network, but expected to succeed")
except Exception as ex:
networks = None
if expected:
self.fail(f"Failed to list network, but expected to succeed : {ex}")
if networks and not expected:
self.fail("network is listed successfully, but expected to fail")
def list_network_by_filters(self, apiclient, account, network, project, expected_results=None):
# expected results in order: account/domain/accountdomain/shared/all
self.list_network(apiclient, account, network, project, NETWORK_FILTER_ACCOUNT, expected_results[0])
self.list_network(apiclient, account, network, project, NETWORK_FILTER_DOMAIN, expected_results[1])
self.list_network(apiclient, account, network, project, NETWORK_FILTER_ACCOUNT_DOMAIN, expected_results[2])
self.list_network(apiclient, account, network, project, NETWORK_FILTER_SHARED, expected_results[3])
self.list_network(apiclient, account, network, project, NETWORK_FILTER_ALL, expected_results[4])
def create_network_permission(self, apiclient, network, account, project, expected=True):
account_id = None
project_id = None
if account:
account_id = account.id
if project:
project_id = project.id
result = True
try:
NetworkPermission.create(
apiclient,
networkid=network.id,
accountids=account_id,
projectids=project_id
)
except Exception as ex:
result = False
if expected:
self.fail(f"Failed to create network permissions, but expected to succeed : {ex}")
if result and not expected:
self.fail("network permission is created successfully, but expected to fail")
def remove_network_permission(self, apiclient, network, account, project, expected=True):
account_id = None
project_id = None
if account:
account_id = account.id
if project:
project_id = project.id
result = True
try:
NetworkPermission.remove(
apiclient,
networkid=network.id,
accountids=account_id,
projectids=project_id
)
except Exception as ex:
result = False
if expected:
self.fail(f"Failed to remove network permissions, but expected to succeed : {ex}")
if result and not expected:
self.fail("network permission is removed successfully, but expected to fail")
def reset_network_permission(self, apiclient, network, expected=True):
result = True
try:
NetworkPermission.reset(
apiclient,
networkid=network.id
)
except Exception as ex:
result = False
if expected:
self.fail(f"Failed to reset network permissions, but expected to succeed : {ex}")
if result and not expected:
self.fail("network permission is reset successfully, but expected to fail")
def exec_command(self, apiclient_str, command, expected=None):
result = True
try:
command = command.format(apiclient = apiclient_str)
exec(command)
except Exception as ex:
result = False
if expected:
self.fail(f"Failed to execute command '{command}' with exception : {ex}")
if result and expected is False:
self.fail(f"command {command} is executed successfully, but expected to fail")
if expected is None:
# if expected is None, display the command and result
self.logger.info(f"Result of command '{command}' : {result}")
return result
@attr(tags=["advanced"], required_hardware="false")
def test_01_network_permission_on_project_network(self):
""" Testing network permissions on project network """
self.create_network_permission(self.apiclient, self.project_network, self.domain_admin, None, expected=False)
self.create_network_permission(self.domainadmin_apiclient, self.project_network, self.domain_admin, None, expected=False)
self.create_network_permission(self.user_apiclient, self.project_network, self.network_owner, None, expected=False)
@attr(tags=["advanced"], required_hardware="false")
def test_02_network_permission_on_user_network(self):
""" Testing network permissions on user network """
# List user network by domain admin
self.list_network_by_filters(self.domainadmin_apiclient, None, self.user_network, None, [True, False, True, False, True])
self.list_network_by_filters(self.domainadmin_apiclient, self.domain_admin, self.user_network, None, [False, False, False, False, False])
# Create network permissions
self.create_network_permission(self.apiclient, self.user_network, self.domain_admin, None, expected=True)
self.create_network_permission(self.domainadmin_apiclient, self.user_network, self.domain_admin, None, expected=True)
self.create_network_permission(self.user_apiclient, self.user_network, self.network_owner, None, expected=True)
self.create_network_permission(self.user_apiclient, self.user_network, self.other_user, None, expected=True)
self.create_network_permission(self.user_apiclient, self.user_network, None, self.project, expected=False)
self.create_network_permission(self.domainadmin_apiclient, self.user_network, None, self.project, expected=True)
self.create_network_permission(self.otheruser_apiclient, self.user_network, self.network_owner, None, expected=False)
# List domain admin network by domain admin
self.list_network_by_filters(self.domainadmin_apiclient, None, self.domainadmin_network, None, [True, False, True, False, True])
self.list_network_by_filters(self.domainadmin_apiclient, self.domain_admin, self.domainadmin_network, None, [True, False, True, False, True])
# List user network by domain admin
self.list_network_by_filters(self.domainadmin_apiclient, None, self.user_network, None, [True, False, True, True, True])
self.list_network_by_filters(self.domainadmin_apiclient, self.domain_admin, self.user_network, None, [False, False, False, True, True])
# List user network by user
self.list_network_by_filters(self.user_apiclient, None, self.user_network, None, [True, False, True, False, True])
self.list_network_by_filters(self.user_apiclient, self.network_owner, self.user_network, None, [True, False, True, False, True])
# List user network by other user
self.list_network_by_filters(self.otheruser_apiclient, None, self.user_network, None, [False, False, False, True, True])
self.list_network_by_filters(self.otheruser_apiclient, self.network_owner, self.user_network, None, [False, False, False, False, False])
# Remove network permissions
self.remove_network_permission(self.domainadmin_apiclient, self.user_network, self.domain_admin, None, expected=True)
# List user network by domain admin
self.list_network_by_filters(self.domainadmin_apiclient, None, self.user_network, None, [True, False, True, True, True])
self.list_network_by_filters(self.domainadmin_apiclient, self.domain_admin, self.user_network, None, [False, False, False, False, False])
# Reset network permissions
self.reset_network_permission(self.domainadmin_apiclient, self.user_network, expected=True)
# List user network by domain admin
self.list_network_by_filters(self.domainadmin_apiclient, None, self.user_network, None, [True, False, True, False, True])
self.list_network_by_filters(self.domainadmin_apiclient, self.domain_admin, self.user_network, None, [False, False, False, False, False])
@attr(tags=["advanced"], required_hardware="false")
def test_03_network_operations_on_created_vm_of_otheruser(self):
""" Testing network operations on a create vm owned by other user"""
# 1. Create an Isolated network by other user
self.services["network"]["name"] = "Test Network Isolated - Other user"
otheruser_network = Network.create(
self.otheruser_apiclient,
self.services["network"],
networkofferingid=self.network_offering_isolated.id,
zoneid=self.zone.id
)
self.cleanup.append(otheruser_network)
# 2. Deploy vm1 on other user's network
self.virtual_machine = VirtualMachine.create(
self.otheruser_apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
serviceofferingid=self.service_offering.id,
networkids=otheruser_network.id,
zoneid=self.zone.id
)
# 3. Add user network to vm1, should fail by vm owner and network owner
command = """self.virtual_machine.add_nic({apiclient}, self.user_network.id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=False)
# 4. Create network permission for other user, should succeed by network owner
command = """self.create_network_permission({apiclient}, self.user_network, self.other_user, None, expected=True)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
# 5. Add user network to vm1, should succeed by vm owner
command = """self.virtual_machine.add_nic({apiclient}, self.user_network.id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 6. Stop vm1 with forced=true, should succeed by vm owner
command = """self.virtual_machine.stop({apiclient}, forced=True)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# Get id of the additional nic
list_vms = VirtualMachine.list(
self.otheruser_apiclient,
id = self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vms, list),
True,
"Check if virtual machine is present"
)
self.assertEqual(
len(list_vms) > 0,
True,
"Check if virtual machine list is empty"
)
self.vm_default_nic_id = None
self.vm_new_nic_id = None
for vm_nic in list_vms[0].nic:
if vm_nic.networkid == self.user_network.id:
self.vm_new_nic_id = vm_nic.id
else:
self.vm_default_nic_id = vm_nic.id
# 6. Update vm1 nic IP, should succeed by vm owner
command = """NIC.updateIp({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 7. Start vm1, should succeed by vm owner
command = """self.virtual_machine.start({apiclient})"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 8. Add secondary IP to nic, should succeed by vm owner
command = """self.secondaryip = NIC.addIp({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 9 Remove secondary IP from nic, should succeed by vm owner
command = """NIC.removeIp({apiclient}, self.secondaryip.id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 10. Update default NIC, should succeed by vm owner
command = """self.virtual_machine.update_default_nic({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
command = """self.virtual_machine.update_default_nic({apiclient}, self.vm_default_nic_id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 11. Stop vm1 with forced=true
command = """self.virtual_machine.stop({apiclient}, forced=True)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 12. Remove nic from vm1, should succeed by vm owner
command = """self.virtual_machine.remove_nic({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 13. Test operations by domain admin
command = """self.virtual_machine.add_nic({apiclient}, self.user_network.id)"""
self.exec_command("self.domainadmin_apiclient", command, expected=True)
list_vms = VirtualMachine.list(
self.otheruser_apiclient,
id = self.virtual_machine.id
)
self.vm_default_nic_id = None
self.vm_new_nic_id = None
for vm_nic in list_vms[0].nic:
if vm_nic.networkid == self.user_network.id:
self.vm_new_nic_id = vm_nic.id
else:
self.vm_default_nic_id = vm_nic.id
command = """NIC.updateIp({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.domainadmin_apiclient", command, expected=True)
command = """self.secondaryip = NIC.addIp({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.domainadmin_apiclient", command, expected=True)
command = """NIC.removeIp({apiclient}, self.secondaryip.id)"""
self.exec_command("self.domainadmin_apiclient", command, expected=True)
command = """self.virtual_machine.update_default_nic({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.domainadmin_apiclient", command, expected=True)
command = """self.virtual_machine.update_default_nic({apiclient}, self.vm_default_nic_id)"""
self.exec_command("self.domainadmin_apiclient", command, expected=True)
command = """self.virtual_machine.remove_nic({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 14. Test operations by vm owner, when network permission is removed
command = """self.virtual_machine.add_nic({apiclient}, self.user_network.id)"""
self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 15. Reset network permissions, should succeed by network owner
command = """self.reset_network_permission({apiclient}, self.user_network, expected=True)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
list_vms = VirtualMachine.list(
self.otheruser_apiclient,
id = self.virtual_machine.id
)
self.vm_default_nic_id = None
self.vm_new_nic_id = None
for vm_nic in list_vms[0].nic:
if vm_nic.networkid == self.user_network.id:
self.vm_new_nic_id = vm_nic.id
else:
self.vm_default_nic_id = vm_nic.id
command = """NIC.updateIp({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.otheruser_apiclient", command, expected=True)
command = """self.secondaryip = NIC.addIp({apiclient}, self.vm_new_nic_id)"""
if self.exec_command("self.otheruser_apiclient", command, expected=True):
command = """NIC.removeIp({apiclient}, self.secondaryip.id)"""
self.exec_command("self.otheruser_apiclient", command, expected=True)
command = """self.virtual_machine.update_default_nic({apiclient}, self.vm_new_nic_id)"""
if self.exec_command("self.otheruser_apiclient", command, expected=True):
command = """self.virtual_machine.update_default_nic({apiclient}, self.vm_default_nic_id)"""
self.exec_command("self.otheruser_apiclient", command, expected=True)
command = """self.virtual_machine.start({apiclient})"""
if self.exec_command("self.otheruser_apiclient", command, expected=True):
command = """self.virtual_machine.stop({apiclient}, forced=True)"""
self.exec_command("self.otheruser_apiclient", command, expected=True)
command = """self.virtual_machine.remove_nic({apiclient}, self.vm_new_nic_id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
#self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 16. Destroy vm1, should succeed by root admin
self.virtual_machine.delete(self.apiclient, expunge=True)
@attr(tags=["advanced"], required_hardware="false")
def test_04_deploy_vm_for_other_user_and_test_vm_operations(self):
""" Deploy VM for other user and test VM operations by vm owner, network owner and domain admin"""
# 1. Create network permission for other user, by user
command = """self.create_network_permission({apiclient}, self.user_network, self.other_user, None, expected=True)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
# 2. Deploy vm2 on user network
command = """self.virtual_machine = VirtualMachine.create(
{apiclient},
self.services["virtual_machine"],
templateid=self.template.id,
serviceofferingid=self.service_offering.id,
networkids=self.user_network.id,
accountid=self.other_user.name,
domainid=self.other_user.domainid,
zoneid=self.zone.id
)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
if not self.virtual_machine:
self.fail("Failed to find self.virtual_machine")
# 3. List vm2
list_vms = VirtualMachine.list(
self.user_apiclient,
id = self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vms, list) and len(list_vms) > 0,
False,
"Check if virtual machine is not present"
)
list_vms = VirtualMachine.list(
self.otheruser_apiclient,
id = self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vms, list) and len(list_vms) > 0,
True,
"Check if virtual machine is present"
)
# 4. Stop vm2 with forced=true
command = """self.virtual_machine.stop({apiclient}, forced=True)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 5. Reset vm password
if self.template.passwordenabled:
command = """self.virtual_machine.resetPassword({apiclient})"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 6. Reset vm SSH key
self.keypair = SSHKeyPair.create(
self.otheruser_apiclient,
name=self.other_user.name + ".pem"
)
command = """self.virtual_machine.resetSshKey({apiclient}, keypair=self.keypair.name)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 7. Start vm2
command = """self.virtual_machine.start({apiclient})"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 8. Acquire public IP, should succeed by domain admin and network owner
command = """self.public_ip = PublicIPAddress.create(
{apiclient},
zoneid=self.zone.id,
networkid=self.user_network.id
)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
#self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 9. Enable static nat, should succeed by domain admin
command = """StaticNATRule.enable(
{apiclient},
ipaddressid=self.public_ip.ipaddress.id,
virtualmachineid=self.virtual_machine.id
)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 10. Disable static nat, should succeed by domain admin and network owner
command = """StaticNATRule.disable(
{apiclient},
ipaddressid=self.public_ip.ipaddress.id
)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
#self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 11. Create port forwarding rule, should succeed by domain admin
command = """self.port_forwarding_rule = NATRule.create(
{apiclient},
virtual_machine=self.virtual_machine,
services=self.services["natrule"],
ipaddressid=self.public_ip.ipaddress.id,
)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 12. Delete port forwarding rule, should succeed by domain admin and network owner
command = """self.port_forwarding_rule.delete({apiclient})"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
#self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 13. Create load balancer rule, should succeed by domain admin and network owner
command = """self.load_balancer_rule = LoadBalancerRule.create(
{apiclient},
self.services["lbrule"],
ipaddressid=self.public_ip.ipaddress.id,
networkid=self.user_network.id,
)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
#self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 14. Assign virtual machine to load balancing rule, should succeed by domain admin
command = """self.load_balancer_rule.assign({apiclient}, vms=[self.virtual_machine])"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 15. Remove virtual machine from load balancing rule, should succeed by domain admin and network owner
command = """self.load_balancer_rule.remove({apiclient}, vms=[self.virtual_machine])"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
#self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 16. Delete load balancing rule, should succeed by domain admin and network owner
command = """self.load_balancer_rule.delete({apiclient})"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
#self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 17. Release public IP, should succeed by domain admin and network owner
command = """self.public_ip.delete({apiclient})"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
#self.exec_command("self.domainadmin_apiclient", command, expected=True)
# 18. Stop vm2 with forced=true, should succeed by vm owner
command = """self.virtual_machine.stop({apiclient}, forced=True)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 19. Update vm2, should succeed by vm owner
command = """self.virtual_machine.update({apiclient}, displayname = self.virtual_machine.displayname + ".new")"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 20. Restore vm2, should succeed by vm owner
command = """self.virtual_machine.restore({apiclient})"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 21. Scale vm2 to another offering, should succeed by vm owner
self.service_offering_new = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["big"]
)
self.cleanup.append(self.service_offering_new)
command = """self.virtual_machine.scale_virtualmachine({apiclient}, self.service_offering_new.id)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 22. Destroy vm2, should succeed by vm owner
command = """self.virtual_machine.delete({apiclient}, expunge=False)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 23. Recover vm2, should succeed by vm owner
allow_expunge_recover_vm = Configurations.list(self.apiclient, name="allow.user.expunge.recover.vm")[0].value
self.logger.debug("Global configuration allow.user.expunge.recover.vm = %s", allow_expunge_recover_vm)
if allow_expunge_recover_vm == "true":
command = """self.virtual_machine.recover({apiclient})"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 24. Destroy vm2, should succeed by vm owner
command = """self.virtual_machine.delete({apiclient}, expunge=False)"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
# 25. Expunge vm2, should succeed by vm owner
if allow_expunge_recover_vm == "true":
command = """self.virtual_machine.expunge({apiclient})"""
self.exec_command("self.user_apiclient", command, expected=False)
self.exec_command("self.otheruser_apiclient", command, expected=True)
else:
self.virtual_machine.expunge(self.apiclient)
# 26. Reset network permissions, should succeed by network owner
command = """self.reset_network_permission({apiclient}, self.user_network, expected=True)"""
self.exec_command("self.otheruser_apiclient", command, expected=False)
self.exec_command("self.user_apiclient", command, expected=True)
| [
"marvin.lib.base.NetworkPermission.remove",
"marvin.lib.base.Domain.create",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.Zone",
"marvin.lib.base.SSHKeyPair.create",
"marvin.lib.base.Network.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.NetworkPermission.create",
"marvin.lib.b... | [((11982, 12032), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (11986, 12032), False, 'from nose.plugins.attrib import attr\n'), ((12536, 12586), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (12540, 12586), False, 'from nose.plugins.attrib import attr\n'), ((16118, 16168), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (16122, 16168), False, 'from nose.plugins.attrib import attr\n'), ((25626, 25676), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (25630, 25676), False, 'from nose.plugins.attrib import attr\n'), ((2363, 2382), 'marvin.lib.base.Zone', 'Zone', (['zone.__dict__'], {}), '(zone.__dict__)\n', (2367, 2382), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((2406, 2446), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id'], {}), '(cls.apiclient, cls.zone.id)\n', (2418, 2446), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((2495, 2538), 'logging.getLogger', 'logging.getLogger', (['"""TestNetworkPermissions"""'], {}), "('TestNetworkPermissions')\n", (2512, 2538), False, 'import logging\n'), ((2568, 2591), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2589, 2591), False, 'import logging\n'), ((2707, 2732), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2717, 2732), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((2805, 2891), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['small']"], {}), "(cls.apiclient, cls.services['service_offerings'][\n 'small'])\n", (2827, 2891), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((3068, 3153), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['isolated_network_offering']"], {}), "(cls.apiclient, cls.services['isolated_network_offering']\n )\n", (3090, 3153), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((3373, 3433), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain1']"], {}), "(cls.apiclient, cls.services['acl']['domain1'])\n", (3386, 3433), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((3586, 3694), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['acl']['accountD1A']"], {'admin': '(True)', 'domainid': 'cls.sub_domain.id'}), "(cls.apiclient, cls.services['acl']['accountD1A'], admin=True,\n domainid=cls.sub_domain.id)\n", (3600, 3694), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((3824, 3922), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['acl']['accountD11A']"], {'domainid': 'cls.sub_domain.id'}), "(cls.apiclient, cls.services['acl']['accountD11A'], domainid=\n cls.sub_domain.id)\n", (3838, 3922), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((4037, 4135), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['acl']['accountD11B']"], {'domainid': 'cls.sub_domain.id'}), "(cls.apiclient, cls.services['acl']['accountD11B'], domainid=\n cls.sub_domain.id)\n", (4051, 4135), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((4269, 4395), 'marvin.lib.base.Project.create', 'Project.create', (['cls.apiclient', "cls.services['project']"], {'account': 'cls.domain_admin.name', 'domainid': 'cls.domain_admin.domainid'}), "(cls.apiclient, cls.services['project'], account=cls.\n domain_admin.name, domainid=cls.domain_admin.domainid)\n", (4283, 4395), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((5303, 5493), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network']"], {'networkofferingid': 'cls.network_offering_isolated.id', 'domainid': 'cls.sub_domain.id', 'projectid': 'cls.project.id', 'zoneid': 'cls.zone.id'}), "(cls.apiclient, cls.services['network'], networkofferingid=\n cls.network_offering_isolated.id, domainid=cls.sub_domain.id, projectid\n =cls.project.id, zoneid=cls.zone.id)\n", (5317, 5493), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((5731, 5928), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network']"], {'networkofferingid': 'cls.network_offering_isolated.id', 'domainid': 'cls.sub_domain.id', 'accountid': 'cls.domain_admin.name', 'zoneid': 'cls.zone.id'}), "(cls.apiclient, cls.services['network'], networkofferingid=\n cls.network_offering_isolated.id, domainid=cls.sub_domain.id, accountid\n =cls.domain_admin.name, zoneid=cls.zone.id)\n", (5745, 5928), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((6162, 6360), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network']"], {'networkofferingid': 'cls.network_offering_isolated.id', 'domainid': 'cls.sub_domain.id', 'accountid': 'cls.network_owner.name', 'zoneid': 'cls.zone.id'}), "(cls.apiclient, cls.services['network'], networkofferingid=\n cls.network_offering_isolated.id, domainid=cls.sub_domain.id, accountid\n =cls.network_owner.name, zoneid=cls.zone.id)\n", (6176, 6360), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((16478, 16622), 'marvin.lib.base.Network.create', 'Network.create', (['self.otheruser_apiclient', "self.services['network']"], {'networkofferingid': 'self.network_offering_isolated.id', 'zoneid': 'self.zone.id'}), "(self.otheruser_apiclient, self.services['network'],\n networkofferingid=self.network_offering_isolated.id, zoneid=self.zone.id)\n", (16492, 16622), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((16804, 17022), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.otheruser_apiclient', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'serviceofferingid': 'self.service_offering.id', 'networkids': 'otheruser_network.id', 'zoneid': 'self.zone.id'}), "(self.otheruser_apiclient, self.services[\n 'virtual_machine'], templateid=self.template.id, serviceofferingid=self\n .service_offering.id, networkids=otheruser_network.id, zoneid=self.zone.id)\n", (16825, 17022), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((18443, 18516), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.otheruser_apiclient'], {'id': 'self.virtual_machine.id'}), '(self.otheruser_apiclient, id=self.virtual_machine.id)\n', (18462, 18516), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((21639, 21712), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.otheruser_apiclient'], {'id': 'self.virtual_machine.id'}), '(self.otheruser_apiclient, id=self.virtual_machine.id)\n', (21658, 21712), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((23628, 23701), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.otheruser_apiclient'], {'id': 'self.virtual_machine.id'}), '(self.otheruser_apiclient, id=self.virtual_machine.id)\n', (23647, 23701), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((27072, 27140), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.user_apiclient'], {'id': 'self.virtual_machine.id'}), '(self.user_apiclient, id=self.virtual_machine.id)\n', (27091, 27140), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((27367, 27440), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.otheruser_apiclient'], {'id': 'self.virtual_machine.id'}), '(self.otheruser_apiclient, id=self.virtual_machine.id)\n', (27386, 27440), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((28275, 28354), 'marvin.lib.base.SSHKeyPair.create', 'SSHKeyPair.create', (['self.otheruser_apiclient'], {'name': "(self.other_user.name + '.pem')"}), "(self.otheruser_apiclient, name=self.other_user.name + '.pem')\n", (28292, 28354), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((34552, 34638), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['big']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'big'])\n", (34574, 34638), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((7544, 7735), 'marvin.lib.base.Network.list', 'Network.list', (['apiclient'], {'canusefordeploy': 'canusefordeploy', 'listall': 'list_all', 'networkfilter': 'network_filter', 'domainid': 'domain_id', 'account': 'account_name', 'projectid': 'project_id', 'id': 'network.id'}), '(apiclient, canusefordeploy=canusefordeploy, listall=list_all,\n networkfilter=network_filter, domainid=domain_id, account=account_name,\n projectid=project_id, id=network.id)\n', (7556, 7735), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((9466, 9574), 'marvin.lib.base.NetworkPermission.create', 'NetworkPermission.create', (['apiclient'], {'networkid': 'network.id', 'accountids': 'account_id', 'projectids': 'project_id'}), '(apiclient, networkid=network.id, accountids=\n account_id, projectids=project_id)\n', (9490, 9574), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((10263, 10371), 'marvin.lib.base.NetworkPermission.remove', 'NetworkPermission.remove', (['apiclient'], {'networkid': 'network.id', 'accountids': 'account_id', 'projectids': 'project_id'}), '(apiclient, networkid=network.id, accountids=\n account_id, projectids=project_id)\n', (10287, 10371), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((10877, 10933), 'marvin.lib.base.NetworkPermission.reset', 'NetworkPermission.reset', (['apiclient'], {'networkid': 'network.id'}), '(apiclient, networkid=network.id)\n', (10900, 10933), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n'), ((35361, 35434), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""allow.user.expunge.recover.vm"""'}), "(self.apiclient, name='allow.user.expunge.recover.vm')\n", (35380, 35434), False, 'from marvin.lib.base import Account, Configurations, Domain, Project, ServiceOffering, VirtualMachine, Zone, Network, NetworkOffering, NetworkPermission, NIC, PublicIPAddress, LoadBalancerRule, NATRule, StaticNATRule, SSHKeyPair\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: <NAME>, <NAME>, and <NAME>
# @Date: 2017-11-08
# @Filename: maps.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: <NAME> (<EMAIL>)
# @Last modified time: 2018-11-14 10:49:45
from __future__ import absolute_import, division, print_function
import copy
import inspect
import warnings
import astropy.io.fits
import astropy.wcs
import numpy as np
import pandas as pd
import six
from pkg_resources import parse_version
import marvin
import marvin.api.api
import marvin.core.exceptions
import marvin.tools.cube
import marvin.tools.modelcube
import marvin.tools.quantities.map
import marvin.tools.spaxel
import marvin.utils.dap.bpt
import marvin.utils.general.general
from marvin.utils.datamodel.dap import datamodel
from marvin.utils.datamodel.dap.base import Channel, Property
from marvin.utils.general import FuzzyDict, turn_off_ion, check_versions
from .core import MarvinToolsClass
from .mixins import DAPallMixIn, GetApertureMixIn, NSAMixIn
from .quantities import AnalysisProperty
try:
import sqlalchemy
except ImportError:
sqlalchemy = None
__all__ = ['Maps']
class Maps(MarvinToolsClass, NSAMixIn, DAPallMixIn, GetApertureMixIn):
"""A class that represents a DAP MAPS file.
Provides access to the data stored in a DAP MAPS file. In addition to
the parameters and variables defined for `~.MarvinToolsClass`, the
following parameters and attributes are specific to `.Maps`.
Parameters:
bintype (str or None):
The binning type. For MPL-4, one of the following: ``'NONE',
'RADIAL', 'STON'`` (if ``None`` defaults to ``'NONE'``).
For MPL-5, one of, ``'ALL', 'NRE', 'SPX', 'VOR10'``
(defaults to ``'SPX'``). MPL-6 also accepts the ``'HYB10'`` binning
schema.
template (str or None):
The stellar template used. For MPL-4, one of
``'M11-STELIB-ZSOL', 'MILES-THIN', 'MIUSCAT-THIN'`` (if ``None``,
defaults to ``'MIUSCAT-THIN'``). For MPL-5 and successive, the only
option in ``'GAU-MILESHC'`` (``None`` defaults to it).
Attributes:
header (`astropy.io.fits.Header`):
The header of the datacube.
wcs (`astropy.wcs.WCS`):
The WCS solution for this plate
"""
def __init__(self, input=None, filename=None, mangaid=None, plateifu=None,
mode=None, data=None, release=None,
drpall=None, download=None, nsa_source='auto',
bintype=None, template=None, template_kin=None):
if template_kin is not None:
warnings.warn('template_kin is deprecated and will be removed in a future version.',
DeprecationWarning)
template = template_kin if template is None else template
# _set_datamodel will replace these strings with datamodel objects.
self.bintype = bintype
self.template = template
self._bitmasks = None
MarvinToolsClass.__init__(self, input=input, filename=filename,
mangaid=mangaid, plateifu=plateifu,
mode=mode, data=data, release=release,
drpall=drpall, download=download)
NSAMixIn.__init__(self, nsa_source=nsa_source)
self.header = None
self.wcs = None
self._shape = None
if self.data_origin == 'file':
self._load_maps_from_file(data=self.data)
elif self.data_origin == 'db':
self._load_maps_from_db(data=self.data)
elif self.data_origin == 'api':
self._load_maps_from_api()
else:
raise marvin.core.exceptions.MarvinError(
'data_origin={0} is not valid'.format(self.data_origin))
self._check_versions(self)
def __repr__(self):
return ('<Marvin Maps (plateifu={0.plateifu!r}, mode={0.mode!r}, '
'data_origin={0.data_origin!r}, bintype={0.bintype.name!r}, '
'template={0.template.name!r})>'.format(self))
def __getitem__(self, value):
"""Gets either a spaxel or a map depending on the type on input."""
if isinstance(value, tuple):
assert len(value) == 2, 'slice must have two elements.'
y, x = value
return self.getSpaxel(x=x, y=y, xyorig='lower')
elif isinstance(value, six.string_types):
return self.getMap(value)
else:
raise marvin.core.exceptions.MarvinError('invalid type for getitem.')
def __getattr__(self, value):
if isinstance(value, six.string_types) and value in self.datamodel:
return self.getMap(value)
return super(Maps, self).__getattribute__(value)
def __dir__(self):
class_members = list(list(zip(*inspect.getmembers(self.__class__)))[0])
instance_attr = list(self.__dict__.keys())
return sorted(class_members + instance_attr) + [prop.full() for prop in self.datamodel]
def _set_datamodel(self):
"""Sets the datamodel."""
self.datamodel = datamodel[self.release].properties
self._bitmasks = datamodel[self.release].bitmasks
self.bintype = self.datamodel.parent.get_bintype(self.bintype)
self.template = self.datamodel.parent.get_template(self.template)
def __deepcopy__(self, memo):
return Maps(plateifu=copy.deepcopy(self.plateifu, memo),
release=copy.deepcopy(self.release, memo),
bintype=copy.deepcopy(self.bintype, memo),
template=copy.deepcopy(self.template, memo),
nsa_source=copy.deepcopy(self.nsa_source, memo))
@staticmethod
def _check_versions(instance):
"""Confirm that drpver and dapver match the ones from the header.
This is written as a staticmethod because we'll also use if for
ModelCube.
"""
header_drpver = instance.header['VERSDRP3']
isMPL4 = False
if instance.release == 'MPL-4' and header_drpver == 'v1_5_0':
header_drpver = 'v1_5_1'
isMPL4 = True
assert header_drpver == instance._drpver, ('mismatch between maps._drpver={0} '
'and header drpver={1}'
.format(instance._drpver, header_drpver))
# MPL-4 does not have VERSDAP
if isMPL4:
assert 'VERSDAP' not in instance.header, \
('VERSDAP is present in the header but this is a MPL-4 MAPS. '
'That should not happen.')
else:
header_dapver = instance.header['VERSDAP']
assert header_dapver == instance._dapver, 'mismatch between maps._dapver and header'
def _getFullPath(self):
"""Returns the full path of the file in the tree."""
params = self._getPathParams()
path_type = params.pop('path_type')
return super(Maps, self)._getFullPath(path_type, **params)
def download(self):
"""Downloads the maps using sdss_access - Rsync"""
if not self.plateifu:
return None
params = self._getPathParams()
path_type = params.pop('path_type')
return super(Maps, self).download(path_type, **params)
def _getPathParams(self):
"""Returns a dictionary with the paramters of the Maps file.
The output of this class is mostly intended to be used by
:func:`Maps._getFullPath` and :func:`Maps.download`.
"""
plate, ifu = self.plateifu.split('-')
if self.release == 'MPL-4':
niter = int('{0}{1}'.format(self.template.n, self.bintype.n))
params = dict(drpver=self._drpver, dapver=self._dapver,
plate=plate, ifu=ifu, bintype=self.bintype.name,
n=niter, path_type='mangamap')
else:
daptype = '{0}-{1}'.format(self.bintype.name, self.template.name)
params = dict(drpver=self._drpver, dapver=self._dapver,
plate=plate, ifu=ifu, mode='MAPS', daptype=daptype,
path_type='mangadap5')
return params
def _load_maps_from_file(self, data=None):
"""Loads a MAPS file."""
if data is not None:
assert isinstance(data, astropy.io.fits.HDUList), 'data is not a HDUList.'
else:
self.data = astropy.io.fits.open(self.filename)
self.header = self.data[0].header
self.mangaid = self.header['MANGAID'].strip()
self.plateifu = self.header['PLATEIFU'].strip()
self._check_file(self.header, self.data, 'Maps')
# We use EMLINE_GFLUX because is present in MPL-4 and 5 and is not expected to go away.
header = self.data['EMLINE_GFLUX'].header
naxis = header['NAXIS']
wcs_pre = astropy.wcs.WCS(header)
# Takes only the first two axis.
self.wcs = wcs_pre.sub(2) if naxis > 2 else naxis
self._shape = (header['NAXIS2'], header['NAXIS1'])
# Checks and populates release.
file_drpver = self.header['VERSDRP3']
file_drpver = 'v1_5_1' if file_drpver == 'v1_5_0' else file_drpver
file_ver = marvin.config.lookUpRelease(file_drpver)
assert file_ver is not None, 'cannot find file version.'
if file_ver != self._release:
warnings.warn('mismatch between file version={0} and object release={1}. '
'Setting object release to {0}'.format(file_ver, self._release),
marvin.core.exceptions.MarvinUserWarning)
self._release = file_ver
self._drpver, self._dapver = marvin.config.lookUpVersions(release=self._release)
self.datamodel = datamodel[self._dapver].properties
# Checks the bintype from the header
is_MPL4 = 'MPL-4' in self.datamodel.parent.aliases
if not is_MPL4:
header_bintype = self.data[0].header['BINKEY'].strip().upper()
header_bintype = 'SPX' if header_bintype == 'NONE' else header_bintype
else:
header_bintype = self.data[0].header['BINTYPE'].strip().upper()
# Checks the template from the header
#is_MPL8 = parse_version(self._dapver) >= parse_version(datamodel['MPL-8'].release)
is_MPL8 = check_versions(self._dapver, datamodel['MPL-8'].release)
header_template_key = 'TPLKEY' if is_MPL4 else 'DAPTYPE' if is_MPL8 else 'SCKEY'
if is_MPL8:
template_val = self.data[0].header[header_template_key].split('-', 1)[-1]
else:
template_val = self.data[0].header[header_template_key]
header_template = template_val.strip().upper()
if self.bintype.name != header_bintype:
self.bintype = self.datamodel.parent.get_bintype(header_bintype)
if self.template.name != header_template:
self.template = self.datamodel.parent.get_template(header_template)
def _load_maps_from_db(self, data=None):
"""Loads the ``mangadap.File`` object for this Maps."""
mdb = marvin.marvindb
plate, ifu = self.plateifu.split('-')
if not mdb.isdbconnected:
raise marvin.core.exceptions.MarvinError('No db connected')
if sqlalchemy is None:
raise marvin.core.exceptions.MarvinError('sqlalchemy required to access the local DB.')
dm = datamodel[self.release]
if dm.db_only:
if self.bintype not in dm.db_only:
raise marvin.core.exceptions.MarvinError('Specified bintype {0} is not available '
'in the DB'.format(self.bintype.name))
if data is not None:
assert isinstance(data, mdb.dapdb.File), 'data in not a marvindb.dapdb.File object.'
else:
datadb = mdb.datadb
dapdb = mdb.dapdb
# Initial query for version
version_query = mdb.session.query(dapdb.File).join(
datadb.PipelineInfo,
datadb.PipelineVersion).filter(
datadb.PipelineVersion.version == self._dapver).from_self()
# Query for maps parameters
db_maps_file = version_query.join(
datadb.Cube,
datadb.IFUDesign).filter(
datadb.Cube.plate == plate,
datadb.IFUDesign.name == str(ifu)).from_self().join(
dapdb.FileType).filter(dapdb.FileType.value == 'MAPS').join(
dapdb.Structure, dapdb.BinType).join(
dapdb.Template,
dapdb.Structure.template_kin_pk == dapdb.Template.pk).filter(
dapdb.BinType.name == self.bintype.name,
dapdb.Template.name == self.template.name).all()
if len(db_maps_file) > 1:
raise marvin.core.exceptions.MarvinError(
'more than one Maps file found for this combination of parameters.')
elif len(db_maps_file) == 0:
raise marvin.core.exceptions.MarvinError(
'no Maps file found for this combination of parameters.')
self.data = db_maps_file[0]
self.header = self.data.primary_header
# Gets the cube header
cubehdr = self.data.cube.header
# Gets the mangaid
self.mangaid = cubehdr['MANGAID'].strip()
# Creates the WCS from the cube's WCS header
self.wcs = astropy.wcs.WCS(self.data.cube.wcs.makeHeader())
self._shape = self.data.cube.shape.shape
def _load_maps_from_api(self):
"""Loads a Maps object from remote."""
url = marvin.config.urlmap['api']['getMaps']['url']
url_full = url.format(name=self.plateifu,
bintype=self.bintype.name,
template=self.template.name)
try:
response = self._toolInteraction(url_full)
except Exception as ee:
raise marvin.core.exceptions.MarvinError(
'found a problem when checking if remote maps exists: {0}'.format(str(ee)))
data = response.getData()
if self.plateifu not in data['plateifu']:
raise marvin.core.exceptions.MarvinError('remote maps has a different plateifu!')
self.header = astropy.io.fits.Header.fromstring(data['header'])
# Sets the mangaid
self.mangaid = data['mangaid']
# Sets the WCS
self.wcs = astropy.wcs.WCS(astropy.io.fits.Header.fromstring(data['wcs']))
self._shape = data['shape']
return
def _get_spaxel_quantities(self, x, y, spaxel=None):
"""Returns a dictionary of spaxel quantities."""
maps_quantities = FuzzyDict({})
if self.data_origin == 'file' or self.data_origin == 'db':
# Stores a dictionary of (table, row)
_db_rows = {}
for dm in self.datamodel:
data = {'value': None, 'ivar': None, 'mask': None}
for key in data:
if key == 'ivar' and not dm.has_ivar():
continue
if key == 'mask' and not dm.has_mask():
continue
if self.data_origin == 'file':
extname = dm.name + '' if key == 'value' else dm.name + '_' + key
if dm.channel:
data[key] = self.data[extname].data[dm.channel.idx, y, x]
else:
data[key] = self.data[extname].data[y, x]
elif self.data_origin == 'db':
mdb = marvin.marvindb
table = getattr(mdb.dapdb, dm.model)
if table not in _db_rows:
_db_rows[table] = mdb.session.query(table).filter(
table.file_pk == self.data.pk, table.x == x, table.y == y).one()
colname = dm.db_column(ext=None if key == 'value' else key)
data[key] = getattr(_db_rows[table], colname)
quantity = AnalysisProperty(data['value'], unit=dm.unit, ivar=data['ivar'],
mask=data['mask'], pixmask_flag=dm.pixmask_flag)
if spaxel:
quantity._init_bin(spaxel=spaxel, parent=self, datamodel=dm)
maps_quantities[dm.full()] = quantity
if self.data_origin == 'api':
params = {'release': self._release}
url = marvin.config.urlmap['api']['getMapsQuantitiesSpaxel']['url']
try:
response = self._toolInteraction(url.format(name=self.plateifu,
x=x, y=y,
bintype=self.bintype.name,
template=self.template.name,
params=params))
except Exception as ee:
raise marvin.core.exceptions.MarvinError(
'found a problem when checking if remote cube exists: {0}'.format(str(ee)))
data = response.getData()
for dm in self.datamodel:
quantity = AnalysisProperty(data[dm.full()]['value'],
ivar=data[dm.full()]['ivar'],
mask=data[dm.full()]['mask'],
unit=dm.unit,
pixmask_flag=dm.pixmask_flag)
if spaxel:
quantity._init_bin(spaxel=spaxel, parent=self, datamodel=dm)
maps_quantities[dm.full()] = quantity
return maps_quantities
def get_binid(self, property=None):
"""Returns the binid map associated with a property.
Parameters
----------
property : `datamodel.Property` or None
The property for which the associated binid map will be returned.
If ``binid=None``, the default binid is returned.
Returns
-------
binid : `Map`
A `Map` with the binid associated with ``property`` or the default
binid.
"""
assert property is None or isinstance(property, Property), \
'property must be None or a Property.'
if property is None:
assert self.datamodel.parent.default_binid is not None
binid = self.datamodel.parent.default_binid
else:
binid = property.binid
return self.getMap(binid)
def getCube(self):
"""Returns the :class:`~marvin.tools.cube.Cube` for with this Maps."""
if self.data_origin == 'db':
cube_data = self.data.cube
else:
cube_data = None
return marvin.tools.cube.Cube(data=cube_data,
plateifu=self.plateifu,
release=self.release)
def getModelCube(self):
"""Returns the `~marvin.tools.cube.ModelCube` for with this Maps."""
return marvin.tools.modelcube.ModelCube(plateifu=self.plateifu,
release=self.release,
bintype=self.bintype,
template=self.template)
def getSpaxel(self, x=None, y=None, ra=None, dec=None,
cube=False, modelcube=False, **kwargs):
"""Returns the :class:`~marvin.tools.spaxel.Spaxel` matching certain coordinates.
The coordinates of the spaxel to return can be input as ``x, y`` pixels
relative to``xyorig`` in the cube, or as ``ra, dec`` celestial
coordinates.
If ``spectrum=True``, the returned |spaxel| will be instantiated with the
DRP spectrum of the spaxel for the DRP cube associated with this Maps.
Parameters:
x,y (int or array):
The spaxel coordinates relative to ``xyorig``. If ``x`` is an
array of coordinates, the size of ``x`` must much that of
``y``.
ra,dec (float or array):
The coordinates of the spaxel to return. The closest spaxel to
those coordinates will be returned. If ``ra`` is an array of
coordinates, the size of ``ra`` must much that of ``dec``.
xyorig ({'center', 'lower'}):
The reference point from which ``x`` and ``y`` are measured.
Valid values are ``'center'`` (default), for the centre of the
spatial dimensions of the cube, or ``'lower'`` for the
lower-left corner. This keyword is ignored if ``ra`` and
``dec`` are defined.
cube (bool):
If ``True``, the |spaxel| will be initialised with the
corresponding DRP cube data.
modelcube (bool):
If ``True``, the |spaxel| will be initialised with the
corresponding `.ModelCube` data.
Returns:
spaxels (list):
The |spaxel|_ objects for this cube/maps corresponding to the
input coordinates. The length of the list is equal to the
number of input coordinates.
.. |spaxel| replace:: :class:`~marvin.tools.spaxel.Spaxel`
"""
for old_param in ['drp', 'model', 'models']:
if old_param in kwargs:
raise marvin.core.exceptions.MarvinDeprecationError(
'the {0} parameter has been deprecated. '
'Use cube or modelcube.'.format(old_param))
return marvin.utils.general.general.getSpaxel(
x=x, y=y, ra=ra, dec=dec,
cube=cube, maps=self, modelcube=modelcube, **kwargs)
def _match_properties(self, property_name, channel=None, exact=False):
"""Returns the best match for a property_name+channel."""
channel = channel.name if isinstance(channel, Channel) else channel
channel = None if channel == 'None' else channel
if channel is not None:
property_name = property_name + '_' + channel
best = self.datamodel[property_name]
assert isinstance(best, Property), 'the retrived value is not a property.'
if exact:
assert best.full() == property_name, \
'retrieved property {0!r} does not match input {1!r}'.format(best.full(),
property_name)
return best
def getMap(self, property_name, channel=None, exact=False):
"""Retrieves a :class:`~marvin.tools.quantities.Map` object.
Parameters:
property_name (str):
The property of the map to be extractred. It may the name
of the channel (e.g. ``'emline_gflux_ha_6564'``) or just the
name of the property (``'emline_gflux'``).
channel (str or None):
If defined, the name of the channel to be appended to
``property_name`` (e.g., ``'ha_6564'``).
exact (bool):
If ``exact=False``, fuzzy matching will be used, retrieving
the best match for the property name and channel. If ``True``,
will check that the name of returned map matched the input
value exactly.
"""
if isinstance(property_name, Property):
best = property_name
else:
best = self._match_properties(property_name, channel=channel, exact=exact)
# raise error when property is MPL-6 stellar_sigmacorr
if best.full() == 'stellar_sigmacorr' and self.release == 'MPL-6':
raise marvin.core.exceptions.MarvinError('stellar_sigmacorr is unreliable in MPL-6. '
'Please use MPL-7.')
return marvin.tools.quantities.Map.from_maps(self, best)
def getMapRatio(self, property_name, channel_1, channel_2):
"""Returns a ratio `~marvin.tools.quantities.Map`.
.. attention::
Deprecated, see :ref:`Enhanced Map<marvin-enhanced-map>`.
For a given ``property_name``, returns a `~marvin.tools.quantities.Map`
which is the ratio of ``channel_1/channel_2``.
For a given ``property_name``, returns a `~marvin.tools.quantities.Map`
which is the ratio of ``channel_1/channel_2``.
Parameters:
property_name (str):
The property_name of the map to be extractred.
E.g., `'emline_gflux'`.
channel_1,channel_2 (str):
The channels to use.
"""
map_1 = self.getMap(property_name, channel=channel_1)
map_2 = self.getMap(property_name, channel=channel_2)
return map_1 / map_2
def is_binned(self):
"""Returns True if the Maps is not unbinned."""
return self.bintype.binned
def get_unbinned(self):
"""Returns a version of ``self`` corresponding to the unbinned Maps."""
if self.is_binned is False:
return self
else:
return Maps(plateifu=self.plateifu, release=self.release,
bintype=self.datamodel.parent.get_unbinned(),
template=self.template, mode=self.mode)
def get_bpt(self, method='kewley06', snr_min=3, return_figure=True,
show_plot=True, use_oi=True, **kwargs):
"""Returns the BPT diagram for this target.
This method produces the BPT diagram for this target using emission
line maps and returns a dictionary of classification masks, that can be
used to select spaxels that have been classified as belonging to a
certain excitation process. It also provides plotting functionalities.
Extensive documentation can be found in :ref:`marvin-bpt`.
Parameters:
method ({'kewley06'}):
The method used to determine the boundaries between different
excitation mechanisms. Currently, the only available method is
``'kewley06'``, based on Kewley et al. (2006). Other methods
may be added in the future. For a detailed explanation of the
implementation of the method check the
:ref:`BPT documentation <marvin-bpt>`.
snr_min (float or dict):
The signal-to-noise cutoff value for the emission lines used
to generate the BPT diagram. If ``snr_min`` is a single value,
that signal-to-noise will be used for all the lines.
Alternatively, a dictionary of signal-to-noise values, with the
emission line channels as keys, can be used. E.g.,
``snr_min={'ha': 5, 'nii': 3, 'oi': 1}``. If some values are
not provided, they will default to ``SNR>=3``.
return_figure (bool):
If ``True``, it also returns the matplotlib
`~matplotlib.figure.Figure` of the BPT diagram plot, which can
be used to modify the style of the plot.
show_plot (bool):
If ``True``, interactively display the BPT plot.
use_oi (bool):
If ``True``, turns uses the OI diagnostic line in classifying
BPT spaxels
Returns:
bpt_return:
``get_bpt`` always returns a dictionary of classification
masks. These classification masks (not to be confused with
bitmasks) are boolean arrays with the same shape as the
`~marvin.tools.maps.Maps` or `~marvin.tools.cube.Cube` (without
the spectral dimension) that can be used to select spaxels
belonging to a certain excitation process (e.g., star forming).
The keys of the dictionary, i.e., the classification
categories, may change depending on the selected method.
Consult the :ref:`BPT <marvin-bpt>` documentation for more
details. If ``return_figure=True``, ``~.Maps.get_bpt`` will
also return the matplotlib `~matplotlib.figure.Figure` for the
generated plot, and a list of axes for each one of the
subplots.
Example:
>>> cube = Cube(plateifu='8485-1901')
>>> maps = cube.getMaps()
>>> bpt_masks, bpt_figure = maps.get_bpt(snr=5, return_figure=True,
>>> show_plot=False)
Now we can use the masks to select star forming spaxels from the
cube
>>> sf_spaxels = cube.flux[bpt_masks['sf']['global']]
And we can save the figure as a PDF
>>> bpt_figure.savefig('8485_1901_bpt.pdf')
.. _figure: http://matplotlib.org/api/figure_api.html
"""
if 'snr' in kwargs:
warnings.warn('snr is deprecated. Use snr_min instead. '
'snr will be removed in a future version of marvin',
marvin.core.exceptions.MarvinDeprecationWarning)
snr_min = kwargs.pop('snr')
if len(kwargs.keys()) > 0:
raise marvin.core.exceptions.MarvinError(
'unknown keyword {0}'.format(list(kwargs.keys())[0]))
# Makes sure all the keys in the snr keyword are lowercase
if isinstance(snr_min, dict):
snr_min = dict((kk.lower(), vv) for kk, vv in snr_min.items())
# If we don't want the figure but want to show the plot, we still need to
# temporarily get it.
do_return_figure = True if return_figure or show_plot else False
with turn_off_ion(show_plot=show_plot):
bpt_return = marvin.utils.dap.bpt.bpt_kewley06(self, snr_min=snr_min,
return_figure=do_return_figure,
use_oi=use_oi)
# Returs what we actually asked for.
if return_figure and do_return_figure:
return bpt_return
elif not return_figure and do_return_figure:
return bpt_return[0]
else:
return bpt_return
def to_dataframe(self, columns=None, mask=None):
"""Converts the maps object into a Pandas dataframe.
Parameters:
columns (list):
The properties+channels you want to include.
Defaults to all of them.
mask (array):
A 2D mask array for filtering your data output
Returns:
df (`~pandas.DataFrame`):
A Pandas `~pandas.DataFrame`.
"""
allprops = [p.full() for p in self.datamodel]
if columns:
allprops = [p for p in allprops if p in columns]
data = np.array([self[p].value[mask].flatten() for p in allprops])
# add a column for spaxel index
spaxarr = np.array([np.where(mask.flatten())[0]]) \
if mask is not None else np.array([np.arange(data.shape[1])])
data = np.concatenate((spaxarr, data), axis=0)
allprops = ['spaxelid'] + allprops
# create the dataframe
df = pd.DataFrame(data.transpose(), columns=allprops)
return df
| [
"marvin.config.lookUpRelease",
"marvin.tools.modelcube.ModelCube",
"marvin.utils.general.check_versions",
"marvin.tools.quantities.Map.from_maps",
"marvin.utils.general.FuzzyDict",
"marvin.utils.general.general.getSpaxel",
"marvin.tools.cube.Cube",
"marvin.config.lookUpVersions",
"marvin.utils.dap.b... | [((9387, 9427), 'marvin.config.lookUpRelease', 'marvin.config.lookUpRelease', (['file_drpver'], {}), '(file_drpver)\n', (9414, 9427), False, 'import marvin\n'), ((9853, 9904), 'marvin.config.lookUpVersions', 'marvin.config.lookUpVersions', ([], {'release': 'self._release'}), '(release=self._release)\n', (9881, 9904), False, 'import marvin\n'), ((10499, 10555), 'marvin.utils.general.check_versions', 'check_versions', (['self._dapver', "datamodel['MPL-8'].release"], {}), "(self._dapver, datamodel['MPL-8'].release)\n", (10513, 10555), False, 'from marvin.utils.general import FuzzyDict, turn_off_ion, check_versions\n'), ((15037, 15050), 'marvin.utils.general.FuzzyDict', 'FuzzyDict', (['{}'], {}), '({})\n', (15046, 15050), False, 'from marvin.utils.general import FuzzyDict, turn_off_ion, check_versions\n'), ((19281, 19370), 'marvin.tools.cube.Cube', 'marvin.tools.cube.Cube', ([], {'data': 'cube_data', 'plateifu': 'self.plateifu', 'release': 'self.release'}), '(data=cube_data, plateifu=self.plateifu, release=self\n .release)\n', (19303, 19370), False, 'import marvin\n'), ((19564, 19693), 'marvin.tools.modelcube.ModelCube', 'marvin.tools.modelcube.ModelCube', ([], {'plateifu': 'self.plateifu', 'release': 'self.release', 'bintype': 'self.bintype', 'template': 'self.template'}), '(plateifu=self.plateifu, release=self.\n release, bintype=self.bintype, template=self.template)\n', (19596, 19693), False, 'import marvin\n'), ((22168, 22289), 'marvin.utils.general.general.getSpaxel', 'marvin.utils.general.general.getSpaxel', ([], {'x': 'x', 'y': 'y', 'ra': 'ra', 'dec': 'dec', 'cube': 'cube', 'maps': 'self', 'modelcube': 'modelcube'}), '(x=x, y=y, ra=ra, dec=dec, cube=cube,\n maps=self, modelcube=modelcube, **kwargs)\n', (22206, 22289), False, 'import marvin\n'), ((24450, 24499), 'marvin.tools.quantities.Map.from_maps', 'marvin.tools.quantities.Map.from_maps', (['self', 'best'], {}), '(self, best)\n', (24487, 24499), False, 'import marvin\n'), ((31749, 31788), 'numpy.concatenate', 'np.concatenate', (['(spaxarr, data)'], {'axis': '(0)'}), '((spaxarr, data), axis=0)\n', (31763, 31788), True, 'import numpy as np\n'), ((2689, 2802), 'warnings.warn', 'warnings.warn', (['"""template_kin is deprecated and will be removed in a future version."""', 'DeprecationWarning'], {}), "(\n 'template_kin is deprecated and will be removed in a future version.',\n DeprecationWarning)\n", (2702, 2802), False, 'import warnings\n'), ((11386, 11439), 'marvin.core.exceptions.MarvinError', 'marvin.core.exceptions.MarvinError', (['"""No db connected"""'], {}), "('No db connected')\n", (11420, 11439), False, 'import marvin\n'), ((11490, 11576), 'marvin.core.exceptions.MarvinError', 'marvin.core.exceptions.MarvinError', (['"""sqlalchemy required to access the local DB."""'], {}), "(\n 'sqlalchemy required to access the local DB.')\n", (11524, 11576), False, 'import marvin\n'), ((14519, 14594), 'marvin.core.exceptions.MarvinError', 'marvin.core.exceptions.MarvinError', (['"""remote maps has a different plateifu!"""'], {}), "('remote maps has a different plateifu!')\n", (14553, 14594), False, 'import marvin\n'), ((24280, 24382), 'marvin.core.exceptions.MarvinError', 'marvin.core.exceptions.MarvinError', (['"""stellar_sigmacorr is unreliable in MPL-6. Please use MPL-7."""'], {}), "(\n 'stellar_sigmacorr is unreliable in MPL-6. Please use MPL-7.')\n", (24314, 24382), False, 'import marvin\n'), ((29550, 29715), 'warnings.warn', 'warnings.warn', (['"""snr is deprecated. Use snr_min instead. snr will be removed in a future version of marvin"""', 'marvin.core.exceptions.MarvinDeprecationWarning'], {}), "(\n 'snr is deprecated. Use snr_min instead. snr will be removed in a future version of marvin'\n , marvin.core.exceptions.MarvinDeprecationWarning)\n", (29563, 29715), False, 'import warnings\n'), ((30342, 30375), 'marvin.utils.general.turn_off_ion', 'turn_off_ion', ([], {'show_plot': 'show_plot'}), '(show_plot=show_plot)\n', (30354, 30375), False, 'from marvin.utils.general import FuzzyDict, turn_off_ion, check_versions\n'), ((30402, 30510), 'marvin.utils.dap.bpt.bpt_kewley06', 'marvin.utils.dap.bpt.bpt_kewley06', (['self'], {'snr_min': 'snr_min', 'return_figure': 'do_return_figure', 'use_oi': 'use_oi'}), '(self, snr_min=snr_min, return_figure=\n do_return_figure, use_oi=use_oi)\n', (30435, 30510), False, 'import marvin\n'), ((4585, 4648), 'marvin.core.exceptions.MarvinError', 'marvin.core.exceptions.MarvinError', (['"""invalid type for getitem."""'], {}), "('invalid type for getitem.')\n", (4619, 4648), False, 'import marvin\n'), ((5503, 5537), 'copy.deepcopy', 'copy.deepcopy', (['self.plateifu', 'memo'], {}), '(self.plateifu, memo)\n', (5516, 5537), False, 'import copy\n'), ((5567, 5600), 'copy.deepcopy', 'copy.deepcopy', (['self.release', 'memo'], {}), '(self.release, memo)\n', (5580, 5600), False, 'import copy\n'), ((5630, 5663), 'copy.deepcopy', 'copy.deepcopy', (['self.bintype', 'memo'], {}), '(self.bintype, memo)\n', (5643, 5663), False, 'import copy\n'), ((5694, 5728), 'copy.deepcopy', 'copy.deepcopy', (['self.template', 'memo'], {}), '(self.template, memo)\n', (5707, 5728), False, 'import copy\n'), ((5761, 5797), 'copy.deepcopy', 'copy.deepcopy', (['self.nsa_source', 'memo'], {}), '(self.nsa_source, memo)\n', (5774, 5797), False, 'import copy\n'), ((13144, 13252), 'marvin.core.exceptions.MarvinError', 'marvin.core.exceptions.MarvinError', (['"""more than one Maps file found for this combination of parameters."""'], {}), "(\n 'more than one Maps file found for this combination of parameters.')\n", (13178, 13252), False, 'import marvin\n'), ((13332, 13429), 'marvin.core.exceptions.MarvinError', 'marvin.core.exceptions.MarvinError', (['"""no Maps file found for this combination of parameters."""'], {}), "(\n 'no Maps file found for this combination of parameters.')\n", (13366, 13429), False, 'import marvin\n'), ((31707, 31731), 'numpy.arange', 'np.arange', (['data.shape[1]'], {}), '(data.shape[1])\n', (31716, 31731), True, 'import numpy as np\n'), ((4921, 4955), 'inspect.getmembers', 'inspect.getmembers', (['self.__class__'], {}), '(self.__class__)\n', (4939, 4955), False, 'import inspect\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Test from the Marvin - Testing in Python wiki
# All tests inherit from cloudstackTestCase
from marvin.cloudstackTestCase import cloudstackTestCase
# Import Integration Libraries
# base - contains all resources as entities and defines create, delete,
# list operations on them
from marvin.lib.base import (Account,
VirtualMachine,
ServiceOffering,
NetworkOffering,
Network,
Template,
DiskOffering,
StoragePool,
Volume,
Host,
GuestOs)
# utils - utility classes for common cleanup, external library wrappers etc
from marvin.lib.utils import cleanup_resources, get_hypervisor_type, validateList
# common - commonly used methods for all tests are listed here
from marvin.lib.common import get_zone, get_domain, get_template, list_hosts, get_pod
from marvin.sshClient import SshClient
from marvin.codes import FAILED, PASS
from nose.plugins.attrib import attr
import xml.etree.ElementTree as ET
import code
import logging
class Templates:
"""Test data for templates
"""
def __init__(self):
self.templates = {
"kvmvirtioscsi": {
"kvm": {
"name": "tiny-kvm-scsi",
"displaytext": "virtio-scsi kvm",
"format": "qcow2",
"hypervisor": "kvm",
"ostype": "Other PV Virtio-SCSI (64-bit)",
"url": "http://dl.openvm.eu/cloudstack/ubuntu/x86_64/ubuntu-16.04-kvm.qcow2.bz2",
"requireshvm": True,
"ispublic": True,
"passwordenabled": True
}
}
}
class TestDeployVirtioSCSIVM(cloudstackTestCase):
"""
Test deploy a kvm virtio scsi template
"""
@classmethod
def setUpClass(cls):
cls.logger = logging.getLogger('TestDeployVirtioSCSIVM')
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
testClient = super(TestDeployVirtioSCSIVM, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
cls.hostConfig = cls.config.__dict__["zones"][0].__dict__["pods"][0].__dict__["clusters"][0].__dict__["hosts"][0].__dict__
cls.hypervisorNotSupported = False
cls.hypervisor = testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.pod = get_pod(cls.apiclient, cls.zone.id)
cls.services['mode'] = cls.zone.networktype
cls._cleanup = []
if cls.hypervisor.lower() not in ['kvm']:
cls.hypervisorNotSupported = True
return
kvmvirtioscsi = Templates().templates["kvmvirtioscsi"]
cls.template = Template.register(
cls.apiclient,
kvmvirtioscsi[cls.hypervisor.lower()],
cls.zone.id,
hypervisor=cls.hypervisor.lower(),
domainid=cls.domain.id)
cls.template.download(cls.apiclient)
if cls.template == FAILED:
assert False, "get_template() failed to return template"
cls.services["domainid"] = cls.domain.id
cls.services["small"]["zoneid"] = cls.zone.id
cls.services["zoneid"] = cls.zone.id
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id
)
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["small"]
)
cls.sparse_disk_offering = DiskOffering.create(
cls.apiclient,
cls.services["sparse_disk_offering"]
)
cls.virtual_machine = VirtualMachine.create(
cls.apiclient,
cls.services["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
zoneid=cls.zone.id,
serviceofferingid=cls.service_offering.id,
diskofferingid=cls.sparse_disk_offering.id,
mode=cls.zone.networktype
)
hosts = Host.list(cls.apiclient, id=cls.virtual_machine.hostid)
if len(hosts) != 1:
assert False, "Could not find host with id " + cls.virtual_machine.hostid
cls.vmhost = hosts[0]
password = cls.virtual_machine.resetPassword(cls.apiclient)
cls.virtual_machine.username = "ubuntu"
cls.virtual_machine.password = password
cls._cleanup = [
cls.template,
cls.service_offering,
cls.sparse_disk_offering,
cls.account
]
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
# Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def verifyVirshState(self, diskcount):
host = self.vmhost.ipaddress
instancename = self.virtual_machine.instancename
virshxml = self.getVirshXML(host, instancename)
root = ET.fromstring(virshxml)
scsis = root.findall("./devices/controller[@type='scsi']/alias[@name='scsi0']/..")
self.assertEqual(len(scsis), 1, "SCSI controller not found")
scsiindex = scsis[0].get('index')
self.assertNotEqual(scsiindex, None, "Could not find index of SCSI controller")
# find all scsi disks
disks = root.findall("./devices/disk[@device='disk']/target[@bus='scsi']/..")
self.assertEqual(len(disks), diskcount, "Could not find expected number of disks")
for disk in disks:
for child in disk:
if child.tag.lower() == "target":
dev = child.get("dev")
self.assert_(dev != None and dev.startswith("sd"), "disk dev is invalid")
elif child.tag.lower() == "address":
con = child.get("controller")
self.assertEqual(con, scsiindex, "disk controller not equal to SCSI " \
"controller index")
elif child.tag.lower() == "driver":
discard = child.get("discard")
self.assertEqual(discard, "unmap", "discard settings not unmap")
def verifyGuestState(self, diskcount):
ssh = self.virtual_machine.get_ssh_client(reconnect=True)
output = ssh.execute("lspci | grep \"Virtio SCSI\"")
self.assertTrue(len(output) > 0, "Could not find virtio scsi controller")
output = ssh.execute("lsblk -rS | grep sd")
for disk in output:
self.logger.debug("disk " + disk + " found")
self.assertEqual(len(output), diskcount,
"Could not find appropriate number of scsi disks in guest")
def getVirshXML(self, host, instancename):
if host == None:
self.logger.debug("getVirshXML: host is none")
return ""
else:
self.logger.debug("host is: " + host)
if instancename == None:
self.logger.debug("getVirshXML: instancename is none")
return ""
else:
self.logger.debug("instancename is: " + instancename)
sshc = SshClient(
host=host,
port=self.services['configurableData']['host']["publicport"],
user=self.hostConfig['username'],
passwd=self.hostConfig['password'])
ssh = sshc.ssh
chan = ssh.get_transport().open_session()
chan.exec_command("virsh dumpxml " + instancename)
stdout = ""
while True:
b = chan.recv(10000)
if len(b) == 0:
break
stdout += b
stderr = ""
while True:
b = chan.recv_stderr(10000)
if len(b) == 0:
break
stderr += b
xstatus = chan.recv_exit_status()
chan.close()
if xstatus != 0:
raise CommandNonzeroException(xstatus, stderr)
# rely on sshClient to close ssh
self.logger.debug("xml is: \n\n%s\n\n" % (stdout))
return stdout
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_01_verify_libvirt(self):
"""Test that libvirt properly created domain with scsi controller
"""
# Validate virsh dumpxml
if self.hypervisorNotSupported:
self.skipTest("Hypervisor not supported")
self.verifyVirshState(2)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_02_verify_libvirt_after_restart(self):
""" Verify that libvirt settings are as expected after a VM stop / start
"""
if self.hypervisorNotSupported:
self.skipTest("Hypervisor not supported")
self.virtual_machine.stop(self.apiclient)
self.virtual_machine.start(self.apiclient)
self.verifyVirshState(2)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_03_verify_libvirt_attach_disk(self):
""" Verify that libvirt settings are expected after a disk add
"""
if self.hypervisorNotSupported:
self.skipTest("Hypervisor not supported")
self.volume = Volume.create(
self.apiclient,
self.services,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid,
diskofferingid=self.sparse_disk_offering.id
)
self.virtual_machine.attach_volume(
self.apiclient,
self.volume
)
self.verifyVirshState(3)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_04_verify_guest_lspci(self):
""" Verify that guest sees scsi controller and disks
"""
if self.hypervisorNotSupported:
self.skipTest("Hypervisor not supported")
self.verifyGuestState(3)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_05_change_vm_ostype_restart(self):
""" Update os type to Ubuntu, change vm details rootdiskController
explicitly to scsi.
"""
if self.hypervisorNotSupported:
self.skipTest("Hypervisor not supported")
self.virtual_machine.stop(self.apiclient)
ostypes = GuestOs.listMapping(self.apiclient, hypervisor="kvm")
self.assertTrue(len(ostypes) > 0)
ostypeid = None
for ostype in ostypes:
if ostype.osdisplayname == "Ubuntu 16.04 (64-bit)":
ostypeid = ostype.ostypeid
break
self.assertIsNotNone(ostypeid,
"Could not find ostypeid for Ubuntu 16.0.4 (64-bit) mapped to kvm")
self.virtual_machine.update(self.apiclient, ostypeid=ostypeid,
details=[{"rootDiskController":"scsi"}])
self.virtual_machine.start(self.apiclient)
self.verifyVirshState(3)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_06_verify_guest_lspci_again(self):
""" Verify that guest sees scsi controller and disks after switching ostype and rdc
"""
if self.hypervisorNotSupported:
self.skipTest("Hypervisor not supported")
self.verifyGuestState(3)
class CommandNonzeroException(Exception):
def __init__(self, code, stderr):
self.code = code
self.stderr = stderr
def __str__(self):
return "Status code %d: %s" % (self.code, self.stderr)
| [
"marvin.lib.base.GuestOs.listMapping",
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.DiskOffering.create",
"marvin.lib.common.get_pod",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.Host.list",
"marvin.lib.bas... | [((9926, 9998), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (9930, 9998), False, 'from nose.plugins.attrib import attr\n'), ((10291, 10363), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (10295, 10363), False, 'from nose.plugins.attrib import attr\n'), ((10745, 10817), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (10749, 10817), False, 'from nose.plugins.attrib import attr\n'), ((11467, 11539), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (11471, 11539), False, 'from nose.plugins.attrib import attr\n'), ((11790, 11862), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (11794, 11862), False, 'from nose.plugins.attrib import attr\n'), ((12853, 12925), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (12857, 12925), False, 'from nose.plugins.attrib import attr\n'), ((2843, 2886), 'logging.getLogger', 'logging.getLogger', (['"""TestDeployVirtioSCSIVM"""'], {}), "('TestDeployVirtioSCSIVM')\n", (2860, 2886), False, 'import logging\n'), ((2916, 2939), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2937, 2939), False, 'import logging\n'), ((3517, 3542), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (3527, 3542), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_hosts, get_pod\n'), ((3634, 3669), 'marvin.lib.common.get_pod', 'get_pod', (['cls.apiclient', 'cls.zone.id'], {}), '(cls.apiclient, cls.zone.id)\n', (3641, 3669), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_hosts, get_pod\n'), ((4475, 4553), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (4489, 4553), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NetworkOffering, Network, Template, DiskOffering, StoragePool, Volume, Host, GuestOs\n'), ((4632, 4718), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['small']"], {}), "(cls.apiclient, cls.services['service_offerings'][\n 'small'])\n", (4654, 4718), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NetworkOffering, Network, Template, DiskOffering, StoragePool, Volume, Host, GuestOs\n'), ((4785, 4857), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.apiclient', "cls.services['sparse_disk_offering']"], {}), "(cls.apiclient, cls.services['sparse_disk_offering'])\n", (4804, 4857), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NetworkOffering, Network, Template, DiskOffering, StoragePool, Volume, Host, GuestOs\n'), ((4923, 5216), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'zoneid': 'cls.zone.id', 'serviceofferingid': 'cls.service_offering.id', 'diskofferingid': 'cls.sparse_disk_offering.id', 'mode': 'cls.zone.networktype'}), "(cls.apiclient, cls.services['small'], templateid=cls.\n template.id, accountid=cls.account.name, domainid=cls.account.domainid,\n zoneid=cls.zone.id, serviceofferingid=cls.service_offering.id,\n diskofferingid=cls.sparse_disk_offering.id, mode=cls.zone.networktype)\n", (4944, 5216), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NetworkOffering, Network, Template, DiskOffering, StoragePool, Volume, Host, GuestOs\n'), ((5339, 5394), 'marvin.lib.base.Host.list', 'Host.list', (['cls.apiclient'], {'id': 'cls.virtual_machine.hostid'}), '(cls.apiclient, id=cls.virtual_machine.hostid)\n', (5348, 5394), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NetworkOffering, Network, Template, DiskOffering, StoragePool, Volume, Host, GuestOs\n'), ((6823, 6846), 'xml.etree.ElementTree.fromstring', 'ET.fromstring', (['virshxml'], {}), '(virshxml)\n', (6836, 6846), True, 'import xml.etree.ElementTree as ET\n'), ((8995, 9157), 'marvin.sshClient.SshClient', 'SshClient', ([], {'host': 'host', 'port': "self.services['configurableData']['host']['publicport']", 'user': "self.hostConfig['username']", 'passwd': "self.hostConfig['password']"}), "(host=host, port=self.services['configurableData']['host'][\n 'publicport'], user=self.hostConfig['username'], passwd=self.hostConfig\n ['password'])\n", (9004, 9157), False, 'from marvin.sshClient import SshClient\n'), ((11068, 11247), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', 'self.services'], {'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'diskofferingid': 'self.sparse_disk_offering.id'}), '(self.apiclient, self.services, zoneid=self.zone.id, account=\n self.account.name, domainid=self.account.domainid, diskofferingid=self.\n sparse_disk_offering.id)\n', (11081, 11247), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NetworkOffering, Network, Template, DiskOffering, StoragePool, Volume, Host, GuestOs\n'), ((12193, 12246), 'marvin.lib.base.GuestOs.listMapping', 'GuestOs.listMapping', (['self.apiclient'], {'hypervisor': '"""kvm"""'}), "(self.apiclient, hypervisor='kvm')\n", (12212, 12246), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NetworkOffering, Network, Template, DiskOffering, StoragePool, Volume, Host, GuestOs\n'), ((5973, 6019), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (5990, 6019), False, 'from marvin.lib.utils import cleanup_resources, get_hypervisor_type, validateList\n'), ((6445, 6492), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (6462, 6492), False, 'from marvin.lib.utils import cleanup_resources, get_hypervisor_type, validateList\n')] |
# !usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2017-04-06 15:30:50
# @Last modified by: <NAME>
# @Last Modified time: 2018-04-03 16:08:48
from __future__ import print_function, division, absolute_import
import os
import pytest
import requests
from flask import url_for
from selenium import webdriver
from marvin.web import create_app
from tests.web.frontend.live_server import live_server
from marvin.web.settings import TestConfig, CustomConfig
browserstack = os.environ.get('USE_BROWSERSTACK', None)
if browserstack:
osdict = {'OS X': ['El Capitan', 'Sierra']}
browserdict = {'chrome': ['55', '54'], 'firefox': ['52', '51'], 'safari': ['10', '9.1']}
else:
osdict = {'OS X': ['El Capitan']}
browserdict = {'chrome': ['55']}
osstuff = [(k, i) for k, v in osdict.items() for i in v]
browserstuff = [(k, i) for k, v in browserdict.items() for i in v]
@pytest.fixture(params=osstuff)
def osinfo(request):
return request.param
@pytest.fixture(params=browserstuff)
def browserinfo(request):
return request.param
@pytest.fixture(scope='session')
def app():
object_config = type('Config', (TestConfig, CustomConfig), dict())
app = create_app(debug=True, local=True, object_config=object_config)
# app = create_app(debug=True, local=True, use_profiler=False)
# app.config['TESTING'] = True
# app.config['WTF_CSRF_ENABLED'] = False
# app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
app.config['LIVESERVER_PORT'] = 8443
return app
@pytest.fixture(scope='function')
def base_url(live_server):
url = live_server.url()
#url = url.replace('localhost', '127.0.0.1')
return '{0}/marvin/'.format(url)
@pytest.fixture(scope='function')
def driver(base_url, osinfo, browserinfo):
ostype, os_version = osinfo
browser, browser_version = browserinfo
buildid = '{0}_{1}_{2}_{3}'.format(ostype.lower().replace(' ', '_'),
os_version.lower().replace(' ', '_'), browser, browser_version)
# skip some combinations
if os_version == 'Sierra' and browser == 'safari' and browser_version == '9.1':
pytest.skip('cannot have Sierra running safari 9.1')
elif os_version == 'El Capitan' and browser == 'safari' and browser_version == '10':
pytest.skip('cannot have El Capitan running safari 10')
# set driver
if browserstack:
username = os.environ.get('BROWSERSTACK_USER', None)
access = os.environ.get('BROWSERSTACK_ACCESS_KEY', None)
desired_cap = {'os': ostype, 'os_version': os_version, 'browser': browser, 'build': buildid,
'browser_version': browser_version, 'project': 'marvin', 'resolution': '1920x1080'}
desired_cap['browserstack.local'] = True
desired_cap['browserstack.debug'] = True
desired_cap['browserstack.localIdentifier'] = os.environ['BROWSERSTACK_LOCAL_IDENTIFIER']
driver = webdriver.Remote(
command_executor='http://{0}:{1}@hub.browserstack.com:80/wd/hub'.format(username, access),
desired_capabilities=desired_cap)
else:
if browser == 'chrome':
driver = webdriver.Chrome()
elif browser == 'firefox':
driver = webdriver.Firefox()
elif browser == 'safari':
driver = webdriver.Safari()
driver.get(base_url)
yield driver
# teardown
driver.quit()
@pytest.mark.usefixtures('live_server')
class TestLiveServer(object):
def test_server_is_up_and_running(self, base_url):
response = requests.get(base_url)
assert response.status_code == 200
| [
"marvin.web.create_app"
] | [((539, 579), 'os.environ.get', 'os.environ.get', (['"""USE_BROWSERSTACK"""', 'None'], {}), "('USE_BROWSERSTACK', None)\n", (553, 579), False, 'import os\n'), ((949, 979), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'osstuff'}), '(params=osstuff)\n', (963, 979), False, 'import pytest\n'), ((1029, 1064), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'browserstuff'}), '(params=browserstuff)\n', (1043, 1064), False, 'import pytest\n'), ((1119, 1150), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1133, 1150), False, 'import pytest\n'), ((1571, 1603), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1585, 1603), False, 'import pytest\n'), ((1748, 1780), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1762, 1780), False, 'import pytest\n'), ((3466, 3504), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""live_server"""'], {}), "('live_server')\n", (3489, 3504), False, 'import pytest\n'), ((1243, 1306), 'marvin.web.create_app', 'create_app', ([], {'debug': '(True)', 'local': '(True)', 'object_config': 'object_config'}), '(debug=True, local=True, object_config=object_config)\n', (1253, 1306), False, 'from marvin.web import create_app\n'), ((1641, 1658), 'tests.web.frontend.live_server.live_server.url', 'live_server.url', ([], {}), '()\n', (1656, 1658), False, 'from tests.web.frontend.live_server import live_server\n'), ((2196, 2248), 'pytest.skip', 'pytest.skip', (['"""cannot have Sierra running safari 9.1"""'], {}), "('cannot have Sierra running safari 9.1')\n", (2207, 2248), False, 'import pytest\n'), ((2460, 2501), 'os.environ.get', 'os.environ.get', (['"""BROWSERSTACK_USER"""', 'None'], {}), "('BROWSERSTACK_USER', None)\n", (2474, 2501), False, 'import os\n'), ((2519, 2566), 'os.environ.get', 'os.environ.get', (['"""BROWSERSTACK_ACCESS_KEY"""', 'None'], {}), "('BROWSERSTACK_ACCESS_KEY', None)\n", (2533, 2566), False, 'import os\n'), ((3610, 3632), 'requests.get', 'requests.get', (['base_url'], {}), '(base_url)\n', (3622, 3632), False, 'import requests\n'), ((2346, 2401), 'pytest.skip', 'pytest.skip', (['"""cannot have El Capitan running safari 10"""'], {}), "('cannot have El Capitan running safari 10')\n", (2357, 2401), False, 'import pytest\n'), ((3218, 3236), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {}), '()\n', (3234, 3236), False, 'from selenium import webdriver\n'), ((3293, 3312), 'selenium.webdriver.Firefox', 'webdriver.Firefox', ([], {}), '()\n', (3310, 3312), False, 'from selenium import webdriver\n'), ((3368, 3386), 'selenium.webdriver.Safari', 'webdriver.Safari', ([], {}), '()\n', (3384, 3386), False, 'from selenium import webdriver\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for testing resize of root volume functionality
Test Plan: https://cwiki.apache.org/confluence/display/CLOUDSTACK/
Root+Resize+Support
Issue Link: https://issues.apache.org/jira/browse/CLOUDSTACK-9829
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.lib.base import (Account,
ServiceOffering,
VirtualMachine,
Resources,
Domain,
Volume,
Snapshot,
Template,
VmSnapshot,
Host,
Configurations,
StoragePool)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
matchResourceCount,
list_snapshots,
list_hosts,
list_configurations,
list_storage_pools)
from marvin.lib.utils import (cleanup_resources,
validateList)
from marvin.codes import (PASS,
FAIL,
FAILED,
RESOURCE_PRIMARY_STORAGE,
INVALID_INPUT)
from marvin.lib.utils import checkVolumeSize
import time
from marvin.sshClient import SshClient
class TestResizeVolume(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestResizeVolume, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.hypervisor = (cls.testClient.getHypervisorInfo()).lower()
cls.storageID = None
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(
cls.api_client,
cls.testClient.getZoneForTests())
cls.services["mode"] = cls.zone.networktype
cls._cleanup = []
cls.unsupportedStorageType = False
cls.unsupportedHypervisorType = False
cls.updateclone = False
if cls.hypervisor not in ['xenserver',"kvm","vmware"]:
cls.unsupportedHypervisorType=True
return
cls.template = get_template(
cls.api_client,
cls.zone.id
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.services["volume"]["zoneid"] = cls.zone.id
try:
cls.parent_domain = Domain.create(cls.api_client,
services=cls.services[
"domain"],
parentdomainid=cls.domain.id)
cls.parentd_admin = Account.create(cls.api_client,
cls.services["account"],
admin=True,
domainid=cls.parent_domain.id)
cls._cleanup.append(cls.parentd_admin)
cls._cleanup.append(cls.parent_domain)
list_pool_resp = list_storage_pools(cls.api_client,
account=cls.parentd_admin.name,domainid=cls.parent_domain.id)
res = validateList(list_pool_resp)
if res[2]== INVALID_INPUT:
raise Exception("Failed to list storage pool-no storagepools found ")
#Identify the storage pool type and set vmware fullclone to true if storage is VMFS
if cls.hypervisor == 'vmware':
for strpool in list_pool_resp:
if strpool.type.lower() == "vmfs" or strpool.type.lower()== "networkfilesystem":
list_config_storage_response = list_configurations(
cls.api_client
, name=
"vmware.create.full.clone",storageid=strpool.id)
res = validateList(list_config_storage_response)
if res[2]== INVALID_INPUT:
raise Exception("Failed to list configurations ")
if list_config_storage_response[0].value == "false":
Configurations.update(cls.api_client,
"vmware.create.full.clone",
value="true",storageid=strpool.id)
cls.updateclone = True
StoragePool.update(cls.api_client,id=strpool.id,tags="scsi")
cls.storageID = strpool.id
cls.unsupportedStorageType = False
break
else:
cls.unsupportedStorageType = True
# Creating service offering with normal config
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"])
cls.services_offering_vmware=ServiceOffering.create(
cls.api_client,cls.services["service_offering"],tags="scsi")
cls._cleanup.extend([cls.service_offering,cls.services_offering_vmware])
except Exception as e:
cls.tearDownClass()
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
if cls.updateclone:
Configurations.update(cls.api_client,
"vmware.create.full.clone",
value="false",storageid=cls.storageID)
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
if self.unsupportedStorageType:
self.skipTest("Tests are Skipped - unsupported Storage type used ")
elif self.unsupportedHypervisorType:
self.skipTest("Tests are Skipped - unsupported Hypervisor type used")
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
# Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.apiclient, self.cleanup)
pass
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def updateResourceLimits(self, accountLimit=None, domainLimit=None):
"""Update primary storage limits of the parent domain and its
child domains"""
try:
if domainLimit:
# Update resource limit for domain
Resources.updateLimit(self.apiclient, resourcetype=10,
max=domainLimit,
domainid=self.parent_domain.id)
if accountLimit:
# Update resource limit for domain
Resources.updateLimit(self.apiclient,
resourcetype=10,
max=accountLimit,
account=self.parentd_admin.name,
domainid=self.parent_domain.id)
except Exception as e:
return [FAIL, e]
return [PASS, None]
def setupAccounts(self):
try:
self.parent_domain = Domain.create(self.apiclient,
services=self.services[
"domain"],
parentdomainid=self.domain.id)
self.parentd_admin = Account.create(self.apiclient,
self.services["account"],
admin=True,
domainid=self.parent_domain.id)
# Cleanup the resources created at end of test
self.cleanup.append(self.parent_domain)
self.cleanup.append(self.parentd_admin)
except Exception as e:
return [FAIL, e]
return [PASS, None]
def chk_volume_resize(self, apiclient, vm):
self.assertEqual(
vm.state,
"Running",
msg="VM is not in Running state"
)
# get root vol from created vm, verify its size
list_volume_response = Volume.list(
apiclient,
virtualmachineid=vm.id,
type='ROOT',
listall='True'
)
rootvolume = list_volume_response[0]
if vm.state == "Running" and vm.hypervisor.lower() == "xenserver":
self.virtual_machine.stop(apiclient)
time.sleep(self.services["sleep"])
if vm.hypervisor.lower() == "vmware":
rootdiskcontroller = self.getDiskController(vm)
if rootdiskcontroller!="scsi":
raise Exception("root volume resize only supported on scsi disk ,"
"please check rootdiskcontroller type")
rootvolobj = Volume(rootvolume.__dict__)
newsize = (rootvolume.size >> 30) + 2
success = False
if rootvolume is not None:
try:
rootvolobj.resize(apiclient, size=newsize)
if vm.hypervisor.lower() == "xenserver":
self.virtual_machine.start(apiclient)
time.sleep(self.services["sleep"])
ssh = SshClient(self.virtual_machine.ssh_ip, 22,
"root", "password")
newsizeinbytes = newsize * 1024 * 1024 * 1024
if vm.hypervisor.lower() == "xenserver":
volume_name = "/dev/xvd" + \
chr(ord('a') +
int(
list_volume_response[0].deviceid))
self.debug(" Using XenServer"
" volume_name: %s" % volume_name)
ret = checkVolumeSize(ssh_handle=ssh,
volume_name=volume_name,
size_to_verify=newsizeinbytes)
success = True
elif vm.hypervisor.lower() == "kvm":
volume_name = "/dev/vd" + chr(ord('a') + int
(list_volume_response[0]
.deviceid))
self.debug(" Using KVM volume_name:"
" %s" % volume_name)
ret = checkVolumeSize(ssh_handle=ssh,
volume_name=volume_name,
size_to_verify=newsizeinbytes)
success = True
elif vm.hypervisor.lower() == "vmware":
ret = checkVolumeSize(ssh_handle=ssh,
volume_name="/dev/sdb",
size_to_verify=newsizeinbytes)
success = True
self.debug(" Volume Size Expected %s "
" Actual :%s" % (newsizeinbytes, ret[1]))
except Exception as e:
# need to write the rootdisk controller code.
if vm.hypervisor == "vmware" and rootdiskcontroller == "ide":
assert "Found unsupported root disk " \
"controller :ide" in e.message, \
"able to resize ide root volume Testcase failed"
else:
raise Exception("fail to resize the volume: %s" % e)
else:
self.debug("hypervisor %s unsupported for test "
", verifying it errors properly" % self.hypervisor)
success = False
return success
def getDiskController(self, vm, diskcontroller="ide"):
if vm.hypervisor.lower() == "vmware":
try:
qresultvmuuid = self.dbclient.execute(
"select id from vm_instance where uuid = '%s' ;" %
vm.id
)
self.assertNotEqual(
len(qresultvmuuid),
0,
"Check DB Query result set"
)
vmid = int(qresultvmuuid[0][0])
qresult = self.dbclient.execute(
"select rootDiskController from"
" user_vm_details where id = '%s';" % vmid
)
self.debug("Query result: %s" % qresult)
diskcontroller = qresult[0][0]
except Exception as e:
raise Exception("Warning: Exception while"
" checking usage event for the "
"root_volume_resize : %s" % e)
return diskcontroller
@attr(tags=["advanced"], required_hardware="true")
def test_01_create__snapshot_new_resized_rootvolume_size(self):
"""Test create snapshot on resized root volume
# Validate the following
# 1. Deploy a VM without any disk offering (only root disk)
# 2. Perform(resize) of the root volume
# 3. Perform snapshot on resized volume
"""
# deploy a vm
try:
if self.updateclone:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.services_offering_vmware.id,
mode=self.zone.networktype
)
else:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id,
mode=self.zone.networktype
)
# listVirtual machine
list_vms = VirtualMachine.list(self.apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s" %
self.virtual_machine.id
)
res = validateList(list_vms)
self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
vm = list_vms[0]
self.assertEqual(
vm.id,
self.virtual_machine.id,
"Virtual Machine ids do not match"
)
self.assertEqual(
vm.name,
self.virtual_machine.name,
"Virtual Machine names do not match"
)
self.assertEqual(
vm.state,
"Running",
msg="VM is not in Running state"
)
result = self.chk_volume_resize(self.apiclient, vm)
if result:
# get root vol from created vm, verify it is correct size
list_volume_response = Volume.list(
self.apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
res = validateList(list_volume_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
rootvolume = list_volume_response[0]
self.debug("Creating a Snapshot from root volume: "
"%s" % rootvolume.id)
snapshot = Snapshot.create(
self.apiclient,
rootvolume.id,
account=self.parentd_admin.name,
domainid=self.parent_domain.id
)
snapshots = list_snapshots(
self.apiclient,
id=snapshot.id
)
res = validateList(snapshots)
self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
self.assertEqual(
snapshots[0].id,
snapshot.id,
"Check resource id in list resources call"
)
else:
self.debug("Volume resize is failed")
except Exception as e:
raise Exception("Exception while performing"
" the snapshot on resized root volume"
" test case: %s" % e)
self.cleanup.append(self.virtual_machine)
self.cleanup.append(snapshot)
return
@attr(tags=["advanced"], required_hardware="true")
def test_02_create__template_new_resized_rootvolume_size(self):
"""Test create Template resized root volume
# Validate the following
# 1. Deploy a VM without any disk offering (only root disk)
# 2. Perform(resize) of the root volume
# 3. Stop the vm
# 4. Create a template from resized root volume
"""
result = self.setupAccounts()
self.assertEqual(result[0], PASS, result[1])
apiclient = self.testClient.getUserApiClient(
UserName=self.parentd_admin.name,
DomainName=self.parentd_admin.domain)
self.assertNotEqual(apiclient, FAILED, "Failed to get api client\
of account: %s" % self.parentd_admin.name)
# deploy a vm
try:
if self.updateclone:
self.virtual_machine = VirtualMachine.create(
apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.services_offering_vmware.id,
mode=self.zone.networktype
)
else:
self.virtual_machine = VirtualMachine.create(
apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id,
mode=self.zone.networktype
)
# listVirtual macine
list_vms = VirtualMachine.list(apiclient,
id=self.virtual_machine.id)
self.debug("Verify listVirtualMachines response"
" for virtual machine: %s" % self.virtual_machine.id
)
res = validateList(list_vms)
self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
self.cleanup.append(self.virtual_machine)
vm = list_vms[0]
self.assertEqual(
vm.id,
self.virtual_machine.id,
"Virtual Machine ids do not match"
)
self.assertEqual(
vm.name,
self.virtual_machine.name,
"Virtual Machine names do not match"
)
self.assertEqual(
vm.state,
"Running",
msg="VM is not in Running state"
)
# get root vol from created vm, verify it is correct size
list_volume_response = Volume.list(
apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
res = validateList(list_volume_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
rootvolume = list_volume_response[0]
newsize = (rootvolume.size >> 30) + 2
result = self.chk_volume_resize(apiclient, vm)
if result:
try:
# create a template from stopped VM instances root volume
if vm.state == "Running":
self.virtual_machine.stop(apiclient)
template_from_root = Template.create(
apiclient,
self.services["template"],
volumeid=rootvolume.id,
account=self.parentd_admin.name,
domainid=self.parent_domain.id)
list_template_response = Template.list(
apiclient,
id=template_from_root.id,
templatefilter="all")
res = validateList(list_template_response)
self.assertNotEqual(res[2], INVALID_INPUT, "Check if template exists in ListTemplates")
# Deploy new virtual machine using template
self.virtual_machine2 = VirtualMachine.create(
apiclient,
self.services["virtual_machine"],
templateid=template_from_root.id,
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id,
)
vm_response = VirtualMachine.list(
apiclient,
id=self.virtual_machine2.id,
account=self.parentd_admin.name,
domainid=self.parent_domain.id
)
res = validateList(vm_response)
self.assertNotEqual(res[2], INVALID_INPUT, "Check for list VM response return valid list")
self.cleanup.append(self.virtual_machine2)
self.cleanup.reverse()
vm2 = vm_response[0]
self.assertEqual(
vm2.state,
'Running',
"Check the state of VM created from Template"
)
list_volume_response = Volume.list(
apiclient,
virtualmachineid=vm2.id,
type='ROOT',
listall='True'
)
self.assertEqual(
list_volume_response[0].size,
(newsize * 1024 * 1024 * 1024),
"Check for root volume size not matched with template size"
)
except Exception as e:
raise Exception("Exception while resizing the "
"root volume: %s" % e)
else:
self.debug(" volume resize failed for root volume")
except Exception as e:
raise Exception("Exception while performing"
" template creation from "
"resized_root_volume : %s" % e)
return
# @attr(tags=["advanced"], required_hardware="true")
@attr(tags=["TODO"], required_hardware="true")
def test_03_vmsnapshot__on_resized_rootvolume_vm(self):
"""Test vmsnapshot on resized root volume
# Validate the following
# 1. Deploy a VM without any disk offering (only root disk)
# 2. Perform(resize) of the root volume
# 3. Perform VM snapshot on VM
"""
# deploy a vm
try:
if self.updateclone:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.services_offering_vmware.id,
mode=self.zone.networktype
)
else:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id,
mode=self.zone.networktype
)
# listVirtual macine
list_vms = VirtualMachine.list(self.apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s" \
% self.virtual_machine.id
)
res = validateList(list_vms)
self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
self.cleanup.append(self.virtual_machine)
vm = list_vms[0]
self.assertEqual(
vm.id,
self.virtual_machine.id,
"Virtual Machine ids do not match"
)
# get root vol from created vm, verify it is correct size
list_volume_response = Volume.list(
self.apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
res = validateList(list_volume_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
rootvolume = list_volume_response[0]
newsize = (rootvolume.size >> 30) + 2
result = self.chk_volume_resize(self.apiclient, vm)
if result:
try:
if 'kvm' in self.hypervisor.lower():
self.virtual_machine.stop(self.apiclient)
virtualmachine_snapshot = VmSnapshot.create \
(self.apiclient, self.virtual_machine.id)
virtulmachine_snapshot_list = VmSnapshot. \
list(self.apiclient,
vmsnapshotid=virtualmachine_snapshot.id)
status = validateList(virtulmachine_snapshot_list)
self.assertEqual(
PASS,
status[0],
"Listing of configuration failed")
self.assertEqual(virtualmachine_snapshot.id,
virtulmachine_snapshot_list[0].id,
"Virtual Machine Snapshot id do not match")
except Exception as e:
raise Exception("Issue CLOUDSTACK-10080: Exception while performing"
" vmsnapshot: %s" % e)
else:
self.debug("volume resize failed for root volume")
except Exception as e:
raise Exception("Exception while performing"
" vmsnapshot on resized volume Test: %s" % e)
@attr(tags=["advanced"], required_hardware="true")
def test_04_vmreset_after_migrate_vm__rootvolume_resized(self):
"""Test migrate vm after root volume resize
# Validate the following
# 1. Deploy a VM without any disk offering (only root disk)
# 2. Perform(resize) of the root volume
# 3. migrate vm from host to another
# 4. perform vm reset after vm migration
"""
try:
if self.updateclone:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.services_offering_vmware.id,
mode=self.zone.networktype
)
else:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id,
mode=self.zone.networktype
)
# listVirtual macine
list_vms = VirtualMachine.list(self.apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s" \
% self.virtual_machine.id
)
res = validateList(list_vms)
self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
self.cleanup.append(self.virtual_machine)
vm = list_vms[0]
self.assertEqual(
vm.id,
self.virtual_machine.id,
"Virtual Machine ids do not match"
)
# get root vol from created vm, verify it is correct size
list_volume_response = Volume.list(
self.apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
res = validateList(list_volume_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
rootvolume = list_volume_response[0]
result = self.chk_volume_resize(self.apiclient, vm)
if result:
try:
list_host_response = list_hosts(
self.apiclient,
id=self.virtual_machine.hostid
)
res = validateList(list_host_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listHosts returned invalid object in response")
sourcehost = list_host_response[0]
try:
self.list_hosts_suitable = Host.listForMigration \
(self.apiclient,
virtualmachineid=self.virtual_machine.id
)
except Exception as e:
self.debug("Not found suitable host")
raise Exception("Exception while getting hosts"
" list suitable for migration: %s" % e)
self.virtualmachine_migrate_response = \
self.virtual_machine.migrate(
self.apiclient,
self.list_hosts_suitable[0].id)
list_vms = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id,
hostid=self.list_hosts_suitable[0].id)
res = validateList(list_vms)
self.assertNotEqual(res[2], INVALID_INPUT, "listVirtualMachines returned "
"invalid object in response")
self.virtual_machine_reset = self.virtual_machine.restore \
(self.apiclient,
self.services["virtual_machine"]["template"])
list_restorevolume_response = Volume.list(
self.apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
restorerootvolume = list_restorevolume_response[0]
self.assertEqual(rootvolume.size, restorerootvolume.size,
"root volume and restore root"
" volume size differs - CLOUDSTACK-10079")
except Exception as e:
raise Exception("Warning: Exception "
"during VM migration: %s" % e)
except Exception as e:
raise Exception("Warning: Exception during executing"
" the test-migrate_vm_after_rootvolume_resize: %s" % e)
return
@attr(tags=["advanced"], required_hardware="true")
def test_5_vmdeployment_with_size(self):
"""Test vm deployment with new rootdisk size parameter
# Validate the following
# 1. Deploy a VM without any disk offering (only root disk)
# 2. Verify the root disksize after deployment
"""
templateSize = (self.template.size / (1024 ** 3))
newsize = templateSize + 2
# deploy a vm
try:
if self.updateclone:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.services_offering_vmware.id,
mode=self.zone.networktype
)
else:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id,
mode=self.zone.networktype
)
# listVirtual macine
list_vms = VirtualMachine.list(self.apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s"
% self.virtual_machine.id
)
res = validateList(list_vms)
self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
self.cleanup.append(self.virtual_machine)
vm = list_vms[0]
ssh = SshClient(self.virtual_machine.ssh_ip, 22, "root",
"password")
newsize = newsize * 1024 * 1024 * 1024
list_volume_response = Volume.list(
self.apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
res = validateList(list_volume_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
if vm.hypervisor.lower() == "xenserver":
volume_name = "/dev/xvd" + chr(ord('a') + int(
list_volume_response[0].deviceid))
self.debug(" Using XenServer"
" volume_name: %s" % volume_name)
ret = checkVolumeSize(ssh_handle=ssh,
volume_name=volume_name,
size_to_verify=newsize)
elif vm.hypervisor.lower() == "kvm":
volume_name = "/dev/vd" + chr(ord('a')
+ int(
list_volume_response[0].deviceid))
self.debug(" Using KVM volume_name: %s" % volume_name)
ret = checkVolumeSize(ssh_handle=ssh,
volume_name=volume_name,
size_to_verify=newsize)
elif vm.hypervisor.lower() == "vmware":
ret = checkVolumeSize(ssh_handle=ssh,
volume_name="/dev/sdb",
size_to_verify=newsize)
self.debug(" Volume Size Expected %s"
" Actual :%s" % (newsize, ret[1]))
except Exception as e:
raise Exception("Warning: Exception during"
" VM deployment with new"
" rootdisk paramter : %s" % e)
@attr(tags=["advanced"], required_hardware="true")
def test_6_resized_rootvolume_with_lessvalue(self):
"""Test resize root volume with less than original volume size
# Validate the following
# 1. Deploy a VM without any disk offering (only root disk)
# 2. Perform(resize) of the root volume with less
than current root volume
# 3. Check for proper error message
"""
# deploy a vm
try:
if self.updateclone:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.services_offering_vmware.id,
mode=self.zone.networktype
)
else:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id,
mode=self.zone.networktype
)
# listVirtual macine
time.sleep(self.services["sleep"])
list_vms = VirtualMachine.list(self.apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s" \
% self.virtual_machine.id
)
res = validateList(list_vms)
self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
self.cleanup.append(self.virtual_machine)
vm = list_vms[0]
self.assertEqual(
vm.id,
self.virtual_machine.id,
"Virtual Machine ids do not match"
)
# get root vol from created vm, verify it is correct size
list_volume_response = Volume.list(
self.apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
res = validateList(list_volume_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
if vm.state == "Running" and vm.hypervisor.lower() == "xenserver":
self.virtual_machine.stop(self.apiclient)
time.sleep(self.services["sleep"])
rootvolume = list_volume_response[0]
# converting json response to Volume Object
rootvol = Volume(rootvolume.__dict__)
newsize = (rootvolume.size >> 30) - 1
success = False
if rootvolume is not None and 'vmware' in vm.hypervisor.lower():
try:
rootvol.resize(self.apiclient, size=newsize)
except Exception as e:
assert "Shrink operation on ROOT volume not supported" \
in e.message, \
"TestCase Failed,able to resize root volume or error message is not matched"
except Exception as e:
raise Exception("Warning: Exception "
"during executing test resize"
" volume with less value : %s" % e)
if rootvol is not None and 'kvm' or 'xenserver' in vm.hypervisor.lower():
rootvol.resize(self.apiclient, size=newsize)
# @attr(tags=["advanced"], required_hrdware="true")
@attr(tags=["TODO"], required_hrdware="true")
def test_7_usage_events_after_rootvolume_resized_(self):
"""Test check usage events after root volume resize
# Validate the following
# 1. Deploy a VM without any disk offering (only root disk)
# 2. Perform(resize) of the root volume
# 3. Check the corresponding usage events
"""
# deploy a vm
try:
if self.updateclone:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.services_offering_vmware.id,
mode=self.zone.networktype
)
else:
self.virtual_machine = VirtualMachine.create(
self.apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id,
mode=self.zone.networktype
)
# listVirtual macine
time.sleep(self.services["sleep"])
list_vms = VirtualMachine.list(self.apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s"
% self.virtual_machine.id
)
res = validateList(list_vms)
self.assertNotEqual(res[2], INVALID_INPUT, "Invalid list response")
self.cleanup.append(self.virtual_machine)
vm = list_vms[0]
self.assertEqual(
vm.id,
self.virtual_machine.id,
"Virtual Machine ids do not match"
)
# get root vol from created vm, verify it is correct size
list_volume_response = Volume.list(
self.apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
res = validateList(list_volume_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
if vm.state == "Running" and vm.hypervisor.lower() == "xenserver":
self.virtual_machine.stop(self.apiclient)
time.sleep(self.services["sleep"])
rootvolume = list_volume_response[0]
# converting json response to Volume Object
rootvol = Volume(rootvolume.__dict__)
newsize = (rootvolume.size >> 30) + 2
success = False
if rootvolume is not None:
try:
rootvol.resize(self.apiclient, size=newsize)
qresultset = self.dbclient.execute(
"select id from account where uuid = '%s';"
% self.parentd_admin.id)
res = validateList(qresultset)
self.assertNotEqual(res[2], INVALID_INPUT, "Check DB Query result set")
qresult = qresultset[0]
account_id = qresult[0]
self.debug("select type,size from usage_event"
" where account_id = '%s';"
% account_id)
qresultsize = self.dbclient.execute(
"select size from usage_event where account_id = '%s' "
"and type='VOLUME.RESIZE' ORDER BY ID DESC LIMIT 1;"
% account_id
)
res = validateList(qresultsize)
self.assertNotEqual(res[2], INVALID_INPUT, "Check DB Query result set")
qresult = int(qresultsize[0][0])
self.debug("Query result: %s" % qresult)
self.assertEqual(
qresult,
(newsize * 1024 * 1024 * 1024),
"Usage event not logged properly with right volume"
" size please check ")
except Exception as e:
raise Exception("Warning: Exception while checking usage "
"event for the root volume resize : %s"
% e)
except Exception as e:
raise Exception("Warning: Exception performing "
"usage_events_after_rootvolume_resized Test : %s"
% e)
@attr(tags=["advanced"], required_hardware="true")
def test_08_increase_volume_size_within_account_limit(self):
"""Test increasing volume size within the account limit and verify
primary storage usage
# Validate the following
# 1. Create a domain and its admin account
# 2. Set account primary storage limit well beyond (20 GB volume +
# template size of VM)
# 3. Deploy a VM without any disk offering (only root disk)
#
# 4. Increase (resize) the volume to 20 GB
# 6. Resize operation should be successful and primary storage count
# for account should be updated successfully"""
# Setting up account and domain hierarchy
result = self.setupAccounts()
self.assertEqual(result[0], PASS, result[1])
apiclient = self.testClient.getUserApiClient(
UserName=self.parentd_admin.name,
DomainName=self.parentd_admin.domain)
self.assertNotEqual(apiclient, FAILED, "Failed to get api client\
of account: %s" % self.parentd_admin.name)
templateSize = (self.template.size / (1024 ** 3))
accountLimit = (templateSize + 20)
response = self.updateResourceLimits(accountLimit=accountLimit)
self.assertEqual(response[0], PASS, response[1])
try:
if self.updateclone:
self.virtual_machine = VirtualMachine.create(
apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.services_offering_vmware.id
)
else:
self.virtual_machine = VirtualMachine.create(
apiclient, self.services["virtual_machine"],
accountid=self.parentd_admin.name,
domainid=self.parent_domain.id,
serviceofferingid=self.service_offering.id
)
list_vms = VirtualMachine.list(apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s" \
% self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vms, list),
True,
"List VM response was not a valid list"
)
self.cleanup.append(self.virtual_machine)
self.cleanup.reverse()
vm = list_vms[0]
list_volume_response = Volume.list(
apiclient,
virtualmachineid=
self.virtual_machine.id,
type='ROOT',
listall='True'
)
res = validateList(list_volume_response)
self.assertNotEqual(res[2], INVALID_INPUT, "listVolumes returned invalid object in response")
if vm.state == "Running" and vm.hypervisor.lower() == "xenserver":
self.virtual_machine.stop(self.apiclient)
time.sleep(self.services["sleep"])
rootvolume = list_volume_response[0]
# converting json response to Volume Object
rootvol = Volume(rootvolume.__dict__)
newsize = (rootvolume.size >> 30) + 20
if rootvolume is not None:
try:
rootvol.resize(apiclient, size=newsize)
response = matchResourceCount(
self.apiclient, newsize,
RESOURCE_PRIMARY_STORAGE,
accountid=self.parentd_admin.id)
if response[0] == FAIL:
raise Exception(response[1])
except Exception as e:
self.fail("Failed with exception: %s" % e)
except Exception as e:
raise Exception("Warning: Exception while checking primary"
" storage capacity after root "
"volume resize : %s" % e)
return
| [
"marvin.lib.common.list_snapshots",
"marvin.lib.common.list_storage_pools",
"marvin.lib.base.Domain.create",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.Template.create",
"marvin.lib.base.Volume",
"marvin.lib.base.VmSnapshot.list",
"marvin.lib.base.StoragePool.update",
"marvin.lib.base.T... | [((14349, 14398), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (14353, 14398), False, 'from nose.plugins.attrib import attr\n'), ((18400, 18449), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (18404, 18449), False, 'from nose.plugins.attrib import attr\n'), ((24833, 24878), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['TODO']", 'required_hardware': '"""true"""'}), "(tags=['TODO'], required_hardware='true')\n", (24837, 24878), False, 'from nose.plugins.attrib import attr\n'), ((28705, 28754), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (28709, 28754), False, 'from nose.plugins.attrib import attr\n'), ((33962, 34011), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (33966, 34011), False, 'from nose.plugins.attrib import attr\n'), ((37755, 37804), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (37759, 37804), False, 'from nose.plugins.attrib import attr\n'), ((41470, 41514), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['TODO']", 'required_hrdware': '"""true"""'}), "(tags=['TODO'], required_hrdware='true')\n", (41474, 41514), False, 'from nose.plugins.attrib import attr\n'), ((46222, 46271), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (46226, 46271), False, 'from nose.plugins.attrib import attr\n'), ((2884, 2910), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2894, 2910), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, list_snapshots, list_hosts, list_configurations, list_storage_pools\n'), ((3365, 3406), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id'], {}), '(cls.api_client, cls.zone.id)\n', (3377, 3406), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, list_snapshots, list_hosts, list_configurations, list_storage_pools\n'), ((9822, 9897), 'marvin.lib.base.Volume.list', 'Volume.list', (['apiclient'], {'virtualmachineid': 'vm.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(apiclient, virtualmachineid=vm.id, type='ROOT', listall='True')\n", (9833, 9897), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((10498, 10525), 'marvin.lib.base.Volume', 'Volume', (['rootvolume.__dict__'], {}), '(rootvolume.__dict__)\n', (10504, 10525), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((3675, 3771), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.api_client'], {'services': "cls.services['domain']", 'parentdomainid': 'cls.domain.id'}), "(cls.api_client, services=cls.services['domain'],\n parentdomainid=cls.domain.id)\n", (3688, 3771), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((3943, 4045), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.parent_domain.id'}), "(cls.api_client, cls.services['account'], admin=True,\n domainid=cls.parent_domain.id)\n", (3957, 4045), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((4314, 4416), 'marvin.lib.common.list_storage_pools', 'list_storage_pools', (['cls.api_client'], {'account': 'cls.parentd_admin.name', 'domainid': 'cls.parent_domain.id'}), '(cls.api_client, account=cls.parentd_admin.name, domainid\n =cls.parent_domain.id)\n', (4332, 4416), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, list_snapshots, list_hosts, list_configurations, list_storage_pools\n'), ((4476, 4504), 'marvin.lib.utils.validateList', 'validateList', (['list_pool_resp'], {}), '(list_pool_resp)\n', (4488, 4504), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((6127, 6199), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (6149, 6199), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((6274, 6363), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {'tags': '"""scsi"""'}), "(cls.api_client, cls.services['service_offering'],\n tags='scsi')\n", (6296, 6363), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((6878, 6925), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (6895, 6925), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((7600, 7647), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (7617, 7647), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((8793, 8891), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.apiclient'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.apiclient, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (8806, 8891), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((9064, 9168), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.parent_domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.parent_domain.id)\n", (9078, 9168), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((10137, 10171), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (10147, 10171), False, 'import time\n'), ((15682, 15745), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (15701, 15745), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((15966, 15988), 'marvin.lib.utils.validateList', 'validateList', (['list_vms'], {}), '(list_vms)\n', (15978, 15988), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((20084, 20142), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['apiclient'], {'id': 'self.virtual_machine.id'}), '(apiclient, id=self.virtual_machine.id)\n', (20103, 20142), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((20366, 20388), 'marvin.lib.utils.validateList', 'validateList', (['list_vms'], {}), '(list_vms)\n', (20378, 20388), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((21127, 21225), 'marvin.lib.base.Volume.list', 'Volume.list', (['apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (21138, 21225), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((21334, 21368), 'marvin.lib.utils.validateList', 'validateList', (['list_volume_response'], {}), '(list_volume_response)\n', (21346, 21368), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((26083, 26146), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (26102, 26146), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((26368, 26390), 'marvin.lib.utils.validateList', 'validateList', (['list_vms'], {}), '(list_vms)\n', (26380, 26390), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((26818, 26921), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (26829, 26921), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((27030, 27064), 'marvin.lib.utils.validateList', 'validateList', (['list_volume_response'], {}), '(list_volume_response)\n', (27042, 27064), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((30002, 30065), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (30021, 30065), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((30287, 30309), 'marvin.lib.utils.validateList', 'validateList', (['list_vms'], {}), '(list_vms)\n', (30299, 30309), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((30737, 30840), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (30748, 30840), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((30949, 30983), 'marvin.lib.utils.validateList', 'validateList', (['list_volume_response'], {}), '(list_volume_response)\n', (30961, 30983), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((35272, 35335), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (35291, 35335), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((35555, 35577), 'marvin.lib.utils.validateList', 'validateList', (['list_vms'], {}), '(list_vms)\n', (35567, 35577), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((35759, 35821), 'marvin.sshClient.SshClient', 'SshClient', (['self.virtual_machine.ssh_ip', '(22)', '"""root"""', '"""password"""'], {}), "(self.virtual_machine.ssh_ip, 22, 'root', 'password')\n", (35768, 35821), False, 'from marvin.sshClient import SshClient\n'), ((35936, 36039), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (35947, 36039), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((36148, 36182), 'marvin.lib.utils.validateList', 'validateList', (['list_volume_response'], {}), '(list_volume_response)\n', (36160, 36182), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((39064, 39098), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (39074, 39098), False, 'import time\n'), ((39122, 39185), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (39141, 39185), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((39407, 39429), 'marvin.lib.utils.validateList', 'validateList', (['list_vms'], {}), '(list_vms)\n', (39419, 39429), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((39857, 39960), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (39868, 39960), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((40069, 40103), 'marvin.lib.utils.validateList', 'validateList', (['list_volume_response'], {}), '(list_volume_response)\n', (40081, 40103), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((40527, 40554), 'marvin.lib.base.Volume', 'Volume', (['rootvolume.__dict__'], {}), '(rootvolume.__dict__)\n', (40533, 40554), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((42728, 42762), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (42738, 42762), False, 'import time\n'), ((42786, 42849), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (42805, 42849), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((43069, 43091), 'marvin.lib.utils.validateList', 'validateList', (['list_vms'], {}), '(list_vms)\n', (43081, 43091), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((43519, 43622), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (43530, 43622), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((43731, 43765), 'marvin.lib.utils.validateList', 'validateList', (['list_volume_response'], {}), '(list_volume_response)\n', (43743, 43765), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((44188, 44215), 'marvin.lib.base.Volume', 'Volume', (['rootvolume.__dict__'], {}), '(rootvolume.__dict__)\n', (44194, 44215), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((48301, 48359), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['apiclient'], {'id': 'self.virtual_machine.id'}), '(apiclient, id=self.virtual_machine.id)\n', (48320, 48359), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((48882, 48980), 'marvin.lib.base.Volume.list', 'Volume.list', (['apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (48893, 48980), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((49089, 49123), 'marvin.lib.utils.validateList', 'validateList', (['list_volume_response'], {}), '(list_volume_response)\n', (49101, 49123), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((49546, 49573), 'marvin.lib.base.Volume', 'Volume', (['rootvolume.__dict__'], {}), '(rootvolume.__dict__)\n', (49552, 49573), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((6684, 6794), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.api_client', '"""vmware.create.full.clone"""'], {'value': '"""false"""', 'storageid': 'cls.storageID'}), "(cls.api_client, 'vmware.create.full.clone', value=\n 'false', storageid=cls.storageID)\n", (6705, 6794), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((8062, 8169), 'marvin.lib.base.Resources.updateLimit', 'Resources.updateLimit', (['self.apiclient'], {'resourcetype': '(10)', 'max': 'domainLimit', 'domainid': 'self.parent_domain.id'}), '(self.apiclient, resourcetype=10, max=domainLimit,\n domainid=self.parent_domain.id)\n', (8083, 8169), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((8338, 8479), 'marvin.lib.base.Resources.updateLimit', 'Resources.updateLimit', (['self.apiclient'], {'resourcetype': '(10)', 'max': 'accountLimit', 'account': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id'}), '(self.apiclient, resourcetype=10, max=accountLimit,\n account=self.parentd_admin.name, domainid=self.parent_domain.id)\n', (8359, 8479), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((10899, 10961), 'marvin.sshClient.SshClient', 'SshClient', (['self.virtual_machine.ssh_ip', '(22)', '"""root"""', '"""password"""'], {}), "(self.virtual_machine.ssh_ip, 22, 'root', 'password')\n", (10908, 10961), False, 'from marvin.sshClient import SshClient\n'), ((14849, 15080), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.services_offering_vmware.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.services_offering_vmware.id, mode=self.zone.\n networktype)\n", (14870, 15080), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((15271, 15489), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.service_offering.id, mode=self.zone.networktype)\n", (15292, 15489), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((16769, 16872), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (16780, 16872), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((17009, 17043), 'marvin.lib.utils.validateList', 'validateList', (['list_volume_response'], {}), '(list_volume_response)\n', (17021, 17043), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((17352, 17468), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'rootvolume.id'], {'account': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id'}), '(self.apiclient, rootvolume.id, account=self.parentd_admin.\n name, domainid=self.parent_domain.id)\n', (17367, 17468), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((17590, 17636), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'id': 'snapshot.id'}), '(self.apiclient, id=snapshot.id)\n', (17604, 17636), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, list_snapshots, list_hosts, list_configurations, list_storage_pools\n'), ((17717, 17740), 'marvin.lib.utils.validateList', 'validateList', (['snapshots'], {}), '(snapshots)\n', (17729, 17740), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((19314, 19540), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.services_offering_vmware.id', 'mode': 'self.zone.networktype'}), "(apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.services_offering_vmware.id, mode=self.zone.\n networktype)\n", (19335, 19540), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((19703, 19916), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id', 'mode': 'self.zone.networktype'}), "(apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.service_offering.id, mode=self.zone.networktype)\n", (19724, 19916), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((25303, 25534), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.services_offering_vmware.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.services_offering_vmware.id, mode=self.zone.\n networktype)\n", (25324, 25534), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((25697, 25915), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.service_offering.id, mode=self.zone.networktype)\n", (25718, 25915), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((29222, 29453), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.services_offering_vmware.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.services_offering_vmware.id, mode=self.zone.\n networktype)\n", (29243, 29453), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((29616, 29834), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.service_offering.id, mode=self.zone.networktype)\n", (29637, 29834), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((34492, 34723), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.services_offering_vmware.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.services_offering_vmware.id, mode=self.zone.\n networktype)\n", (34513, 34723), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((34886, 35104), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.service_offering.id, mode=self.zone.networktype)\n", (34907, 35104), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((36589, 36674), 'marvin.lib.utils.checkVolumeSize', 'checkVolumeSize', ([], {'ssh_handle': 'ssh', 'volume_name': 'volume_name', 'size_to_verify': 'newsize'}), '(ssh_handle=ssh, volume_name=volume_name, size_to_verify=newsize\n )\n', (36604, 36674), False, 'from marvin.lib.utils import checkVolumeSize\n'), ((38295, 38526), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.services_offering_vmware.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.services_offering_vmware.id, mode=self.zone.\n networktype)\n", (38316, 38526), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((38689, 38907), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.service_offering.id, mode=self.zone.networktype)\n", (38710, 38907), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((40363, 40397), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (40373, 40397), False, 'import time\n'), ((41960, 42191), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.services_offering_vmware.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.services_offering_vmware.id, mode=self.zone.\n networktype)\n", (41981, 42191), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((42354, 42572), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.service_offering.id, mode=self.zone.networktype)\n", (42375, 42572), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((44025, 44059), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (44035, 44059), False, 'import time\n'), ((47661, 47854), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.services_offering_vmware.id'}), "(apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.services_offering_vmware.id)\n", (47682, 47854), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((48002, 48187), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['apiclient', "self.services['virtual_machine']"], {'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id'}), "(apiclient, self.services['virtual_machine'],\n accountid=self.parentd_admin.name, domainid=self.parent_domain.id,\n serviceofferingid=self.service_offering.id)\n", (48023, 48187), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((49383, 49417), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (49393, 49417), False, 'import time\n'), ((10842, 10876), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (10852, 10876), False, 'import time\n'), ((11473, 11565), 'marvin.lib.utils.checkVolumeSize', 'checkVolumeSize', ([], {'ssh_handle': 'ssh', 'volume_name': 'volume_name', 'size_to_verify': 'newsizeinbytes'}), '(ssh_handle=ssh, volume_name=volume_name, size_to_verify=\n newsizeinbytes)\n', (11488, 11565), False, 'from marvin.lib.utils import checkVolumeSize\n'), ((21903, 22050), 'marvin.lib.base.Template.create', 'Template.create', (['apiclient', "self.services['template']"], {'volumeid': 'rootvolume.id', 'account': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id'}), "(apiclient, self.services['template'], volumeid=rootvolume.\n id, account=self.parentd_admin.name, domainid=self.parent_domain.id)\n", (21918, 22050), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((22212, 22284), 'marvin.lib.base.Template.list', 'Template.list', (['apiclient'], {'id': 'template_from_root.id', 'templatefilter': '"""all"""'}), "(apiclient, id=template_from_root.id, templatefilter='all')\n", (22225, 22284), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((22384, 22420), 'marvin.lib.utils.validateList', 'validateList', (['list_template_response'], {}), '(list_template_response)\n', (22396, 22420), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((22637, 22856), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['apiclient', "self.services['virtual_machine']"], {'templateid': 'template_from_root.id', 'accountid': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id', 'serviceofferingid': 'self.service_offering.id'}), "(apiclient, self.services['virtual_machine'],\n templateid=template_from_root.id, accountid=self.parentd_admin.name,\n domainid=self.parent_domain.id, serviceofferingid=self.service_offering.id)\n", (22658, 22856), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((23051, 23180), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['apiclient'], {'id': 'self.virtual_machine2.id', 'account': 'self.parentd_admin.name', 'domainid': 'self.parent_domain.id'}), '(apiclient, id=self.virtual_machine2.id, account=self.\n parentd_admin.name, domainid=self.parent_domain.id)\n', (23070, 23180), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((23320, 23345), 'marvin.lib.utils.validateList', 'validateList', (['vm_response'], {}), '(vm_response)\n', (23332, 23345), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((23847, 23923), 'marvin.lib.base.Volume.list', 'Volume.list', (['apiclient'], {'virtualmachineid': 'vm2.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(apiclient, virtualmachineid=vm2.id, type='ROOT', listall='True')\n", (23858, 23923), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((27547, 27605), 'marvin.lib.base.VmSnapshot.create', 'VmSnapshot.create', (['self.apiclient', 'self.virtual_machine.id'], {}), '(self.apiclient, self.virtual_machine.id)\n', (27564, 27605), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((27683, 27755), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'vmsnapshotid': 'virtualmachine_snapshot.id'}), '(self.apiclient, vmsnapshotid=virtualmachine_snapshot.id)\n', (27698, 27755), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((27841, 27882), 'marvin.lib.utils.validateList', 'validateList', (['virtulmachine_snapshot_list'], {}), '(virtulmachine_snapshot_list)\n', (27853, 27882), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((31288, 31346), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'self.virtual_machine.hostid'}), '(self.apiclient, id=self.virtual_machine.hostid)\n', (31298, 31346), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, list_snapshots, list_hosts, list_configurations, list_storage_pools\n'), ((31443, 31475), 'marvin.lib.utils.validateList', 'validateList', (['list_host_response'], {}), '(list_host_response)\n', (31455, 31475), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((32397, 32504), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id', 'hostid': 'self.list_hosts_suitable[0].id'}), '(self.apiclient, id=self.virtual_machine.id, hostid=self\n .list_hosts_suitable[0].id)\n', (32416, 32504), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((32600, 32622), 'marvin.lib.utils.validateList', 'validateList', (['list_vms'], {}), '(list_vms)\n', (32612, 32622), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((33054, 33157), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '"""True"""'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall='True')\n", (33065, 33157), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((37051, 37136), 'marvin.lib.utils.checkVolumeSize', 'checkVolumeSize', ([], {'ssh_handle': 'ssh', 'volume_name': 'volume_name', 'size_to_verify': 'newsize'}), '(ssh_handle=ssh, volume_name=volume_name, size_to_verify=newsize\n )\n', (37066, 37136), False, 'from marvin.lib.utils import checkVolumeSize\n'), ((44619, 44643), 'marvin.lib.utils.validateList', 'validateList', (['qresultset'], {}), '(qresultset)\n', (44631, 44643), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((45295, 45320), 'marvin.lib.utils.validateList', 'validateList', (['qresultsize'], {}), '(qresultsize)\n', (45307, 45320), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((49776, 49882), 'marvin.lib.common.matchResourceCount', 'matchResourceCount', (['self.apiclient', 'newsize', 'RESOURCE_PRIMARY_STORAGE'], {'accountid': 'self.parentd_admin.id'}), '(self.apiclient, newsize, RESOURCE_PRIMARY_STORAGE,\n accountid=self.parentd_admin.id)\n', (49794, 49882), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, list_snapshots, list_hosts, list_configurations, list_storage_pools\n'), ((4974, 5068), 'marvin.lib.common.list_configurations', 'list_configurations', (['cls.api_client'], {'name': '"""vmware.create.full.clone"""', 'storageid': 'strpool.id'}), "(cls.api_client, name='vmware.create.full.clone',\n storageid=strpool.id)\n", (4993, 5068), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, list_snapshots, list_hosts, list_configurations, list_storage_pools\n'), ((5181, 5223), 'marvin.lib.utils.validateList', 'validateList', (['list_config_storage_response'], {}), '(list_config_storage_response)\n', (5193, 5223), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((12011, 12103), 'marvin.lib.utils.checkVolumeSize', 'checkVolumeSize', ([], {'ssh_handle': 'ssh', 'volume_name': 'volume_name', 'size_to_verify': 'newsizeinbytes'}), '(ssh_handle=ssh, volume_name=volume_name, size_to_verify=\n newsizeinbytes)\n', (12026, 12103), False, 'from marvin.lib.utils import checkVolumeSize\n'), ((31720, 31799), 'marvin.lib.base.Host.listForMigration', 'Host.listForMigration', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id)\n', (31741, 31799), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((37282, 37361), 'marvin.lib.utils.checkVolumeSize', 'checkVolumeSize', ([], {'ssh_handle': 'ssh', 'volume_name': '"""/dev/sdb"""', 'size_to_verify': 'newsize'}), "(ssh_handle=ssh, volume_name='/dev/sdb', size_to_verify=newsize)\n", (37297, 37361), False, 'from marvin.lib.utils import checkVolumeSize\n'), ((5456, 5562), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.api_client', '"""vmware.create.full.clone"""'], {'value': '"""true"""', 'storageid': 'strpool.id'}), "(cls.api_client, 'vmware.create.full.clone', value=\n 'true', storageid=strpool.id)\n", (5477, 5562), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((5736, 5798), 'marvin.lib.base.StoragePool.update', 'StoragePool.update', (['cls.api_client'], {'id': 'strpool.id', 'tags': '"""scsi"""'}), "(cls.api_client, id=strpool.id, tags='scsi')\n", (5754, 5798), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Volume, Snapshot, Template, VmSnapshot, Host, Configurations, StoragePool\n'), ((12300, 12391), 'marvin.lib.utils.checkVolumeSize', 'checkVolumeSize', ([], {'ssh_handle': 'ssh', 'volume_name': '"""/dev/sdb"""', 'size_to_verify': 'newsizeinbytes'}), "(ssh_handle=ssh, volume_name='/dev/sdb', size_to_verify=\n newsizeinbytes)\n", (12315, 12391), False, 'from marvin.lib.utils import checkVolumeSize\n')] |
#!/usr/bin/env python
# encoding: utf-8
#
# test_map.py
#
# @Author: <NAME> <andrews>
# @Date: 2017-07-02 13:08:00
# @Last modified by: andrews
# @Last modified time: 2018-03-01 11:03:79
from copy import deepcopy
import numpy as np
from astropy import units as u
import matplotlib
import pytest
from marvin import config
from marvin.core.exceptions import MarvinError
from marvin.tools.maps import Maps
from marvin.tools.quantities import Map, EnhancedMap
from marvin.tests import marvin_test_if
from marvin.utils.datamodel.dap import datamodel
from marvin.utils.datamodel.dap.plotting import get_default_plot_params
from marvin.utils.general.maskbit import Maskbit
value1 = np.array([[16.35, 0.8],
[0, -10.]])
value2 = np.array([[591., 1e-8],
[4., 10]])
value_prod12 = np.array([[9.66285000e+03, 8e-9],
[0, -100]])
ivar1 = np.array([[4, 1],
[6.97789734e+36, 1e8]])
ivar2 = np.array([[10, 1e-8],
[5.76744385e+36, 0]])
ivar_sum12 = np.array([[2.85714286e+00, 9.99999990e-09],
[3.15759543e+36, 0]])
ivar_prod12 = np.array([[1.10616234e-05, 1.56250000e-08],
[0, 0.]])
ivar_pow_2 = np.array([[5.23472002e-08, 9.53674316e-01],
[0, 25]])
ivar_pow_05 = np.array([[3.66072168e-03, 7.81250000e+00],
[0, 0]])
ivar_pow_0 = np.array([[0, 0],
[0, 0]])
ivar_pow_m1 = np.array([[4, 1.],
[0, 1e+08]])
ivar_pow_m2 = np.array([[2.67322500e+02, 1.6e-01],
[0, 2.5e+09]])
ivar_pow_m05 = np.array([[0.97859327, 5],
[0, 0]])
u_flux = u.erg / u.cm**2 / u.s / u.def_unit('spaxel')
u_flux2 = u_flux * u_flux
def _get_maps_kwargs(galaxy, data_origin):
if data_origin == 'file':
maps_kwargs = dict(filename=galaxy.mapspath)
else:
maps_kwargs = dict(plateifu=galaxy.plateifu, release=galaxy.release,
bintype=galaxy.bintype, template_kin=galaxy.template,
mode='local' if data_origin == 'db' else 'remote')
return maps_kwargs
@pytest.fixture(scope='function', params=[('emline_gflux', 'ha_6564'),
('emline_gvel', 'oiii_5008'),
('stellar_vel', None),
('stellar_sigma', None)])
def map_(request, galaxy, data_origin):
maps = Maps(**_get_maps_kwargs(galaxy, data_origin))
map_ = maps.getMap(property_name=request.param[0], channel=request.param[1])
map_.data_origin = data_origin
return map_
class TestMap(object):
def test_map(self, map_, galaxy):
assert map_.getMaps().release == galaxy.release
assert tuple(map_.shape) == tuple(galaxy.shape)
assert map_.value.shape == tuple(galaxy.shape)
assert map_.ivar.shape == tuple(galaxy.shape)
assert map_.mask.shape == tuple(galaxy.shape)
assert (map_.masked.data == map_.value).all()
assert (map_.masked.mask == map_.mask.astype(bool)).all()
assert map_.snr == pytest.approx(np.abs(map_.value * np.sqrt(map_.ivar)))
assert datamodel[map_.getMaps()._dapver][map_.datamodel.full()].unit == map_.unit
def test_plot(self, map_):
fig, ax = map_.plot()
assert isinstance(fig, matplotlib.figure.Figure)
assert isinstance(ax, matplotlib.axes._subplots.Subplot)
assert 'Make single panel map or one panel of multi-panel map plot.' in map_.plot.__doc__
@marvin_test_if(mark='skip', map_={'data_origin': ['db']})
def test_save_and_restore(self, temp_scratch, map_):
fout = temp_scratch.join('test_map.mpf')
map_.save(str(fout))
assert fout.check() is True
map_restored = Map.restore(str(fout), delete=True)
assert tuple(map_.shape) == tuple(map_restored.shape)
@pytest.mark.parametrize('property_name, channel',
[('emline_gflux', 'ha_6564'),
('stellar_vel', None)])
def test_deepcopy(self, galaxy, property_name, channel):
maps = Maps(plateifu=galaxy.plateifu)
map1 = maps.getMap(property_name=property_name, channel=channel)
map2 = deepcopy(map1)
for attr in vars(map1):
if not attr.startswith('_'):
value = getattr(map1, attr)
value2 = getattr(map2, attr)
if isinstance(value, np.ndarray):
assert np.isclose(value, value2).all()
elif isinstance(value, np.ma.core.MaskedArray):
assert (np.isclose(value.data, value2.data).all() and
(value.mask == value2.mask).all())
elif isinstance(value, Maskbit) or isinstance(value[0], Maskbit):
if isinstance(value, Maskbit):
value = [value]
value2 = [value2]
for mb, mb2 in zip(value, value2):
for it in ['bits', 'description', 'labels', 'mask', 'name']:
assert getattr(mb, it) == getattr(mb2, it)
assert (mb.schema == mb2.schema).all().all()
elif isinstance(value, Maps):
pass
else:
assert value == value2, attr
def test_getMap_invalid_property(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
with pytest.raises(ValueError) as ee:
maps.getMap(property_name='mythical_property')
assert 'Your input value is too ambiguous.' in str(ee.value)
def test_getMap_invalid_channel(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
with pytest.raises(ValueError) as ee:
maps.getMap(property_name='emline_gflux', channel='mythical_channel')
assert 'Your input value is too ambiguous.' in str(ee.value)
@marvin_test_if(mark='include', maps={'plateifu': '8485-1901',
'release': 'MPL-6',
'mode': 'local',
'data_origin': 'file'})
def test_quatities_reorder(self, maps):
"""Asserts the unit survives a quantity reorder (issue #374)."""
ha = maps['emline_gflux_ha']
assert ha is not None
assert ha.unit is not None
reordered_ha = np.moveaxis(ha, 0, -1)
assert reordered_ha.unit is not None
class TestMapArith(object):
def test_add_constant(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
ha = maps['emline_gflux_ha_6564']
ha10 = ha + 10.
assert ha10.value == pytest.approx(ha.value + 10.)
assert ha10.ivar == pytest.approx(ha.ivar)
assert ha10.mask == pytest.approx(ha.mask)
def test_subtract_constant(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
ha = maps['emline_gflux_ha_6564']
ha10 = ha - 10.
assert ha10.value == pytest.approx(ha.value - 10.)
assert ha10.ivar == pytest.approx(ha.ivar)
assert ha10.mask == pytest.approx(ha.mask)
def test_multiply_constant(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
ha = maps['emline_gflux_ha_6564']
ha10 = ha * 10.
assert ha10.value == pytest.approx(ha.value * 10.)
assert ha10.ivar == pytest.approx(ha.ivar / 10.**2)
assert ha10.mask == pytest.approx(ha.mask)
def test_divide_constant(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
ha = maps['emline_gflux_ha_6564']
ha10 = ha / 10.
assert ha10.value == pytest.approx(ha.value / 10.)
assert ha10.ivar == pytest.approx(ha.ivar * 10.**2)
assert ha10.mask == pytest.approx(ha.mask)
@pytest.mark.parametrize('ivar1, ivar2, expected',
[(ivar1, ivar2, ivar_sum12)])
def test_add_ivar(self, ivar1, ivar2, expected):
assert Map._add_ivar(ivar1, ivar2) == pytest.approx(expected)
@pytest.mark.parametrize('ivar1, ivar2, value1, value2, value_prod12, expected',
[(ivar1, ivar2, value1, value2, value_prod12, ivar_prod12)])
def test_mul_ivar(self, ivar1, ivar2, value1, value2, value_prod12, expected):
ivar = Map._mul_ivar(ivar1, ivar2, value1, value2, value_prod12)
ivar[np.isnan(ivar)] = 0
ivar[np.isinf(ivar)] = 0
assert ivar == pytest.approx(expected)
@pytest.mark.parametrize('power, expected',
[(2, ivar_pow_2),
(0.5, ivar_pow_05),
(0, ivar_pow_0),
(-1, ivar_pow_m1),
(-2, ivar_pow_m2),
(-0.5, ivar_pow_m05)])
@pytest.mark.parametrize('ivar, value,',
[(ivar1, value1)])
def test_pow_ivar(self, ivar, value, power, expected):
ivar = Map._pow_ivar(ivar, value, power)
ivar[np.isnan(ivar)] = 0
ivar[np.isinf(ivar)] = 0
assert ivar == pytest.approx(expected)
@pytest.mark.parametrize('power', [2, 0.5, 0, -1, -2, -0.5])
def test_pow_ivar_none(self, power):
assert Map._pow_ivar(None, np.arange(4), power) == pytest.approx(np.zeros(4))
@pytest.mark.parametrize('unit1, unit2, op, expected',
[(u_flux, u_flux, '+', u_flux),
(u_flux, u_flux, '-', u_flux),
(u_flux, u_flux, '*', u_flux2),
(u_flux, u_flux, '/', u.dimensionless_unscaled),
(u.km, u.s, '*', u.km * u.s),
(u.km, u.s, '/', u.km / u.s)])
def test_unit_propagation(self, unit1, unit2, op, expected):
assert Map._unit_propagation(unit1, unit2, op) == expected
@pytest.mark.parametrize('unit1, unit2, op',
[(u_flux, u.km, '+'),
(u_flux, u.km, '-')])
def test_unit_propagation_mismatch(self, unit1, unit2, op):
with pytest.warns(UserWarning):
assert Map._unit_propagation(unit1, unit2, op) is None
@pytest.mark.parametrize('property1, channel1, property2, channel2',
[('emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'),
('emline_gvel', 'ha_6564', 'stellar_vel', None)])
def test_add_maps(self, galaxy, property1, channel1, property2, channel2):
maps = Maps(plateifu=galaxy.plateifu)
map1 = maps.getMap(property_name=property1, channel=channel1)
map2 = maps.getMap(property_name=property2, channel=channel2)
map12 = map1 + map2
assert map12.value == pytest.approx(map1.value + map2.value)
assert map12.ivar == pytest.approx(map1._add_ivar(map1.ivar, map2.ivar))
assert map12.mask == pytest.approx(map1.mask | map2.mask)
@pytest.mark.parametrize('property1, channel1, property2, channel2',
[('emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'),
('emline_gvel', 'ha_6564', 'stellar_vel', None)])
def test_subtract_maps(self, galaxy, property1, channel1, property2, channel2):
maps = Maps(plateifu=galaxy.plateifu)
map1 = maps.getMap(property_name=property1, channel=channel1)
map2 = maps.getMap(property_name=property2, channel=channel2)
map12 = map1 - map2
assert map12.value == pytest.approx(map1.value - map2.value)
assert map12.ivar == pytest.approx(map1._add_ivar(map1.ivar, map2.ivar))
assert map12.mask == pytest.approx(map1.mask | map2.mask)
@pytest.mark.parametrize('property1, channel1, property2, channel2',
[('emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'),
('emline_gvel', 'ha_6564', 'stellar_vel', None)])
def test_multiply_maps(self, galaxy, property1, channel1, property2, channel2):
maps = Maps(plateifu=galaxy.plateifu)
map1 = maps.getMap(property_name=property1, channel=channel1)
map2 = maps.getMap(property_name=property2, channel=channel2)
map12 = map1 * map2
ivar = map1._mul_ivar(map1.ivar, map2.ivar, map1.value, map2.value, map12.value)
ivar[np.isnan(ivar)] = 0
ivar[np.isinf(ivar)] = 0
assert map12.value == pytest.approx(map1.value * map2.value)
assert map12.ivar == pytest.approx(ivar)
assert map12.mask == pytest.approx(map1.mask | map2.mask)
@pytest.mark.parametrize('property1, channel1, property2, channel2',
[('emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'),
('emline_gvel', 'ha_6564', 'stellar_vel', None)])
def test_divide_maps(self, galaxy, property1, channel1, property2, channel2):
maps = Maps(plateifu=galaxy.plateifu)
map1 = maps.getMap(property_name=property1, channel=channel1)
map2 = maps.getMap(property_name=property2, channel=channel2)
map12 = map1 / map2
ivar = map1._mul_ivar(map1.ivar, map2.ivar, map1.value, map2.value, map12.value)
ivar[np.isnan(ivar)] = 0
ivar[np.isinf(ivar)] = 0
mask = map1.mask | map2.mask
bad = np.isnan(map12.value) | np.isinf(map12.value)
mask[bad] = mask[bad] | map12.pixmask.labels_to_value('DONOTUSE')
with np.errstate(divide='ignore', invalid='ignore'):
assert map12.value == pytest.approx(map1.value / map2.value, nan_ok=True)
assert map12.ivar == pytest.approx(ivar)
assert map12.mask == pytest.approx(mask)
@pytest.mark.runslow
@pytest.mark.parametrize('power', [2, 0.5, 0, -1, -2, -0.5])
@pytest.mark.parametrize('property_name, channel',
[('emline_gflux', 'ha_6564'),
('stellar_vel', None)])
def test_pow(self, galaxy, property_name, channel, power):
maps = Maps(plateifu=galaxy.plateifu)
map_orig = maps.getMap(property_name=property_name, channel=channel)
map_new = map_orig**power
sig_orig = np.sqrt(1. / map_orig.ivar)
sig_new = map_new.value * power * sig_orig * map_orig.value
ivar_new = 1 / sig_new**2.
ivar_new[np.isnan(ivar_new)] = 0
ivar_new[np.isinf(ivar_new)] = 0
assert map_new.value == pytest.approx(map_orig.value**power, nan_ok=True)
assert map_new.ivar == pytest.approx(ivar_new)
assert (map_new.mask == map_orig.mask).all()
@marvin_test_if(mark='skip', galaxy=dict(release=['MPL-4']))
def test_stellar_sigma_correction(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
stsig = maps['stellar_sigma']
stsigcorr = maps['stellar_sigmacorr']
expected = (stsig**2 - stsigcorr**2)**0.5
actual = stsig.inst_sigma_correction()
assert actual.value == pytest.approx(expected.value, nan_ok=True)
assert actual.ivar == pytest.approx(expected.ivar)
assert (actual.mask == expected.mask).all()
@marvin_test_if(mark='include', galaxy=dict(release=['MPL-4']))
def test_stellar_sigma_correction_MPL4(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
stsig = maps['stellar_sigma']
with pytest.raises(MarvinError) as ee:
stsig.inst_sigma_correction()
assert 'Instrumental broadening correction not implemented for MPL-4.' in str(ee.value)
def test_stellar_sigma_correction_invalid_property(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
ha = maps['emline_gflux_ha_6564']
with pytest.raises(MarvinError) as ee:
ha.inst_sigma_correction()
assert ('Cannot correct {0}_{1} '.format(ha.datamodel.name, ha.datamodel.channel) +
'for instrumental broadening.') in str(ee.value)
def test_emline_sigma_correction(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
hasig = maps['emline_gsigma_ha_6564']
emsigcorr = maps['emline_instsigma_ha_6564']
expected = (hasig**2 - emsigcorr**2)**0.5
actual = hasig.inst_sigma_correction()
assert actual.value == pytest.approx(expected.value, nan_ok=True)
assert actual.ivar == pytest.approx(expected.ivar)
assert (actual.mask == expected.mask).all()
class TestMaskbit(object):
def test_masked(self, maps_release_only):
__, dapver = config.lookUpVersions(maps_release_only.release)
params = get_default_plot_params(dapver)
ha = maps_release_only['emline_gflux_ha_6564']
expected = ha.pixmask.get_mask(params['default']['bitmasks'], dtype=bool)
assert ha.masked.data == pytest.approx(ha.value)
assert (ha.masked.mask == expected).all()
@marvin_test_if(mark='include', maps_release_only=dict(release=['MPL-4']))
def test_values_to_bits_mpl4(self, maps_release_only):
ha = maps_release_only['emline_gflux_ha_6564']
assert ha.pixmask.values_to_bits(1) == [0]
@marvin_test_if(mark='skip', maps_release_only=dict(release=['MPL-4']))
def test_values_to_bits(self, maps_release_only):
ha = maps_release_only['emline_gflux_ha_6564']
assert ha.pixmask.values_to_bits(3) == [0, 1]
@marvin_test_if(mark='include', maps_release_only=dict(release=['MPL-4']))
def test_values_to_labels_mpl4(self, maps_release_only):
ha = maps_release_only['emline_gflux_ha_6564']
assert ha.pixmask.values_to_labels(1) == ['DONOTUSE']
@marvin_test_if(mark='skip', maps_release_only=dict(release=['MPL-4']))
def test_values_to_labels(self, maps_release_only):
ha = maps_release_only['emline_gflux_ha_6564']
assert ha.pixmask.values_to_labels(3) == ['NOCOV', 'LOWCOV']
@marvin_test_if(mark='include', maps_release_only=dict(release=['MPL-4']))
def test_labels_to_value_mpl4(self, maps_release_only):
ha = maps_release_only['emline_gflux_ha_6564']
assert ha.pixmask.labels_to_value('DONOTUSE') == 1
@marvin_test_if(mark='skip', maps_release_only=dict(release=['MPL-4']))
@pytest.mark.parametrize('names, expected',
[(['NOCOV', 'LOWCOV'], 3),
('DONOTUSE', 1073741824)])
def test_labels_to_value(self, maps_release_only, names, expected):
ha = maps_release_only['emline_gflux_ha_6564']
assert ha.pixmask.labels_to_value(names) == expected
@marvin_test_if(mark='skip', maps_release_only=dict(release=['MPL-4']))
def test_quality_flag(self, maps_release_only):
ha = maps_release_only['emline_gflux_ha_6564']
assert ha.quality_flag is not None
@pytest.mark.parametrize('flag',
['manga_target1',
'manga_target2',
'manga_target3',
'target_flags',
'pixmask'])
def test_flag(self, flag, maps_release_only):
ha = maps_release_only['emline_gflux_ha_6564']
assert getattr(ha, flag, None) is not None
class TestEnhancedMap(object):
def test_overridden_methods(self, galaxy):
maps = Maps(plateifu=galaxy.plateifu)
ha = maps['emline_gflux_ha_6564']
nii = maps['emline_gflux_nii_6585']
n2ha = nii / ha
assert isinstance(n2ha, EnhancedMap)
methods = ['_init_map_from_maps', '_get_from_file', '_get_from_db', '_get_from_api',
'inst_sigma_correction']
for method in methods:
with pytest.raises(AttributeError) as ee:
meth = getattr(n2ha, method)
meth()
assert "'EnhancedMap' has no attribute '{}'.".format(method) in str(ee.value)
| [
"marvin.tools.maps.Maps",
"marvin.tools.quantities.Map._add_ivar",
"marvin.tests.marvin_test_if",
"marvin.tools.quantities.Map._unit_propagation",
"marvin.tools.quantities.Map._mul_ivar",
"marvin.tools.quantities.Map._pow_ivar",
"marvin.config.lookUpVersions",
"marvin.utils.datamodel.dap.plotting.get_... | [((683, 719), 'numpy.array', 'np.array', (['[[16.35, 0.8], [0, -10.0]]'], {}), '([[16.35, 0.8], [0, -10.0]])\n', (691, 719), True, 'import numpy as np\n'), ((747, 784), 'numpy.array', 'np.array', (['[[591.0, 1e-08], [4.0, 10]]'], {}), '([[591.0, 1e-08], [4.0, 10]])\n', (755, 784), True, 'import numpy as np\n'), ((817, 856), 'numpy.array', 'np.array', (['[[9662.85, 8e-09], [0, -100]]'], {}), '([[9662.85, 8e-09], [0, -100]])\n', (825, 856), True, 'import numpy as np\n'), ((897, 946), 'numpy.array', 'np.array', (['[[4, 1], [6.97789734e+36, 100000000.0]]'], {}), '([[4, 1], [6.97789734e+36, 100000000.0]])\n', (905, 946), True, 'import numpy as np\n'), ((965, 1009), 'numpy.array', 'np.array', (['[[10, 1e-08], [5.76744385e+36, 0]]'], {}), '([[10, 1e-08], [5.76744385e+36, 0]])\n', (973, 1009), True, 'import numpy as np\n'), ((1041, 1101), 'numpy.array', 'np.array', (['[[2.85714286, 9.9999999e-09], [3.15759543e+36, 0]]'], {}), '([[2.85714286, 9.9999999e-09], [3.15759543e+36, 0]])\n', (1049, 1101), True, 'import numpy as np\n'), ((1145, 1195), 'numpy.array', 'np.array', (['[[1.10616234e-05, 1.5625e-08], [0, 0.0]]'], {}), '([[1.10616234e-05, 1.5625e-08], [0, 0.0]])\n', (1153, 1195), True, 'import numpy as np\n'), ((1237, 1287), 'numpy.array', 'np.array', (['[[5.23472002e-08, 0.953674316], [0, 25]]'], {}), '([[5.23472002e-08, 0.953674316], [0, 25]])\n', (1245, 1287), True, 'import numpy as np\n'), ((1327, 1370), 'numpy.array', 'np.array', (['[[0.00366072168, 7.8125], [0, 0]]'], {}), '([[0.00366072168, 7.8125], [0, 0]])\n', (1335, 1370), True, 'import numpy as np\n'), ((1416, 1442), 'numpy.array', 'np.array', (['[[0, 0], [0, 0]]'], {}), '([[0, 0], [0, 0]])\n', (1424, 1442), True, 'import numpy as np\n'), ((1479, 1517), 'numpy.array', 'np.array', (['[[4, 1.0], [0, 100000000.0]]'], {}), '([[4, 1.0], [0, 100000000.0]])\n', (1487, 1517), True, 'import numpy as np\n'), ((1549, 1596), 'numpy.array', 'np.array', (['[[267.3225, 0.16], [0, 2500000000.0]]'], {}), '([[267.3225, 0.16], [0, 2500000000.0]])\n', (1557, 1596), True, 'import numpy as np\n'), ((1640, 1675), 'numpy.array', 'np.array', (['[[0.97859327, 5], [0, 0]]'], {}), '([[0.97859327, 5], [0, 0]])\n', (1648, 1675), True, 'import numpy as np\n'), ((2184, 2341), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'params': "[('emline_gflux', 'ha_6564'), ('emline_gvel', 'oiii_5008'), ('stellar_vel',\n None), ('stellar_sigma', None)]"}), "(scope='function', params=[('emline_gflux', 'ha_6564'), (\n 'emline_gvel', 'oiii_5008'), ('stellar_vel', None), ('stellar_sigma',\n None)])\n", (2198, 2341), False, 'import pytest\n'), ((1735, 1755), 'astropy.units.def_unit', 'u.def_unit', (['"""spaxel"""'], {}), "('spaxel')\n", (1745, 1755), True, 'from astropy import units as u\n'), ((3612, 3669), 'marvin.tests.marvin_test_if', 'marvin_test_if', ([], {'mark': '"""skip"""', 'map_': "{'data_origin': ['db']}"}), "(mark='skip', map_={'data_origin': ['db']})\n", (3626, 3669), False, 'from marvin.tests import marvin_test_if\n'), ((3970, 4077), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""property_name, channel"""', "[('emline_gflux', 'ha_6564'), ('stellar_vel', None)]"], {}), "('property_name, channel', [('emline_gflux',\n 'ha_6564'), ('stellar_vel', None)])\n", (3993, 4077), False, 'import pytest\n'), ((6037, 6163), 'marvin.tests.marvin_test_if', 'marvin_test_if', ([], {'mark': '"""include"""', 'maps': "{'plateifu': '8485-1901', 'release': 'MPL-6', 'mode': 'local',\n 'data_origin': 'file'}"}), "(mark='include', maps={'plateifu': '8485-1901', 'release':\n 'MPL-6', 'mode': 'local', 'data_origin': 'file'})\n", (6051, 6163), False, 'from marvin.tests import marvin_test_if\n'), ((7930, 8009), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ivar1, ivar2, expected"""', '[(ivar1, ivar2, ivar_sum12)]'], {}), "('ivar1, ivar2, expected', [(ivar1, ivar2, ivar_sum12)])\n", (7953, 8009), False, 'import pytest\n'), ((8168, 8312), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ivar1, ivar2, value1, value2, value_prod12, expected"""', '[(ivar1, ivar2, value1, value2, value_prod12, ivar_prod12)]'], {}), "('ivar1, ivar2, value1, value2, value_prod12, expected',\n [(ivar1, ivar2, value1, value2, value_prod12, ivar_prod12)])\n", (8191, 8312), False, 'import pytest\n'), ((8613, 8780), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""power, expected"""', '[(2, ivar_pow_2), (0.5, ivar_pow_05), (0, ivar_pow_0), (-1, ivar_pow_m1), (\n -2, ivar_pow_m2), (-0.5, ivar_pow_m05)]'], {}), "('power, expected', [(2, ivar_pow_2), (0.5,\n ivar_pow_05), (0, ivar_pow_0), (-1, ivar_pow_m1), (-2, ivar_pow_m2), (-\n 0.5, ivar_pow_m05)])\n", (8636, 8780), False, 'import pytest\n'), ((8956, 9014), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ivar, value,"""', '[(ivar1, value1)]'], {}), "('ivar, value,', [(ivar1, value1)])\n", (8979, 9014), False, 'import pytest\n'), ((9271, 9330), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""power"""', '[2, 0.5, 0, -1, -2, -0.5]'], {}), "('power', [2, 0.5, 0, -1, -2, -0.5])\n", (9294, 9330), False, 'import pytest\n'), ((9464, 9734), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""unit1, unit2, op, expected"""', "[(u_flux, u_flux, '+', u_flux), (u_flux, u_flux, '-', u_flux), (u_flux,\n u_flux, '*', u_flux2), (u_flux, u_flux, '/', u.dimensionless_unscaled),\n (u.km, u.s, '*', u.km * u.s), (u.km, u.s, '/', u.km / u.s)]"], {}), "('unit1, unit2, op, expected', [(u_flux, u_flux, '+',\n u_flux), (u_flux, u_flux, '-', u_flux), (u_flux, u_flux, '*', u_flux2),\n (u_flux, u_flux, '/', u.dimensionless_unscaled), (u.km, u.s, '*', u.km *\n u.s), (u.km, u.s, '/', u.km / u.s)])\n", (9487, 9734), False, 'import pytest\n'), ((10040, 10131), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""unit1, unit2, op"""', "[(u_flux, u.km, '+'), (u_flux, u.km, '-')]"], {}), "('unit1, unit2, op', [(u_flux, u.km, '+'), (u_flux,\n u.km, '-')])\n", (10063, 10131), False, 'import pytest\n'), ((10364, 10548), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""property1, channel1, property2, channel2"""', "[('emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'), ('emline_gvel',\n 'ha_6564', 'stellar_vel', None)]"], {}), "('property1, channel1, property2, channel2', [(\n 'emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'), ('emline_gvel',\n 'ha_6564', 'stellar_vel', None)])\n", (10387, 10548), False, 'import pytest\n'), ((11115, 11299), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""property1, channel1, property2, channel2"""', "[('emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'), ('emline_gvel',\n 'ha_6564', 'stellar_vel', None)]"], {}), "('property1, channel1, property2, channel2', [(\n 'emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'), ('emline_gvel',\n 'ha_6564', 'stellar_vel', None)])\n", (11138, 11299), False, 'import pytest\n'), ((11871, 12055), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""property1, channel1, property2, channel2"""', "[('emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'), ('emline_gvel',\n 'ha_6564', 'stellar_vel', None)]"], {}), "('property1, channel1, property2, channel2', [(\n 'emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'), ('emline_gvel',\n 'ha_6564', 'stellar_vel', None)])\n", (11894, 12055), False, 'import pytest\n'), ((12751, 12935), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""property1, channel1, property2, channel2"""', "[('emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'), ('emline_gvel',\n 'ha_6564', 'stellar_vel', None)]"], {}), "('property1, channel1, property2, channel2', [(\n 'emline_gflux', 'ha_6564', 'emline_gflux', 'nii_6585'), ('emline_gvel',\n 'ha_6564', 'stellar_vel', None)])\n", (12774, 12935), False, 'import pytest\n'), ((13888, 13947), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""power"""', '[2, 0.5, 0, -1, -2, -0.5]'], {}), "('power', [2, 0.5, 0, -1, -2, -0.5])\n", (13911, 13947), False, 'import pytest\n'), ((13953, 14060), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""property_name, channel"""', "[('emline_gflux', 'ha_6564'), ('stellar_vel', None)]"], {}), "('property_name, channel', [('emline_gflux',\n 'ha_6564'), ('stellar_vel', None)])\n", (13976, 14060), False, 'import pytest\n'), ((18350, 18451), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""names, expected"""', "[(['NOCOV', 'LOWCOV'], 3), ('DONOTUSE', 1073741824)]"], {}), "('names, expected', [(['NOCOV', 'LOWCOV'], 3), (\n 'DONOTUSE', 1073741824)])\n", (18373, 18451), False, 'import pytest\n'), ((18927, 19042), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""flag"""', "['manga_target1', 'manga_target2', 'manga_target3', 'target_flags', 'pixmask']"], {}), "('flag', ['manga_target1', 'manga_target2',\n 'manga_target3', 'target_flags', 'pixmask'])\n", (18950, 19042), False, 'import pytest\n'), ((4209, 4239), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (4213, 4239), False, 'from marvin.tools.maps import Maps\n'), ((4328, 4342), 'copy.deepcopy', 'deepcopy', (['map1'], {}), '(map1)\n', (4336, 4342), False, 'from copy import deepcopy\n'), ((5529, 5559), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (5533, 5559), False, 'from marvin.tools.maps import Maps\n'), ((5802, 5832), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (5806, 5832), False, 'from marvin.tools.maps import Maps\n'), ((6531, 6553), 'numpy.moveaxis', 'np.moveaxis', (['ha', '(0)', '(-1)'], {}), '(ha, 0, -1)\n', (6542, 6553), True, 'import numpy as np\n'), ((6686, 6716), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (6690, 6716), False, 'from marvin.tools.maps import Maps\n'), ((7007, 7037), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (7011, 7037), False, 'from marvin.tools.maps import Maps\n'), ((7328, 7358), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (7332, 7358), False, 'from marvin.tools.maps import Maps\n'), ((7656, 7686), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (7660, 7686), False, 'from marvin.tools.maps import Maps\n'), ((8436, 8493), 'marvin.tools.quantities.Map._mul_ivar', 'Map._mul_ivar', (['ivar1', 'ivar2', 'value1', 'value2', 'value_prod12'], {}), '(ivar1, ivar2, value1, value2, value_prod12)\n', (8449, 8493), False, 'from marvin.tools.quantities import Map, EnhancedMap\n'), ((9118, 9151), 'marvin.tools.quantities.Map._pow_ivar', 'Map._pow_ivar', (['ivar', 'value', 'power'], {}), '(ivar, value, power)\n', (9131, 9151), False, 'from marvin.tools.quantities import Map, EnhancedMap\n'), ((10693, 10723), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (10697, 10723), False, 'from marvin.tools.maps import Maps\n'), ((11449, 11479), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (11453, 11479), False, 'from marvin.tools.maps import Maps\n'), ((12205, 12235), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (12209, 12235), False, 'from marvin.tools.maps import Maps\n'), ((13083, 13113), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (13087, 13113), False, 'from marvin.tools.maps import Maps\n'), ((14194, 14224), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (14198, 14224), False, 'from marvin.tools.maps import Maps\n'), ((14356, 14384), 'numpy.sqrt', 'np.sqrt', (['(1.0 / map_orig.ivar)'], {}), '(1.0 / map_orig.ivar)\n', (14363, 14384), True, 'import numpy as np\n'), ((14894, 14924), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (14898, 14924), False, 'from marvin.tools.maps import Maps\n'), ((15433, 15463), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (15437, 15463), False, 'from marvin.tools.maps import Maps\n'), ((15774, 15804), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (15778, 15804), False, 'from marvin.tools.maps import Maps\n'), ((16160, 16190), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (16164, 16190), False, 'from marvin.tools.maps import Maps\n'), ((16671, 16719), 'marvin.config.lookUpVersions', 'config.lookUpVersions', (['maps_release_only.release'], {}), '(maps_release_only.release)\n', (16692, 16719), False, 'from marvin import config\n'), ((16737, 16768), 'marvin.utils.datamodel.dap.plotting.get_default_plot_params', 'get_default_plot_params', (['dapver'], {}), '(dapver)\n', (16760, 16768), False, 'from marvin.utils.datamodel.dap.plotting import get_default_plot_params\n'), ((19440, 19470), 'marvin.tools.maps.Maps', 'Maps', ([], {'plateifu': 'galaxy.plateifu'}), '(plateifu=galaxy.plateifu)\n', (19444, 19470), False, 'from marvin.tools.maps import Maps\n'), ((5573, 5598), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5586, 5598), False, 'import pytest\n'), ((5846, 5871), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5859, 5871), False, 'import pytest\n'), ((6813, 6843), 'pytest.approx', 'pytest.approx', (['(ha.value + 10.0)'], {}), '(ha.value + 10.0)\n', (6826, 6843), False, 'import pytest\n'), ((6871, 6893), 'pytest.approx', 'pytest.approx', (['ha.ivar'], {}), '(ha.ivar)\n', (6884, 6893), False, 'import pytest\n'), ((6922, 6944), 'pytest.approx', 'pytest.approx', (['ha.mask'], {}), '(ha.mask)\n', (6935, 6944), False, 'import pytest\n'), ((7134, 7164), 'pytest.approx', 'pytest.approx', (['(ha.value - 10.0)'], {}), '(ha.value - 10.0)\n', (7147, 7164), False, 'import pytest\n'), ((7192, 7214), 'pytest.approx', 'pytest.approx', (['ha.ivar'], {}), '(ha.ivar)\n', (7205, 7214), False, 'import pytest\n'), ((7243, 7265), 'pytest.approx', 'pytest.approx', (['ha.mask'], {}), '(ha.mask)\n', (7256, 7265), False, 'import pytest\n'), ((7455, 7485), 'pytest.approx', 'pytest.approx', (['(ha.value * 10.0)'], {}), '(ha.value * 10.0)\n', (7468, 7485), False, 'import pytest\n'), ((7513, 7547), 'pytest.approx', 'pytest.approx', (['(ha.ivar / 10.0 ** 2)'], {}), '(ha.ivar / 10.0 ** 2)\n', (7526, 7547), False, 'import pytest\n'), ((7573, 7595), 'pytest.approx', 'pytest.approx', (['ha.mask'], {}), '(ha.mask)\n', (7586, 7595), False, 'import pytest\n'), ((7783, 7813), 'pytest.approx', 'pytest.approx', (['(ha.value / 10.0)'], {}), '(ha.value / 10.0)\n', (7796, 7813), False, 'import pytest\n'), ((7841, 7875), 'pytest.approx', 'pytest.approx', (['(ha.ivar * 10.0 ** 2)'], {}), '(ha.ivar * 10.0 ** 2)\n', (7854, 7875), False, 'import pytest\n'), ((7901, 7923), 'pytest.approx', 'pytest.approx', (['ha.mask'], {}), '(ha.mask)\n', (7914, 7923), False, 'import pytest\n'), ((8107, 8134), 'marvin.tools.quantities.Map._add_ivar', 'Map._add_ivar', (['ivar1', 'ivar2'], {}), '(ivar1, ivar2)\n', (8120, 8134), False, 'from marvin.tools.quantities import Map, EnhancedMap\n'), ((8138, 8161), 'pytest.approx', 'pytest.approx', (['expected'], {}), '(expected)\n', (8151, 8161), False, 'import pytest\n'), ((8507, 8521), 'numpy.isnan', 'np.isnan', (['ivar'], {}), '(ivar)\n', (8515, 8521), True, 'import numpy as np\n'), ((8540, 8554), 'numpy.isinf', 'np.isinf', (['ivar'], {}), '(ivar)\n', (8548, 8554), True, 'import numpy as np\n'), ((8583, 8606), 'pytest.approx', 'pytest.approx', (['expected'], {}), '(expected)\n', (8596, 8606), False, 'import pytest\n'), ((9165, 9179), 'numpy.isnan', 'np.isnan', (['ivar'], {}), '(ivar)\n', (9173, 9179), True, 'import numpy as np\n'), ((9198, 9212), 'numpy.isinf', 'np.isinf', (['ivar'], {}), '(ivar)\n', (9206, 9212), True, 'import numpy as np\n'), ((9241, 9264), 'pytest.approx', 'pytest.approx', (['expected'], {}), '(expected)\n', (9254, 9264), False, 'import pytest\n'), ((9982, 10021), 'marvin.tools.quantities.Map._unit_propagation', 'Map._unit_propagation', (['unit1', 'unit2', 'op'], {}), '(unit1, unit2, op)\n', (10003, 10021), False, 'from marvin.tools.quantities import Map, EnhancedMap\n'), ((10264, 10289), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (10276, 10289), False, 'import pytest\n'), ((10923, 10961), 'pytest.approx', 'pytest.approx', (['(map1.value + map2.value)'], {}), '(map1.value + map2.value)\n', (10936, 10961), False, 'import pytest\n'), ((11072, 11108), 'pytest.approx', 'pytest.approx', (['(map1.mask | map2.mask)'], {}), '(map1.mask | map2.mask)\n', (11085, 11108), False, 'import pytest\n'), ((11679, 11717), 'pytest.approx', 'pytest.approx', (['(map1.value - map2.value)'], {}), '(map1.value - map2.value)\n', (11692, 11717), False, 'import pytest\n'), ((11828, 11864), 'pytest.approx', 'pytest.approx', (['(map1.mask | map2.mask)'], {}), '(map1.mask | map2.mask)\n', (11841, 11864), False, 'import pytest\n'), ((12507, 12521), 'numpy.isnan', 'np.isnan', (['ivar'], {}), '(ivar)\n', (12515, 12521), True, 'import numpy as np\n'), ((12540, 12554), 'numpy.isinf', 'np.isinf', (['ivar'], {}), '(ivar)\n', (12548, 12554), True, 'import numpy as np\n'), ((12591, 12629), 'pytest.approx', 'pytest.approx', (['(map1.value * map2.value)'], {}), '(map1.value * map2.value)\n', (12604, 12629), False, 'import pytest\n'), ((12659, 12678), 'pytest.approx', 'pytest.approx', (['ivar'], {}), '(ivar)\n', (12672, 12678), False, 'import pytest\n'), ((12708, 12744), 'pytest.approx', 'pytest.approx', (['(map1.mask | map2.mask)'], {}), '(map1.mask | map2.mask)\n', (12721, 12744), False, 'import pytest\n'), ((13385, 13399), 'numpy.isnan', 'np.isnan', (['ivar'], {}), '(ivar)\n', (13393, 13399), True, 'import numpy as np\n'), ((13418, 13432), 'numpy.isinf', 'np.isinf', (['ivar'], {}), '(ivar)\n', (13426, 13432), True, 'import numpy as np\n'), ((13490, 13511), 'numpy.isnan', 'np.isnan', (['map12.value'], {}), '(map12.value)\n', (13498, 13511), True, 'import numpy as np\n'), ((13514, 13535), 'numpy.isinf', 'np.isinf', (['map12.value'], {}), '(map12.value)\n', (13522, 13535), True, 'import numpy as np\n'), ((13624, 13670), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (13635, 13670), True, 'import numpy as np\n'), ((13788, 13807), 'pytest.approx', 'pytest.approx', (['ivar'], {}), '(ivar)\n', (13801, 13807), False, 'import pytest\n'), ((13837, 13856), 'pytest.approx', 'pytest.approx', (['mask'], {}), '(mask)\n', (13850, 13856), False, 'import pytest\n'), ((14504, 14522), 'numpy.isnan', 'np.isnan', (['ivar_new'], {}), '(ivar_new)\n', (14512, 14522), True, 'import numpy as np\n'), ((14545, 14563), 'numpy.isinf', 'np.isinf', (['ivar_new'], {}), '(ivar_new)\n', (14553, 14563), True, 'import numpy as np\n'), ((14602, 14653), 'pytest.approx', 'pytest.approx', (['(map_orig.value ** power)'], {'nan_ok': '(True)'}), '(map_orig.value ** power, nan_ok=True)\n', (14615, 14653), False, 'import pytest\n'), ((14683, 14706), 'pytest.approx', 'pytest.approx', (['ivar_new'], {}), '(ivar_new)\n', (14696, 14706), False, 'import pytest\n'), ((15137, 15179), 'pytest.approx', 'pytest.approx', (['expected.value'], {'nan_ok': '(True)'}), '(expected.value, nan_ok=True)\n', (15150, 15179), False, 'import pytest\n'), ((15210, 15238), 'pytest.approx', 'pytest.approx', (['expected.ivar'], {}), '(expected.ivar)\n', (15223, 15238), False, 'import pytest\n'), ((15515, 15541), 'pytest.raises', 'pytest.raises', (['MarvinError'], {}), '(MarvinError)\n', (15528, 15541), False, 'import pytest\n'), ((15861, 15887), 'pytest.raises', 'pytest.raises', (['MarvinError'], {}), '(MarvinError)\n', (15874, 15887), False, 'import pytest\n'), ((16420, 16462), 'pytest.approx', 'pytest.approx', (['expected.value'], {'nan_ok': '(True)'}), '(expected.value, nan_ok=True)\n', (16433, 16462), False, 'import pytest\n'), ((16493, 16521), 'pytest.approx', 'pytest.approx', (['expected.ivar'], {}), '(expected.ivar)\n', (16506, 16521), False, 'import pytest\n'), ((16940, 16963), 'pytest.approx', 'pytest.approx', (['ha.value'], {}), '(ha.value)\n', (16953, 16963), False, 'import pytest\n'), ((9407, 9419), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (9416, 9419), True, 'import numpy as np\n'), ((9445, 9456), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (9453, 9456), True, 'import numpy as np\n'), ((10310, 10349), 'marvin.tools.quantities.Map._unit_propagation', 'Map._unit_propagation', (['unit1', 'unit2', 'op'], {}), '(unit1, unit2, op)\n', (10331, 10349), False, 'from marvin.tools.quantities import Map, EnhancedMap\n'), ((13706, 13757), 'pytest.approx', 'pytest.approx', (['(map1.value / map2.value)'], {'nan_ok': '(True)'}), '(map1.value / map2.value, nan_ok=True)\n', (13719, 13757), False, 'import pytest\n'), ((19814, 19843), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (19827, 19843), False, 'import pytest\n'), ((3212, 3230), 'numpy.sqrt', 'np.sqrt', (['map_.ivar'], {}), '(map_.ivar)\n', (3219, 3230), True, 'import numpy as np\n'), ((4584, 4609), 'numpy.isclose', 'np.isclose', (['value', 'value2'], {}), '(value, value2)\n', (4594, 4609), True, 'import numpy as np\n'), ((4709, 4744), 'numpy.isclose', 'np.isclose', (['value.data', 'value2.data'], {}), '(value.data, value2.data)\n', (4719, 4744), True, 'import numpy as np\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for Kubernetes supported version """
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.cloudstackAPI import (listInfrastructure,
listKubernetesSupportedVersions,
addKubernetesSupportedVersion,
deleteKubernetesSupportedVersion,
createKubernetesCluster,
stopKubernetesCluster,
deleteKubernetesCluster,
upgradeKubernetesCluster,
scaleKubernetesCluster)
from marvin.cloudstackException import CloudstackAPIException
from marvin.codes import FAILED
from marvin.lib.base import (Template,
ServiceOffering,
Configurations)
from marvin.lib.utils import (cleanup_resources,
random_gen)
from marvin.lib.common import (get_zone)
from marvin.sshClient import SshClient
from nose.plugins.attrib import attr
import time
_multiprocess_shared_ = True
class TestKubernetesCluster(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestKubernetesCluster, cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
cls.cks_template_name_key = "cloud.kubernetes.cluster.template.name." + cls.hypervisor.lower()
cls.setup_failed = False
cls.initial_configuration_cks_enabled = Configurations.list(cls.apiclient,
name="cloud.kubernetes.service.enabled")[0].value
if cls.initial_configuration_cks_enabled not in ["true", True]:
cls.debug("Enabling CloudStack Kubernetes Service plugin and restarting management server")
Configurations.update(cls.apiclient,
"cloud.kubernetes.service.enabled",
"true")
cls.restartServer()
cls.cks_template = None
cls.initial_configuration_cks_template_name = None
cls.cks_service_offering = None
cls.kubernetes_version_ids = []
if cls.setup_failed == False:
try:
cls.kubernetes_version_1 = cls.addKubernetesSupportedVersion('1.14.9', 'http://download.cloudstack.org/cks/setup-1.14.9.iso')
cls.kubernetes_version_ids.append(cls.kubernetes_version_1.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, http://download.cloudstack.org/cks/setup-1.14.9.iso, %s" % e)
if cls.setup_failed == False:
try:
cls.kubernetes_version_2 = cls.addKubernetesSupportedVersion('1.15.0', 'http://download.cloudstack.org/cks/setup-1.15.0.iso')
cls.kubernetes_version_ids.append(cls.kubernetes_version_2.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, http://download.cloudstack.org/cks/setup-1.15.0.iso, %s" % e)
if cls.setup_failed == False:
try:
cls.kubernetes_version_3 = cls.addKubernetesSupportedVersion('1.16.0', 'http://download.cloudstack.org/cks/setup-1.16.0.iso')
cls.kubernetes_version_ids.append(cls.kubernetes_version_3.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, http://download.cloudstack.org/cks/setup-1.16.0.iso, %s" % e)
if cls.setup_failed == False:
try:
cls.kubernetes_version_4 = cls.addKubernetesSupportedVersion('1.16.3', 'http://download.cloudstack.org/cks/setup-1.16.3.iso')
cls.kubernetes_version_ids.append(cls.kubernetes_version_4.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, http://download.cloudstack.org/cks/setup-1.16.3.iso, %s" % e)
cks_template_data = {
"name": "Kubernetes-Service-Template",
"displaytext": "Kubernetes-Service-Template",
"format": "qcow2",
"hypervisor": "kvm",
"ostype": "CoreOS",
"url": "http://dl.openvm.eu/cloudstack/coreos/x86_64/coreos_production_cloudstack_image-kvm.qcow2.bz2",
"ispublic": "True",
"isextractable": "True"
}
cks_template_data_details = []
if cls.hypervisor.lower() == "vmware":
cks_template_data["url"] = "http://dl.openvm.eu/cloudstack/coreos/x86_64/coreos_production_cloudstack_image-vmware.ova"
cks_template_data["format"] = "OVA"
cks_template_data_details = [{"keyboard":"us","nicAdapter":"Vmxnet3","rootDiskController":"pvscsi"}]
elif cls.hypervisor.lower() == "xenserver":
cks_template_data["url"] = "http://dl.openvm.eu/cloudstack/coreos/x86_64/coreos_production_cloudstack_image-xen.vhd.bz2"
cks_template_data["format"] = "VHD"
elif cls.hypervisor.lower() == "kvm":
cks_template_data["requireshvm"] = "True"
if cls.setup_failed == False:
cls.cks_template = Template.register(
cls.apiclient,
cks_template_data,
zoneid=cls.zone.id,
hypervisor=cls.hypervisor,
details=cks_template_data_details
)
cls.debug("Waiting for CKS template with ID %s to be ready" % cls.cks_template.id)
try:
cls.waitForTemplateReadyState(cls.cks_template.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get CKS template in ready state, {}, {}".format(cks_template_data["url"], e))
cls.initial_configuration_cks_template_name = Configurations.list(cls.apiclient,
name=cls.cks_template_name_key)[0].value
Configurations.update(cls.apiclient,
cls.cks_template_name_key,
cls.cks_template.name)
cks_offering_data = {
"name": "CKS-Instance",
"displaytext": "CKS Instance",
"cpunumber": 2,
"cpuspeed": 1000,
"memory": 2048,
}
cks_offering_data["name"] = cks_offering_data["name"] + '-' + random_gen()
if cls.setup_failed == False:
cls.cks_service_offering = ServiceOffering.create(
cls.apiclient,
cks_offering_data
)
cls._cleanup = []
if cls.cks_template != None:
cls._cleanup.append(cls.cks_template)
if cls.cks_service_offering != None:
cls._cleanup.append(cls.cks_service_offering)
return
@classmethod
def tearDownClass(cls):
version_delete_failed = False
# Delete added Kubernetes supported version
for version_id in cls.kubernetes_version_ids:
try:
cls.deleteKubernetesSupportedVersion(version_id)
except Exception as e:
version_delete_failed = True
cls.debug("Error: Exception during cleanup for added Kubernetes supported versions: %s" % e)
try:
# Restore original CKS template
if cls.initial_configuration_cks_template_name != None:
Configurations.update(cls.apiclient,
cls.cks_template_name_key,
cls.initial_configuration_cks_template_name)
# Delete created CKS template
if cls.setup_failed == False and cls.cks_template != None:
cls.cks_template.delete(cls.apiclient,
cls.zone.id)
# Restore CKS enabled
if cls.initial_configuration_cks_enabled not in ["true", True]:
cls.debug("Restoring Kubernetes Service enabled value")
Configurations.update(cls.apiclient,
"cloud.kubernetes.service.enabled",
"false")
cls.restartServer()
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
if version_delete_failed == True:
raise Exception("Warning: Exception during cleanup, unable to delete Kubernetes supported versions")
return
@classmethod
def restartServer(cls):
"""Restart management server"""
cls.debug("Restarting management server")
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-management stop"
sshClient.execute(command)
command = "service cloudstack-management start"
sshClient.execute(command)
#Waits for management to come up in 5 mins, when it's up it will continue
timeout = time.time() + 300
while time.time() < timeout:
if cls.isManagementUp() is True: return
time.sleep(5)
cls.setup_failed = True
cls.debug("Management server did not come up, failing")
return
@classmethod
def isManagementUp(cls):
try:
cls.apiclient.listInfrastructure(listInfrastructure.listInfrastructureCmd())
return True
except Exception:
return False
@classmethod
def waitForTemplateReadyState(cls, template_id, retries=30, interval=60):
"""Check if template download will finish"""
while retries > 0:
time.sleep(interval)
template_response = Template.list(
cls.apiclient,
id=template_id,
zoneid=cls.zone.id,
templatefilter='self'
)
if isinstance(template_response, list):
template = template_response[0]
if not hasattr(template, 'status') or not template or not template.status:
retries = retries - 1
continue
if 'Failed' == template.status:
raise Exception("Failed to download template: status - %s" % template.status)
elif template.status == 'Download Complete' and template.isready:
return
retries = retries - 1
raise Exception("Template download timed out")
@classmethod
def waitForKubernetesSupportedVersionIsoReadyState(cls, version_id, retries=30, interval=60):
"""Check if Kubernetes supported version ISO is in Ready state"""
while retries > 0:
time.sleep(interval)
list_versions_response = cls.listKubernetesSupportedVersion(version_id)
if not hasattr(list_versions_response, 'isostate') or not list_versions_response or not list_versions_response.isostate:
retries = retries - 1
continue
if 'Ready' == list_versions_response.isostate:
return
elif 'Failed' == list_versions_response.isostate:
raise Exception( "Failed to download template: status - %s" % template.status)
retries = retries - 1
raise Exception("Kubernetes supported version Ready state timed out")
@classmethod
def listKubernetesSupportedVersion(cls, version_id):
listKubernetesSupportedVersionsCmd = listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd()
listKubernetesSupportedVersionsCmd.id = version_id
versionResponse = cls.apiclient.listKubernetesSupportedVersions(listKubernetesSupportedVersionsCmd)
return versionResponse[0]
@classmethod
def addKubernetesSupportedVersion(cls, semantic_version, iso_url):
addKubernetesSupportedVersionCmd = addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd()
addKubernetesSupportedVersionCmd.semanticversion = semantic_version
addKubernetesSupportedVersionCmd.name = 'v' + semantic_version + '-' + random_gen()
addKubernetesSupportedVersionCmd.url = iso_url
addKubernetesSupportedVersionCmd.mincpunumber = 2
addKubernetesSupportedVersionCmd.minmemory = 2048
kubernetes_version = cls.apiclient.addKubernetesSupportedVersion(addKubernetesSupportedVersionCmd)
cls.debug("Waiting for Kubernetes version with ID %s to be ready" % kubernetes_version.id)
cls.waitForKubernetesSupportedVersionIsoReadyState(kubernetes_version.id)
kubernetes_version = cls.listKubernetesSupportedVersion(kubernetes_version.id)
return kubernetes_version
@classmethod
def deleteKubernetesSupportedVersion(cls, version_id):
deleteKubernetesSupportedVersionCmd = deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd()
deleteKubernetesSupportedVersionCmd.id = version_id
deleteKubernetesSupportedVersionCmd.deleteiso = True
cls.apiclient.deleteKubernetesSupportedVersion(deleteKubernetesSupportedVersionCmd)
def setUp(self):
self.services = self.testClient.getParsedTestDataConfig()
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_01_deploy_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
# 3. stopKubernetesCluster should stop the cluster
"""
if self.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
self.skipTest("CKS not supported for hypervisor: %s" % self.hypervisor.lower())
if self.setup_failed == True:
self.skipTest("Setup incomplete")
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
cluster_response = self.createKubernetesCluster(name, self.kubernetes_version_2.id)
self.verifyKubernetesCluster(cluster_response, name, self.kubernetes_version_2.id)
self.debug("Kubernetes cluster with ID: %s successfully deployed, now stopping it" % cluster_response.id)
self.stopAndVerifyKubernetesCluster(cluster_response.id)
self.debug("Kubernetes cluster with ID: %s successfully stopped, now deleting it" % cluster_response.id)
self.deleteAndVerifyKubernetesCluster(cluster_response.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % cluster_response.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_02_deploy_kubernetes_ha_cluster(self):
"""Test to deploy a new Kubernetes cluster
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
"""
if self.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
self.skipTest("CKS not supported for hypervisor: %s" % self.hypervisor.lower())
if self.setup_failed == True:
self.skipTest("Setup incomplete")
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
cluster_response = self.createKubernetesCluster(name, self.kubernetes_version_3.id, 1, 2)
self.verifyKubernetesCluster(cluster_response, name, self.kubernetes_version_3.id, 1, 2)
self.debug("Kubernetes cluster with ID: %s successfully deployed, now deleting it" % cluster_response.id)
self.deleteAndVerifyKubernetesCluster(cluster_response.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % cluster_response.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_03_deploy_invalid_kubernetes_ha_cluster(self):
"""Test to deploy a new Kubernetes cluster
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
"""
if self.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
self.skipTest("CKS not supported for hypervisor: %s" % self.hypervisor.lower())
if self.setup_failed == True:
self.skipTest("Setup incomplete")
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
try:
cluster_response = self.createKubernetesCluster(name, self.kubernetes_version_2.id, 1, 2)
self.debug("Invslid CKS Kubernetes HA cluster deployed with ID: %s. Deleting it and failing test." % cluster_response.id)
self.deleteKubernetesCluster(cluster_response.id)
self.fail("HA Kubernetes cluster deployed with Kubernetes supported version below version 1.16.0. Must be an error.")
except CloudstackAPIException as e:
self.debug("HA Kubernetes cluster with invalid Kubernetes supported version check successful, API failure: %s" % e)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_04_deploy_and_upgrade_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster and upgrade it to newer version
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
# 3. upgradeKubernetesCluster should return valid info for the cluster
"""
if self.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
self.skipTest("CKS not supported for hypervisor: %s" % self.hypervisor.lower())
if self.setup_failed == True:
self.skipTest("Setup incomplete")
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
cluster_response = self.createKubernetesCluster(name, self.kubernetes_version_2.id)
self.verifyKubernetesCluster(cluster_response, name, self.kubernetes_version_2.id)
self.debug("Kubernetes cluster with ID: %s successfully deployed, now upgrading it" % cluster_response.id)
try:
cluster_response = self.upgradeKubernetesCluster(cluster_response.id, self.kubernetes_version_3.id)
except Exception as e:
self.deleteKubernetesCluster(cluster_response.id)
self.fail("Failed to upgrade Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterUpgrade(cluster_response, self.kubernetes_version_3.id)
self.debug("Kubernetes cluster with ID: %s successfully upgraded, now deleting it" % cluster_response.id)
self.deleteAndVerifyKubernetesCluster(cluster_response.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % cluster_response.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_05_deploy_and_upgrade_kubernetes_ha_cluster(self):
"""Test to deploy a new HA Kubernetes cluster and upgrade it to newer version
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
# 3. upgradeKubernetesCluster should return valid info for the cluster
"""
if self.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
self.skipTest("CKS not supported for hypervisor: %s" % self.hypervisor.lower())
if self.setup_failed == True:
self.skipTest("Setup incomplete")
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
cluster_response = self.createKubernetesCluster(name, self.kubernetes_version_3.id, 1, 2)
self.verifyKubernetesCluster(cluster_response, name, self.kubernetes_version_3.id, 1, 2)
self.debug("Kubernetes cluster with ID: %s successfully deployed, now upgrading it" % cluster_response.id)
try:
cluster_response = self.upgradeKubernetesCluster(cluster_response.id, self.kubernetes_version_4.id)
except Exception as e:
self.deleteKubernetesCluster(cluster_response.id)
self.fail("Failed to upgrade Kubernetes HA cluster due to: %s" % e)
self.verifyKubernetesClusterUpgrade(cluster_response, self.kubernetes_version_4.id)
self.debug("Kubernetes cluster with ID: %s successfully upgraded, now deleting it" % cluster_response.id)
self.deleteAndVerifyKubernetesCluster(cluster_response.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % cluster_response.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_06_deploy_and_invalid_upgrade_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster and check for failure while tying to upgrade it to a lower version
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
# 3. upgradeKubernetesCluster should fail
"""
if self.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
self.skipTest("CKS not supported for hypervisor: %s" % self.hypervisor.lower())
if self.setup_failed == True:
self.skipTest("Setup incomplete")
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
cluster_response = self.createKubernetesCluster(name, self.kubernetes_version_2.id)
self.verifyKubernetesCluster(cluster_response, name, self.kubernetes_version_2.id)
self.debug("Kubernetes cluster with ID: %s successfully deployed, now scaling it" % cluster_response.id)
try:
cluster_response = self.upgradeKubernetesCluster(cluster_response.id, self.kubernetes_version_1.id)
self.debug("Invalid CKS Kubernetes HA cluster deployed with ID: %s. Deleting it and failing test." % kubernetes_version_1.id)
self.deleteKubernetesCluster(cluster_response.id)
self.fail("Kubernetes cluster upgraded to a lower Kubernetes supported version. Must be an error.")
except Exception as e:
self.debug("Upgrading Kubernetes cluster with invalid Kubernetes supported version check successful, API failure: %s" % e)
self.debug("Deleting Kubernetes cluster with ID: %s" % cluster_response.id)
self.deleteAndVerifyKubernetesCluster(cluster_response.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % cluster_response.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
def test_07_deploy_and_scale_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster and check for failure while tying to scale it
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
# 3. scaleKubernetesCluster should return valid info for the cluster when it is scaled up
# 4. scaleKubernetesCluster should return valid info for the cluster when it is scaled down
"""
if self.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
self.skipTest("CKS not supported for hypervisor: %s" % self.hypervisor.lower())
if self.setup_failed == True:
self.skipTest("Setup incomplete")
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
cluster_response = self.createKubernetesCluster(name, self.kubernetes_version_2.id)
self.verifyKubernetesCluster(cluster_response, name, self.kubernetes_version_2.id)
self.debug("Kubernetes cluster with ID: %s successfully deployed, now upscaling it" % cluster_response.id)
try:
cluster_response = self.scaleKubernetesCluster(cluster_response.id, 2)
except Exception as e:
self.deleteKubernetesCluster(cluster_response.id)
self.fail("Failed to upscale Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterScale(cluster_response, 2)
self.debug("Kubernetes cluster with ID: %s successfully upscaled, now downscaling it" % cluster_response.id)
try:
cluster_response = self.scaleKubernetesCluster(cluster_response.id, 1)
except Exception as e:
self.deleteKubernetesCluster(cluster_response.id)
self.fail("Failed to downscale Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterScale(cluster_response)
self.debug("Kubernetes cluster with ID: %s successfully downscaled, now deleting it" % cluster_response.id)
self.deleteAndVerifyKubernetesCluster(cluster_response.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % cluster_response.id)
return
def listKubernetesCluster(self, cluster_id):
listKubernetesClustersCmd = listKubernetesClusters.listKubernetesClustersCmd()
listKubernetesClustersCmd.id = cluster_id
clusterResponse = self.apiclient.listKubernetesClusters(listKubernetesClustersCmd)
return clusterResponse[0]
def createKubernetesCluster(self, name, version_id, size=1, master_nodes=1):
createKubernetesClusterCmd = createKubernetesCluster.createKubernetesClusterCmd()
createKubernetesClusterCmd.name = name
createKubernetesClusterCmd.description = name + "-description"
createKubernetesClusterCmd.kubernetesversionid = version_id
createKubernetesClusterCmd.size = size
createKubernetesClusterCmd.masternodes = master_nodes
createKubernetesClusterCmd.serviceofferingid = self.cks_service_offering.id
createKubernetesClusterCmd.zoneid = self.zone.id
createKubernetesClusterCmd.noderootdisksize = 10
clusterResponse = self.apiclient.createKubernetesCluster(createKubernetesClusterCmd)
if not clusterResponse:
self.cleanup.append(clusterResponse)
return clusterResponse
def stopKubernetesCluster(self, cluster_id):
stopKubernetesClusterCmd = stopKubernetesCluster.stopKubernetesClusterCmd()
stopKubernetesClusterCmd.id = cluster_id
response = self.apiclient.stopKubernetesCluster(stopKubernetesClusterCmd)
return response
def deleteKubernetesCluster(self, cluster_id):
deleteKubernetesClusterCmd = deleteKubernetesCluster.deleteKubernetesClusterCmd()
deleteKubernetesClusterCmd.id = cluster_id
response = self.apiclient.deleteKubernetesCluster(deleteKubernetesClusterCmd)
return response
def upgradeKubernetesCluster(self, cluster_id, version_id):
upgradeKubernetesClusterCmd = upgradeKubernetesCluster.upgradeKubernetesClusterCmd()
upgradeKubernetesClusterCmd.id = cluster_id
upgradeKubernetesClusterCmd.kubernetesversionid = version_id
response = self.apiclient.upgradeKubernetesCluster(upgradeKubernetesClusterCmd)
return response
def scaleKubernetesCluster(self, cluster_id, size):
scaleKubernetesClusterCmd = scaleKubernetesCluster.scaleKubernetesClusterCmd()
scaleKubernetesClusterCmd.id = cluster_id
scaleKubernetesClusterCmd.size = size
response = self.apiclient.scaleKubernetesCluster(scaleKubernetesClusterCmd)
return response
def verifyKubernetesCluster(self, cluster_response, name, version_id, size=1, master_nodes=1):
"""Check if Kubernetes cluster is valid"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
self.assertEqual(
cluster_response.name,
name,
"Check KubernetesCluster name {}, {}".format(cluster_response.name, name)
)
self.verifyKubernetesClusterVersion(cluster_response, version_id)
self.assertEqual(
cluster_response.zoneid,
self.zone.id,
"Check KubernetesCluster zone {}, {}".format(cluster_response.zoneid, self.zone.id)
)
self.verifyKubernetesClusterSize(cluster_response, size, master_nodes)
db_cluster_name = self.dbclient.execute("select name from kubernetes_cluster where uuid = '%s';" % cluster_response.id)[0][0]
self.assertEqual(
str(db_cluster_name),
name,
"Check KubernetesCluster name in DB {}, {}".format(db_cluster_name, name)
)
def verifyKubernetesClusterState(self, cluster_response, state):
"""Check if Kubernetes cluster state is Running"""
self.assertEqual(
cluster_response.state,
'Running',
"Check KubernetesCluster state {}, {}".format(cluster_response.state, state)
)
def verifyKubernetesClusterVersion(self, cluster_response, version_id):
"""Check if Kubernetes cluster node sizes are valid"""
self.assertEqual(
cluster_response.kubernetesversionid,
version_id,
"Check KubernetesCluster version {}, {}".format(cluster_response.kubernetesversionid, version_id)
)
def verifyKubernetesClusterSize(self, cluster_response, size=1, master_nodes=1):
"""Check if Kubernetes cluster node sizes are valid"""
self.assertEqual(
cluster_response.size,
size,
"Check KubernetesCluster size {}, {}".format(cluster_response.size, size)
)
self.assertEqual(
cluster_response.masternodes,
master_nodes,
"Check KubernetesCluster master nodes {}, {}".format(cluster_response.masternodes, master_nodes)
)
def verifyKubernetesClusterUpgrade(self, cluster_response, version_id):
"""Check if Kubernetes cluster state and version are valid after upgrade"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
self.verifyKubernetesClusterVersion(cluster_response, version_id)
def verifyKubernetesClusterScale(self, cluster_response, size=1, master_nodes=1):
"""Check if Kubernetes cluster state and node sizes are valid after upgrade"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
self.verifyKubernetesClusterSize(cluster_response, size, master_nodes)
def stopAndVerifyKubernetesCluster(self, cluster_id):
"""Stop Kubernetes cluster and check if it is really stopped"""
stop_response = self.stopKubernetesCluster(cluster_id)
self.assertEqual(
stop_response.success,
True,
"Check KubernetesCluster stop response {}, {}".format(stop_response.success, True)
)
db_cluster_state = self.dbclient.execute("select state from kubernetes_cluster where uuid = '%s';" % cluster_id)[0][0]
self.assertEqual(
db_cluster_state,
'Stopped',
"KubernetesCluster not stopped in DB, {}".format(db_cluster_state)
)
def deleteAndVerifyKubernetesCluster(self, cluster_id):
"""Delete Kubernetes cluster and check if it is really deleted"""
delete_response = self.deleteKubernetesCluster(cluster_id)
self.assertEqual(
delete_response.success,
True,
"Check KubernetesCluster delete response {}, {}".format(delete_response.success, True)
)
db_cluster_removed = self.dbclient.execute("select removed from kubernetes_cluster where uuid = '%s';" % cluster_id)[0][0]
self.assertNotEqual(
db_cluster_removed,
None,
"KubernetesCluster not removed in DB, {}".format(db_cluster_removed)
)
| [
"marvin.lib.base.Template.register",
"marvin.lib.utils.random_gen",
"marvin.cloudstackAPI.scaleKubernetesCluster.scaleKubernetesClusterCmd",
"marvin.lib.base.Template.list",
"marvin.lib.utils.cleanup_resources",
"marvin.cloudstackAPI.listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd",
"... | [((15484, 15542), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (15488, 15542), False, 'from nose.plugins.attrib import attr\n'), ((16926, 16984), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (16930, 16984), False, 'from nose.plugins.attrib import attr\n'), ((18144, 18202), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (18148, 18202), False, 'from nose.plugins.attrib import attr\n'), ((19507, 19565), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (19511, 19565), False, 'from nose.plugins.attrib import attr\n'), ((21339, 21397), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (21343, 21397), False, 'from nose.plugins.attrib import attr\n'), ((23191, 23249), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (23195, 23249), False, 'from nose.plugins.attrib import attr\n'), ((25219, 25277), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (25223, 25277), False, 'from nose.plugins.attrib import attr\n'), ((10404, 10509), 'marvin.sshClient.SshClient', 'SshClient', (["cls.mgtSvrDetails['mgtSvrIp']", '(22)', "cls.mgtSvrDetails['user']", "cls.mgtSvrDetails['passwd']"], {}), "(cls.mgtSvrDetails['mgtSvrIp'], 22, cls.mgtSvrDetails['user'], cls\n .mgtSvrDetails['passwd'])\n", (10413, 10509), False, 'from marvin.sshClient import SshClient\n'), ((13338, 13406), 'marvin.cloudstackAPI.listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd', 'listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd', ([], {}), '()\n', (13404, 13406), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((13741, 13805), 'marvin.cloudstackAPI.addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd', 'addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd', ([], {}), '()\n', (13803, 13805), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((14677, 14747), 'marvin.cloudstackAPI.deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd', 'deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd', ([], {}), '()\n', (14745, 14747), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((27998, 28050), 'marvin.cloudstackAPI.createKubernetesCluster.createKubernetesClusterCmd', 'createKubernetesCluster.createKubernetesClusterCmd', ([], {}), '()\n', (28048, 28050), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((28834, 28882), 'marvin.cloudstackAPI.stopKubernetesCluster.stopKubernetesClusterCmd', 'stopKubernetesCluster.stopKubernetesClusterCmd', ([], {}), '()\n', (28880, 28882), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((29127, 29179), 'marvin.cloudstackAPI.deleteKubernetesCluster.deleteKubernetesClusterCmd', 'deleteKubernetesCluster.deleteKubernetesClusterCmd', ([], {}), '()\n', (29177, 29179), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((29444, 29498), 'marvin.cloudstackAPI.upgradeKubernetesCluster.upgradeKubernetesClusterCmd', 'upgradeKubernetesCluster.upgradeKubernetesClusterCmd', ([], {}), '()\n', (29496, 29498), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((29825, 29875), 'marvin.cloudstackAPI.scaleKubernetesCluster.scaleKubernetesClusterCmd', 'scaleKubernetesCluster.scaleKubernetesClusterCmd', ([], {}), '()\n', (29873, 29875), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((2967, 3052), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""cloud.kubernetes.service.enabled"""', '"""true"""'], {}), "(cls.apiclient, 'cloud.kubernetes.service.enabled', 'true'\n )\n", (2988, 3052), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n'), ((6504, 6641), 'marvin.lib.base.Template.register', 'Template.register', (['cls.apiclient', 'cks_template_data'], {'zoneid': 'cls.zone.id', 'hypervisor': 'cls.hypervisor', 'details': 'cks_template_data_details'}), '(cls.apiclient, cks_template_data, zoneid=cls.zone.id,\n hypervisor=cls.hypervisor, details=cks_template_data_details)\n', (6521, 6641), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n'), ((7503, 7594), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', 'cls.cks_template_name_key', 'cls.cks_template.name'], {}), '(cls.apiclient, cls.cks_template_name_key, cls.\n cks_template.name)\n', (7524, 7594), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n'), ((7934, 7946), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (7944, 7946), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((8024, 8080), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', 'cks_offering_data'], {}), '(cls.apiclient, cks_offering_data)\n', (8046, 8080), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n'), ((9913, 9959), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (9930, 9959), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((10854, 10865), 'time.time', 'time.time', ([], {}), '()\n', (10863, 10865), False, 'import time\n'), ((10886, 10897), 'time.time', 'time.time', ([], {}), '()\n', (10895, 10897), False, 'import time\n'), ((10973, 10986), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (10983, 10986), False, 'import time\n'), ((11510, 11530), 'time.sleep', 'time.sleep', (['interval'], {}), '(interval)\n', (11520, 11530), False, 'import time\n'), ((11563, 11654), 'marvin.lib.base.Template.list', 'Template.list', (['cls.apiclient'], {'id': 'template_id', 'zoneid': 'cls.zone.id', 'templatefilter': '"""self"""'}), "(cls.apiclient, id=template_id, zoneid=cls.zone.id,\n templatefilter='self')\n", (11576, 11654), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n'), ((12566, 12586), 'time.sleep', 'time.sleep', (['interval'], {}), '(interval)\n', (12576, 12586), False, 'import time\n'), ((13961, 13973), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (13971, 13973), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((15309, 15356), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (15326, 15356), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((16172, 16184), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (16182, 16184), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((17558, 17570), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (17568, 17570), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((18784, 18796), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (18794, 18796), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((20259, 20271), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (20269, 20271), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((22097, 22109), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (22107, 22109), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((23957, 23969), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (23967, 23969), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((26102, 26114), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (26112, 26114), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((2626, 2701), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""cloud.kubernetes.service.enabled"""'}), "(cls.apiclient, name='cloud.kubernetes.service.enabled')\n", (2645, 2701), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n'), ((9102, 9215), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', 'cls.cks_template_name_key', 'cls.initial_configuration_cks_template_name'], {}), '(cls.apiclient, cls.cks_template_name_key, cls.\n initial_configuration_cks_template_name)\n', (9123, 9215), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n'), ((9706, 9791), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""cloud.kubernetes.service.enabled"""', '"""false"""'], {}), "(cls.apiclient, 'cloud.kubernetes.service.enabled',\n 'false')\n", (9727, 9791), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n'), ((11203, 11245), 'marvin.cloudstackAPI.listInfrastructure.listInfrastructureCmd', 'listInfrastructure.listInfrastructureCmd', ([], {}), '()\n', (11243, 11245), False, 'from marvin.cloudstackAPI import listInfrastructure, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, createKubernetesCluster, stopKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster\n'), ((7337, 7403), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': 'cls.cks_template_name_key'}), '(cls.apiclient, name=cls.cks_template_name_key)\n', (7356, 7403), False, 'from marvin.lib.base import Template, ServiceOffering, Configurations\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Import Local Modules
from marvin.codes import PASS, FAILED
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import (stopVirtualMachine,
stopRouter,
startRouter)
from marvin.lib.utils import (cleanup_resources,
get_process_status,
get_host_credentials)
from marvin.lib.base import (ServiceOffering,
VirtualMachine,
Account,
Template,
ServiceOffering,
NATRule,
NetworkACL,
FireWallRule,
PublicIPAddress,
NetworkOffering,
Network,
Router,
EgressFireWallRule)
from marvin.lib.common import (get_zone,
get_test_template,
get_domain,
list_virtual_machines,
list_networks,
list_configurations,
list_routers,
list_nat_rules,
list_publicIP,
list_firewall_rules,
list_hosts)
# Import System modules
import time
import logging
def check_router_command(virtual_machine, public_ip, ssh_command, check_string, test_case, retries=5):
result = 'failed'
try:
ssh = virtual_machine.get_ssh_client(ipaddress=public_ip, retries=retries)
result = str(ssh.execute(ssh_command))
except Exception as e:
test_case.fail("Failed to SSH into the Virtual Machine: %s" % e)
logging.debug("Result from SSH into the Virtual Machine: %s" % result)
return result.count(check_string)
class TestRedundantIsolateNetworks(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.logger = logging.getLogger('TestRedundantIsolateNetworks')
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
cls.testClient = super(TestRedundantIsolateNetworks, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.template = get_test_template(cls.api_client, cls.zone.id, cls.hypervisor)
if cls.template == FAILED:
assert False, "get_test_template() failed to return template"
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
# Create an account, network, VM and IP addresses
cls.account = Account.create(
cls.api_client,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.services["nw_off_persistent_RVR_egress_true"] = cls.services["nw_off_persistent_RVR"].copy()
cls.services["nw_off_persistent_RVR_egress_true"]["egress_policy"] = "true"
cls.services["nw_off_persistent_RVR_egress_false"] = cls.services["nw_off_persistent_RVR"].copy()
cls.services["nw_off_persistent_RVR_egress_false"]["egress_policy"] = "false"
cls.services["egress_80"] = {
"startport": 80,
"endport": 80,
"protocol": "TCP",
"cidrlist": ["0.0.0.0/0"]
}
cls.services["egress_53"] = {
"startport": 53,
"endport": 53,
"protocol": "UDP",
"cidrlist": ["0.0.0.0/0"]
}
cls._cleanup = [
cls.service_offering,
cls.account
]
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
return
def tearDown(self):
try:
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "advancedns", "ssh"], required_hardware="true")
def test_01_RVR_Network_FW_PF_SSH_default_routes_egress_true(self):
""" Test redundant router internals """
self.logger.debug("Starting test_01_RVR_Network_FW_PF_SSH_default_routes_egress_true...")
self.logger.debug("Creating Network Offering with default egress TRUE")
network_offering_egress_true = NetworkOffering.create(
self.apiclient,
self.services["nw_off_persistent_RVR_egress_true"],
conservemode=True
)
network_offering_egress_true.update(self.api_client, state='Enabled')
self.logger.debug("Creating network with network offering: %s" % network_offering_egress_true.id)
network = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=network_offering_egress_true.id,
zoneid=self.zone.id
)
self.logger.debug("Created network with ID: %s" % network.id)
networks = Network.list(
self.apiclient,
id=network.id,
listall=True
)
self.assertEqual(
isinstance(networks, list),
True,
"List networks should return a valid response for created network"
)
nw_response = networks[0]
self.logger.debug("Deploying VM in account: %s" % self.account.name)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(network.id)]
)
self.logger.debug("Deployed VM in network: %s" % network.id)
self.cleanup.insert(0, network_offering_egress_true)
self.cleanup.insert(0, network)
self.cleanup.insert(0, virtual_machine)
vms = VirtualMachine.list(
self.apiclient,
id=virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"List Vms should return a valid list"
)
vm = vms[0]
self.assertEqual(
vm.state,
"Running",
"VM should be in running state after deployment"
)
self.logger.debug("Listing routers for network: %s" % network.name)
routers = Router.list(
self.apiclient,
networkid=network.id,
listall=True
)
self.assertEqual(
isinstance(routers, list),
True,
"list router should return Primary and backup routers"
)
self.assertEqual(
len(routers),
2,
"Length of the list router should be 2 (Backup & Primary)"
)
public_ips = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
public_ip = public_ips[0]
self.assertEqual(
isinstance(public_ips, list),
True,
"Check for list public IPs response return valid data"
)
self.logger.debug("Creating Firewall rule for VM ID: %s" % virtual_machine.id)
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.id,
protocol=self.services["natrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["natrule"]["publicport"],
endport=self.services["natrule"]["publicport"]
)
self.logger.debug("Creating NAT rule for VM ID: %s" % virtual_machine.id)
nat_rule = NATRule.create(
self.apiclient,
virtual_machine,
self.services["natrule"],
public_ip.id
)
# Test SSH after closing port 22
expected = 1
ssh_command = "ping -c 3 8.8.8.8"
check_string = " 0% packet loss"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Ping to outside world from VM should be successful!"
)
expected = 1
ssh_command = "wget -t 1 -T 5 www.google.com"
check_string = "HTTP request sent, awaiting response... 200 OK"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Attempt to retrieve google.com index page should be successful!"
)
EgressFireWallRule.create(
self.apiclient,
networkid=network.id,
protocol=self.services["egress_80"]["protocol"],
startport=self.services["egress_80"]["startport"],
endport=self.services["egress_80"]["endport"],
cidrlist=self.services["egress_80"]["cidrlist"]
)
expected = 0
ssh_command = "wget -t 1 -T 1 www.google.com"
check_string = "HTTP request sent, awaiting response... 200 OK"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Attempt to retrieve google.com index page should NOT be successful once rule is added!"
)
return
@attr(tags=["advanced", "advancedns", "ssh"], required_hardware="true")
def test_02_RVR_Network_FW_PF_SSH_default_routes_egress_false(self):
""" Test redundant router internals """
self.logger.debug("Starting test_02_RVR_Network_FW_PF_SSH_default_routes_egress_false...")
self.logger.debug("Creating Network Offering with default egress FALSE")
network_offering_egress_false = NetworkOffering.create(
self.apiclient,
self.services["nw_off_persistent_RVR_egress_false"],
conservemode=True
)
network_offering_egress_false.update(self.api_client, state='Enabled')
self.logger.debug("Creating network with network offering: %s" % network_offering_egress_false.id)
network = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=network_offering_egress_false.id,
zoneid=self.zone.id
)
self.logger.debug("Created network with ID: %s" % network.id)
networks = Network.list(
self.apiclient,
id=network.id,
listall=True
)
self.assertEqual(
isinstance(networks, list),
True,
"List networks should return a valid response for created network"
)
nw_response = networks[0]
self.logger.debug("Deploying VM in account: %s" % self.account.name)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(network.id)]
)
self.logger.debug("Deployed VM in network: %s" % network.id)
self.cleanup.insert(0, network_offering_egress_false)
self.cleanup.insert(0, network)
self.cleanup.insert(0, virtual_machine)
vms = VirtualMachine.list(
self.apiclient,
id=virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"List Vms should return a valid list"
)
vm = vms[0]
self.assertEqual(
vm.state,
"Running",
"VM should be in running state after deployment"
)
self.logger.debug("Listing routers for network: %s" % network.name)
routers = Router.list(
self.apiclient,
networkid=network.id,
listall=True
)
self.assertEqual(
isinstance(routers, list),
True,
"list router should return Primary and backup routers"
)
self.assertEqual(
len(routers),
2,
"Length of the list router should be 2 (Backup & Primary)"
)
public_ips = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(public_ips, list),
True,
"Check for list public IPs response return valid data"
)
public_ip = public_ips[0]
self.logger.debug("Creating Firewall rule for VM ID: %s" % virtual_machine.id)
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.id,
protocol=self.services["natrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["natrule"]["publicport"],
endport=self.services["natrule"]["publicport"]
)
self.logger.debug("Creating NAT rule for VM ID: %s" % virtual_machine.id)
nat_rule = NATRule.create(
self.apiclient,
virtual_machine,
self.services["natrule"],
public_ip.id
)
expected = 0
ssh_command = "ping -c 3 8.8.8.8"
check_string = " 0% packet loss"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Ping to outside world from VM should NOT be successful"
)
expected = 0
ssh_command = "wget -t 1 -T 1 www.google.com"
check_string = "HTTP request sent, awaiting response... 200 OK"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Attempt to retrieve google.com index page should NOT be successful"
)
EgressFireWallRule.create(
self.apiclient,
networkid=network.id,
protocol=self.services["egress_80"]["protocol"],
startport=self.services["egress_80"]["startport"],
endport=self.services["egress_80"]["endport"],
cidrlist=self.services["egress_80"]["cidrlist"]
)
EgressFireWallRule.create(
self.apiclient,
networkid=network.id,
protocol=self.services["egress_53"]["protocol"],
startport=self.services["egress_53"]["startport"],
endport=self.services["egress_53"]["endport"],
cidrlist=self.services["egress_53"]["cidrlist"]
)
expected = 1
ssh_command = "wget -t 1 -T 5 www.google.com"
check_string = "HTTP request sent, awaiting response... 200 OK"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Attempt to retrieve google.com index page should be successful once rule is added!"
)
return
@attr(tags=["advanced", "advancedns", "ssh"], required_hardware="true")
def test_03_RVR_Network_check_router_state(self):
""" Test redundant router internals """
self.logger.debug("Starting test_03_RVR_Network_check_router_state...")
hypervisor = self.testClient.getHypervisorInfo()
self.logger.debug("Creating Network Offering with default egress FALSE")
network_offering_egress_false = NetworkOffering.create(
self.apiclient,
self.services["nw_off_persistent_RVR_egress_false"],
conservemode=True
)
network_offering_egress_false.update(self.apiclient, state='Enabled')
self.logger.debug("Creating network with network offering: %s" % network_offering_egress_false.id)
network = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=network_offering_egress_false.id,
zoneid=self.zone.id
)
self.logger.debug("Created network with ID: %s" % network.id)
networks = Network.list(
self.apiclient,
id=network.id,
listall=True
)
self.assertEqual(
isinstance(networks, list),
True,
"List networks should return a valid response for created network"
)
nw_response = networks[0]
self.logger.debug("Deploying VM in account: %s" % self.account.name)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(network.id)]
)
self.logger.debug("Deployed VM in network: %s" % network.id)
self.cleanup.insert(0, network_offering_egress_false)
self.cleanup.insert(0, network)
self.cleanup.insert(0, virtual_machine)
vms = VirtualMachine.list(
self.apiclient,
id=virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"List Vms should return a valid list"
)
vm = vms[0]
self.assertEqual(
vm.state,
"Running",
"VM should be in running state after deployment"
)
self.logger.debug("Listing routers for network: %s" % network.name)
routers = Router.list(
self.apiclient,
networkid=network.id,
listall=True
)
self.assertEqual(
isinstance(routers, list),
True,
"list router should return Primary and backup routers"
)
self.assertEqual(
len(routers),
2,
"Length of the list router should be 2 (Backup & Primary)"
)
vals = ["PRIMARY", "BACKUP", "UNKNOWN"]
cnts = [0, 0, 0]
result = "UNKNOWN"
for router in routers:
if router.state == "Running":
hosts = list_hosts(
self.apiclient,
zoneid=router.zoneid,
type='Routing',
state='Up',
id=router.hostid
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check list host returns a valid list"
)
host = hosts[0]
if hypervisor.lower() in ('vmware', 'hyperv'):
result = str(get_process_status(
self.apiclient.connection.mgtSvr,
22,
self.apiclient.connection.user,
self.apiclient.connection.passwd,
router.linklocalip,
"sh /opt/cloud/bin/checkrouter.sh ",
hypervisor=hypervisor
))
else:
try:
host.user, host.passwd = get_host_credentials(
self.config, host.ipaddress)
result = str(get_process_status(
host.ipaddress,
22,
host.user,
host.passwd,
router.linklocalip,
"sh /opt/cloud/bin/checkrouter.sh "
))
except KeyError:
self.skipTest(
"Marvin configuration has no host credentials to\
check router services")
if result.count(vals[0]) == 1:
cnts[vals.index(vals[0])] += 1
if cnts[vals.index('PRIMARY')] != 1:
self.fail("No Primary or too many primary routers found %s" % cnts[vals.index('PRIMARY')])
return
class TestIsolatedNetworks(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.logger = logging.getLogger('TestIsolatedNetworks')
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
cls.testClient = super(TestIsolatedNetworks, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.services['mode'] = cls.zone.networktype
cls.template = get_test_template(
cls.api_client,
cls.zone.id,
cls.hypervisor
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
# Create an account, network, VM and IP addresses
cls.account = Account.create(
cls.api_client,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.services["network_offering_egress_true"] = cls.services["network_offering"].copy()
cls.services["network_offering_egress_true"]["egress_policy"] = "true"
cls.services["network_offering_egress_false"] = cls.services["network_offering"].copy()
cls.services["network_offering_egress_false"]["egress_policy"] = "false"
cls.services["egress_80"] = {
"startport": 80,
"endport": 80,
"protocol": "TCP",
"cidrlist": ["0.0.0.0/0"]
}
cls._cleanup = [
cls.service_offering,
cls.account
]
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "advancedns", "ssh"], required_hardware="true")
def test_01_isolate_network_FW_PF_default_routes_egress_true(self):
""" Test redundant router internals """
self.logger.debug("Starting test_01_isolate_network_FW_PF_default_routes_egress_true...")
self.logger.debug("Creating Network Offering with default egress TRUE")
network_offering_egress_true = NetworkOffering.create(self.apiclient,
self.services["network_offering_egress_true"],
conservemode=True)
network_offering_egress_true.update(self.apiclient, state='Enabled')
self.logger.debug("Creating Network with Network Offering ID %s" % network_offering_egress_true.id)
network = Network.create(self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=network_offering_egress_true.id,
zoneid=self.zone.id)
self.logger.debug("Deploying Virtual Machine on Network %s" % network.id)
virtual_machine = VirtualMachine.create(self.apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.domain.id,
serviceofferingid=self.service_offering.id,
networkids=[str(network.id)])
self.logger.debug("Deployed VM in network: %s" % network.id)
self.cleanup.insert(0, network_offering_egress_true)
self.cleanup.insert(0, network)
self.cleanup.insert(0, virtual_machine)
self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
routers = list_routers(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
router = routers[0]
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
public_ips = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(public_ips, list),
True,
"Check for list public IPs response return valid data"
)
public_ip = public_ips[0]
self.logger.debug("Creating Firewall rule for VM ID: %s" % virtual_machine.id)
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.id,
protocol=self.services["natrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["natrule"]["publicport"],
endport=self.services["natrule"]["publicport"]
)
self.logger.debug("Creating NAT rule for VM ID: %s" % virtual_machine.id)
# Create NAT rule
nat_rule = NATRule.create(
self.apiclient,
virtual_machine,
self.services["natrule"],
public_ip.id
)
nat_rules = list_nat_rules(
self.apiclient,
id=nat_rule.id
)
self.assertEqual(
isinstance(nat_rules, list),
True,
"Check for list NAT rules response return valid data"
)
self.assertEqual(
nat_rules[0].state,
'Active',
"Check list port forwarding rules"
)
# Test SSH after closing port 22
expected = 1
ssh_command = "ping -c 3 8.8.8.8"
check_string = " 0% packet loss"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Ping to outside world from VM should be successful!"
)
expected = 1
ssh_command = "wget -t 1 -T 5 www.google.com"
check_string = "HTTP request sent, awaiting response... 200 OK"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Attempt to retrieve google.com index page should be successful!"
)
EgressFireWallRule.create(
self.apiclient,
networkid=network.id,
protocol=self.services["egress_80"]["protocol"],
startport=self.services["egress_80"]["startport"],
endport=self.services["egress_80"]["endport"],
cidrlist=self.services["egress_80"]["cidrlist"]
)
expected = 0
ssh_command = "wget -t 1 -T 1 www.google.com"
check_string = "HTTP request sent, awaiting response... 200 OK"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Attempt to retrieve google.com index page should NOT be successful once rule is added!"
)
return
@attr(tags=["advanced", "advancedns", "ssh"], required_hardware="true")
def test_02_isolate_network_FW_PF_default_routes_egress_false(self):
""" Test redundant router internals """
self.logger.debug("Starting test_02_isolate_network_FW_PF_default_routes_egress_false...")
self.logger.debug("Creating Network Offering with default egress FALSE")
network_offering_egress_false = NetworkOffering.create(self.apiclient,
self.services["network_offering_egress_false"],
conservemode=True)
network_offering_egress_false.update(self.apiclient, state='Enabled')
self.logger.debug("Creating Network with Network Offering ID %s" % network_offering_egress_false.id)
network = Network.create(self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=network_offering_egress_false.id,
zoneid=self.zone.id)
self.logger.debug("Deploying Virtual Machine on Network %s" % network.id)
virtual_machine = VirtualMachine.create(self.apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.domain.id,
serviceofferingid=self.service_offering.id,
networkids=[str(network.id)])
self.logger.debug("Deployed VM in network: %s" % network.id)
self.cleanup.insert(0, network_offering_egress_false)
self.cleanup.insert(0, network)
self.cleanup.insert(0, virtual_machine)
self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
routers = list_routers(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
router = routers[0]
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
public_ips = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(public_ips, list),
True,
"Check for list public IPs response return valid data"
)
public_ip = public_ips[0]
self.logger.debug("Creating Firewall rule for VM ID: %s" % virtual_machine.id)
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.id,
protocol=self.services["natrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["natrule"]["publicport"],
endport=self.services["natrule"]["publicport"]
)
self.logger.debug("Creating NAT rule for VM ID: %s" % virtual_machine.id)
# Create NAT rule
nat_rule = NATRule.create(
self.apiclient,
virtual_machine,
self.services["natrule"],
public_ip.id
)
nat_rules = list_nat_rules(
self.apiclient,
id=nat_rule.id
)
self.assertEqual(
isinstance(nat_rules, list),
True,
"Check for list NAT rules response return valid data"
)
self.assertEqual(
nat_rules[0].state,
'Active',
"Check list port forwarding rules"
)
expected = 0
ssh_command = "ping -c 3 8.8.8.8"
check_string = " 0% packet loss"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Ping to outside world from VM should NOT be successful"
)
expected = 0
ssh_command = "wget -t 1 -T 1 www.google.com"
check_string = "HTTP request sent, awaiting response... 200 OK"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Attempt to retrieve google.com index page should NOT be successful"
)
EgressFireWallRule.create(
self.apiclient,
networkid=network.id,
protocol=self.services["egress_80"]["protocol"],
startport=self.services["egress_80"]["startport"],
endport=self.services["egress_80"]["endport"],
cidrlist=self.services["egress_80"]["cidrlist"]
)
expected = 1
ssh_command = "wget -t 1 -T 5 www.google.com"
check_string = "HTTP request sent, awaiting response... 200 OK"
result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)
self.assertEqual(
result,
expected,
"Attempt to retrieve google.com index page should be successful once rule is added!"
)
return
| [
"marvin.lib.utils.get_process_status",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.FireWallRule.create",
"marvin.lib.utils.get_host_credentials",
"marvin.lib.common.list_publicIP",
"marvin.lib.common.list_nat_rules",
"marvin.lib.base.Network.create",
"marvin.lib.common.list_routers",
"ma... | [((2733, 2803), 'logging.debug', 'logging.debug', (["('Result from SSH into the Virtual Machine: %s' % result)"], {}), "('Result from SSH into the Virtual Machine: %s' % result)\n", (2746, 2803), False, 'import logging\n'), ((6059, 6129), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'ssh']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'ssh'], required_hardware='true')\n", (6063, 6129), False, 'from nose.plugins.attrib import attr\n'), ((12985, 13055), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'ssh']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'ssh'], required_hardware='true')\n", (12989, 13055), False, 'from nose.plugins.attrib import attr\n'), ((20383, 20453), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'ssh']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'ssh'], required_hardware='true')\n", (20387, 20453), False, 'from nose.plugins.attrib import attr\n'), ((29198, 29268), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'ssh']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'ssh'], required_hardware='true')\n", (29202, 29268), False, 'from nose.plugins.attrib import attr\n'), ((35312, 35382), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'ssh']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'ssh'], required_hardware='true')\n", (35316, 35382), False, 'from nose.plugins.attrib import attr\n'), ((2965, 3014), 'logging.getLogger', 'logging.getLogger', (['"""TestRedundantIsolateNetworks"""'], {}), "('TestRedundantIsolateNetworks')\n", (2982, 3014), False, 'import logging\n'), ((3044, 3067), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (3065, 3067), False, 'import logging\n'), ((3429, 3455), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (3439, 3455), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((3671, 3733), 'marvin.lib.common.get_test_template', 'get_test_template', (['cls.api_client', 'cls.zone.id', 'cls.hypervisor'], {}), '(cls.api_client, cls.zone.id, cls.hypervisor)\n', (3688, 3733), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((4059, 4154), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], admin=True,\n domainid=cls.domain.id)\n", (4073, 4154), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((4240, 4312), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (4262, 4312), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((6468, 6582), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['nw_off_persistent_RVR_egress_true']"], {'conservemode': '(True)'}), "(self.apiclient, self.services[\n 'nw_off_persistent_RVR_egress_true'], conservemode=True)\n", (6490, 6582), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((6959, 7158), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'network_offering_egress_true.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=\n network_offering_egress_true.id, zoneid=self.zone.id)\n", (6973, 7158), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((7465, 7522), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'network.id', 'listall': '(True)'}), '(self.apiclient, id=network.id, listall=True)\n', (7477, 7522), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((8714, 8786), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, id=virtual_machine.id, listall=True)\n', (8733, 8786), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((9433, 9496), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'network.id', 'listall': '(True)'}), '(self.apiclient, networkid=network.id, listall=True)\n', (9444, 9496), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((10021, 10135), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, zoneid=self.zone.id)\n', (10034, 10135), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((10484, 10729), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=public_ip.id, protocol=self\n .services['natrule']['protocol'], cidrlist=['0.0.0.0/0'], startport=\n self.services['natrule']['publicport'], endport=self.services['natrule'\n ]['publicport'])\n", (10503, 10729), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((10899, 10990), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'virtual_machine', "self.services['natrule']", 'public_ip.id'], {}), "(self.apiclient, virtual_machine, self.services['natrule'],\n public_ip.id)\n", (10913, 10990), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((11978, 12252), 'marvin.lib.base.EgressFireWallRule.create', 'EgressFireWallRule.create', (['self.apiclient'], {'networkid': 'network.id', 'protocol': "self.services['egress_80']['protocol']", 'startport': "self.services['egress_80']['startport']", 'endport': "self.services['egress_80']['endport']", 'cidrlist': "self.services['egress_80']['cidrlist']"}), "(self.apiclient, networkid=network.id, protocol=\n self.services['egress_80']['protocol'], startport=self.services[\n 'egress_80']['startport'], endport=self.services['egress_80']['endport'\n ], cidrlist=self.services['egress_80']['cidrlist'])\n", (12003, 12252), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((13398, 13513), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['nw_off_persistent_RVR_egress_false']"], {'conservemode': '(True)'}), "(self.apiclient, self.services[\n 'nw_off_persistent_RVR_egress_false'], conservemode=True)\n", (13420, 13513), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((13892, 14092), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'network_offering_egress_false.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=\n network_offering_egress_false.id, zoneid=self.zone.id)\n", (13906, 14092), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((14399, 14456), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'network.id', 'listall': '(True)'}), '(self.apiclient, id=network.id, listall=True)\n', (14411, 14456), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((15649, 15721), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, id=virtual_machine.id, listall=True)\n', (15668, 15721), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((16368, 16431), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'network.id', 'listall': '(True)'}), '(self.apiclient, networkid=network.id, listall=True)\n', (16379, 16431), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((16956, 17070), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, zoneid=self.zone.id)\n', (16969, 17070), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((17419, 17664), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=public_ip.id, protocol=self\n .services['natrule']['protocol'], cidrlist=['0.0.0.0/0'], startport=\n self.services['natrule']['publicport'], endport=self.services['natrule'\n ]['publicport'])\n", (17438, 17664), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((17834, 17925), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'virtual_machine', "self.services['natrule']", 'public_ip.id'], {}), "(self.apiclient, virtual_machine, self.services['natrule'],\n public_ip.id)\n", (17848, 17925), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((18878, 19152), 'marvin.lib.base.EgressFireWallRule.create', 'EgressFireWallRule.create', (['self.apiclient'], {'networkid': 'network.id', 'protocol': "self.services['egress_80']['protocol']", 'startport': "self.services['egress_80']['startport']", 'endport': "self.services['egress_80']['endport']", 'cidrlist': "self.services['egress_80']['cidrlist']"}), "(self.apiclient, networkid=network.id, protocol=\n self.services['egress_80']['protocol'], startport=self.services[\n 'egress_80']['startport'], endport=self.services['egress_80']['endport'\n ], cidrlist=self.services['egress_80']['cidrlist'])\n", (18903, 19152), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((19380, 19654), 'marvin.lib.base.EgressFireWallRule.create', 'EgressFireWallRule.create', (['self.apiclient'], {'networkid': 'network.id', 'protocol': "self.services['egress_53']['protocol']", 'startport': "self.services['egress_53']['startport']", 'endport': "self.services['egress_53']['endport']", 'cidrlist': "self.services['egress_53']['cidrlist']"}), "(self.apiclient, networkid=network.id, protocol=\n self.services['egress_53']['protocol'], startport=self.services[\n 'egress_53']['startport'], endport=self.services['egress_53']['endport'\n ], cidrlist=self.services['egress_53']['cidrlist'])\n", (19405, 19654), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((20816, 20931), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['nw_off_persistent_RVR_egress_false']"], {'conservemode': '(True)'}), "(self.apiclient, self.services[\n 'nw_off_persistent_RVR_egress_false'], conservemode=True)\n", (20838, 20931), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((21309, 21509), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'network_offering_egress_false.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=\n network_offering_egress_false.id, zoneid=self.zone.id)\n", (21323, 21509), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((21816, 21873), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'network.id', 'listall': '(True)'}), '(self.apiclient, id=network.id, listall=True)\n', (21828, 21873), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((23066, 23138), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, id=virtual_machine.id, listall=True)\n', (23085, 23138), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((23785, 23848), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'network.id', 'listall': '(True)'}), '(self.apiclient, networkid=network.id, listall=True)\n', (23796, 23848), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((26625, 26666), 'logging.getLogger', 'logging.getLogger', (['"""TestIsolatedNetworks"""'], {}), "('TestIsolatedNetworks')\n", (26642, 26666), False, 'import logging\n'), ((26696, 26719), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (26717, 26719), False, 'import logging\n'), ((27073, 27099), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (27083, 27099), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((27313, 27375), 'marvin.lib.common.get_test_template', 'get_test_template', (['cls.api_client', 'cls.zone.id', 'cls.hypervisor'], {}), '(cls.api_client, cls.zone.id, cls.hypervisor)\n', (27330, 27375), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((27567, 27662), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], admin=True,\n domainid=cls.domain.id)\n", (27581, 27662), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((27748, 27820), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (27770, 27820), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((29607, 29716), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering_egress_true']"], {'conservemode': '(True)'}), "(self.apiclient, self.services[\n 'network_offering_egress_true'], conservemode=True)\n", (29629, 29716), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((30027, 30226), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'network_offering_egress_true.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=\n network_offering_egress_true.id, zoneid=self.zone.id)\n", (30041, 30226), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((31313, 31405), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (31325, 31405), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((31922, 32036), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, zoneid=self.zone.id)\n', (31935, 32036), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((32385, 32630), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=public_ip.id, protocol=self\n .services['natrule']['protocol'], cidrlist=['0.0.0.0/0'], startport=\n self.services['natrule']['publicport'], endport=self.services['natrule'\n ]['publicport'])\n", (32404, 32630), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((32826, 32917), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'virtual_machine', "self.services['natrule']", 'public_ip.id'], {}), "(self.apiclient, virtual_machine, self.services['natrule'],\n public_ip.id)\n", (32840, 32917), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((32993, 33039), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'id': 'nat_rule.id'}), '(self.apiclient, id=nat_rule.id)\n', (33007, 33039), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((34305, 34579), 'marvin.lib.base.EgressFireWallRule.create', 'EgressFireWallRule.create', (['self.apiclient'], {'networkid': 'network.id', 'protocol': "self.services['egress_80']['protocol']", 'startport': "self.services['egress_80']['startport']", 'endport': "self.services['egress_80']['endport']", 'cidrlist': "self.services['egress_80']['cidrlist']"}), "(self.apiclient, networkid=network.id, protocol=\n self.services['egress_80']['protocol'], startport=self.services[\n 'egress_80']['startport'], endport=self.services['egress_80']['endport'\n ], cidrlist=self.services['egress_80']['cidrlist'])\n", (34330, 34579), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((35725, 35835), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering_egress_false']"], {'conservemode': '(True)'}), "(self.apiclient, self.services[\n 'network_offering_egress_false'], conservemode=True)\n", (35747, 35835), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((36148, 36348), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'network_offering_egress_false.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=\n network_offering_egress_false.id, zoneid=self.zone.id)\n", (36162, 36348), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((37436, 37528), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (37448, 37528), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((38045, 38159), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, zoneid=self.zone.id)\n', (38058, 38159), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((38508, 38753), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=public_ip.id, protocol=self\n .services['natrule']['protocol'], cidrlist=['0.0.0.0/0'], startport=\n self.services['natrule']['publicport'], endport=self.services['natrule'\n ]['publicport'])\n", (38527, 38753), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((38949, 39040), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'virtual_machine', "self.services['natrule']", 'public_ip.id'], {}), "(self.apiclient, virtual_machine, self.services['natrule'],\n public_ip.id)\n", (38963, 39040), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((39116, 39162), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'id': 'nat_rule.id'}), '(self.apiclient, id=nat_rule.id)\n', (39130, 39162), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((40393, 40667), 'marvin.lib.base.EgressFireWallRule.create', 'EgressFireWallRule.create', (['self.apiclient'], {'networkid': 'network.id', 'protocol': "self.services['egress_80']['protocol']", 'startport': "self.services['egress_80']['startport']", 'endport': "self.services['egress_80']['endport']", 'cidrlist': "self.services['egress_80']['cidrlist']"}), "(self.apiclient, networkid=network.id, protocol=\n self.services['egress_80']['protocol'], startport=self.services[\n 'egress_80']['startport'], endport=self.services['egress_80']['endport'\n ], cidrlist=self.services['egress_80']['cidrlist'])\n", (40418, 40667), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, Template, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router, EgressFireWallRule\n'), ((5547, 5594), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (5564, 5594), False, 'from marvin.lib.utils import cleanup_resources, get_process_status, get_host_credentials\n'), ((5884, 5932), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.api_client', 'self.cleanup'], {}), '(self.api_client, self.cleanup)\n', (5901, 5932), False, 'from marvin.lib.utils import cleanup_resources, get_process_status, get_host_credentials\n'), ((28687, 28734), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (28704, 28734), False, 'from marvin.lib.utils import cleanup_resources, get_process_status, get_host_credentials\n'), ((29024, 29071), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (29041, 29071), False, 'from marvin.lib.utils import cleanup_resources, get_process_status, get_host_credentials\n'), ((24550, 24648), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'zoneid': 'router.zoneid', 'type': '"""Routing"""', 'state': '"""Up"""', 'id': 'router.hostid'}), "(self.apiclient, zoneid=router.zoneid, type='Routing', state='Up',\n id=router.hostid)\n", (24560, 24648), False, 'from marvin.lib.common import get_zone, get_test_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((25078, 25289), 'marvin.lib.utils.get_process_status', 'get_process_status', (['self.apiclient.connection.mgtSvr', '(22)', 'self.apiclient.connection.user', 'self.apiclient.connection.passwd', 'router.linklocalip', '"""sh /opt/cloud/bin/checkrouter.sh """'], {'hypervisor': 'hypervisor'}), "(self.apiclient.connection.mgtSvr, 22, self.apiclient.\n connection.user, self.apiclient.connection.passwd, router.linklocalip,\n 'sh /opt/cloud/bin/checkrouter.sh ', hypervisor=hypervisor)\n", (25096, 25289), False, 'from marvin.lib.utils import cleanup_resources, get_process_status, get_host_credentials\n'), ((25600, 25649), 'marvin.lib.utils.get_host_credentials', 'get_host_credentials', (['self.config', 'host.ipaddress'], {}), '(self.config, host.ipaddress)\n', (25620, 25649), False, 'from marvin.lib.utils import cleanup_resources, get_process_status, get_host_credentials\n'), ((25716, 25840), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', '(22)', 'host.user', 'host.passwd', 'router.linklocalip', '"""sh /opt/cloud/bin/checkrouter.sh """'], {}), "(host.ipaddress, 22, host.user, host.passwd, router.\n linklocalip, 'sh /opt/cloud/bin/checkrouter.sh ')\n", (25734, 25840), False, 'from marvin.lib.utils import cleanup_resources, get_process_status, get_host_credentials\n')] |
from marvin.lib.base import (Vpn,
VpnCustomerGateway,
StaticRoute,
PrivateGateway,
Network,
NATRule,
PublicIPAddress,
VirtualMachine,
NetworkACL,
NetworkACLList,
VPC,
Account,
Domain,
EgressFireWallRule,
FireWallRule,
Tag)
from marvin.lib.common import (get_vpngateway,
get_vpc,
get_virtual_machine,
get_network,
get_network_acl)
from marvin.lib.utils import (random_gen,
cleanup_resources)
from marvin.utils.MarvinLog import MarvinLog
class TestScenarioManager:
def __init__(self, api_client, scenario_data, test_data, zone, randomizeNames, cleanup):
self.api_client = api_client
self.scenario_data = scenario_data
self.test_data = test_data
self.zone = zone
self.logger = MarvinLog(MarvinLog.LOGGER_TEST).get_logger()
self.dynamic_names = {
'accounts': {},
'vpcs': {},
'vms': {},
}
self.randomizeNames = randomizeNames
self.resources_to_cleanup = []
self.cleanup = cleanup
@property
def test_data(self):
return self.test_data
def get_dynamic_name(self, section, name):
if name in self.dynamic_names[section]:
return self.dynamic_names[section][name]
else:
return name
def setup_infra(self):
scenario_data = self.scenario_data['data']
self.deploy_domains(scenario_data['domains'])
def deploy_domains(self, domains_data):
for domain in domains_data:
self.deploy_domain(domain['data'])
def deploy_domain(self, domain_data):
if domain_data['name'] == 'ROOT':
domain_list = Domain.list(
api_client=self.api_client,
name=domain_data['name']
)
domain = domain_list[0]
else:
self.logger.debug('>>> DOMAIN => Creating "%s"...', domain_data['name'])
domain = Domain.create(
api_client=self.api_client,
name=domain_data['name'] + ('-' + random_gen() if self.randomizeNames else '')
)
self.logger.debug('>>> DOMAIN => ID: %s => Name: %s => Path: %s => State: %s', domain.id, domain.name,
domain.path, domain.state)
self.deploy_accounts(domain_data['accounts'], domain)
def deploy_accounts(self, accounts_data, domain):
for account in accounts_data:
self.deploy_account(account['data'], domain)
def deploy_account(self, account_data, domain):
self.logger.debug('>>> ACCOUNT => Creating "%s"...', account_data['username'])
account = None
if not self.randomizeNames:
account_list = Account.list(api_client=self.api_client, name=account_data['username'], listall=True)
if isinstance(account_list, list) and len(account_list) >= 1:
if account_list[0].name == account_data['username']:
account = account_list[0]
self.logger.debug('>>> ACCOUNT => Loaded from (pre) existing account, ID: %s', account.id)
return
if not account:
account = Account.create(
api_client=self.api_client,
services=account_data,
domainid=domain.uuid,
randomizeID=self.randomizeNames
)
self.resources_to_cleanup.append(account)
self.dynamic_names['accounts'][account_data['username']] = account.name
self.logger.debug('>>> ACCOUNT => ID: %s => Name: %s => State: %s => Domain: %s', account.id,
account.name, account.state, account.domainid)
self.deploy_vpcs(account_data['vpcs'], account)
self.deploy_isolatednetworks(account_data['isolatednetworks'], account)
self.deploy_vms(account_data['virtualmachines'], account)
self.deploy_vpcs_publicipaddresses(account_data['vpcs'], account_data['virtualmachines'])
self.deploy_isolatednetworks_publicipaddresses(account_data['isolatednetworks'], account_data['virtualmachines'])
self.deploy_privatenetworks(account_data['privatenetworks'], account, domain)
self.deploy_vpcs_privategateways(account_data['vpcs'])
self.enable_vpcs_localvpngateway(account_data['vpcs'])
self.deploy_vpcs_remotevpngateways(account_data['vpcs'], account)
def deploy_vpcs(self, vpcs_data, account):
for vpc in vpcs_data:
self.deploy_vpc(vpc['data'], account)
def deploy_vpc(self, vpc_data, account):
self.logger.debug('>>> VPC => Creating "%s"...', vpc_data['name'])
vpc = VPC.create(
api_client=self.api_client,
data=vpc_data,
zone=self.zone,
account=account,
randomizeID=self.randomizeNames
)
self.dynamic_names['vpcs'][vpc_data['name']] = vpc.name
self.logger.debug('>>> VPC => ID: %s => Name: %s => CIDR: %s => State: %s => Offering: %s '
'=> Account: %s => Domain: %s', vpc.id, vpc.name, vpc.cidr, vpc.state, vpc.vpcofferingid,
vpc.account, vpc.domainid)
self.deploy_acls(vpc_data['acls'], vpc)
self.deploy_networks(vpc_data['networks'], vpc)
def deploy_acls(self, acls_data, vpc):
for acl in acls_data:
self.deploy_acl(acl['data'], vpc)
def deploy_acl(self, acl_data, vpc):
self.logger.debug('>>> ACL => Creating "%s"...', acl_data['name'])
acl = NetworkACLList.create(
api_client=self.api_client,
data=acl_data,
vpc=vpc
)
self.logger.debug('>>> ACL => ID: %s => Name: %s => VPC: %s', acl.id, acl.name, acl.vpcid)
self.deploy_rules(acl_data['rules'], acl)
def deploy_rules(self, rules_data, acl):
for rule in rules_data:
self.deploy_rule(rule['data'], acl)
def deploy_rule(self, rule_data, acl):
self.logger.debug('>>> ACL RULE => Creating...')
rule = NetworkACL.create(
api_client=self.api_client,
data=rule_data,
acl=acl
)
self.logger.debug('>>> ACL RULE => ID: %s => Number: %s => Action: %s => Traffic Type: %s '
'=> CIDR List: %s => Protocol: %s => Start Port: %s => End Port: %s => ACL: %s',
rule.id, rule.number, rule.action, rule.traffictype, rule.cidrlist, rule.protocol.upper(),
rule.startport, rule.endport, rule.aclid)
def deploy_networks(self, networks_data, vpc):
for network in networks_data:
self.deploy_network(network['data'], vpc)
def deploy_network(self, network_data, vpc):
acl = get_network_acl(api_client=self.api_client, name=network_data['aclname'], vpc=vpc)
self.logger.debug('>>> TIER => Creating "%s"...', network_data['name'])
network = Network.create(
self.api_client,
data=network_data,
vpc=vpc,
zone=self.zone,
acl=acl
)
self.logger.debug('>>> TIER => ID: %s => Name: %s => CIDR: %s => Gateway: %s => Type: %s '
'=> Traffic Type: %s => State: %s => Offering: %s => ACL: %s '
'=> Physical Network: %s => VPC: %s => Domain: %s', network.id, network.name,
network.cidr, network.gateway, network.type, network.traffictype, network.state,
network.networkofferingid, network.aclid, network.physicalnetworkid, network.vpcid,
network.domainid)
def deploy_vms(self, vms_data, account):
for vm in vms_data:
self.deploy_vm(vm['data'], account)
def deploy_vm(self, vm_data, account):
network_and_ip_list = []
for nic in vm_data['nics']:
network = get_network(api_client=self.api_client, name=nic['data']['networkname'])
network_and_ip = {
'networkid': network.id
}
if 'guestip' in nic['data']:
network_and_ip['ip'] = nic['data']['guestip']
network_and_ip_list.append(network_and_ip)
self.logger.debug('>>> VM => Creating "%s"...', vm_data['name'])
vm = VirtualMachine.create(
self.api_client,
data=vm_data,
zone=self.zone,
account=account,
network_and_ip_list=network_and_ip_list
)
self.dynamic_names['vms'][vm_data['name']] = vm.name
self.logger.debug('>>> VM => ID: %s => Name: %s => IP: %s => State: %s => Offering: %s '
'=> Template: %s => Hypervisor: %s => Domain: %s', vm.id, vm.name, vm.ipaddress,
vm.state, vm.serviceofferingid, vm.templateid, vm.hypervisor, vm.domainid)
def deploy_vpcs_publicipaddresses(self, vpcs_data, virtualmachines_data):
for vpc in vpcs_data:
self.deploy_vpc_publicipaddresses(vpc['data'], virtualmachines_data)
def deploy_vpc_publicipaddresses(self, vpc_data, virtualmachines_data):
vpc = get_vpc(api_client=self.api_client, name=self.dynamic_names['vpcs'][vpc_data['name']])
for publicipaddress in vpc_data['publicipaddresses']:
self.deploy_publicipaddress(publicipaddress['data'], virtualmachines_data, vpc)
def deploy_publicipaddress(self, publicipaddress_data, virtualmachines_data, vpc):
self.logger.debug('>>> PUBLIC IP ADDRESS => Creating...')
publicipaddress = PublicIPAddress.create(
api_client=self.api_client,
data=publicipaddress_data,
vpc=vpc
)
ipaddress = publicipaddress.ipaddress
self.logger.debug('>>> PUBLIC IP ADDRESS => ID: %s => IP: %s => State: %s => Source NAT: %s '
'=> Static NAT: %s => ACL: %s => VLAN: %s => Physical Network: %s => Network: %s '
'=> VPC: %s => Domain: %s', ipaddress.id, ipaddress.ipaddress, ipaddress.state,
ipaddress.issourcenat, ipaddress.isstaticnat, ipaddress.aclid, ipaddress.vlanid,
ipaddress.physicalnetworkid, ipaddress.networkid, ipaddress.vpcid, ipaddress.domainid)
self.deploy_portforwards(publicipaddress_data['portforwards'], virtualmachines_data, vpc, publicipaddress)
def deploy_portforwards(self, portforwards_data, virtualmachines_data, vpc, publicipaddress):
for portforward_data in portforwards_data:
for virtualmachine_data in virtualmachines_data:
if virtualmachine_data['data']['name'] == portforward_data['data']['virtualmachinename']:
for nic_data in virtualmachine_data['data']['nics']:
if nic_data['data']['guestip'] == portforward_data['data']['nic']:
network = get_network(
api_client=self.api_client,
name=nic_data['data']['networkname'],
vpc=vpc
)
virtualmachine = get_virtual_machine(
api_client=self.api_client,
name=self.dynamic_names['vms'][virtualmachine_data['data']['name']],
network=network
)
self.logger.debug('>>> PORT FORWARD => Creating...')
portforward = NATRule.create(
api_client=self.api_client,
data=portforward_data['data'],
network=network,
virtual_machine=virtualmachine,
ipaddress=publicipaddress
)
Tag.create(
api_client=self.api_client,
resourceType='UserVm',
resourceIds=[virtualmachine.id],
tags=[
{
'key': 'sship',
'value': publicipaddress.ipaddress.ipaddress
},
{
'key': 'sshport',
'value': portforward_data['data']['publicport']
}
]
)
self.logger.debug('>>> PORT FORWARD => ID: %s => Public Start Port: %s '
'=> Public End Port: %s => Private Start Port: %s '
'=> Private End Port: %s => CIDR List: %s => Protocol: %s '
'=> State: %s => IP: %s => VM: %s', portforward.id,
portforward.publicport, portforward.publicendport,
portforward.privateport, portforward.privateendport, portforward.cidrlist,
portforward.protocol, portforward.state, portforward.ipaddressid,
portforward.virtualmachineid)
def deploy_privatenetworks(self, privatenetworks_data, account, domain):
for privatenetwork in privatenetworks_data:
self.deploy_privatenetwork(privatenetwork['data'], account, domain)
def deploy_privatenetwork(self, privatenetwork_data, account, domain):
self.logger.debug('>>> PRIVATE GATEWAY NETWORK => Creating "%s"...', privatenetwork_data['name'])
private_gateways_network = Network.create(
api_client=self.api_client,
data=privatenetwork_data,
zone=self.zone,
domain=domain,
account=account
)
self.logger.debug('>>> PRIVATE GATEWAY NETWORK => ID: %s => Name: %s => CIDR: %s => Type: %s '
'=> Traffic Type: %s => State: %s => Offering: %s => Broadcast Domain Type: %s '
'=> Broadcast URI: %s => Physical Network: %s => Domain: %s',
private_gateways_network.id, private_gateways_network.name, private_gateways_network.cidr,
private_gateways_network.type, private_gateways_network.traffictype,
private_gateways_network.state, private_gateways_network.networkofferingid,
private_gateways_network.broadcastdomaintype, private_gateways_network.broadcasturi,
private_gateways_network.physicalnetworkid, private_gateways_network.domainid)
def deploy_vpcs_privategateways(self, vpcs_data):
for vpc in vpcs_data:
self.deploy_vpc_privategateways(vpc['data'])
def deploy_vpc_privategateways(self, vpc_data):
vpc = get_vpc(api_client=self.api_client, name=self.dynamic_names['vpcs'][vpc_data['name']])
for privategateway in vpc_data['privategateways']:
self.deploy_privategateway(privategateway['data'], vpc)
def deploy_privategateway(self, privategateway_data, vpc):
self.logger.debug('>>> PRIVATE GATEWAY => Creating "%s"...', privategateway_data['ip'])
private_gateway = PrivateGateway.create(
api_client=self.api_client,
data=privategateway_data,
vpc=vpc
)
self.logger.debug('>>> PRIVATE GATEWAY => ID: %s => IP: %s => CIDR: %s => State: %s '
'=> Source NAT: %s => ACL: %s => Network: %s => VPC: %s => Domain: %s',
private_gateway.id, private_gateway.ipaddress, private_gateway.cidr, private_gateway.state,
private_gateway.sourcenatsupported, private_gateway.aclid, private_gateway.networkid,
private_gateway.vpcid, private_gateway.domainid)
self.deploy_staticroutes(privategateway_data['staticroutes'], vpc)
def deploy_staticroutes(self, staticroutes_data, vpc):
for staticroute_data in staticroutes_data:
self.logger.debug('>>> STATIC ROUTE => Creating...')
staticroute = StaticRoute.create(
api_client=self.api_client,
data=staticroute_data['data'],
vpc=vpc
)
self.logger.debug('>>> STATIC ROUTE => ID: %s => CIDR: %s => Next Hop: %s => State: %s '
'=> VPC: %s => Domain: %s', staticroute.id, staticroute.cidr, staticroute.nexthop,
staticroute.state, staticroute.vpcid, staticroute.domainid)
def enable_vpcs_localvpngateway(self, vpcs_data):
for vpc_data in vpcs_data:
vpc = get_vpc(api_client=self.api_client, name=self.dynamic_names['vpcs'][vpc_data['data']['name']])
if vpc_data['data']['vpnconnections']:
self.logger.debug('>>> VPN LOCAL GATEWAY => Creating on VPC "%s"...', vpc_data['data']['name'])
localvpngateway = Vpn.createVpnGateway(api_client=self.api_client, vpc=vpc)
self.logger.debug('>>> VPN LOCAL GATEWAY => ID: %s => IP: %s => VPC: %s => Domain: %s',
localvpngateway['id'], localvpngateway['publicip'], localvpngateway['vpcid'],
localvpngateway['domainid'])
def deploy_vpcs_remotevpngateways(self, vpcs_data, account):
for vpc_data in vpcs_data:
for vpnconnection_data in vpc_data['data']['vpnconnections']:
vpc = get_vpc(api_client=self.api_client, name=self.dynamic_names['vpcs'][vpc_data['data']['name']])
vpc_vpngateway = get_vpngateway(api_client=self.api_client, vpc=vpc)
remotevpc = get_vpc(api_client=self.api_client, name=self.dynamic_names['vpcs'][vpnconnection_data])
remotevpc_vpngateway = get_vpngateway(api_client=self.api_client, vpc=remotevpc)
self.logger.debug('>>> VPN CUSTOMER GATEWAY => Creating to VPC "%s"...', vpnconnection_data)
vpncustomergateway = VpnCustomerGateway.create(
api_client=self.api_client,
name="remotegateway_to_" + remotevpc.name,
gateway=remotevpc_vpngateway.publicip,
cidrlist=remotevpc.cidr,
presharedkey='notasecret',
ikepolicy='aes128-sha256;modp2048',
esppolicy='aes128-sha256;modp2048',
account=account.name,
domainid=account.domainid
)
self.logger.debug('>>> VPN CUSTOMER GATEWAY => ID: %s => Name: %s => CIDR List: %s '
'=> Gateway: %s => Domain: %s', vpncustomergateway.id, vpncustomergateway.name,
vpncustomergateway.cidrlist, vpncustomergateway.gateway, vpncustomergateway.domainid)
self.logger.debug('>>> VPN CONNECTION => Creating from VPC "%s" to VPC "%s"...',
vpc_data['data']['name'], vpnconnection_data)
vpnconnection = Vpn.createVpnConnection(
api_client=self.api_client,
s2svpngatewayid=vpc_vpngateway.id,
s2scustomergatewayid=vpncustomergateway.id
)
self.logger.debug('>>> VPN CONNECTION => ID: %s => VPN Local Gateway: %s '
'=> VPN Customer Gateway: %s => State: %s', vpnconnection['id'],
vpnconnection['s2svpngatewayid'], vpnconnection['s2scustomergatewayid'],
vpnconnection['state'])
def deploy_isolatednetworks(self, isolatednetworks_data, account):
for isolatednetwork in isolatednetworks_data:
self.deploy_isolatednetwork(isolatednetwork['data'], account)
def deploy_isolatednetwork(self, isolatednetwork_data, account):
self.logger.debug('>>> ISOLATED NETWORK => Creating "%s"...', isolatednetwork_data['name'])
isolatednetwork = Network.create(
self.api_client,
data=isolatednetwork_data,
account=account,
zone=self.zone
)
self.logger.debug('>>> ISOLATED NETWORK => ID: %s => Name: %s => CIDR: %s '
'=> Gateway: %s => Type: %s => Traffic Type: %s => State: %s '
'=> Offering: %s => Physical Network: %s => Domain: %s',
isolatednetwork.id, isolatednetwork.name, isolatednetwork.cidr,
isolatednetwork.gateway, isolatednetwork.type, isolatednetwork.traffictype,
isolatednetwork.state, isolatednetwork.networkofferingid,
isolatednetwork.physicalnetworkid, isolatednetwork.domainid)
def deploy_isolatednetworks_publicipaddresses(self, isolatednetworks_data, virtualmachines_data):
for isolatednetwork in isolatednetworks_data:
network = get_network(self.api_client, isolatednetwork['data']['name'])
self.deploy_isolatednetwork_egresses(isolatednetwork['data'], network)
self.deploy_isolatednetwork_publicipaddresses(isolatednetwork['data'], virtualmachines_data, network)
def deploy_isolatednetwork_egresses(self, isolatednetwork_data, network):
self.logger.debug('>>> ISOLATED NETWORK EGRESS RULE => Creating...')
for egress_data in isolatednetwork_data['egressrules']:
egress = EgressFireWallRule.create(
self.api_client,
network=network,
data=egress_data['data']
)
self.logger.debug('>>> ISOLATED NETWORK EGRESS RULE => ID: %s => Start Port: %s '
'=> End Port: %s => CIDR: %s => Protocol: %s => State: %s '
'=> Network: %s',
egress.id, egress.startport, egress.endport, egress.cidrlist,
egress.protocol, egress.state, egress.networkid)
def deploy_isolatednetwork_publicipaddresses(self, isolatednetwork_data, virtual_machines, network):
for ipaddress in isolatednetwork_data['publicipaddresses']:
self.deploy_isolatednetwork_publicipaddress(ipaddress['data'], virtual_machines, network)
def deploy_isolatednetwork_publicipaddress(self, ipaddress_data, virtualmachines_data, network):
self.logger.debug('>>> ISOLATED NETWORK PUBLIC IP ADDRESS => Creating...')
publicipaddress = PublicIPAddress.create(
api_client=self.api_client,
data=ipaddress_data,
network=network
)
self.logger.debug('>>> ISOLATED NETWORK PUBLIC IP ADDRESS => Created! TODO: MISSING FIELDS!')
self.deploy_firewallrules(ipaddress_data, publicipaddress)
self.deploy_portforwards(ipaddress_data['portforwards'], virtualmachines_data, None, publicipaddress)
def deploy_firewallrules(self, ipaddress_data, publicipaddress):
self.logger.debug('>>> ISOLATED NETWORK FIREWALL RULE => Creating...')
for firewallrule in ipaddress_data['firewallrules']:
self.deploy_firewallrule(firewallrule, publicipaddress)
def deploy_firewallrule(self, firewallrule, publicipaddress):
firewall = FireWallRule.create(
self.api_client,
data=firewallrule['data'],
ipaddress=publicipaddress
)
self.logger.debug('>>> ISOLATED NETWORKS FIREWALL RULE => ID: %s => Start Port: %s '
'=> End Port: %s => CIDR: %s => Protocol: %s => State: %s '
'=> Network: %s => IP: %s',
firewall.id, firewall.startport, firewall.endport, firewall.cidrlist,
firewall.protocol, firewall.state, firewall.networkid, firewall.ipaddress)
def get_vpc(self, name):
vpc = VPC(get_vpc(api_client=self.api_client, name=name).__dict__, api_client=self.api_client)
return vpc
def get_virtual_machine(self, vm_name):
virtual_machine = VirtualMachine(get_virtual_machine(
api_client=self.api_client,
name=self.get_dynamic_name('vms', vm_name)
).__dict__, [])
virtual_machine_tags = Tag.list(
api_client=self.api_client,
resourceId=[virtual_machine.id],
listall=True)
for key in virtual_machine_tags:
if key.key == 'sshport':
virtual_machine.ssh_port = int(key.value.encode('ascii', 'ignore'))
if key.key == 'sship':
virtual_machine.ssh_ip = key.value.encode('ascii', 'ignore')
return virtual_machine
def get_network(self, name=None, id=None):
return Network(get_network(api_client=self.api_client, name=name, id=id).__dict__)
def get_network_acl_list(self, name=None, id=None):
return NetworkACLList(get_network_acl(api_client=self.api_client, name=name, id=id).__dict__)
def get_default_allow_acl_list(self):
return self.get_network_acl_list(name='default_allow')
def get_default_deny_acl_list(self):
return self.get_network_acl_list(name='default_deny')
def deploy_network_acl_list(self, acl_list_name, acl_config, network=None, vpc=None):
if network:
networkid=network.id
if network.vpcid:
vpcid=network.vpcid
acl_list = NetworkACLList.create(self.api_client, name=acl_list_name, services=[], vpcid=vpcid, vpc=vpc)
NetworkACL.create(self.api_client,
acl_config,
networkid=networkid,
aclid=acl_list.id)
return acl_list
def finalize(self):
if self.cleanup:
try:
self.logger.info('=== Scenario Manager, Cleaning Up of "%s" Started ===',
self.scenario_data['metadata']['name'])
cleanup_resources(self.api_client, self.resources_to_cleanup, self.logger)
self.logger.info('=== Scenario Manager, Cleaning Up of "%s" Finished ===',
self.scenario_data['metadata']['name'])
except:
self.logger.exception('Oops! Unable to clean up resources of "%s"!', self.scenario_data['metadata']['name'])
else:
self.logger.info('=== Scenario Manager, Skipping Cleaning Up of "%s" ===',
self.scenario_data['metadata']['name'])
| [
"marvin.utils.MarvinLog.MarvinLog",
"marvin.lib.base.PrivateGateway.create",
"marvin.lib.base.NetworkACLList.create",
"marvin.lib.base.StaticRoute.create",
"marvin.lib.base.PublicIPAddress.create",
"marvin.lib.base.FireWallRule.create",
"marvin.lib.base.Domain.list",
"marvin.lib.base.Tag.create",
"m... | [((5227, 5350), 'marvin.lib.base.VPC.create', 'VPC.create', ([], {'api_client': 'self.api_client', 'data': 'vpc_data', 'zone': 'self.zone', 'account': 'account', 'randomizeID': 'self.randomizeNames'}), '(api_client=self.api_client, data=vpc_data, zone=self.zone,\n account=account, randomizeID=self.randomizeNames)\n', (5237, 5350), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((6125, 6198), 'marvin.lib.base.NetworkACLList.create', 'NetworkACLList.create', ([], {'api_client': 'self.api_client', 'data': 'acl_data', 'vpc': 'vpc'}), '(api_client=self.api_client, data=acl_data, vpc=vpc)\n', (6146, 6198), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((6648, 6718), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', ([], {'api_client': 'self.api_client', 'data': 'rule_data', 'acl': 'acl'}), '(api_client=self.api_client, data=rule_data, acl=acl)\n', (6665, 6718), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((7385, 7471), 'marvin.lib.common.get_network_acl', 'get_network_acl', ([], {'api_client': 'self.api_client', 'name': "network_data['aclname']", 'vpc': 'vpc'}), "(api_client=self.api_client, name=network_data['aclname'],\n vpc=vpc)\n", (7400, 7471), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((7570, 7658), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client'], {'data': 'network_data', 'vpc': 'vpc', 'zone': 'self.zone', 'acl': 'acl'}), '(self.api_client, data=network_data, vpc=vpc, zone=self.zone,\n acl=acl)\n', (7584, 7658), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((8967, 9097), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client'], {'data': 'vm_data', 'zone': 'self.zone', 'account': 'account', 'network_and_ip_list': 'network_and_ip_list'}), '(self.api_client, data=vm_data, zone=self.zone,\n account=account, network_and_ip_list=network_and_ip_list)\n', (8988, 9097), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((9829, 9920), 'marvin.lib.common.get_vpc', 'get_vpc', ([], {'api_client': 'self.api_client', 'name': "self.dynamic_names['vpcs'][vpc_data['name']]"}), "(api_client=self.api_client, name=self.dynamic_names['vpcs'][\n vpc_data['name']])\n", (9836, 9920), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((10253, 10344), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', ([], {'api_client': 'self.api_client', 'data': 'publicipaddress_data', 'vpc': 'vpc'}), '(api_client=self.api_client, data=\n publicipaddress_data, vpc=vpc)\n', (10275, 10344), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((14638, 14759), 'marvin.lib.base.Network.create', 'Network.create', ([], {'api_client': 'self.api_client', 'data': 'privatenetwork_data', 'zone': 'self.zone', 'domain': 'domain', 'account': 'account'}), '(api_client=self.api_client, data=privatenetwork_data, zone=\n self.zone, domain=domain, account=account)\n', (14652, 14759), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((15886, 15977), 'marvin.lib.common.get_vpc', 'get_vpc', ([], {'api_client': 'self.api_client', 'name': "self.dynamic_names['vpcs'][vpc_data['name']]"}), "(api_client=self.api_client, name=self.dynamic_names['vpcs'][\n vpc_data['name']])\n", (15893, 15977), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((16289, 16377), 'marvin.lib.base.PrivateGateway.create', 'PrivateGateway.create', ([], {'api_client': 'self.api_client', 'data': 'privategateway_data', 'vpc': 'vpc'}), '(api_client=self.api_client, data=privategateway_data,\n vpc=vpc)\n', (16310, 16377), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((21217, 21312), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client'], {'data': 'isolatednetwork_data', 'account': 'account', 'zone': 'self.zone'}), '(self.api_client, data=isolatednetwork_data, account=account,\n zone=self.zone)\n', (21231, 21312), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((23746, 23838), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', ([], {'api_client': 'self.api_client', 'data': 'ipaddress_data', 'network': 'network'}), '(api_client=self.api_client, data=ipaddress_data,\n network=network)\n', (23768, 23838), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((24534, 24629), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.api_client'], {'data': "firewallrule['data']", 'ipaddress': 'publicipaddress'}), "(self.api_client, data=firewallrule['data'], ipaddress=\n publicipaddress)\n", (24553, 24629), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((25527, 25614), 'marvin.lib.base.Tag.list', 'Tag.list', ([], {'api_client': 'self.api_client', 'resourceId': '[virtual_machine.id]', 'listall': '(True)'}), '(api_client=self.api_client, resourceId=[virtual_machine.id],\n listall=True)\n', (25535, 25614), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((26778, 26875), 'marvin.lib.base.NetworkACLList.create', 'NetworkACLList.create', (['self.api_client'], {'name': 'acl_list_name', 'services': '[]', 'vpcid': 'vpcid', 'vpc': 'vpc'}), '(self.api_client, name=acl_list_name, services=[],\n vpcid=vpcid, vpc=vpc)\n', (26799, 26875), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((26881, 26972), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', (['self.api_client', 'acl_config'], {'networkid': 'networkid', 'aclid': 'acl_list.id'}), '(self.api_client, acl_config, networkid=networkid, aclid=\n acl_list.id)\n', (26898, 26972), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((2219, 2284), 'marvin.lib.base.Domain.list', 'Domain.list', ([], {'api_client': 'self.api_client', 'name': "domain_data['name']"}), "(api_client=self.api_client, name=domain_data['name'])\n", (2230, 2284), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((3274, 3363), 'marvin.lib.base.Account.list', 'Account.list', ([], {'api_client': 'self.api_client', 'name': "account_data['username']", 'listall': '(True)'}), "(api_client=self.api_client, name=account_data['username'],\n listall=True)\n", (3286, 3363), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((3738, 3863), 'marvin.lib.base.Account.create', 'Account.create', ([], {'api_client': 'self.api_client', 'services': 'account_data', 'domainid': 'domain.uuid', 'randomizeID': 'self.randomizeNames'}), '(api_client=self.api_client, services=account_data, domainid=\n domain.uuid, randomizeID=self.randomizeNames)\n', (3752, 3863), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((8561, 8633), 'marvin.lib.common.get_network', 'get_network', ([], {'api_client': 'self.api_client', 'name': "nic['data']['networkname']"}), "(api_client=self.api_client, name=nic['data']['networkname'])\n", (8572, 8633), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((17218, 17309), 'marvin.lib.base.StaticRoute.create', 'StaticRoute.create', ([], {'api_client': 'self.api_client', 'data': "staticroute_data['data']", 'vpc': 'vpc'}), "(api_client=self.api_client, data=staticroute_data['data'\n ], vpc=vpc)\n", (17236, 17309), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((17793, 17892), 'marvin.lib.common.get_vpc', 'get_vpc', ([], {'api_client': 'self.api_client', 'name': "self.dynamic_names['vpcs'][vpc_data['data']['name']]"}), "(api_client=self.api_client, name=self.dynamic_names['vpcs'][\n vpc_data['data']['name']])\n", (17800, 17892), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((22187, 22248), 'marvin.lib.common.get_network', 'get_network', (['self.api_client', "isolatednetwork['data']['name']"], {}), "(self.api_client, isolatednetwork['data']['name'])\n", (22198, 22248), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((22690, 22780), 'marvin.lib.base.EgressFireWallRule.create', 'EgressFireWallRule.create', (['self.api_client'], {'network': 'network', 'data': "egress_data['data']"}), "(self.api_client, network=network, data=\n egress_data['data'])\n", (22715, 22780), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((1313, 1345), 'marvin.utils.MarvinLog.MarvinLog', 'MarvinLog', (['MarvinLog.LOGGER_TEST'], {}), '(MarvinLog.LOGGER_TEST)\n', (1322, 1345), False, 'from marvin.utils.MarvinLog import MarvinLog\n'), ((18088, 18145), 'marvin.lib.base.Vpn.createVpnGateway', 'Vpn.createVpnGateway', ([], {'api_client': 'self.api_client', 'vpc': 'vpc'}), '(api_client=self.api_client, vpc=vpc)\n', (18108, 18145), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((18632, 18731), 'marvin.lib.common.get_vpc', 'get_vpc', ([], {'api_client': 'self.api_client', 'name': "self.dynamic_names['vpcs'][vpc_data['data']['name']]"}), "(api_client=self.api_client, name=self.dynamic_names['vpcs'][\n vpc_data['data']['name']])\n", (18639, 18731), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((18760, 18811), 'marvin.lib.common.get_vpngateway', 'get_vpngateway', ([], {'api_client': 'self.api_client', 'vpc': 'vpc'}), '(api_client=self.api_client, vpc=vpc)\n', (18774, 18811), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((18841, 18934), 'marvin.lib.common.get_vpc', 'get_vpc', ([], {'api_client': 'self.api_client', 'name': "self.dynamic_names['vpcs'][vpnconnection_data]"}), "(api_client=self.api_client, name=self.dynamic_names['vpcs'][\n vpnconnection_data])\n", (18848, 18934), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((18969, 19026), 'marvin.lib.common.get_vpngateway', 'get_vpngateway', ([], {'api_client': 'self.api_client', 'vpc': 'remotevpc'}), '(api_client=self.api_client, vpc=remotevpc)\n', (18983, 19026), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((19177, 19505), 'marvin.lib.base.VpnCustomerGateway.create', 'VpnCustomerGateway.create', ([], {'api_client': 'self.api_client', 'name': "('remotegateway_to_' + remotevpc.name)", 'gateway': 'remotevpc_vpngateway.publicip', 'cidrlist': 'remotevpc.cidr', 'presharedkey': '"""notasecret"""', 'ikepolicy': '"""aes128-sha256;modp2048"""', 'esppolicy': '"""aes128-sha256;modp2048"""', 'account': 'account.name', 'domainid': 'account.domainid'}), "(api_client=self.api_client, name=\n 'remotegateway_to_' + remotevpc.name, gateway=remotevpc_vpngateway.\n publicip, cidrlist=remotevpc.cidr, presharedkey='notasecret', ikepolicy\n ='aes128-sha256;modp2048', esppolicy='aes128-sha256;modp2048', account=\n account.name, domainid=account.domainid)\n", (19202, 19505), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((20244, 20379), 'marvin.lib.base.Vpn.createVpnConnection', 'Vpn.createVpnConnection', ([], {'api_client': 'self.api_client', 's2svpngatewayid': 'vpc_vpngateway.id', 's2scustomergatewayid': 'vpncustomergateway.id'}), '(api_client=self.api_client, s2svpngatewayid=\n vpc_vpngateway.id, s2scustomergatewayid=vpncustomergateway.id)\n', (20267, 20379), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((25165, 25211), 'marvin.lib.common.get_vpc', 'get_vpc', ([], {'api_client': 'self.api_client', 'name': 'name'}), '(api_client=self.api_client, name=name)\n', (25172, 25211), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((26110, 26167), 'marvin.lib.common.get_network', 'get_network', ([], {'api_client': 'self.api_client', 'name': 'name', 'id': 'id'}), '(api_client=self.api_client, name=name, id=id)\n', (26121, 26167), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((26265, 26326), 'marvin.lib.common.get_network_acl', 'get_network_acl', ([], {'api_client': 'self.api_client', 'name': 'name', 'id': 'id'}), '(api_client=self.api_client, name=name, id=id)\n', (26280, 26326), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((27318, 27392), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.api_client', 'self.resources_to_cleanup', 'self.logger'], {}), '(self.api_client, self.resources_to_cleanup, self.logger)\n', (27335, 27392), False, 'from marvin.lib.utils import random_gen, cleanup_resources\n'), ((11628, 11719), 'marvin.lib.common.get_network', 'get_network', ([], {'api_client': 'self.api_client', 'name': "nic_data['data']['networkname']", 'vpc': 'vpc'}), "(api_client=self.api_client, name=nic_data['data']['networkname'\n ], vpc=vpc)\n", (11639, 11719), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((11886, 12024), 'marvin.lib.common.get_virtual_machine', 'get_virtual_machine', ([], {'api_client': 'self.api_client', 'name': "self.dynamic_names['vms'][virtualmachine_data['data']['name']]", 'network': 'network'}), "(api_client=self.api_client, name=self.dynamic_names[\n 'vms'][virtualmachine_data['data']['name']], network=network)\n", (11905, 12024), False, 'from marvin.lib.common import get_vpngateway, get_vpc, get_virtual_machine, get_network, get_network_acl\n'), ((12273, 12426), 'marvin.lib.base.NATRule.create', 'NATRule.create', ([], {'api_client': 'self.api_client', 'data': "portforward_data['data']", 'network': 'network', 'virtual_machine': 'virtualmachine', 'ipaddress': 'publicipaddress'}), "(api_client=self.api_client, data=portforward_data['data'],\n network=network, virtual_machine=virtualmachine, ipaddress=publicipaddress)\n", (12287, 12426), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((12642, 12891), 'marvin.lib.base.Tag.create', 'Tag.create', ([], {'api_client': 'self.api_client', 'resourceType': '"""UserVm"""', 'resourceIds': '[virtualmachine.id]', 'tags': "[{'key': 'sship', 'value': publicipaddress.ipaddress.ipaddress}, {'key':\n 'sshport', 'value': portforward_data['data']['publicport']}]"}), "(api_client=self.api_client, resourceType='UserVm', resourceIds=[\n virtualmachine.id], tags=[{'key': 'sship', 'value': publicipaddress.\n ipaddress.ipaddress}, {'key': 'sshport', 'value': portforward_data[\n 'data']['publicport']}])\n", (12652, 12891), False, 'from marvin.lib.base import Vpn, VpnCustomerGateway, StaticRoute, PrivateGateway, Network, NATRule, PublicIPAddress, VirtualMachine, NetworkACL, NetworkACLList, VPC, Account, Domain, EgressFireWallRule, FireWallRule, Tag\n'), ((2599, 2611), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (2609, 2611), False, 'from marvin.lib.utils import random_gen, cleanup_resources\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Import Local Modules
from marvin.codes import FAILED, KVM, PASS
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import random_gen, cleanup_resources, validateList
from marvin.lib.base import (Account,
ServiceOffering,
VirtualMachine,
VmSnapshot,
Volume,
Snapshot)
from marvin.lib.common import (get_zone,
get_domain,
get_template)
import time
class TestVmSnapshot(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestVmSnapshot, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls._cleanup = []
cls.unsupportedHypervisor = False
cls.hypervisor = testClient.getHypervisorInfo()
if cls.hypervisor.lower() in (KVM.lower(), "hyperv", "lxc"):
cls.unsupportedHypervisor = True
return
cls.services = testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
template = get_template(
cls.apiclient,
cls.zone.id,
cls.services["ostype"]
)
if template == FAILED:
assert False, "get_template() failed to return template\
with description %s" % cls.services["ostype"]
cls.services["domainid"] = cls.domain.id
cls.services["server"]["zoneid"] = cls.zone.id
cls.services["templates"]["ostypeid"] = template.ostypeid
cls.services["zoneid"] = cls.zone.id
# Create VMs, NAT Rules etc
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]
)
cls._cleanup.append(cls.service_offering)
cls.virtual_machine = VirtualMachine.create(
cls.apiclient,
cls.services["server"],
templateid=template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
mode=cls.zone.networktype
)
cls.random_data_0 = random_gen(size=100)
cls.test_dir = "/tmp"
cls.random_data = "random.data"
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
if self.unsupportedHypervisor:
self.skipTest("Skipping test because unsupported hypervisor\
%s" % self.hypervisor)
return
def tearDown(self):
try:
# Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_01_create_vm_snapshots(self):
"""Test to create VM snapshots
"""
try:
# Login to VM and write data to file system
ssh_client = self.virtual_machine.get_ssh_client()
cmds = [
"echo %s > %s/%s" %
(self.random_data_0, self.test_dir, self.random_data),
"cat %s/%s" %
(self.test_dir, self.random_data)]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
self.assertEqual(
self.random_data_0,
result[0],
"Check the random data has be write into temp file!"
)
time.sleep(self.services["sleep"])
vm_snapshot = VmSnapshot.create(
self.apiclient,
self.virtual_machine.id,
"false",
"TestSnapshot",
"Dsiplay Text"
)
self.assertEqual(
vm_snapshot.state,
"Ready",
"Check the snapshot of vm is ready!"
)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_02_revert_vm_snapshots(self):
"""Test to revert VM snapshots
"""
try:
ssh_client = self.virtual_machine.get_ssh_client()
cmds = [
"rm -rf %s/%s" % (self.test_dir, self.random_data),
"ls %s/%s" % (self.test_dir, self.random_data)
]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
if str(result[0]).index("No such file or directory") == -1:
self.fail("Check the random data has be delete from temp file!")
time.sleep(self.services["sleep"])
list_snapshot_response = VmSnapshot.list(
self.apiclient,
vmid=self.virtual_machine.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
self.assertEqual(
list_snapshot_response[0].state,
"Ready",
"Check the snapshot of vm is ready!"
)
self.virtual_machine.stop(self.apiclient)
VmSnapshot.revertToSnapshot(
self.apiclient,
list_snapshot_response[0].id)
self.virtual_machine.start(self.apiclient)
try:
ssh_client = self.virtual_machine.get_ssh_client(reconnect=True)
cmds = [
"cat %s/%s" % (self.test_dir, self.random_data)
]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
self.assertEqual(
self.random_data_0,
result[0],
"Check the random data is equal with the ramdom file!"
)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_03_delete_vm_snapshots(self):
"""Test to delete vm snapshots
"""
list_snapshot_response = VmSnapshot.list(
self.apiclient,
vmid=self.virtual_machine.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
VmSnapshot.deleteVMSnapshot(
self.apiclient,
list_snapshot_response[0].id)
time.sleep(self.services["sleep"] * 3)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
vmid=self.virtual_machine.id,
listall=True)
self.assertEqual(
list_snapshot_response,
None,
"Check list vm snapshot has be deleted"
)
class TestSnapshots(cloudstackTestCase):
@classmethod
def setUpClass(cls):
try:
cls._cleanup = []
cls.testClient = super(TestSnapshots, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
cls.unsupportedHypervisor = False
cls.hypervisor = cls.testClient.getHypervisorInfo()
if cls.hypervisor.lower() in (KVM.lower(), "hyperv", "lxc"):
cls.unsupportedHypervisor = True
return
# Get Domain, Zone, Template
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(
cls.api_client,
cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
if cls.zone.localstorageenabled:
cls.storagetype = 'local'
cls.services["service_offerings"][
"tiny"]["storagetype"] = 'local'
else:
cls.storagetype = 'shared'
cls.services["service_offerings"][
"tiny"]["storagetype"] = 'shared'
cls.services['mode'] = cls.zone.networktype
cls.services["virtual_machine"]["hypervisor"] = cls.hypervisor
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.services["custom_volume"]["zoneid"] = cls.zone.id
# Creating Disk offering, Service Offering and Account
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offerings"]["tiny"]
)
cls._cleanup.append(cls.service_offering)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
except Exception as e:
cls.tearDownClass()
raise Exception("Warning: Exception in setup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
if self.unsupportedHypervisor:
self.skipTest("Skipping test because unsupported\
hypervisor %s" % self.hypervisor)
def tearDown(self):
# Clean up, terminate the created resources
cleanup_resources(self.apiclient, self.cleanup)
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "basic", "smoke"], required_hardware="true")
def test_01_test_vm_volume_snapshot(self):
"""
@Desc: Test that Volume snapshot for root volume not allowed
when VM snapshot is present for the VM
@Steps:
1: Deploy a VM and create a VM snapshot for VM
2: Try to create snapshot for the root volume of the VM,
It should fail
"""
# Creating Virtual Machine
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
)
VmSnapshot.create(
self.apiclient,
virtual_machine.id,
)
volumes = Volume.list(self.apiclient,
virtualmachineid=virtual_machine.id,
type="ROOT",
listall=True)
self.assertEqual(validateList(volumes)[0], PASS,
"Failed to get root volume of the VM")
volume = volumes[0]
with self.assertRaises(Exception):
Snapshot.create(self.apiclient,
volume_id=volume.id)
return
| [
"marvin.lib.utils.random_gen",
"marvin.lib.base.VmSnapshot.create",
"marvin.lib.utils.validateList",
"marvin.lib.base.VmSnapshot.list",
"marvin.lib.base.VmSnapshot.deleteVMSnapshot",
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.Volume.list",
"marvin.lib.base.Sna... | [((4398, 4470), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (4402, 4470), False, 'from nose.plugins.attrib import attr\n'), ((5741, 5813), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (5745, 5813), False, 'from nose.plugins.attrib import attr\n'), ((8084, 8156), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (8088, 8156), False, 'from nose.plugins.attrib import attr\n'), ((12097, 12164), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic', 'smoke'], required_hardware='true')\n", (12101, 12164), False, 'from nose.plugins.attrib import attr\n'), ((1990, 2015), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2000, 2015), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((2109, 2173), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (2121, 2173), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((2661, 2739), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (2675, 2739), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((2859, 2931), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']"], {}), "(cls.apiclient, cls.services['service_offerings'])\n", (2881, 2931), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((3046, 3268), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['server']"], {'templateid': 'template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id', 'mode': 'cls.zone.networktype'}), "(cls.apiclient, cls.services['server'], templateid=\n template.id, accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering.id, mode=cls.zone.networktype)\n", (3067, 3268), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((3382, 3402), 'marvin.lib.utils.random_gen', 'random_gen', ([], {'size': '(100)'}), '(size=100)\n', (3392, 3402), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList\n'), ((5355, 5389), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (5365, 5389), False, 'import time\n'), ((5413, 5516), 'marvin.lib.base.VmSnapshot.create', 'VmSnapshot.create', (['self.apiclient', 'self.virtual_machine.id', '"""false"""', '"""TestSnapshot"""', '"""Dsiplay Text"""'], {}), "(self.apiclient, self.virtual_machine.id, 'false',\n 'TestSnapshot', 'Dsiplay Text')\n", (5430, 5516), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((6589, 6623), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (6599, 6623), False, 'import time\n'), ((6658, 6733), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'vmid': 'self.virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, vmid=self.virtual_machine.id, listall=True)\n', (6673, 6733), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((7295, 7368), 'marvin.lib.base.VmSnapshot.revertToSnapshot', 'VmSnapshot.revertToSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (7322, 7368), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((8285, 8360), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'vmid': 'self.virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, vmid=self.virtual_machine.id, listall=True)\n', (8300, 8360), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((8718, 8791), 'marvin.lib.base.VmSnapshot.deleteVMSnapshot', 'VmSnapshot.deleteVMSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (8745, 8791), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((8826, 8864), 'time.sleep', 'time.sleep', (["(self.services['sleep'] * 3)"], {}), "(self.services['sleep'] * 3)\n", (8836, 8864), False, 'import time\n'), ((8899, 8974), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'vmid': 'self.virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, vmid=self.virtual_machine.id, listall=True)\n', (8914, 8974), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((11788, 11835), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (11805, 11835), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList\n'), ((12573, 12757), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id)\n", (12594, 12757), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((12830, 12883), 'marvin.lib.base.VmSnapshot.create', 'VmSnapshot.create', (['self.apiclient', 'virtual_machine.id'], {}), '(self.apiclient, virtual_machine.id)\n', (12847, 12883), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((12938, 13034), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=virtual_machine.id, type=\n 'ROOT', listall=True)\n", (12949, 13034), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((3596, 3642), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (3613, 3642), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList\n'), ((4224, 4271), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (4241, 4271), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList\n'), ((9805, 9831), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (9815, 9831), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((9974, 10039), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (9986, 10039), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((10901, 10987), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offerings']['tiny']"], {}), "(cls.api_client, cls.services['service_offerings'][\n 'tiny'])\n", (10923, 10987), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((11109, 11188), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], domainid=cls.domain.id)\n", (11123, 11188), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((11922, 11969), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (11939, 11969), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList\n'), ((13318, 13370), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume.id'}), '(self.apiclient, volume_id=volume.id)\n', (13333, 13370), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, VmSnapshot, Volume, Snapshot\n'), ((1772, 1783), 'marvin.codes.KVM.lower', 'KVM.lower', ([], {}), '()\n', (1781, 1783), False, 'from marvin.codes import FAILED, KVM, PASS\n'), ((13146, 13167), 'marvin.lib.utils.validateList', 'validateList', (['volumes'], {}), '(volumes)\n', (13158, 13167), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList\n'), ((9636, 9647), 'marvin.codes.KVM.lower', 'KVM.lower', ([], {}), '()\n', (9645, 9647), False, 'from marvin.codes import FAILED, KVM, PASS\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Test cases to Check Snapshots size in database
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (cleanup_resources,
)
from marvin.lib.base import (Account,
Network,
NetworkOffering,
ServiceOffering,
VirtualMachine,
)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
list_networks)
def ipv4_cidr_to_netmask(bits):
""" Convert CIDR bits to netmask """
netmask = ''
for i in range(4):
if i:
netmask += '.'
if bits >= 8:
netmask += '%d' % (2 ** 8 - 1)
bits -= 8
else:
netmask += '%d' % (256 - 2 ** (8 - bits))
bits = 0
return netmask
class TestCheckNetmask(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestCheckNetmask, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
cls.hypervisor = cls.testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
cls._cleanup = []
cls.skiptest = False
if cls.hypervisor.lower() not in ["xenserver"]:
cls.skiptest = True
return
try:
# Create an account
cls.account = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
# Create Service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
)
cls.testdata["shared_network_offering"]["specifyVlan"] = 'True'
cls.testdata["shared_network_offering"]["specifyIpRanges"] = 'True'
cls.shared_network_offering = NetworkOffering.create(
cls.apiclient,
cls.testdata["shared_network_offering"]
)
NetworkOffering.update(
cls.shared_network_offering,
cls.apiclient,
id=cls.shared_network_offering.id,
state="enabled"
)
cls.network = Network.create(
cls.apiclient,
cls.testdata["network2"],
networkofferingid=cls.shared_network_offering.id,
zoneid=cls.zone.id,
accountid=cls.account.name,
domainid=cls.account.domainid
)
cls.vm = VirtualMachine.create(
cls.apiclient,
cls.testdata["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
zoneid=cls.zone.id,
networkids=cls.network.id,
)
cls._cleanup.extend([cls.account,
cls.service_offering,
cls.shared_network_offering])
except Exception as e:
cls.tearDownClass()
raise e
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
if self.skiptest:
self.skipTest(
"Test not to be run on %s" %
self.hypervisor)
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced"], required_hardware="false")
def test_01_netmask_value_check(self):
""" Check Netmask value in database
1. Check if netmask attribute in nics table
stores correct value.
"""
# Step 1
# Get the netmask from ipv4 address of the VM
qryresult_netmask = self.dbclient.execute(
" select id, uuid, netmask\
from nics where ip4_address='%s';" %
self.vm.nic[0].ipaddress)
self.assertNotEqual(
len(qryresult_netmask),
0,
"Check if netmask attribute in nics table \
stores correct value")
# Step 2
netmask_id = qryresult_netmask[0][2]
netlist = list_networks(self.apiclient,
account=self.account.name,
domainid=self.account.domainid)
self.assertNotEqual(len(netlist), 0,
"Check if list networks returned an empty list.")
cidr = netlist[0].cidr.split("/")[1]
# Get netmask from CIDR
netmask = ipv4_cidr_to_netmask(int(cidr))
# Validate the netmask
self.assertEqual(netmask_id,
netmask,
"Check if the netmask is from guest CIDR")
return
| [
"marvin.lib.common.list_networks",
"marvin.lib.base.Network.create",
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.NetworkOffering.update",
"marvin.lib.common.get_template",
"marvi... | [((5182, 5232), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (5186, 5232), False, 'from nose.plugins.attrib import attr\n'), ((2178, 2203), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2188, 2203), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_networks\n'), ((2301, 2365), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.testdata['ostype'])\n", (2313, 2365), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_networks\n'), ((5937, 6030), 'marvin.lib.common.list_networks', 'list_networks', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (5950, 6030), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_networks\n'), ((2641, 2719), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.testdata['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.testdata['account'], domainid=cls.domain.id)\n", (2655, 2719), False, 'from marvin.lib.base import Account, Network, NetworkOffering, ServiceOffering, VirtualMachine\n'), ((2856, 2927), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {}), "(cls.apiclient, cls.testdata['service_offering'])\n", (2878, 2927), False, 'from marvin.lib.base import Account, Network, NetworkOffering, ServiceOffering, VirtualMachine\n'), ((3175, 3253), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.testdata['shared_network_offering']"], {}), "(cls.apiclient, cls.testdata['shared_network_offering'])\n", (3197, 3253), False, 'from marvin.lib.base import Account, Network, NetworkOffering, ServiceOffering, VirtualMachine\n'), ((3313, 3436), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['cls.shared_network_offering', 'cls.apiclient'], {'id': 'cls.shared_network_offering.id', 'state': '"""enabled"""'}), "(cls.shared_network_offering, cls.apiclient, id=cls.\n shared_network_offering.id, state='enabled')\n", (3335, 3436), False, 'from marvin.lib.base import Account, Network, NetworkOffering, ServiceOffering, VirtualMachine\n'), ((3537, 3731), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.testdata['network2']"], {'networkofferingid': 'cls.shared_network_offering.id', 'zoneid': 'cls.zone.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid'}), "(cls.apiclient, cls.testdata['network2'], networkofferingid=\n cls.shared_network_offering.id, zoneid=cls.zone.id, accountid=cls.\n account.name, domainid=cls.account.domainid)\n", (3551, 3731), False, 'from marvin.lib.base import Account, Network, NetworkOffering, ServiceOffering, VirtualMachine\n'), ((3854, 4103), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.testdata['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id', 'zoneid': 'cls.zone.id', 'networkids': 'cls.network.id'}), "(cls.apiclient, cls.testdata['small'], templateid=cls.\n template.id, accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering.id, zoneid=cls.zone.id,\n networkids=cls.network.id)\n", (3875, 4103), False, 'from marvin.lib.base import Account, Network, NetworkOffering, ServiceOffering, VirtualMachine\n'), ((4569, 4615), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (4586, 4615), False, 'from marvin.lib.utils import cleanup_resources\n'), ((5008, 5055), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (5025, 5055), False, 'from marvin.lib.utils import cleanup_resources\n')] |
# Imports
from time import sleep as wait # to have a pause
from json import load # parse and add json data
from threading import Thread # thread to maximize efficency of marvin
from marvin.essentials import speak # speak to user
##########################
# File for contacts code #
##########################
# Functions
# Function to check contacts
def checkcontact(contact_path, name):
with open(contact_path, 'r') as check_name:
name_check = load(check_name)
name_low = name.lower()
if name_low in name_check['contacts']:
return name
elif name_low in name_check['nicks']:
real_name = name_check['nicks'][name_low]['real_name']
return real_name
else:
return 'None'
# Function to show contacts with variables to determine what extra information to show
class ContactShow:
def __init__(self, contact_path, _type_, speak_type):
self.contact_path = contact_path
self._type_ = _type_
self.speak_type = speak_type
with open(self.contact_path, 'r') as contact_data_list: # get contact data
self.list_contact_data = load(contact_data_list) # parse contact data
self.contact_list = list_contact_data['contacts'] # put all contacts in variable
def listofcontacts(self):
wait(0.5) # delay so it starts speaking first
for c in self.contact_list: # loop for however many contacts
c_letters = list(c) # break contacts into letters
c_letter_first = c_letters[0] # get first letter
c_letters_rest = c_letters[1:] # get all other letters
c_letters_rest_joined = ("").join(c_letters_rest) # join all other letters back into a word
c_letter_first_upper = str(c_letter_first.upper()) # make the first letter uppercase
print(c_letter_first_upper + c_letters_rest_joined) # print the uppercase letter and rest of name to look like normal name
if self._type_ != 1: # if this doesn't need contact data
email_c = self.contact_list[c]['email'] # get email of contact
if self._type_ != 'email': # if you want phone and email
phone_c = self.contact_list[c]['number'] # get phone numbers
print(' ' + email_c + '\n ' + phone_c + '\n') # print email and phone
else: # only email
print(' ' + email_c + '\n') # print only email
# Function to open contact file and help sort for what information needed from listofcontacts()
def contactList(self):
if not self.list_contact_data['contacts']: # if no contacts
print('No contacts use the add contacts command to add some') # no contact message
elif not self.list_contact_data: # missing file and data
print('Fatal Error\nMissing data make sure that you ran setup.py before running this script') # missing file and data message
else: # there are contacts and there was a file
thread_list_contact = Thread(target = listofcontacts) # thread arguments to print list while speaking because of slow speak times
thread_list_contact.start() # start thread of lisofcontacts function
speak('Opening contact list\n', self.speak_type) # speak | [
"marvin.essentials.speak"
] | [((461, 477), 'json.load', 'load', (['check_name'], {}), '(check_name)\n', (465, 477), False, 'from json import load\n'), ((1300, 1309), 'time.sleep', 'wait', (['(0.5)'], {}), '(0.5)\n', (1304, 1309), True, 'from time import sleep as wait\n'), ((1123, 1146), 'json.load', 'load', (['contact_data_list'], {}), '(contact_data_list)\n', (1127, 1146), False, 'from json import load\n'), ((3029, 3058), 'threading.Thread', 'Thread', ([], {'target': 'listofcontacts'}), '(target=listofcontacts)\n', (3035, 3058), False, 'from threading import Thread\n'), ((3230, 3278), 'marvin.essentials.speak', 'speak', (['"""Opening contact list\n"""', 'self.speak_type'], {}), "('Opening contact list\\n', self.speak_type)\n", (3235, 3278), False, 'from marvin.essentials import speak\n')] |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Filename: caching.py
# Project: db
# Author: <NAME>
# Created: Friday, 24th January 2020 2:47:54 pm
# License: BSD 3-clause "New" or "Revised" License
# Copyright (c) 2020 <NAME>
# Last Modified: Monday, 27th January 2020 6:36:07 pm
# Modified By: <NAME>
from __future__ import print_function, division, absolute_import
from marvin import config
from hashlib import md5
from dogpile.cache.region import make_region
import os
import copy
try:
import redis
except ImportError:
redis = None
# DOGPILE CACHING SETUP
# dogpile cache regions. A home base for cache configurations.
regions = {}
# create the dogpile directory for file-based caches
dogpath = os.environ.get('MANGA_SCRATCH_DIR', None)
if dogpath and os.path.isdir(dogpath):
dogpath = dogpath
else:
dogpath = os.path.expanduser('~')
dogroot = os.path.join(dogpath, 'dogpile_data')
if not os.path.isdir(dogroot):
os.makedirs(dogroot)
# db hash key
def md5_key_mangler(key):
"""Receive cache keys as long concatenated strings;
distill them into an md5 hash.
"""
return md5(key.encode('ascii')).hexdigest()
def redis_key_mangler(key):
''' Set a redis key mangler
Prefix the cache key for redis caches to distinguish dogpile
caches in redis from other caches in redis. See
https://dogpilecache.sqlalchemy.org/en/latest/recipes.html#prefixing-all-keys-in-redis
'''
return "marvin:dogpile:" + key
# cache backend type
cache_type = {
'null': {'name': 'dogpile.cache.null', 'args': {}},
'file': {'name': 'dogpile.cache.dbm', 'args': {'filename': dogroot}},
'redis': {'name': 'dogpile.cache.redis',
'args': {'url': os.environ.get('SESSION_REDIS'),
'distributed_lock': True, 'lock_sleep': 1,
'lock_timeout': 5, 'thread_local_lock': False}}
}
def make_new_region(name='cache.dbm', backend='file', expiration=3600, redis_exp_multiplier=2):
''' make a new dogpile cache region
Creates a new dogpile cache region. Default is to create a file-based
cache called cache.dbm, with an expiration of 1 hour.
Parameters:
name (str):
The name of the file-based cache
backend (str):
The type of cache backend to use. Default is file.
expiration (int):
Expiration time in seconds of dogpile cache. Default is 3600 seconds.
redis_exp_multiplier (int):
Integer factor to compute redis cache expiration time from dogpile expiration.
Default is 2x the expiration.
'''
# select the backend
cache_backend = copy.deepcopy(cache_type[backend])
# set the key mangler
key_mangler = redis_key_mangler if backend == 'redis' else md5_key_mangler
# create the cache filename
if backend == 'file':
fileroot = cache_backend['args'].get('filename', dogroot)
cache_backend['args']['filename'] = os.path.join(fileroot, name)
# update the redis expiration time
if backend == 'redis':
cache_backend['args']['redis_expiration_time'] = expiration * redis_exp_multiplier
assert cache_backend['args']['url'] and cache_backend['args']['url'].startswith('redis'), \
'Must have a redis url set to use a redis backend'
# make the region
reg = make_region(key_mangler=key_mangler).configure(
cache_backend['name'],
expiration_time=expiration,
arguments=cache_backend['args']
)
return reg
# make a default cache region
regions['default'] = make_new_region()
# make a null cache for tests and dumps
regions['null'] = make_new_region(backend='null')
# make cache regions for NSA tables
for mpl in config._allowed_releases.keys():
nsacache = 'nsa_{0}'.format(mpl.lower().replace('-', ''))
regions[nsacache] = make_new_region(name=nsacache)
backend = 'file' if not redis or not os.environ.get('SESSION_REDIS') else 'redis'
# make a maps redis cache
regions['maps'] = make_new_region(backend=backend)
# make a modelcube redis cache
regions['models'] = make_new_region(backend=backend)
| [
"marvin.config._allowed_releases.keys"
] | [((717, 758), 'os.environ.get', 'os.environ.get', (['"""MANGA_SCRATCH_DIR"""', 'None'], {}), "('MANGA_SCRATCH_DIR', None)\n", (731, 758), False, 'import os\n'), ((875, 912), 'os.path.join', 'os.path.join', (['dogpath', '"""dogpile_data"""'], {}), "(dogpath, 'dogpile_data')\n", (887, 912), False, 'import os\n'), ((3741, 3772), 'marvin.config._allowed_releases.keys', 'config._allowed_releases.keys', ([], {}), '()\n', (3770, 3772), False, 'from marvin import config\n'), ((774, 796), 'os.path.isdir', 'os.path.isdir', (['dogpath'], {}), '(dogpath)\n', (787, 796), False, 'import os\n'), ((840, 863), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (858, 863), False, 'import os\n'), ((920, 942), 'os.path.isdir', 'os.path.isdir', (['dogroot'], {}), '(dogroot)\n', (933, 942), False, 'import os\n'), ((948, 968), 'os.makedirs', 'os.makedirs', (['dogroot'], {}), '(dogroot)\n', (959, 968), False, 'import os\n'), ((2662, 2696), 'copy.deepcopy', 'copy.deepcopy', (['cache_type[backend]'], {}), '(cache_type[backend])\n', (2675, 2696), False, 'import copy\n'), ((2972, 3000), 'os.path.join', 'os.path.join', (['fileroot', 'name'], {}), '(fileroot, name)\n', (2984, 3000), False, 'import os\n'), ((1718, 1749), 'os.environ.get', 'os.environ.get', (['"""SESSION_REDIS"""'], {}), "('SESSION_REDIS')\n", (1732, 1749), False, 'import os\n'), ((3355, 3391), 'dogpile.cache.region.make_region', 'make_region', ([], {'key_mangler': 'key_mangler'}), '(key_mangler=key_mangler)\n', (3366, 3391), False, 'from dogpile.cache.region import make_region\n'), ((3929, 3960), 'os.environ.get', 'os.environ.get', (['"""SESSION_REDIS"""'], {}), "('SESSION_REDIS')\n", (3943, 3960), False, 'import os\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import random
import SignedAPICall
import XenAPI
from solidfire.factory import ElementFactory
from util import sf_util
from marvin.cloudstackAPI import destroySystemVm
# All tests inherit from cloudstackTestCase
from marvin.cloudstackTestCase import cloudstackTestCase
# Import Integration Libraries
# base - contains all resources as entities and defines create, delete, list operations on them
from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone
# common - commonly used methods for all tests are listed here
from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers
# utils - utility classes for common cleanup, external library wrappers, etc.
from marvin.lib.utils import cleanup_resources, wait_until
# Prerequisites:
# * Only use one SolidFire cluster for the two primary storages based on the "SolidFire" storage plug-in.
# * Do not run other workloads on the SolidFire cluster while running this test as this test checks at a certain
# point to make sure no active SolidFire volumes exist.
# * Only one zone
# * Only one secondary storage VM and one console proxy VM running on NFS (no virtual router or user VMs exist)
# * Only one pod
# * Only one cluster
#
# Running the tests:
# Change the "hypervisor_type" variable to control which hypervisor type to test.
# If using XenServer, verify the "xen_server_hostname" variable is correct.
# Set the Global Setting "storage.cleanup.enabled" to true.
# Set the Global Setting "storage.cleanup.interval" to 150.
# Set the Global Setting "storage.cleanup.delay" to 60.
class TestData():
# constants
account = "account"
capacityBytes = "capacitybytes"
capacityIops = "capacityiops"
clusterId = "clusterid"
computeOffering = "computeoffering"
diskOffering = "diskoffering"
domainId = "domainid"
email = "email"
firstname = "firstname"
hypervisor = "hypervisor"
kvm = "kvm"
lastname = "lastname"
max_iops = "maxiops"
min_iops = "miniops"
mvip = "mvip"
name = "name"
password = "password"
port = "port"
primaryStorage = "primarystorage"
provider = "provider"
scope = "scope"
solidFire = "solidfire"
storageTag = "SolidFire_SAN_1"
systemOffering = "systemoffering"
systemOfferingFailure = "systemofferingFailure"
tags = "tags"
url = "url"
user = "user"
username = "username"
virtualMachine = "virtualmachine"
xenServer = "xenserver"
zoneId = "zoneid"
# modify to control which hypervisor type to test
hypervisor_type = xenServer
xen_server_hostname = "XenServer-6.5-1"
def __init__(self):
self.testdata = {
TestData.solidFire: {
TestData.mvip: "10.117.40.120",
TestData.username: "admin",
TestData.password: "<PASSWORD>",
TestData.port: 443,
TestData.url: "https://10.117.40.120:443"
},
TestData.kvm: {
TestData.username: "root",
TestData.password: "<PASSWORD>"
},
TestData.xenServer: {
TestData.username: "root",
TestData.password: "<PASSWORD>"
},
TestData.account: {
TestData.email: "<EMAIL>",
TestData.firstname: "John",
TestData.lastname: "Doe",
TestData.username: "test",
TestData.password: "<PASSWORD>"
},
TestData.user: {
TestData.email: "<EMAIL>",
TestData.firstname: "Jane",
TestData.lastname: "Doe",
TestData.username: "testuser",
TestData.password: "password"
},
TestData.primaryStorage: {
TestData.name: TestData.get_name_for_solidfire_storage(),
TestData.scope: "ZONE",
TestData.url: "MVIP=10.117.40.120;SVIP=10.117.41.120;" +
"clusterAdminUsername=admin;clusterAdminPassword=<PASSWORD>;" +
"clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" +
"clusterDefaultBurstIopsPercentOfMaxIops=1.5;",
TestData.provider: "SolidFire",
TestData.tags: TestData.storageTag,
TestData.capacityIops: 4500000,
TestData.capacityBytes: 2251799813685248,
TestData.hypervisor: "Any",
TestData.zoneId: 1
},
TestData.virtualMachine: {
TestData.name: "TestVM",
"displayname": "Test VM"
},
TestData.computeOffering: {
TestData.name: "SF_CO_1",
"displaytext": "SF_CO_1 (Min IOPS = 10,000; Max IOPS = 15,000)",
"cpunumber": 1,
"cpuspeed": 100,
"memory": 128,
"storagetype": "shared",
"customizediops": False,
TestData.min_iops: 10000,
TestData.max_iops: 15000,
"hypervisorsnapshotreserve": 200,
TestData.tags: TestData.storageTag
},
TestData.systemOffering: {
TestData.name: "SF_SO_1",
"displaytext": "Managed SO (Min IOPS = 4,000; Max IOPS = 8,000)",
"cpunumber": 1,
"cpuspeed": 100,
"memory": 128,
"storagetype": "shared",
TestData.min_iops: 4000,
TestData.max_iops: 8000,
TestData.tags: TestData.storageTag,
"issystem": True
},
TestData.systemOfferingFailure: {
TestData.name: "SF_SO_2",
"displaytext": "Managed SO (Customized IOPS)",
"cpunumber": 1,
"cpuspeed": 100,
"memory": 128,
"storagetype": "shared",
"customizediops": True,
TestData.tags: TestData.storageTag,
"issystem": True
},
TestData.zoneId: 1,
TestData.clusterId: 1,
TestData.domainId: 1,
TestData.url: "10.117.40.114"
}
@staticmethod
def get_name_for_solidfire_storage():
return "SolidFire-%d" % random.randint(0, 100)
class TestManagedSystemVMs(cloudstackTestCase):
_unique_name_suffix = "-Temp"
_secondary_storage_unique_name = "Cloud.com-SecondaryStorage"
_secondary_storage_temp_unique_name = _secondary_storage_unique_name + _unique_name_suffix
_console_proxy_unique_name = "Cloud.com-ConsoleProxy"
_console_proxy_temp_unique_name = _console_proxy_unique_name + _unique_name_suffix
_virtual_router_unique_name = "Cloud.com-SoftwareRouter"
_virtual_router_temp_unique_name = _virtual_router_unique_name + _unique_name_suffix
@classmethod
def setUpClass(cls):
# Set up API client
testclient = super(TestManagedSystemVMs, cls).getClsTestClient()
cls.apiClient = testclient.getApiClient()
cls.configData = testclient.getParsedTestDataConfig()
cls.dbConnection = testclient.getDbConnection()
cls.testdata = TestData().testdata
cls._connect_to_hypervisor()
# Set up SolidFire connection
solidfire = cls.testdata[TestData.solidFire]
cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password])
# Get Resources from Cloud Infrastructure
cls.zone = Zone(get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]).__dict__)
cls.cluster = list_clusters(cls.apiClient)[0]
cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type)
cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId])
# Create test account
cls.account = Account.create(
cls.apiClient,
cls.testdata["account"],
admin=1
)
# Set up connection to make customized API calls
cls.user = User.create(
cls.apiClient,
cls.testdata["user"],
account=cls.account.name,
domainid=cls.domain.id
)
url = cls.testdata[TestData.url]
api_url = "http://" + url + ":8080/client/api"
userkeys = User.registerUserKeys(cls.apiClient, cls.user.id)
cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey)
cls.compute_offering = ServiceOffering.create(
cls.apiClient,
cls.testdata[TestData.computeOffering]
)
systemoffering = cls.testdata[TestData.systemOffering]
systemoffering[TestData.name] = "Managed SSVM"
systemoffering['systemvmtype'] = "secondarystoragevm"
cls.secondary_storage_offering = ServiceOffering.create(
cls.apiClient,
systemoffering
)
systemoffering[TestData.name] = "Managed CPVM"
systemoffering['systemvmtype'] = "consoleproxy"
cls.console_proxy_offering = ServiceOffering.create(
cls.apiClient,
systemoffering
)
systemoffering[TestData.name] = "Managed VR"
systemoffering['systemvmtype'] = "domainrouter"
cls.virtual_router_offering = ServiceOffering.create(
cls.apiClient,
systemoffering
)
# Resources that are to be destroyed
cls._cleanup = [
cls.secondary_storage_offering,
cls.console_proxy_offering,
cls.virtual_router_offering,
cls.compute_offering,
cls.user,
cls.account
]
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiClient, cls._cleanup)
except Exception as e:
logging.debug("Exception in tearDownClass(cls): %s" % e)
def setUp(self):
self.cleanup = []
def tearDown(self):
try:
cleanup_resources(self.apiClient, self.cleanup)
sf_util.purge_solidfire_volumes(self.sfe)
except Exception as e:
logging.debug("Exception in tearDownClass(self): %s" % e)
def test_01_create_system_vms_on_managed_storage(self):
self._disable_zone_and_delete_system_vms(None, False)
primary_storage = self.testdata[TestData.primaryStorage]
primary_storage_1 = StoragePool.create(
self.apiClient,
primary_storage
)
self._prepare_to_use_managed_storage_for_system_vms()
enabled = "Enabled"
self.zone.update(self.apiClient, id=self.zone.id, allocationstate=enabled)
system_vms = self._wait_for_and_get_running_system_vms(2)
virtual_machine = VirtualMachine.create(
self.apiClient,
self.testdata[TestData.virtualMachine],
accountid=self.account.name,
zoneid=self.zone.id,
serviceofferingid=self.compute_offering.id,
templateid=self.template.id,
domainid=self.domain.id,
startvm=True
)
# This virtual machine was only created and started so that the virtual router would be created and started.
# Just delete this virtual machine once it has been created and started.
virtual_machine.delete(self.apiClient, True)
virtual_router = list_routers(self.apiClient, listall=True, state="Running")[0]
system_vms.append(virtual_router)
self._check_system_vms(system_vms, primary_storage_1.id)
primary_storage[TestData.name] = TestData.get_name_for_solidfire_storage()
primary_storage_2 = StoragePool.create(
self.apiClient,
primary_storage
)
StoragePool.enableMaintenance(self.apiClient, primary_storage_1.id)
self._wait_for_storage_cleanup_thread(system_vms)
sf_util.purge_solidfire_volumes(self.sfe)
system_vms = self._wait_for_and_get_running_system_vms(2)
virtual_router = list_routers(self.apiClient, listall=True, state="Running")[0]
system_vms.append(virtual_router)
self._check_system_vms(system_vms, primary_storage_2.id)
StoragePool.cancelMaintenance(self.apiClient, primary_storage_1.id)
primary_storage_1.delete(self.apiClient)
self._disable_zone_and_delete_system_vms(virtual_router)
self._wait_for_storage_cleanup_thread(system_vms)
sf_util.purge_solidfire_volumes(self.sfe)
primary_storage_2.delete(self.apiClient)
self._verify_no_active_solidfire_volumes()
self._prepare_to_stop_using_managed_storage_for_system_vms()
self.zone.update(self.apiClient, id=self.zone.id, allocationstate=enabled)
self._wait_for_and_get_running_system_vms(2)
def test_02_failure_to_create_service_offering_with_customized_iops(self):
try:
ServiceOffering.create(
self.apiClient,
self.testdata[TestData.systemOfferingFailure]
)
except:
return
self.assertTrue(False, "The service offering was created, but should not have been.")
def _prepare_to_use_managed_storage_for_system_vms(self):
self._update_system_vm_unique_name(TestManagedSystemVMs._secondary_storage_unique_name, TestManagedSystemVMs._secondary_storage_temp_unique_name)
self._update_system_vm_unique_name(TestManagedSystemVMs._console_proxy_unique_name, TestManagedSystemVMs._console_proxy_temp_unique_name)
self._update_system_vm_unique_name(TestManagedSystemVMs._virtual_router_unique_name, TestManagedSystemVMs._virtual_router_temp_unique_name)
self._update_system_vm_unique_name_based_on_uuid(self.secondary_storage_offering.id, TestManagedSystemVMs._secondary_storage_unique_name)
self._update_system_vm_unique_name_based_on_uuid(self.console_proxy_offering.id, TestManagedSystemVMs._console_proxy_unique_name)
self._update_system_vm_unique_name_based_on_uuid(self.virtual_router_offering.id, TestManagedSystemVMs._virtual_router_unique_name)
def _prepare_to_stop_using_managed_storage_for_system_vms(self):
self._update_system_vm_unique_name_based_on_uuid(self.secondary_storage_offering.id, None)
self._update_system_vm_unique_name_based_on_uuid(self.console_proxy_offering.id, None)
self._update_system_vm_unique_name_based_on_uuid(self.virtual_router_offering.id, None)
self._update_system_vm_unique_name(TestManagedSystemVMs._secondary_storage_temp_unique_name, TestManagedSystemVMs._secondary_storage_unique_name)
self._update_system_vm_unique_name(TestManagedSystemVMs._console_proxy_temp_unique_name, TestManagedSystemVMs._console_proxy_unique_name)
self._update_system_vm_unique_name(TestManagedSystemVMs._virtual_router_temp_unique_name, TestManagedSystemVMs._virtual_router_unique_name)
def _wait_for_storage_cleanup_thread(self, system_vms):
retry_interval = 60
num_tries = 10
wait_result, return_val = wait_until(retry_interval, num_tries, self._check_resource_state, system_vms)
if not wait_result:
raise Exception(return_val)
def _check_resource_state(self, system_vms):
try:
self._verify_system_vms_deleted(system_vms)
return True, None
except:
return False, "The system is not in the necessary state."
def _verify_system_vms_deleted(self, system_vms):
for system_vm in system_vms:
cs_root_volume = self._get_root_volume_for_system_vm(system_vm.id, 'Expunged')
self._verify_managed_system_vm_deleted(cs_root_volume.name)
def _disable_zone_and_delete_system_vms(self, virtual_router, verify_managed_system_vm_deleted=True):
self.zone.update(self.apiClient, id=self.zone.id, allocationstate="Disabled")
if virtual_router is not None:
Router.destroy(self.apiClient, virtual_router.id)
if verify_managed_system_vm_deleted:
cs_root_volume = self._get_root_volume_for_system_vm(virtual_router.id, 'Expunged')
self._verify_managed_system_vm_deleted(cs_root_volume.name)
# list_ssvms lists the secondary storage VM and the console proxy VM
system_vms = list_ssvms(self.apiClient)
for system_vm in system_vms:
destroy_ssvm_cmd = destroySystemVm.destroySystemVmCmd()
destroy_ssvm_cmd.id = system_vm.id
self.apiClient.destroySystemVm(destroy_ssvm_cmd)
if verify_managed_system_vm_deleted:
cs_root_volume = self._get_root_volume_for_system_vm(system_vm.id, 'Expunged')
self._verify_managed_system_vm_deleted(cs_root_volume.name)
def _verify_managed_system_vm_deleted(self, cs_root_volume_name):
sf_not_active_volumes = sf_util.get_not_active_sf_volumes(self.sfe)
sf_root_volume = sf_util.check_and_get_sf_volume(sf_not_active_volumes, cs_root_volume_name, self)
self.assertEqual(
len(sf_root_volume.volume_access_groups),
0,
"The volume should not be in a volume access group."
)
if TestData.hypervisor_type == TestData.xenServer:
sr_name = sf_util.format_iqn(sf_root_volume.iqn)
sf_util.check_xen_sr(sr_name, self.xen_session, self, False)
elif TestData.hypervisor_type == TestData.kvm:
list_hosts_response = list_hosts(
self.apiClient,
type="Routing"
)
kvm_login = self.testdata[TestData.kvm]
sf_util.check_kvm_access_to_volume(sf_root_volume.iqn, list_hosts_response, kvm_login[TestData.username], kvm_login[TestData.password], self, False)
else:
self.assertTrue(False, "Invalid hypervisor type")
def _wait_for_and_get_running_system_vms(self, expected_number_of_system_vms):
retry_interval = 60
num_tries = 10
wait_result, return_val = wait_until(retry_interval, num_tries, self._check_number_of_running_system_vms, expected_number_of_system_vms)
if not wait_result:
raise Exception(return_val)
return return_val
def _check_number_of_running_system_vms(self, expected_number_of_system_vms):
# list_ssvms lists the secondary storage VM and the console proxy VM
system_vms = list_ssvms(self.apiClient, state="Running")
if system_vms is not None and len(system_vms) == expected_number_of_system_vms:
return True, system_vms
return False, "Timed out waiting for running system VMs"
def _verify_no_active_solidfire_volumes(self):
sf_active_volumes = sf_util.get_active_sf_volumes(self.sfe)
sf_util.check_list(sf_active_volumes, 0, self, "There should be no active SolidFire volumes in the cluster.")
def _check_system_vms(self, system_vms, primary_storage_id):
sf_active_volumes = sf_util.get_active_sf_volumes(self.sfe)
sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, primary_storage_id, self)
for system_vm in system_vms:
cs_root_volume = self._get_root_volume_for_system_vm(system_vm.id, 'Ready')
sf_root_volume = sf_util.check_and_get_sf_volume(sf_active_volumes, cs_root_volume.name, self)
sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, cs_root_volume, self)
sf_util.check_size_and_iops(sf_root_volume, cs_root_volume, sf_volume_size, self)
self._check_iops_against_iops_of_system_offering(cs_root_volume, self.testdata[TestData.systemOffering])
sf_util.check_vag(sf_root_volume, sf_vag_id, self)
if TestData.hypervisor_type == TestData.xenServer:
sr_name = sf_util.format_iqn(sf_root_volume.iqn)
sf_util.check_xen_sr(sr_name, self.xen_session, self)
elif TestData.hypervisor_type == TestData.kvm:
list_hosts_response = list_hosts(
self.apiClient,
type="Routing"
)
kvm_login = self.testdata[TestData.kvm]
sf_util.check_kvm_access_to_volume(sf_root_volume.iqn, list_hosts_response, kvm_login[TestData.username], kvm_login[TestData.password], self)
else:
self.assertTrue(False, "Invalid hypervisor type")
def _check_iops_against_iops_of_system_offering(self, cs_volume, system_offering):
self.assertEqual(
system_offering[TestData.min_iops],
cs_volume.miniops,
"Check QoS - Min IOPS: of " + cs_volume.name + " should be " + str(system_offering[TestData.min_iops])
)
self.assertEqual(
system_offering[TestData.max_iops],
cs_volume.maxiops,
"Check QoS - Min IOPS: of " + cs_volume.name + " should be " + str(system_offering[TestData.max_iops])
)
def _get_root_volume_for_system_vm(self, system_vm_id, state):
sql_query = "Select id From vm_instance Where uuid = '" + system_vm_id + "'"
# make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench
sql_result = self.dbConnection.execute(sql_query)
instance_id = sql_result[0][0]
sql_query = "Select uuid, name, min_iops, max_iops From volumes Where instance_id = " + str(instance_id) + \
" and state = '" + state + "' Order by removed desc"
# make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench
sql_result = self.dbConnection.execute(sql_query)
uuid = sql_result[0][0]
name = sql_result[0][1]
min_iops = sql_result[0][2]
max_iops = sql_result[0][3]
class CloudStackVolume(object):
pass
cs_volume = CloudStackVolume()
cs_volume.id = uuid
cs_volume.name = name
cs_volume.miniops = min_iops
cs_volume.maxiops = max_iops
return cs_volume
def _update_system_vm_unique_name(self, unique_name, new_unique_name):
sql_query = "Update disk_offering set unique_name = '" + new_unique_name + "' Where unique_name = '" + unique_name + "'"
# make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench
self.dbConnection.execute(sql_query)
def _update_system_vm_unique_name_based_on_uuid(self, uuid, new_unique_name):
if (new_unique_name is None):
sql_query = "Update disk_offering set unique_name = NULL Where uuid = '" + uuid + "'"
else:
sql_query = "Update disk_offering set unique_name = '" + new_unique_name + "' Where uuid = '" + uuid + "'"
# make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench
self.dbConnection.execute(sql_query)
@classmethod
def _connect_to_hypervisor(cls):
if TestData.hypervisor_type == TestData.kvm:
pass
elif TestData.hypervisor_type == TestData.xenServer:
host_ip = "https://" + \
list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_hostname)[0].ipaddress
cls.xen_session = XenAPI.Session(host_ip)
xen_server = cls.testdata[TestData.xenServer]
cls.xen_session.xenapi.login_with_password(xen_server[TestData.username], xen_server[TestData.password])
| [
"marvin.lib.base.Router.destroy",
"marvin.lib.base.StoragePool.create",
"marvin.lib.base.StoragePool.cancelMaintenance",
"marvin.lib.common.get_zone",
"marvin.lib.base.User.registerUserKeys",
"marvin.lib.common.list_routers",
"marvin.lib.common.get_domain",
"marvin.lib.common.list_clusters",
"marvin... | [((8315, 8427), 'solidfire.factory.ElementFactory.create', 'ElementFactory.create', (['solidfire[TestData.mvip]', 'solidfire[TestData.username]', 'solidfire[TestData.password]'], {}), '(solidfire[TestData.mvip], solidfire[TestData.username\n ], solidfire[TestData.password])\n', (8336, 8427), False, 'from solidfire.factory import ElementFactory\n'), ((8648, 8725), 'marvin.lib.common.get_template', 'get_template', (['cls.apiClient', 'cls.zone.id'], {'hypervisor': 'TestData.hypervisor_type'}), '(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type)\n', (8660, 8725), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((8747, 8805), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiClient', 'cls.testdata[TestData.domainId]'], {}), '(cls.apiClient, cls.testdata[TestData.domainId])\n', (8757, 8805), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((8859, 8922), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiClient', "cls.testdata['account']"], {'admin': '(1)'}), "(cls.apiClient, cls.testdata['account'], admin=1)\n", (8873, 8922), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((9046, 9148), 'marvin.lib.base.User.create', 'User.create', (['cls.apiClient', "cls.testdata['user']"], {'account': 'cls.account.name', 'domainid': 'cls.domain.id'}), "(cls.apiClient, cls.testdata['user'], account=cls.account.name,\n domainid=cls.domain.id)\n", (9057, 9148), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((9320, 9369), 'marvin.lib.base.User.registerUserKeys', 'User.registerUserKeys', (['cls.apiClient', 'cls.user.id'], {}), '(cls.apiClient, cls.user.id)\n', (9341, 9369), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((9392, 9462), 'SignedAPICall.CloudStack', 'SignedAPICall.CloudStack', (['api_url', 'userkeys.apikey', 'userkeys.secretkey'], {}), '(api_url, userkeys.apikey, userkeys.secretkey)\n', (9416, 9462), False, 'import SignedAPICall\n'), ((9495, 9572), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiClient', 'cls.testdata[TestData.computeOffering]'], {}), '(cls.apiClient, cls.testdata[TestData.computeOffering])\n', (9517, 9572), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((9831, 9884), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiClient', 'systemoffering'], {}), '(cls.apiClient, systemoffering)\n', (9853, 9884), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((10069, 10122), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiClient', 'systemoffering'], {}), '(cls.apiClient, systemoffering)\n', (10091, 10122), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((10306, 10359), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiClient', 'systemoffering'], {}), '(cls.apiClient, systemoffering)\n', (10328, 10359), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((11418, 11469), 'marvin.lib.base.StoragePool.create', 'StoragePool.create', (['self.apiClient', 'primary_storage'], {}), '(self.apiClient, primary_storage)\n', (11436, 11469), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((11774, 12028), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiClient', 'self.testdata[TestData.virtualMachine]'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'serviceofferingid': 'self.compute_offering.id', 'templateid': 'self.template.id', 'domainid': 'self.domain.id', 'startvm': '(True)'}), '(self.apiClient, self.testdata[TestData.virtualMachine\n ], accountid=self.account.name, zoneid=self.zone.id, serviceofferingid=\n self.compute_offering.id, templateid=self.template.id, domainid=self.\n domain.id, startvm=True)\n', (11795, 12028), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((12683, 12734), 'marvin.lib.base.StoragePool.create', 'StoragePool.create', (['self.apiClient', 'primary_storage'], {}), '(self.apiClient, primary_storage)\n', (12701, 12734), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((12778, 12845), 'marvin.lib.base.StoragePool.enableMaintenance', 'StoragePool.enableMaintenance', (['self.apiClient', 'primary_storage_1.id'], {}), '(self.apiClient, primary_storage_1.id)\n', (12807, 12845), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((12914, 12955), 'util.sf_util.purge_solidfire_volumes', 'sf_util.purge_solidfire_volumes', (['self.sfe'], {}), '(self.sfe)\n', (12945, 12955), False, 'from util import sf_util\n'), ((13230, 13297), 'marvin.lib.base.StoragePool.cancelMaintenance', 'StoragePool.cancelMaintenance', (['self.apiClient', 'primary_storage_1.id'], {}), '(self.apiClient, primary_storage_1.id)\n', (13259, 13297), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((13482, 13523), 'util.sf_util.purge_solidfire_volumes', 'sf_util.purge_solidfire_volumes', (['self.sfe'], {}), '(self.sfe)\n', (13513, 13523), False, 'from util import sf_util\n'), ((16093, 16170), 'marvin.lib.utils.wait_until', 'wait_until', (['retry_interval', 'num_tries', 'self._check_resource_state', 'system_vms'], {}), '(retry_interval, num_tries, self._check_resource_state, system_vms)\n', (16103, 16170), False, 'from marvin.lib.utils import cleanup_resources, wait_until\n'), ((17353, 17379), 'marvin.lib.common.list_ssvms', 'list_ssvms', (['self.apiClient'], {}), '(self.apiClient)\n', (17363, 17379), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((17921, 17964), 'util.sf_util.get_not_active_sf_volumes', 'sf_util.get_not_active_sf_volumes', (['self.sfe'], {}), '(self.sfe)\n', (17954, 17964), False, 'from util import sf_util\n'), ((17991, 18076), 'util.sf_util.check_and_get_sf_volume', 'sf_util.check_and_get_sf_volume', (['sf_not_active_volumes', 'cs_root_volume_name', 'self'], {}), '(sf_not_active_volumes, cs_root_volume_name,\n self)\n', (18022, 18076), False, 'from util import sf_util\n'), ((19078, 19193), 'marvin.lib.utils.wait_until', 'wait_until', (['retry_interval', 'num_tries', 'self._check_number_of_running_system_vms', 'expected_number_of_system_vms'], {}), '(retry_interval, num_tries, self.\n _check_number_of_running_system_vms, expected_number_of_system_vms)\n', (19088, 19193), False, 'from marvin.lib.utils import cleanup_resources, wait_until\n'), ((19466, 19509), 'marvin.lib.common.list_ssvms', 'list_ssvms', (['self.apiClient'], {'state': '"""Running"""'}), "(self.apiClient, state='Running')\n", (19476, 19509), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((19781, 19820), 'util.sf_util.get_active_sf_volumes', 'sf_util.get_active_sf_volumes', (['self.sfe'], {}), '(self.sfe)\n', (19810, 19820), False, 'from util import sf_util\n'), ((19830, 19943), 'util.sf_util.check_list', 'sf_util.check_list', (['sf_active_volumes', '(0)', 'self', '"""There should be no active SolidFire volumes in the cluster."""'], {}), "(sf_active_volumes, 0, self,\n 'There should be no active SolidFire volumes in the cluster.')\n", (19848, 19943), False, 'from util import sf_util\n'), ((20034, 20073), 'util.sf_util.get_active_sf_volumes', 'sf_util.get_active_sf_volumes', (['self.sfe'], {}), '(self.sfe)\n', (20063, 20073), False, 'from util import sf_util\n'), ((20095, 20169), 'util.sf_util.get_vag_id', 'sf_util.get_vag_id', (['self.cs_api', 'self.cluster.id', 'primary_storage_id', 'self'], {}), '(self.cs_api, self.cluster.id, primary_storage_id, self)\n', (20113, 20169), False, 'from util import sf_util\n'), ((7243, 7265), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (7257, 7265), False, 'import random\n'), ((8593, 8621), 'marvin.lib.common.list_clusters', 'list_clusters', (['cls.apiClient'], {}), '(cls.apiClient)\n', (8606, 8621), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((10751, 10797), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiClient', 'cls._cleanup'], {}), '(cls.apiClient, cls._cleanup)\n', (10768, 10797), False, 'from marvin.lib.utils import cleanup_resources, wait_until\n'), ((10996, 11043), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiClient', 'self.cleanup'], {}), '(self.apiClient, self.cleanup)\n', (11013, 11043), False, 'from marvin.lib.utils import cleanup_resources, wait_until\n'), ((11057, 11098), 'util.sf_util.purge_solidfire_volumes', 'sf_util.purge_solidfire_volumes', (['self.sfe'], {}), '(self.sfe)\n', (11088, 11098), False, 'from util import sf_util\n'), ((12398, 12457), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiClient'], {'listall': '(True)', 'state': '"""Running"""'}), "(self.apiClient, listall=True, state='Running')\n", (12410, 12457), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((13049, 13108), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiClient'], {'listall': '(True)', 'state': '"""Running"""'}), "(self.apiClient, listall=True, state='Running')\n", (13061, 13108), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((13939, 14029), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiClient', 'self.testdata[TestData.systemOfferingFailure]'], {}), '(self.apiClient, self.testdata[TestData.\n systemOfferingFailure])\n', (13961, 14029), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((16977, 17026), 'marvin.lib.base.Router.destroy', 'Router.destroy', (['self.apiClient', 'virtual_router.id'], {}), '(self.apiClient, virtual_router.id)\n', (16991, 17026), False, 'from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone\n'), ((17449, 17485), 'marvin.cloudstackAPI.destroySystemVm.destroySystemVmCmd', 'destroySystemVm.destroySystemVmCmd', ([], {}), '()\n', (17483, 17485), False, 'from marvin.cloudstackAPI import destroySystemVm\n'), ((18326, 18364), 'util.sf_util.format_iqn', 'sf_util.format_iqn', (['sf_root_volume.iqn'], {}), '(sf_root_volume.iqn)\n', (18344, 18364), False, 'from util import sf_util\n'), ((18378, 18438), 'util.sf_util.check_xen_sr', 'sf_util.check_xen_sr', (['sr_name', 'self.xen_session', 'self', '(False)'], {}), '(sr_name, self.xen_session, self, False)\n', (18398, 18438), False, 'from util import sf_util\n'), ((20325, 20402), 'util.sf_util.check_and_get_sf_volume', 'sf_util.check_and_get_sf_volume', (['sf_active_volumes', 'cs_root_volume.name', 'self'], {}), '(sf_active_volumes, cs_root_volume.name, self)\n', (20356, 20402), False, 'from util import sf_util\n'), ((20433, 20500), 'util.sf_util.get_volume_size_with_hsr', 'sf_util.get_volume_size_with_hsr', (['self.cs_api', 'cs_root_volume', 'self'], {}), '(self.cs_api, cs_root_volume, self)\n', (20465, 20500), False, 'from util import sf_util\n'), ((20514, 20599), 'util.sf_util.check_size_and_iops', 'sf_util.check_size_and_iops', (['sf_root_volume', 'cs_root_volume', 'sf_volume_size', 'self'], {}), '(sf_root_volume, cs_root_volume, sf_volume_size,\n self)\n', (20541, 20599), False, 'from util import sf_util\n'), ((20727, 20777), 'util.sf_util.check_vag', 'sf_util.check_vag', (['sf_root_volume', 'sf_vag_id', 'self'], {}), '(sf_root_volume, sf_vag_id, self)\n', (20744, 20777), False, 'from util import sf_util\n'), ((8498, 8560), 'marvin.lib.common.get_zone', 'get_zone', (['cls.apiClient'], {'zone_id': 'cls.testdata[TestData.zoneId]'}), '(cls.apiClient, zone_id=cls.testdata[TestData.zoneId])\n', (8506, 8560), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((10841, 10897), 'logging.debug', 'logging.debug', (["('Exception in tearDownClass(cls): %s' % e)"], {}), "('Exception in tearDownClass(cls): %s' % e)\n", (10854, 10897), False, 'import logging\n'), ((11142, 11199), 'logging.debug', 'logging.debug', (["('Exception in tearDownClass(self): %s' % e)"], {}), "('Exception in tearDownClass(self): %s' % e)\n", (11155, 11199), False, 'import logging\n'), ((18528, 18570), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiClient'], {'type': '"""Routing"""'}), "(self.apiClient, type='Routing')\n", (18538, 18570), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((18683, 18835), 'util.sf_util.check_kvm_access_to_volume', 'sf_util.check_kvm_access_to_volume', (['sf_root_volume.iqn', 'list_hosts_response', 'kvm_login[TestData.username]', 'kvm_login[TestData.password]', 'self', '(False)'], {}), '(sf_root_volume.iqn, list_hosts_response,\n kvm_login[TestData.username], kvm_login[TestData.password], self, False)\n', (18717, 18835), False, 'from util import sf_util\n'), ((20868, 20906), 'util.sf_util.format_iqn', 'sf_util.format_iqn', (['sf_root_volume.iqn'], {}), '(sf_root_volume.iqn)\n', (20886, 20906), False, 'from util import sf_util\n'), ((20924, 20977), 'util.sf_util.check_xen_sr', 'sf_util.check_xen_sr', (['sr_name', 'self.xen_session', 'self'], {}), '(sr_name, self.xen_session, self)\n', (20944, 20977), False, 'from util import sf_util\n'), ((24516, 24539), 'XenAPI.Session', 'XenAPI.Session', (['host_ip'], {}), '(host_ip)\n', (24530, 24539), False, 'import XenAPI\n'), ((21075, 21117), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiClient'], {'type': '"""Routing"""'}), "(self.apiClient, type='Routing')\n", (21085, 21117), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n'), ((21250, 21395), 'util.sf_util.check_kvm_access_to_volume', 'sf_util.check_kvm_access_to_volume', (['sf_root_volume.iqn', 'list_hosts_response', 'kvm_login[TestData.username]', 'kvm_login[TestData.password]', 'self'], {}), '(sf_root_volume.iqn, list_hosts_response,\n kvm_login[TestData.username], kvm_login[TestData.password], self)\n', (21284, 21395), False, 'from util import sf_util\n'), ((24367, 24476), 'marvin.lib.common.list_hosts', 'list_hosts', (['cls.apiClient'], {'clusterid': 'cls.testdata[TestData.clusterId]', 'name': 'TestData.xen_server_hostname'}), '(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=\n TestData.xen_server_hostname)\n', (24377, 24476), False, 'from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers\n')] |
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.table import Table
import numpy as np
from marvin.tools.cube import Cube
import pandas as pd
with fits.open('./data2/manga_firefly-v2_4_3-STELLARPOP.fits')as fin:
firefly_plateifus = fin['GALAXY_INFO'].data['PLATEIFU']
spaxel_binid = fin['SPATIAL_BINID'].data
mstar_all = fin['SURFACE_MASS_DENSITY_VORONOI'].data
spa_info = fin['SPATIAL_INFO'].data
def get_massmap(gal):
# Select galaxy and binids
ind1 = np.where(firefly_plateifus == gal)[0][0]
ind_binid = spaxel_binid[ind1, :, :].astype(int)
cells_binid = spa_info[ind1,:,0]
# Create 2D stellar mass array
mstar = np.ones(ind_binid.shape) * np.nan
for row, inds in enumerate(ind_binid):
inds[inds==-1]=-9999
ind_nans = np.where(np.logical_or(inds==-1,inds==-9999))
# print(inds)
cells=[]
for i in inds:
cells.append(np.where(cells_binid==(i+0.0))[0][0])
mstar[row] = mstar_all[ind1, cells, 0]
mstar[row][ind_nans] = 0.0
# trim mstar to match size of DAP maps
cube = Cube(gal)
len_x = int(cube.header['NAXIS1'])
mdens = mstar[:len_x, :len_x]
mdens_ma = np.ma.array(data=mdens, mask=mdens==0.0)
return mdens_ma
if __name__ == '__main__':
massmap = get_massmap('8932-9102')
plt.imshow(massmap)
plt.colorbar()
plt.show()
| [
"marvin.tools.cube.Cube"
] | [((172, 229), 'astropy.io.fits.open', 'fits.open', (['"""./data2/manga_firefly-v2_4_3-STELLARPOP.fits"""'], {}), "('./data2/manga_firefly-v2_4_3-STELLARPOP.fits')\n", (181, 229), False, 'from astropy.io import fits\n'), ((1125, 1134), 'marvin.tools.cube.Cube', 'Cube', (['gal'], {}), '(gal)\n', (1129, 1134), False, 'from marvin.tools.cube import Cube\n'), ((1223, 1265), 'numpy.ma.array', 'np.ma.array', ([], {'data': 'mdens', 'mask': '(mdens == 0.0)'}), '(data=mdens, mask=mdens == 0.0)\n', (1234, 1265), True, 'import numpy as np\n'), ((1355, 1374), 'matplotlib.pyplot.imshow', 'plt.imshow', (['massmap'], {}), '(massmap)\n', (1365, 1374), True, 'import matplotlib.pyplot as plt\n'), ((1379, 1393), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1391, 1393), True, 'import matplotlib.pyplot as plt\n'), ((1398, 1408), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1406, 1408), True, 'import matplotlib.pyplot as plt\n'), ((683, 707), 'numpy.ones', 'np.ones', (['ind_binid.shape'], {}), '(ind_binid.shape)\n', (690, 707), True, 'import numpy as np\n'), ((504, 538), 'numpy.where', 'np.where', (['(firefly_plateifus == gal)'], {}), '(firefly_plateifus == gal)\n', (512, 538), True, 'import numpy as np\n'), ((817, 857), 'numpy.logical_or', 'np.logical_or', (['(inds == -1)', '(inds == -9999)'], {}), '(inds == -1, inds == -9999)\n', (830, 857), True, 'import numpy as np\n'), ((941, 973), 'numpy.where', 'np.where', (['(cells_binid == i + 0.0)'], {}), '(cells_binid == i + 0.0)\n', (949, 973), True, 'import numpy as np\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
"""
#Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.integration.lib.base import (Account,
Domain,
User,
Project,
Volume,
Snapshot,
DiskOffering,
ServiceOffering,
VirtualMachine)
from marvin.integration.lib.common import (get_domain,
get_zone,
get_template,
list_volumes,
update_resource_limit,
list_networks,
list_snapshots,
list_virtual_machines)
from marvin.integration.lib.utils import cleanup_resources
def log_test_exceptions(func):
def test_wrap_exception_log(self, *args, **kwargs):
try:
func(self, *args, **kwargs)
except Exception as e:
self.debug('Test %s Failed due to Exception=%s' % (func, e))
raise e
test_wrap_exception_log.__doc__ = func.__doc__
return test_wrap_exception_log
class Services:
"""Test service data for:Change the ownershop of
VM/network/datadisk/snapshot/template/ISO from one account to any other account.
"""
def __init__(self):
self.services = {"domain" : {"name": "Domain",},
"account" : {"email" : "<EMAIL>",
"firstname" : "Test",
"lastname" : "User",
"username" : "test",
# Random characters are appended in create account to
# ensure unique username generated each time
"password" : "password",},
"user" : {"email" : "<EMAIL>",
"firstname": "User",
"lastname" : "User",
"username" : "User",
# Random characters are appended for unique
# username
"password" : "<PASSWORD>",},
"project" : {"name" : "Project",
"displaytext" : "Test project",},
"volume" : {"diskname" : "TestDiskServ",
"max" : 6,},
"disk_offering" : {"displaytext" : "Small",
"name" : "Small",
"disksize" : 1},
"virtual_machine" : {"displayname" : "testserver",
"username" : "root",# VM creds for SSH
"password" : "password",
"ssh_port" : 22,
"hypervisor" : 'XenServer',
"privateport" : 22,
"publicport" : 22,
"protocol" : 'TCP',},
"service_offering" : {"name" : "Tiny Instance",
"displaytext" : "Tiny Instance",
"cpunumber" : 1,
"cpuspeed" : 100,# in MHz
"memory" : 128},
#"storagetype" : "local"},
"sleep" : 60,
"ostype" : 'CentOS 5.3 (64-bit)',# CentOS 5.3 (64-bit)
}
class TestVMOwnership(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls._cleanup = []
cls.api_client = super(TestVMOwnership,
cls).getClsTestClient().getApiClient()
cls.services = Services().services
# Get Zone Domain and create Domains and sub Domains.
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.services['mode'] = cls.zone.networktype
# Get and set template id for VM creation.
cls.template = get_template(cls.api_client,
cls.zone.id,
cls.services["ostype"])
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
def create_domain_account_user(parentDomain=None):
domain = Domain.create(cls.api_client,
cls.services["domain"],
parentdomainid=parentDomain.id if parentDomain else None)
cls._cleanup.append(domain)
# Create an Account associated with domain
account = Account.create(cls.api_client,
cls.services["account"],
domainid=domain.id)
cls._cleanup.append(account)
# Create an User, Project, Volume associated with account
user = User.create(cls.api_client,
cls.services["user"],
account=account.name,
domainid=account.domainid)
cls._cleanup.append(user)
project = Project.create(cls.api_client,
cls.services["project"],
account=account.name,
domainid=account.domainid)
cls._cleanup.append(project)
volume = Volume.create(cls.api_client,
cls.services["volume"],
zoneid=cls.zone.id,
account=account.name,
domainid=account.domainid,
diskofferingid=cls.disk_offering.id)
cls._cleanup.append(volume)
return {'domain':domain, 'account':account, 'user':user, 'project':project, 'volume':volume}
# Create disk offerings.
try:
cls.disk_offering = DiskOffering.create(cls.api_client,
cls.services["disk_offering"])
# Create service offerings.
cls.service_offering = ServiceOffering.create(cls.api_client,
cls.services["service_offering"])
# Cleanup
cls._cleanup.append(cls.service_offering)
# Create domain, account, user, project and volumes.
cls.domain_account_user1 = create_domain_account_user()
cls.domain_account_user2 = create_domain_account_user()
cls.sdomain_account_user1 = create_domain_account_user(cls.domain_account_user1['domain'])
cls.sdomain_account_user2 = create_domain_account_user(cls.domain_account_user2['domain'])
cls.ssdomain_account_user2 = create_domain_account_user(cls.sdomain_account_user2['domain'])
except Exception as e:
raise e
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, reversed(cls._cleanup))
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.api_client#self.testClient.getApiClient()
#self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
self.snapshot = None
return
def create_vm(self,
account,
domain,
isRunning=False,
project =None,
limit =None,
pfrule =False,
lbrule =None,
natrule =None,
volume =None,
snapshot =False):
#TODO: Implemnt pfrule/lbrule/natrule
self.debug("Deploying instance in the account: %s" % account.name)
self.virtual_machine = VirtualMachine.create(self.apiclient,
self.services["virtual_machine"],
accountid=account.name,
domainid=domain.id,
serviceofferingid=self.service_offering.id,
mode=self.zone.networktype if pfrule else 'basic',
projectid=project.id if project else None)
self.debug("Deployed instance in account: %s" % account.name)
list_virtual_machines(self.apiclient,
id=self.virtual_machine.id)
if snapshot:
volumes = list_volumes(self.apiclient,
virtualmachineid=self.virtual_machine.id,
type='ROOT',
listall=True)
self.snapshot = Snapshot.create(self.apiclient,
volumes[0].id,
account=account.name,
domainid=account.domainid)
if volume:
self.virtual_machine.attach_volume(self.apiclient,
volume)
if not isRunning:
self.virtual_machine.stop(self.apiclient)
self.cleanup.append(self.virtual_machine)
def check_vm_is_moved_in_account_domainid(self, account):
list_vm_response = list_virtual_machines(self.api_client,
id=self.virtual_machine.id,
account=account.name,
domainid=account.domainid)
self.debug('VM=%s moved to account=%s and domainid=%s' % (list_vm_response, account.name, account.domainid))
self.assertNotEqual(len(list_vm_response), 0, 'Unable to move VM to account=%s domainid=%s' % (account.name, account.domainid))
def tearDown(self):
try:
self.debug("Cleaning up the resources")
cleanup_resources(self.apiclient, reversed(self.cleanup))
self.debug("Cleanup complete!")
except Exception as e:
self.debug("Warning! Exception in tearDown: %s" % e)
@attr(tags = ["advanced"])
@log_test_exceptions
def test_01_move_across_different_domains(self):
"""Test as root, stop a VM from domain1 and attempt to move it to account in domain2
"""
# Validate the following:
# 1. deploy VM in domain_1
# 2. stop VM in domain_1
# 3. assignVirtualMachine to domain_2
self.create_vm(self.domain_account_user1['account'], self.domain_account_user1['domain'])
self.virtual_machine.assign_virtual_machine(self.apiclient, self.domain_account_user2['account'].name ,self.domain_account_user2['domain'].id)
self.check_vm_is_moved_in_account_domainid(self.domain_account_user2['account'])
@attr(tags = ["advanced"])
@log_test_exceptions
def test_02_move_across_subdomains(self):
"""Test as root, stop a VM from subdomain1 and attempt to move it to subdomain2
"""
# Validate the following:
# 1. deploy VM in subdomain_1
# 2. stop VM in subdomain_1
# 3. assignVirtualMachine to subdomain_2
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'])
self.virtual_machine.assign_virtual_machine(self.apiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
self.check_vm_is_moved_in_account_domainid(self.sdomain_account_user2['account'])
@attr(tags = ["advanced"])
@log_test_exceptions
def test_03_move_from_domain_to_subdomain(self):
"""Test as root stop a VM from domain1 and attempt to move it to subdomain1
"""
# Validate the following:
# 1. deploy VM in domain_1
# 2. stop VM in domain_1
# 3. assignVirtualMachine to subdomain_1
self.create_vm(self.domain_account_user1['account'], self.domain_account_user1['domain'])
self.virtual_machine.assign_virtual_machine(self.apiclient, self.sdomain_account_user1['account'].name ,self.sdomain_account_user1['domain'].id)
self.check_vm_is_moved_in_account_domainid(self.sdomain_account_user1['account'])
@attr(tags = ["advanced"])
@log_test_exceptions
def test_04_move_from_domain_to_sub_of_subdomain(self):
"""Test as root, stop a VM from domain1 and attempt to move it to sub-subdomain1
"""
# Validate the following:
# 1. deploy VM in domain_2
# 2. stop VM in domain_2
# 3. assignVirtualMachine to sub subdomain_2
self.create_vm(self.domain_account_user2['account'], self.domain_account_user2['domain'])
self.virtual_machine.assign_virtual_machine(self.apiclient, self.ssdomain_account_user2['account'].name ,self.ssdomain_account_user2['domain'].id)
self.check_vm_is_moved_in_account_domainid(self.ssdomain_account_user2['account'])
@attr(tags = ["advanced"])
@log_test_exceptions
def test_05_move_to_domain_from_sub_of_subdomain(self):
"""Test as root, stop a VM from sub-subdomain1 and attempt to move it to domain1
"""
# Validate the following:
# 1. deploy VM in sub subdomain2
# 2. stop VM in sub subdomain2
# 3. assignVirtualMachine to sub domain2
self.create_vm(self.ssdomain_account_user2['account'], self.ssdomain_account_user2['domain'])
self.virtual_machine.assign_virtual_machine(self.apiclient, self.domain_account_user2['account'].name ,self.domain_account_user2['domain'].id)
self.check_vm_is_moved_in_account_domainid(self.domain_account_user2['account'])
@attr(tags = ["advanced"])
@log_test_exceptions
def test_06_move_to_domain_from_subdomain(self):
"""Test as root, stop a Vm from subdomain1 and attempt to move it to domain1
"""
# Validate the following:
# 1. deploy VM in sub subdomain1
# 2. stop VM in sub subdomain1
# 3. assignVirtualMachine to domain1
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'])
self.virtual_machine.assign_virtual_machine(self.apiclient, self.domain_account_user1['account'].name ,self.domain_account_user1['domain'].id)
self.check_vm_is_moved_in_account_domainid(self.domain_account_user1['account'])
@attr(tags = ["advanced"])
@log_test_exceptions
def test_07_move_across_subdomain(self):
"""Test as root, stop a VM from subdomain1 and attempt to move it to subdomain2
"""
# Validate the following:
# 1. deploy VM in sub subdomain1
# 2. stop VM in sub subdomain1
# 3. assignVirtualMachine to subdomain2
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'])
self.virtual_machine.assign_virtual_machine(self.apiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
self.check_vm_is_moved_in_account_domainid(self.sdomain_account_user2['account'])
@attr(tags = ["advanced"])
@log_test_exceptions
def test_08_move_across_subdomain_network_create(self):
"""Test as root, stop a VM from subdomain1 and attempt to move it to subdomain2, network should get craeted
"""
# Validate the following:
# 1. deploy VM in sub subdomain1
# 2. stop VM in sub subdomain1
# 3. assignVirtualMachine to subdomain2 network should get created
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'])
self.virtual_machine.assign_virtual_machine(self.apiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
self.check_vm_is_moved_in_account_domainid(self.sdomain_account_user2['account'])
networks = list_networks(self.apiclient,
account=self.sdomain_account_user2['account'].name,
domainid=self.sdomain_account_user2['domain'].id)
self.assertEqual(isinstance(networks, list),
True,
"Check for list networks response return valid data")
self.assertNotEqual(len(networks),
0,
"Check list networks response")
@attr(tags = ["advanced"])
@log_test_exceptions
def test_09_move_across_subdomain(self):
"""Test as domain admin, stop a VM from subdomain1 and attempt to move it to subdomain2
"""
# Validate the following:
# 1. deploy VM in sub subdomain1
# 2. stop VM in sub subdomain1
# 3. assignVirtualMachine to subdomain2
userapiclient = self.testClient.getUserApiClient(account=self.sdomain_account_user1['account'].name,
domain=self.sdomain_account_user1['domain'].name,
type=2)
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'])
self.assertRaises(Exception, self.virtual_machine.assign_virtual_machine, userapiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
@attr(tags = ["advanced"])
@log_test_exceptions
def test_10_move_across_subdomain_vm_running(self):
"""Test as domain admin, stop a VM from subdomain1 and attempt to move it to subdomain2
"""
# Validate the following:
# 1. deploy VM in sub subdomain1
# 3. assignVirtualMachine to subdomain2
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'],isRunning=True)
self.assertRaises(Exception, self.virtual_machine.assign_virtual_machine, self.apiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
@attr(tags = ["advanced"])
@log_test_exceptions
def test_11_move_across_subdomain_vm_pfrule(self):
"""Test as domain admin, stop a VM from subdomain1 and attempt to move it to subdomain2
"""
# Validate the following:
# 1. deploy VM in sub subdomain1 with PF rule set.
# 3. assignVirtualMachine to subdomain2
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'],pfrule=True)
self.assertRaises(Exception, self.virtual_machine.assign_virtual_machine, self.apiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
@attr(tags = ["advanced"])
@log_test_exceptions
def test_12_move_across_subdomain_vm_volumes(self):
"""Test as domain admin, stop a VM from subdomain1 and attempt to move it to subdomain2
"""
# Validate the following:
# 1. deploy VM in sub subdomain1 with volumes.
# 3. assignVirtualMachine to subdomain2
userapiclient = self.testClient.getUserApiClient(account=self.sdomain_account_user1['account'].name,
domain=self.sdomain_account_user1['domain'].name,
type=2)
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'],volume=self.sdomain_account_user1['volume'])
self.assertRaises(Exception, self.virtual_machine.assign_virtual_machine, userapiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
# Check all volumes attached to same VM
list_volume_response = list_volumes(self.apiclient,
virtualmachineid=self.virtual_machine.id,
type='DATADISK',
listall=True)
self.assertEqual(isinstance(list_volume_response, list),
True,
"Check list volumes response for valid list")
self.assertNotEqual(list_volume_response[0].domainid, self.sdomain_account_user2['domain'].id, "Volume ownership not changed.")
self.virtual_machine.detach_volume(self.apiclient,
self.sdomain_account_user1['volume'])
@attr(tags = ["advanced"])
@log_test_exceptions
def test_13_move_across_subdomain_vm_snapshot(self):
"""Test as domain admin, stop a VM from subdomain1 and attempt to move it to subdomain2
"""
# Validate the following:
# 1. deploy VM in sub subdomain1 with snapshot.
# 3. assignVirtualMachine to subdomain2
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'], snapshot=True)
self.virtual_machine.assign_virtual_machine(self.apiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
snapshots = list_snapshots(self.apiclient,
id=self.snapshot.id)
self.assertEqual(snapshots,
None,
"Snapshots stil present for a vm in domain")
@attr(tags = ["advanced"])
@log_test_exceptions
def test_14_move_across_subdomain_vm_project(self):
"""Test as domain admin, stop a VM from subdomain1 and attempt to move it to subdomain2
"""
# Validate the following:
# 1. deploy VM in sub subdomain1 with snapshot.
# 3. assignVirtualMachine to subdomain2
userapiclient = self.testClient.getUserApiClient(account=self.sdomain_account_user1['account'].name,
domain=self.sdomain_account_user1['domain'].name,
type=2)
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'], project=self.sdomain_account_user1['project'])
self.assertRaises(Exception, self.virtual_machine.assign_virtual_machine, userapiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
@attr(tags = ["advanced"])
@log_test_exceptions
def test_15_move_across_subdomain_account_limit(self):
"""Test as domain admin, stop a VM from subdomain1 and attempt to move it to subdomain2 when limit reached
"""
# Validate the following:
# 1. deploy VM in sub subdomain1 when account limit is reached.
# 3. assignVirtualMachine to subdomain2
update_resource_limit(self.apiclient,
0, # VM Instances
account=self.sdomain_account_user2['account'].name,
domainid=self.sdomain_account_user2['domain'].id,
max=0)
userapiclient = self.testClient.getUserApiClient(account=self.sdomain_account_user1['account'].name,
domain=self.sdomain_account_user1['domain'].name,
type=2)
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'], snapshot=True)
self.assertRaises(Exception, self.virtual_machine.assign_virtual_machine, userapiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
@attr(tags = ["advanced"])
@log_test_exceptions
def test_16_move_across_subdomain_volume_and_account_limit(self):
"""Test as domain admin, stop a VM from subdomain1 and attempt to move it to subdomain2 volumes are attached and limit reached
"""
# Validate the following:
# 1. deploy VM in sub subdomain1 when account limit is reached.
# 3. assignVirtualMachine to subdomain2
update_resource_limit(
self.apiclient,
0, # VM Instances
account=self.sdomain_account_user2['account'].name,
domainid=self.sdomain_account_user2['domain'].id,
max=0)
userapiclient = self.testClient.getUserApiClient(account=self.sdomain_account_user1['account'].name,
domain=self.sdomain_account_user1['domain'].name,
type=2)
self.create_vm(self.sdomain_account_user1['account'], self.sdomain_account_user1['domain'], snapshot=True, volume=self.sdomain_account_user1['volume'])
self.assertRaises(Exception, self.virtual_machine.assign_virtual_machine, userapiclient, self.sdomain_account_user2['account'].name ,self.sdomain_account_user2['domain'].id)
self.virtual_machine.detach_volume(self.apiclient,
self.sdomain_account_user1['volume'])
| [
"marvin.integration.lib.base.Snapshot.create",
"marvin.integration.lib.base.Domain.create",
"marvin.integration.lib.common.list_snapshots",
"marvin.integration.lib.base.ServiceOffering.create",
"marvin.integration.lib.base.VirtualMachine.create",
"marvin.integration.lib.common.update_resource_limit",
"m... | [((12308, 12331), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (12312, 12331), False, 'from nose.plugins.attrib import attr\n'), ((13009, 13032), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (13013, 13032), False, 'from nose.plugins.attrib import attr\n'), ((13712, 13735), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (13716, 13735), False, 'from nose.plugins.attrib import attr\n'), ((14410, 14433), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (14414, 14433), False, 'from nose.plugins.attrib import attr\n'), ((15127, 15150), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (15131, 15150), False, 'from nose.plugins.attrib import attr\n'), ((15850, 15873), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (15854, 15873), False, 'from nose.plugins.attrib import attr\n'), ((16556, 16579), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (16560, 16579), False, 'from nose.plugins.attrib import attr\n'), ((17263, 17286), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (17267, 17286), False, 'from nose.plugins.attrib import attr\n'), ((18554, 18577), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (18558, 18577), False, 'from nose.plugins.attrib import attr\n'), ((19489, 19512), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (19493, 19512), False, 'from nose.plugins.attrib import attr\n'), ((20131, 20154), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (20135, 20154), False, 'from nose.plugins.attrib import attr\n'), ((20787, 20810), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (20791, 20810), False, 'from nose.plugins.attrib import attr\n'), ((22510, 22533), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (22514, 22533), False, 'from nose.plugins.attrib import attr\n'), ((23382, 23405), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (23386, 23405), False, 'from nose.plugins.attrib import attr\n'), ((24351, 24374), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (24355, 24374), False, 'from nose.plugins.attrib import attr\n'), ((25619, 25642), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (25623, 25642), False, 'from nose.plugins.attrib import attr\n'), ((5671, 5711), 'marvin.integration.lib.common.get_domain', 'get_domain', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (5681, 5711), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((5743, 5781), 'marvin.integration.lib.common.get_zone', 'get_zone', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (5751, 5781), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((5908, 5973), 'marvin.integration.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (5920, 5973), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((9903, 10169), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'account.name', 'domainid': 'domain.id', 'serviceofferingid': 'self.service_offering.id', 'mode': "(self.zone.networktype if pfrule else 'basic')", 'projectid': '(project.id if project else None)'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=account.name, domainid=domain.id, serviceofferingid=self.\n service_offering.id, mode=self.zone.networktype if pfrule else 'basic',\n projectid=project.id if project else None)\n", (9924, 10169), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n'), ((10553, 10618), 'marvin.integration.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (10574, 10618), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((11485, 11605), 'marvin.integration.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.api_client'], {'id': 'self.virtual_machine.id', 'account': 'account.name', 'domainid': 'account.domainid'}), '(self.api_client, id=self.virtual_machine.id, account=\n account.name, domainid=account.domainid)\n', (11506, 11605), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((18053, 18189), 'marvin.integration.lib.common.list_networks', 'list_networks', (['self.apiclient'], {'account': "self.sdomain_account_user2['account'].name", 'domainid': "self.sdomain_account_user2['domain'].id"}), "(self.apiclient, account=self.sdomain_account_user2['account']\n .name, domainid=self.sdomain_account_user2['domain'].id)\n", (18066, 18189), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((21826, 21932), 'marvin.integration.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""DATADISK"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='DATADISK', listall=True)\n", (21838, 21932), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((23152, 23203), 'marvin.integration.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'id': 'self.snapshot.id'}), '(self.apiclient, id=self.snapshot.id)\n', (23166, 23203), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((24750, 24904), 'marvin.integration.lib.common.update_resource_limit', 'update_resource_limit', (['self.apiclient', '(0)'], {'account': "self.sdomain_account_user2['account'].name", 'domainid': "self.sdomain_account_user2['domain'].id", 'max': '(0)'}), "(self.apiclient, 0, account=self.sdomain_account_user2\n ['account'].name, domainid=self.sdomain_account_user2['domain'].id, max=0)\n", (24771, 24904), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((26049, 26203), 'marvin.integration.lib.common.update_resource_limit', 'update_resource_limit', (['self.apiclient', '(0)'], {'account': "self.sdomain_account_user2['account'].name", 'domainid': "self.sdomain_account_user2['domain'].id", 'max': '(0)'}), "(self.apiclient, 0, account=self.sdomain_account_user2\n ['account'].name, domainid=self.sdomain_account_user2['domain'].id, max=0)\n", (26070, 26203), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((6263, 6379), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['cls.api_client', "cls.services['domain']"], {'parentdomainid': '(parentDomain.id if parentDomain else None)'}), "(cls.api_client, cls.services['domain'], parentdomainid=\n parentDomain.id if parentDomain else None)\n", (6276, 6379), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n'), ((6566, 6641), 'marvin.integration.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'domainid': 'domain.id'}), "(cls.api_client, cls.services['account'], domainid=domain.id)\n", (6580, 6641), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n'), ((6849, 6951), 'marvin.integration.lib.base.User.create', 'User.create', (['cls.api_client', "cls.services['user']"], {'account': 'account.name', 'domainid': 'account.domainid'}), "(cls.api_client, cls.services['user'], account=account.name,\n domainid=account.domainid)\n", (6860, 6951), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n'), ((7110, 7219), 'marvin.integration.lib.base.Project.create', 'Project.create', (['cls.api_client', "cls.services['project']"], {'account': 'account.name', 'domainid': 'account.domainid'}), "(cls.api_client, cls.services['project'], account=account.\n name, domainid=account.domainid)\n", (7124, 7219), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n'), ((7389, 7557), 'marvin.integration.lib.base.Volume.create', 'Volume.create', (['cls.api_client', "cls.services['volume']"], {'zoneid': 'cls.zone.id', 'account': 'account.name', 'domainid': 'account.domainid', 'diskofferingid': 'cls.disk_offering.id'}), "(cls.api_client, cls.services['volume'], zoneid=cls.zone.id,\n account=account.name, domainid=account.domainid, diskofferingid=cls.\n disk_offering.id)\n", (7402, 7557), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n'), ((7953, 8019), 'marvin.integration.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.api_client', "cls.services['disk_offering']"], {}), "(cls.api_client, cls.services['disk_offering'])\n", (7972, 8019), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n'), ((8147, 8219), 'marvin.integration.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (8169, 8219), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n'), ((10691, 10793), 'marvin.integration.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='ROOT', listall=True)\n", (10703, 10793), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, list_volumes, update_resource_limit, list_networks, list_snapshots, list_virtual_machines\n'), ((10918, 11017), 'marvin.integration.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'volumes[0].id'], {'account': 'account.name', 'domainid': 'account.domainid'}), '(self.apiclient, volumes[0].id, account=account.name,\n domainid=account.domainid)\n', (10933, 11017), False, 'from marvin.integration.lib.base import Account, Domain, User, Project, Volume, Snapshot, DiskOffering, ServiceOffering, VirtualMachine\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for cpu resource limits related to projects
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.lib.base import (
Account,
ServiceOffering,
VirtualMachine,
Domain,
Project
)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
findSuitableHostForMigration,
get_resource_type
)
from marvin.lib.utils import cleanup_resources
from marvin.codes import ERROR_NO_HOST_FOR_MIGRATION
class TestProjectsCPULimits(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestProjectsCPULimits, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.testdata = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.testdata["mode"] = cls.zone.networktype
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testdata["ostype"]
)
cls.testdata["virtual_machine"]["zoneid"] = cls.zone.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testdata["service_offering_multiple_cores"]
)
cls._cleanup = [cls.service_offering, ]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.account = Account.create(
self.apiclient,
self.testdata["account"],
admin=True
)
self.cleanup = [self.account, ]
self.debug("Setting up account and domain hierarchy")
self.setupProjectAccounts()
api_client = self.testClient.getUserApiClient(
UserName=self.admin.name,
DomainName=self.admin.domain)
self.debug("Creating an instance with service offering: %s" %
self.service_offering.name)
self.vm = self.createInstance(project=self.project,
service_off=self.service_offering, api_client=api_client)
return
def tearDown(self):
try:
# Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.apiclient, self.cleanup)
pass
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def createInstance(self, project, service_off, networks=None, api_client=None):
"""Creates an instance in account"""
if api_client is None:
api_client = self.api_client
try:
self.vm = VirtualMachine.create(
api_client,
self.testdata["virtual_machine"],
templateid=self.template.id,
projectid=project.id,
networkids=networks,
serviceofferingid=service_off.id)
vms = VirtualMachine.list(api_client, projectid=project.id,
id=self.vm.id, listall=True)
self.assertIsInstance(vms,
list,
"List VMs should return a valid response")
self.assertEqual(vms[0].state, "Running",
"Vm state should be running after deployment")
return self.vm
except Exception as e:
self.fail("Failed to deploy an instance: %s" % e)
def setupProjectAccounts(self):
self.debug("Creating a domain under: %s" % self.domain.name)
self.domain = Domain.create(self.apiclient,
services=self.testdata["domain"],
parentdomainid=self.domain.id)
self.admin = Account.create(
self.apiclient,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
# Create project as a domain admin
self.project = Project.create(self.apiclient,
self.testdata["project"],
account=self.admin.name,
domainid=self.admin.domainid)
# Cleanup created project at end of test
self.cleanup.append(self.project)
self.cleanup.append(self.admin)
self.cleanup.append(self.domain)
self.debug("Created project with domain admin with name: %s" %
self.project.name)
projects = Project.list(self.apiclient, id=self.project.id,
listall=True)
self.assertEqual(isinstance(projects, list), True,
"Check for a valid list projects response")
project = projects[0]
self.assertEqual(project.name, self.project.name,
"Check project name from list response")
return
@attr(tags=["advanced", "advancedns","simulator"], required_hardware="false")
def test_01_project_counts_start_stop_instance(self):
# Validate the following
# 1. Assign account to projects and verify the resource updates
# 2. Deploy VM with the accounts added to the project
# 3. Stop VM of an accounts added to the project.
# 4. Resource count should list properly.
project_list = Project.list(self.apiclient, id=self.project.id, listall=True)
self.debug(project_list)
self.assertIsInstance(project_list,
list,
"List Projects should return a valid response"
)
resource_count = project_list[0].cputotal
expected_resource_count = int(self.service_offering.cpunumber)
self.assertEqual(resource_count, expected_resource_count,
"Resource count should match with the expected resource count")
self.debug("Stopping instance: %s" % self.vm.name)
try:
self.vm.stop(self.apiclient)
except Exception as e:
self.fail("Failed to stop instance: %s" % e)
project_list = Project.list(self.apiclient, id=self.project.id, listall=True)
self.assertIsInstance(project_list,
list,
"List Projects should return a valid response"
)
resource_count_after_stop = project_list[0].cputotal
self.assertEqual(resource_count, resource_count_after_stop,
"Resource count should be same after stopping the instance")
self.debug("Starting instance: %s" % self.vm.name)
try:
self.vm.start(self.apiclient)
except Exception as e:
self.fail("Failed to start instance: %s" % e)
project_list = Project.list(self.apiclient, id=self.project.id, listall=True)
self.assertIsInstance(project_list,
list,
"List Projects should return a valid response"
)
resource_count_after_start = project_list[0].cputotal
self.assertEqual(resource_count, resource_count_after_start,
"Resource count should be same after starting the instance")
return
@attr(tags=["advanced", "advancedns","simulator"], required_hardware="true")
def test_02_project_counts_migrate_instance(self):
# Validate the following
# 1. Assign account to projects and verify the resource updates
# 2. Deploy VM with the accounts added to the project
# 3. Migrate VM of an accounts added to the project to a new host
# 4. Resource count should list properly.
self.hypervisor = self.testClient.getHypervisorInfo()
if self.hypervisor.lower() in ['lxc']:
self.skipTest("vm migrate feature is not supported on %s" % self.hypervisor.lower())
project_list = Project.list(self.apiclient, id=self.project.id, listall=True)
self.assertIsInstance(project_list,
list,
"List Projects should return a valid response"
)
resource_count = project_list[0].cputotal
expected_resource_count = int(self.service_offering.cpunumber)
self.assertEqual(resource_count, expected_resource_count,
"Resource count should match with the expected resource count")
host = findSuitableHostForMigration(self.apiclient, self.vm.id)
if host is None:
self.skipTest(ERROR_NO_HOST_FOR_MIGRATION)
self.debug("Migrating instance: %s to host: %s" %
(self.vm.name, host.name))
try:
self.vm.migrate(self.apiclient, host.id)
except Exception as e:
self.fail("Failed to migrate instance: %s" % e)
project_list = Project.list(self.apiclient, id=self.project.id, listall=True)
self.assertIsInstance(project_list,
list,
"List Projects should return a valid response"
)
resource_count_after_migrate = project_list[0].cputotal
self.assertEqual(resource_count, resource_count_after_migrate,
"Resource count should be same after migrating the instance")
return
@attr(tags=["advanced", "advancedns","simulator"], required_hardware="false")
def test_03_project_counts_delete_instance(self):
# Validate the following
# 1. Assign account to projects and verify the resource updates
# 2. Deploy VM with the accounts added to the project
# 3. Destroy VM of an accounts added to the project to a new host
# 4. Resource count should list properly.
project_list = Project.list(self.apiclient, id=self.project.id, listall=True)
self.assertIsInstance(project_list,
list,
"List Projects should return a valid response"
)
resource_count = project_list[0].cputotal
expected_resource_count = int(self.service_offering.cpunumber)
self.assertEqual(resource_count, expected_resource_count,
"Resource count should match with the expected resource count")
self.debug("Destroying instance: %s" % self.vm.name)
try:
self.vm.delete(self.apiclient)
except Exception as e:
self.fail("Failed to delete instance: %s" % e)
project_list = Project.list(self.apiclient, id=self.project.id, listall=True)
self.assertIsInstance(project_list,
list,
"List Projects should return a valid response"
)
resource_count_after_delete = project_list[0].cputotal
self.assertEqual(resource_count_after_delete, 0 , "Resource count for %s should be 0" % get_resource_type(resource_id=8))#CPU
return
| [
"marvin.lib.base.Project.create",
"marvin.lib.common.findSuitableHostForMigration",
"marvin.lib.base.Domain.create",
"marvin.lib.base.Project.list",
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.VirtualMachine.create",
"marv... | [((6904, 6981), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'simulator']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'simulator'], required_hardware='false')\n", (6908, 6981), False, 'from nose.plugins.attrib import attr\n'), ((9315, 9391), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'simulator']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'simulator'], required_hardware='true')\n", (9319, 9391), False, 'from nose.plugins.attrib import attr\n'), ((11465, 11542), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'simulator']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'simulator'], required_hardware='false')\n", (11469, 11542), False, 'from nose.plugins.attrib import attr\n'), ((2071, 2097), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2081, 2097), False, 'from marvin.lib.common import get_domain, get_zone, get_template, findSuitableHostForMigration, get_resource_type\n'), ((2251, 2316), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.testdata['ostype'])\n", (2263, 2316), False, 'from marvin.lib.common import get_domain, get_zone, get_template, findSuitableHostForMigration, get_resource_type\n'), ((2528, 2620), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.testdata['service_offering_multiple_cores']"], {}), "(cls.api_client, cls.testdata[\n 'service_offering_multiple_cores'])\n", (2550, 2620), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((3249, 3317), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testdata['account']"], {'admin': '(True)'}), "(self.apiclient, self.testdata['account'], admin=True)\n", (3263, 3317), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((5459, 5557), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.apiclient'], {'services': "self.testdata['domain']", 'parentdomainid': 'self.domain.id'}), "(self.apiclient, services=self.testdata['domain'],\n parentdomainid=self.domain.id)\n", (5472, 5557), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((5655, 5752), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (5669, 5752), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((5958, 6074), 'marvin.lib.base.Project.create', 'Project.create', (['self.apiclient', "self.testdata['project']"], {'account': 'self.admin.name', 'domainid': 'self.admin.domainid'}), "(self.apiclient, self.testdata['project'], account=self.admin\n .name, domainid=self.admin.domainid)\n", (5972, 6074), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((6507, 6569), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (6519, 6569), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((7339, 7401), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (7351, 7401), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((8128, 8190), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (8140, 8190), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((8824, 8886), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (8836, 8886), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((9968, 10030), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (9980, 10030), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((10514, 10570), 'marvin.lib.common.findSuitableHostForMigration', 'findSuitableHostForMigration', (['self.apiclient', 'self.vm.id'], {}), '(self.apiclient, self.vm.id)\n', (10542, 10570), False, 'from marvin.lib.common import get_domain, get_zone, get_template, findSuitableHostForMigration, get_resource_type\n'), ((10969, 11031), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (10981, 11031), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((11912, 11974), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (11924, 11974), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((12674, 12736), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (12686, 12736), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((2922, 2969), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (2939, 2969), False, 'from marvin.lib.utils import cleanup_resources\n'), ((4100, 4147), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (4117, 4147), False, 'from marvin.lib.utils import cleanup_resources\n'), ((4524, 4705), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['api_client', "self.testdata['virtual_machine']"], {'templateid': 'self.template.id', 'projectid': 'project.id', 'networkids': 'networks', 'serviceofferingid': 'service_off.id'}), "(api_client, self.testdata['virtual_machine'],\n templateid=self.template.id, projectid=project.id, networkids=networks,\n serviceofferingid=service_off.id)\n", (4545, 4705), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((4861, 4947), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['api_client'], {'projectid': 'project.id', 'id': 'self.vm.id', 'listall': '(True)'}), '(api_client, projectid=project.id, id=self.vm.id,\n listall=True)\n', (4880, 4947), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Domain, Project\n'), ((13085, 13117), 'marvin.lib.common.get_resource_type', 'get_resource_type', ([], {'resource_id': '(8)'}), '(resource_id=8)\n', (13102, 13117), False, 'from marvin.lib.common import get_domain, get_zone, get_template, findSuitableHostForMigration, get_resource_type\n')] |
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2017-09-13 16:05:56
# @Last modified by: <NAME> (<EMAIL>)
# @Last modified time: 2018-08-06 11:45:33
from __future__ import absolute_import, division, print_function
import copy
from astropy import units as u
from marvin.utils.datamodel.maskbit import get_maskbits
from .base import Bintype, Channel, DAPDataModel, Model, MultiChannelProperty, Property
from .base import spaxel as spaxel_unit
from .MPL5 import ALL, GAU_MILESHC, NRE, SPX, VOR10
HYB10 = Bintype('HYB10', description='Binning and stellar continuum fitting as VOR10, '
'but emission lines are fitted per spaxel.')
# The two lines in the OII doublet is fitted independently for gaussian
# measurements. In that case oii_3727 and oii_3729 are populated. For summed
# flux measurements, the lines cannot be separated so oiid_3728 contains
# the summed flux. In that case, oii_3729 is null and only kept to maintain`
# the number of channels constant.
oiid_channel = Channel('oiid_3728', formats={'string': 'OIId 3728',
'latex': r'$\forb{O\,IId}\;\lambda\lambda 3728$'}, idx=0)
oii_channel = Channel('oii_3727', formats={'string': 'OII 3727',
'latex': r'$\forb{O\,II}\;\lambda 3727$'}, idx=0)
MPL6_emline_channels = [
Channel('oii_3729', formats={'string': 'OII 3729',
'latex': r'$\forb{O\,II}\;\lambda 3729$'}, idx=1),
Channel('hthe_3798', formats={'string': 'H-theta 3798',
'latex': r'H$\theta\;\lambda 3798$'}, idx=2),
Channel('heta_3836', formats={'string': 'H-eta 3836',
'latex': r'H$\eta\;\lambda 3836$'}, idx=3),
Channel('neiii_3869', formats={'string': 'NeIII 3869',
'latex': r'$\forb{Ne\,III}\;\lambda 3869$'}, idx=4),
Channel('hzet_3890', formats={'string': 'H-zeta 3890',
'latex': r'H$\zeta\;\lambda 3890$'}, idx=5),
Channel('neiii_3968', formats={'string': 'NeIII 3968',
'latex': r'$\forb{Ne\,III}\;\lambda 3968$'}, idx=6),
Channel('heps_3971', formats={'string': 'H-epsilon 3971',
'latex': r'H$\epsilon\;\lambda 3971$'}, idx=7),
Channel('hdel_4102', formats={'string': 'H-delta 4102',
'latex': r'H$\delta\;\lambda 4102$'}, idx=8),
Channel('hgam_4341', formats={'string': 'H-gamma 4341',
'latex': r'H$\gamma\;\lambda 4341$'}, idx=9),
Channel('heii_4687', formats={'string': 'HeII 4681',
'latex': r'He\,II$\;\lambda 4687$'}, idx=10),
Channel('hb_4862', formats={'string': 'H-beta 4862',
'latex': r'H$\beta\;\lambda 4862$'}, idx=11),
Channel('oiii_4960', formats={'string': 'OIII 4960',
'latex': r'$\forb{O\,III}\;\lambda 4960$'}, idx=12),
Channel('oiii_5008', formats={'string': 'OIII 5008',
'latex': r'$\forb{O\,III}\;\lambda 5008$'}, idx=13),
Channel('hei_5877', formats={'string': 'HeI 5877',
'latex': r'He\,I$\;\lambda 5877$'}, idx=14),
Channel('oi_6302', formats={'string': 'OI 6302',
'latex': r'$\forb{O\,I}\;\lambda 6302$'}, idx=15),
Channel('oi_6365', formats={'string': 'OI 6365',
'latex': r'$\forb{O\,I}\;\lambda 6365$'}, idx=16),
Channel('nii_6549', formats={'string': 'NII 6549',
'latex': r'$\forb{N\,II}\;\lambda 6549$'}, idx=17),
Channel('ha_6564', formats={'string': 'H-alpha 6564',
'latex': r'H$\alpha\;\lambda 6564$'}, idx=18),
Channel('nii_6585', formats={'string': 'NII 6585',
'latex': r'$\forb{N\,II}\;\lambda 6585$'}, idx=19),
Channel('sii_6718', formats={'string': 'SII 6718',
'latex': r'$\forb{S\,II}\;\lambda 6718$'}, idx=20),
Channel('sii_6732', formats={'string': 'SII 6732',
'latex': r'$\forb{S\,II}\;\lambda 6732$'}, idx=21)
]
MPL6_specindex_channels = [
Channel('cn1', formats={'string': 'CN1'}, unit=u.mag, idx=0),
Channel('cn2', formats={'string': 'CN2'}, unit=u.mag, idx=1),
Channel('ca4227', formats={'string': 'Ca 4227',
'latex': r'Ca\,\lambda 4227'}, unit=u.Angstrom, idx=2),
Channel('g4300', formats={'string': 'G4300',
'latex': r'G\,\lambda 4300'}, unit=u.Angstrom, idx=3),
Channel('fe4383', formats={'string': 'Fe 4383',
'latex': r'Fe\,\lambda 4383'}, unit=u.Angstrom, idx=4),
Channel('ca4455', formats={'string': 'Ca 4455',
'latex': r'Ca\,\lambda 4455'}, unit=u.Angstrom, idx=5),
Channel('fe4531', formats={'string': 'Fe 4531',
'latex': r'Fe\,\lambda 4531'}, unit=u.Angstrom, idx=6),
Channel('c24668', formats={'string': 'C24668',
'latex': r'C2\,\lambda 4668'}, unit=u.Angstrom, idx=7),
Channel('hb', formats={'string': 'Hb',
'latex': r'H\beta'}, unit=u.Angstrom, idx=8),
Channel('fe5015', formats={'string': 'Fe 5015',
'latex': r'Fe\,\lambda 5015'}, unit=u.Angstrom, idx=9),
Channel('mg1', formats={'string': 'Mg1'}, unit=u.mag, idx=10),
Channel('mg2', formats={'string': 'Mg2'}, unit=u.mag, idx=11),
Channel('mgb', formats={'string': 'Mgb'}, unit=u.Angstrom, idx=12),
Channel('fe5270', formats={'string': 'Fe 5270',
'latex': r'Fe\,\lambda 5270'}, unit=u.Angstrom, idx=13),
Channel('fe5335', formats={'string': 'Fe 5335',
'latex': r'Fe\,\lambda 5335'}, unit=u.Angstrom, idx=14),
Channel('fe5406', formats={'string': 'Fe 5406',
'latex': r'Fe\,\lambda 5406'}, unit=u.Angstrom, idx=15),
Channel('fe5709', formats={'string': 'Fe 5709',
'latex': r'Fe\,\lambda 5709'}, unit=u.Angstrom, idx=16),
Channel('fe5782', formats={'string': 'Fe 5782',
'latex': r'Fe\,\lambda 5782'}, unit=u.Angstrom, idx=17),
Channel('nad', formats={'string': 'NaD'}, unit=u.Angstrom, idx=18),
Channel('tio1', formats={'string': 'TiO1'}, unit=u.mag, idx=19),
Channel('tio2', formats={'string': 'TiO2'}, unit=u.mag, idx=20),
Channel('hdeltaa', formats={'string': 'HDeltaA',
'latex': r'H\delta\,A'}, unit=u.Angstrom, idx=21),
Channel('hgammaa', formats={'string': 'HGammaA',
'latex': r'H\gamma\,F'}, unit=u.Angstrom, idx=22),
Channel('hdeltaf', formats={'string': 'HDeltaA',
'latex': r'H\delta\,F'}, unit=u.Angstrom, idx=23),
Channel('hgammaf', formats={'string': 'HGammaF',
'latex': r'H\gamma\,F'}, unit=u.Angstrom, idx=24),
Channel('cahk', formats={'string': 'CaHK'}, unit=u.Angstrom, idx=25),
Channel('caii1', formats={'string': 'CaII1'}, unit=u.Angstrom, idx=26),
Channel('caii2', formats={'string': 'CaII2'}, unit=u.Angstrom, idx=27),
Channel('caii3', formats={'string': 'CaII3'}, unit=u.Angstrom, idx=28),
Channel('pa17', formats={'string': 'Pa17'}, unit=u.Angstrom, idx=29),
Channel('pa14', formats={'string': 'Pa14'}, unit=u.Angstrom, idx=30),
Channel('pa12', formats={'string': 'Pa12'}, unit=u.Angstrom, idx=31),
Channel('mgicvd', formats={'string': 'MgICvD'}, unit=u.Angstrom, idx=32),
Channel('naicvd', formats={'string': 'NaICvD'}, unit=u.Angstrom, idx=33),
Channel('mgiir', formats={'string': 'MgIIR'}, unit=u.Angstrom, idx=34),
Channel('fehcvd', formats={'string': 'FeHCvD'}, unit=u.Angstrom, idx=35),
Channel('nai', formats={'string': 'NaI'}, unit=u.Angstrom, idx=36),
Channel('btio', formats={'string': 'bTiO'}, unit=u.mag, idx=37),
Channel('atio', formats={'string': 'aTiO'}, unit=u.mag, idx=38),
Channel('cah1', formats={'string': 'CaH1'}, unit=u.mag, idx=39),
Channel('cah2', formats={'string': 'CaH2'}, unit=u.mag, idx=40),
Channel('naisdss', formats={'string': 'NaISDSS'}, unit=u.Angstrom, idx=41),
Channel('tio2sdss', formats={'string': 'TiO2SDSS'}, unit=u.Angstrom, idx=42),
Channel('d4000', formats={'string': 'D4000'}, unit=u.dimensionless_unscaled, idx=43),
Channel('dn4000', formats={'string': 'Dn4000'}, unit=u.dimensionless_unscaled, idx=44),
Channel('tiocvd', formats={'string': 'TiOCvD'}, unit=u.dimensionless_unscaled, idx=45)
]
MPL6_binid_channels = [
Channel('binned_spectra', formats={'string': 'Binned spectra'},
unit=u.dimensionless_unscaled, idx=0),
Channel('stellar_continua', formats={'string': 'Stellar continua'},
unit=u.dimensionless_unscaled, idx=1),
Channel('em_line_moments', formats={'string': 'Emission line moments'},
unit=u.dimensionless_unscaled, idx=2),
Channel('em_line_models', formats={'string': 'Emission line models'},
unit=u.dimensionless_unscaled, idx=3),
Channel('spectral_indices', formats={'string': 'Spectral indices'},
unit=u.dimensionless_unscaled, idx=4)]
binid_properties = MultiChannelProperty('binid', ivar=False, mask=False,
channels=MPL6_binid_channels,
description='Numerical ID for spatial bins.')
MPL6_maps = [
MultiChannelProperty('spx_skycoo', ivar=False, mask=False,
channels=[Channel('on_sky_x', formats={'string': 'On-sky X'}, idx=0),
Channel('on_sky_y', formats={'string': 'On-sky Y'}, idx=1)],
unit=u.arcsec,
formats={'string': 'Sky coordinates'},
description='Offsets of each spaxel from the galaxy center.'),
MultiChannelProperty('spx_ellcoo', ivar=False, mask=False,
channels=[Channel('elliptical_radius',
formats={'string': 'Elliptical radius'},
idx=0, unit=u.arcsec),
Channel('r_re',
formats={'string': 'R/Reff'},
idx=1),
Channel('elliptical_azimuth',
formats={'string': 'Elliptical azimuth'},
idx=2, unit=u.deg)],
formats={'string': 'Elliptical coordinates'},
description='Elliptical polar coordinates of each spaxel from '
'the galaxy center.'),
Property('spx_mflux', ivar=True, mask=False,
unit=u.erg / u.s / (u.cm ** 2) / spaxel_unit, scale=1e-17,
formats={'string': 'r-band mean flux'},
description='Mean flux in r-band (5600.1-6750.0 ang).'),
Property('spx_snr', ivar=False, mask=False,
formats={'string': 'r-band SNR'},
description='r-band signal-to-noise ratio per pixel.'),
binid_properties,
MultiChannelProperty('bin_lwskycoo', ivar=False, mask=False,
channels=[Channel('lum_weighted_on_sky_x',
formats={'string': 'Light-weighted offset X'},
idx=0, unit=u.arcsec),
Channel('lum_weighted_on_sky_y',
formats={'string': 'Light-weighted offset Y'},
idx=1, unit=u.arcsec)],
description='Light-weighted offset of each bin from the galaxy center.'),
MultiChannelProperty('bin_lwellcoo', ivar=False, mask=False,
channels=[Channel('lum_weighted_elliptical_radius',
formats={'string': 'Light-weighted radial offset'},
idx=0, unit=u.arcsec),
Channel('r_re',
formats={'string': 'R/REff'},
idx=1),
Channel('lum_weighted_elliptical_azimuth',
formats={'string': 'Light-weighted azimuthal offset'},
idx=2, unit=u.deg)],
description='Light-weighted elliptical polar coordinates of each bin '
'from the galaxy center.'),
Property('bin_area', ivar=False, mask=False,
unit=u.arcsec ** 2,
formats={'string': 'Bin area'},
description='Area of each bin.'),
Property('bin_farea', ivar=False, mask=False,
formats={'string': 'Bin fractional area'},
description='Fractional area that the bin covers for the expected bin '
'shape (only relevant for radial binning).'),
Property('bin_mflux', ivar=True, mask=True,
unit=u.erg / u.s / (u.cm ** 2) / spaxel_unit, scale=1e-17,
formats={'string': 'r-band binned spectra mean flux'},
description='Mean flux in the r-band for the binned spectra.'),
Property('bin_snr', ivar=False, mask=False,
formats={'string': 'Bin SNR'},
description='r-band signal-to-noise ratio per pixel in the binned spectra.'),
Property('stellar_vel', ivar=True, mask=True,
unit=u.km / u.s,
formats={'string': 'Stellar velocity'},
description='Stellar velocity relative to NSA redshift.'),
Property('stellar_sigma', ivar=True, mask=True,
unit=u.km / u.s,
formats={'string': 'Stellar velocity dispersion', 'latex': r'Stellar $\sigma$'},
description='Stellar velocity dispersion (must be corrected using '
'STELLAR_SIGMACORR)'),
Property('stellar_sigmacorr', ivar=False, mask=False,
unit=u.km / u.s,
formats={'string': 'Stellar sigma correction',
'latex': r'Stellar $\sigma$ correction'},
description='Quadrature correction for STELLAR_SIGMA to obtain the '
'astrophysical velocity dispersion.)'),
MultiChannelProperty('stellar_cont_fresid', ivar=False, mask=False,
channels=[Channel('68th_percentile',
formats={'string': '68th percentile',
'latex': r'68^{th} percentile'}, idx=0),
Channel('99th_percentile',
formats={'string': '99th percentile',
'latex': r'99^{th} percentile'}, idx=1)],
formats={'string': 'Fractional residual growth'},
description='68%% and 99%% growth of the fractional residuals between '
'the model and data.'),
Property('stellar_cont_rchi2', ivar=False, mask=False,
formats={'string': 'Stellar continuum reduced chi-square',
'latex': r'Stellar\ continuum\ reduced\ \chi^2'},
description='Reduced chi-square of the stellar continuum fit.'),
MultiChannelProperty('emline_sflux', ivar=True, mask=True,
channels=[oiid_channel] + MPL6_emline_channels,
formats={'string': 'Emission line summed flux'},
unit=u.erg / u.s / (u.cm ** 2) / spaxel_unit, scale=1e-17,
binid=binid_properties[3],
description='Non-parametric summed flux for emission lines.'),
MultiChannelProperty('emline_sew', ivar=True, mask=True,
channels=[oiid_channel] + MPL6_emline_channels,
formats={'string': 'Emission line EW'},
unit=u.Angstrom,
binid=binid_properties[3],
description='Emission line non-parametric equivalent '
'widths measurements.'),
MultiChannelProperty('emline_gflux', ivar=True, mask=True,
channels=[oii_channel] + MPL6_emline_channels,
formats={'string': 'Emission line Gaussian flux'},
unit=u.erg / u.s / (u.cm ** 2) / spaxel_unit, scale=1e-17,
binid=binid_properties[3],
description='Gaussian profile integrated flux for emission lines.'),
MultiChannelProperty('emline_gvel', ivar=True, mask=True,
channels=[oii_channel] + MPL6_emline_channels,
formats={'string': 'Emission line Gaussian velocity'},
unit=u.km / u.s,
binid=binid_properties[3],
description='Gaussian profile velocity for emission lines.'),
MultiChannelProperty('emline_gew', ivar=True, mask=True,
channels=[oii_channel] + MPL6_emline_channels,
formats={'string': 'Emission line Gaussian EW'},
unit=u.Angstrom,
binid=binid_properties[3],
description='Gaussian-fitted equivalent widths measurements '
'(based on EMLINE_GFLUX).'),
MultiChannelProperty('emline_gsigma', ivar=True, mask=True,
channels=[oii_channel] + MPL6_emline_channels,
formats={'string': 'Emission line Gaussian sigma',
'latex': r'Emission line Gaussian $\sigma$'},
unit=u.km / u.s,
binid=binid_properties[3],
description='Gaussian profile velocity dispersion for emission lines; '
'must be corrected using EMLINE_INSTSIGMA.'),
MultiChannelProperty('emline_instsigma', ivar=False, mask=False,
channels=[oii_channel] + MPL6_emline_channels,
formats={'string': 'Emission line instrumental sigma',
'latex': r'Emission line instrumental $\sigma$'},
unit=u.km / u.s,
binid=binid_properties[3],
description='Instrumental dispersion at the fitted line center.'),
MultiChannelProperty('emline_tplsigma', ivar=False, mask=False,
channels=[oii_channel] + MPL6_emline_channels,
formats={'string': 'Emission line template instrumental sigma',
'latex': r'Emission line template instrumental $\sigma$'},
unit=u.km / u.s,
binid=binid_properties[3],
description='The dispersion of each emission line used in '
'the template spectra'),
MultiChannelProperty('specindex', ivar=True, mask=True,
channels=MPL6_specindex_channels,
formats={'string': 'Spectral index'},
description='Measurements of spectral indices.'),
MultiChannelProperty('specindex_corr', ivar=False, mask=False,
channels=MPL6_specindex_channels,
formats={'string': 'Spectral index sigma correction',
'latex': r'Spectral index $\sigma$ correction'},
description='Velocity dispersion corrections for the '
'spectral index measurements '
'(can be ignored for D4000, Dn4000).')
]
MPL6_models = [
Model('binned_flux', 'FLUX', 'WAVE', extension_ivar='IVAR',
extension_mask='MASK', unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
scale=1e-17, formats={'string': 'Binned flux'},
description='Flux of the binned spectra',
binid=binid_properties[0]),
Model('full_fit', 'MODEL', 'WAVE', extension_ivar=None,
extension_mask='MASK', unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
scale=1e-17, formats={'string': 'Best fitting model'},
description='The best fitting model spectra (sum of the fitted '
'continuum and emission-line models)',
binid=binid_properties[0]),
Model('emline_fit', 'EMLINE', 'WAVE', extension_ivar=None,
extension_mask='EMLINE_MASK',
unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
scale=1e-17, formats={'string': 'Emission line model spectrum'},
description='The model spectrum with only the emission lines.',
binid=binid_properties[3]),
Model('emline_base_fit', 'EMLINE_BASE', 'WAVE', extension_ivar=None,
extension_mask='EMLINE_MASK',
unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
scale=1e-17, formats={'string': 'Emission line baseline fit'},
description='The model of the constant baseline fitted beneath the '
'emission lines.',
binid=binid_properties[3])
]
# MPL-6 DapDataModel goes here
MPL6 = DAPDataModel('2.1.3', aliases=['MPL-6', 'MPL6'],
bintypes=[SPX, HYB10, VOR10, ALL, NRE],
db_only=[SPX, HYB10],
templates=[GAU_MILESHC],
properties=MPL6_maps,
models=MPL6_models,
bitmasks=get_maskbits('MPL-6'),
default_bintype='SPX',
default_template='GAU-MILESHC',
property_table='SpaxelProp6',
default_binid=copy.deepcopy(binid_properties[0]),
default_mapmask=['NOCOV', 'UNRELIABLE', 'DONOTUSE'],
qual_flag='DAPQUAL')
| [
"marvin.utils.datamodel.maskbit.get_maskbits"
] | [((22185, 22206), 'marvin.utils.datamodel.maskbit.get_maskbits', 'get_maskbits', (['"""MPL-6"""'], {}), "('MPL-6')\n", (22197, 22206), False, 'from marvin.utils.datamodel.maskbit import get_maskbits\n'), ((22387, 22421), 'copy.deepcopy', 'copy.deepcopy', (['binid_properties[0]'], {}), '(binid_properties[0])\n', (22400, 22421), False, 'import copy\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" BVT tests for Virtual Machine Life Cycle
"""
# Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import (attachVolume,
detachVolume,
deleteVolume,
attachIso,
detachIso,
deleteIso,
startVirtualMachine,
stopVirtualMachine,
migrateVirtualMachineWithVolume)
from marvin.lib.utils import (cleanup_resources)
from marvin.lib.base import (Account,
Host,
Pod,
StoragePool,
ServiceOffering,
DiskOffering,
VirtualMachine,
Iso,
Volume)
from marvin.lib.common import (get_domain,
get_zone,
get_template)
from marvin.lib.decoratorGenerators import skipTestIf
from marvin.codes import FAILED, PASS
from nose.plugins.attrib import attr
# Import System modules
import time
_multiprocess_shared_ = True
class TestVMMigration(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestVMMigration, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
cls.cleanup = []
cls.hypervisorNotSupported = False
cls.hypervisor = cls.testClient.getHypervisorInfo()
if cls.hypervisor.lower() not in ['vmware']:
cls.hypervisorNotSupported = True
if cls.hypervisorNotSupported == False:
cls.pods = Pod.list(cls.apiclient, zoneid=cls.zone.id, listall=True)
if len(cls.pods) < 2:
assert False, "Not enough pods found: %d" % len(cls.pods)
cls.computeOfferingStorageTags = None
cls.diskOfferingStorageTags = None
for pod in cls.pods:
podStoragePools = StoragePool.list(
cls.apiclient,
scope='CLUSTER',
podid=pod.id)
if len(podStoragePools) < 1:
assert False, "Not enough CLUSTER scope storage pools found for pod: %s" % pod.id
taggedPool = []
for pool in podStoragePools:
if pool.tags != None and len(pool.tags) > 0:
taggedPool.append(pool)
if len(taggedPool) < 2:
assert False, "No CLUSTER scope, tagged storage pools found for pod: %s" % pod.id
if cls.computeOfferingStorageTags == None:
cls.computeOfferingStorageTags = taggedPool[0].tags
if cls.diskOfferingStorageTags == None:
cls.diskOfferingStorageTags = taggedPool[1].tags
template = get_template(
cls.apiclient,
cls.zone.id,
cls.services["ostype"])
if template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]
# Set Zones and disk offerings
cls.services["small"]["zoneid"] = cls.zone.id
cls.services["small"]["template"] = template.id
cls.services["iso"]["zoneid"] = cls.zone.id
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id)
cls.debug(cls.account.id)
compute_offering_service = cls.services["service_offerings"]["tiny"].copy()
compute_offering_service["tags"] = cls.computeOfferingStorageTags
cls.service_offering = ServiceOffering.create(
cls.apiclient,
compute_offering_service)
disk_offering_service = cls.services["disk_offering"].copy()
disk_offering_service["disksize"] = 1
cls.untagged_disk_offering = DiskOffering.create(
cls.apiclient,
disk_offering_service)
disk_offering_service["tags"] = cls.diskOfferingStorageTags
cls.tagged_disk_offering = DiskOffering.create(
cls.apiclient,
disk_offering_service)
cls.hostId = None
host = cls.getOldestHost(cls.pods[0].id, cls.pods[1].id)
if host != None:
cls.hostId = host.id
cls.cleanup = [
cls.service_offering,
cls.untagged_disk_offering,
cls.tagged_disk_offering,
cls.account
]
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.virtual_machine = None
if self.hypervisorNotSupported == False:
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["small"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
mode=self.services['mode'],
hostid=self.hostId
)
self.cleanup = []
def tearDown(self):
try:
if self.virtual_machine != None:
self.virtual_machine.delete(self.apiclient, expunge=True)
# Clean up, terminate the created accounts, domains etc
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def getOldestHost(cls, pod1_id, pod2_id):
selectedHost = None
hosts = Host.list(cls.apiclient, type='Routing', podid=pod1_id)
morehosts = Host.list(cls.apiclient, type='Routing', podid=pod2_id)
if isinstance(morehosts, list) and len(morehosts)>0:
if isinstance(hosts, list) and len(hosts)>0:
hosts.extend(morehosts)
if isinstance(hosts, list) and len(hosts)>0:
selectedHost = hosts[0]
# Very basic way to get lowest version host
for host in hosts:
if int(host.hypervisorversion.replace(".", "")) < int(selectedHost.hypervisorversion.replace(".", "")):
selectedHost = host
return selectedHost
@skipTestIf("hypervisorNotSupported")
@attr(tags=["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"], required_hardware="false")
def test_01_migrate_running_vm(self):
"""Test Running Virtual Machine Migration Without DATA disk or ISO
"""
# Validate the following:
# 1. Start VM if not running
# 2. Migrate VM to a different pod multiple times
vmResponse = self.getVmVerifiedResponse(self.virtual_machine.id)
if vmResponse.state != 'Running':
self.startVm(vmResponse.id)
migrationCount = 1
while migrationCount > 0:
vmResponse = self.getVmVerifiedResponse(self.virtual_machine.id, 'Running')
hostId = self.getDifferentPodHost(vmResponse.id, vmResponse.hostid).id
self.debug("#%d migration, current host ID: %s, new host ID: %s" % ((2-migrationCount), vmResponse.hostid, hostId))
self.migrateVmWithVolume(vmResponse.id, hostId)
migrationCount = migrationCount - 1
if migrationCount > 0:
time.sleep(self.services["sleep"])
return
@skipTestIf("hypervisorNotSupported")
@attr(tags=["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"], required_hardware="false")
def test_02_migrate_running_vm_with_disk_and_iso(self):
"""Test Running Virtual Machine Migration With DATA disks or ISO
"""
# Validate the following:
# 1. Start VM if not running
# 2. Add disks and ISO to the VM
# 3. Migrate VM to a different pod multiple times
# 4. Remove disks and ISO from the VM
vmResponse = self.getVmVerifiedResponse(self.virtual_machine.id)
if vmResponse.state != 'Running':
self.startVm(vmResponse.id)
vol1 = self.addVolumeToVm(vmResponse.id, self.tagged_disk_offering)
vol2 = self.addVolumeToVm(vmResponse.id, self.untagged_disk_offering)
# self.addIsoToVm(vmResponse.id)
migrationCount = 1
while migrationCount > 0:
vmResponse = self.getVmVerifiedResponse(self.virtual_machine.id, 'Running')
hostId = self.getDifferentPodHost(vmResponse.id, vmResponse.hostid).id
self.debug("#%d migration, current host ID: %s, new host ID: %s" % ((2-migrationCount), vmResponse.hostid, hostId))
self.migrateVmWithVolume(vmResponse.id, hostId)
migrationCount = migrationCount - 1
if migrationCount > 0:
time.sleep(self.services["sleep"])
self.removeVolumeFromVm(vol1.id)
self.removeVolumeFromVm(vol2.id)
# self.removeIsoFromVm(vmResponse.id, vmResponse.isoid)
return
@skipTestIf("hypervisorNotSupported")
@attr(tags=["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"], required_hardware="false")
def test_03_migrate_stopped_vm(self):
"""Test Stopped Virtual Machine Migration Without DATA disk or ISO
"""
# Validate the following:
# 1. Stop VM if not already stopped
# 2. Migrate VM to a different pod multiple times with volume to pool mapping
vmResponse = self.getVmVerifiedResponse(self.virtual_machine.id)
if vmResponse.state != 'Stopped':
self.stopVm(vmResponse.id)
migrationCount = 3
while migrationCount > 0:
vmResponse = self.getVmVerifiedResponse(self.virtual_machine.id, 'Stopped')
migrateTo = self.getDifferentPodVolumeStoragePoolMapping(vmResponse.id)
self.debug("#%d migration, mapping: %s" % ((4-migrationCount), migrateTo))
self.migrateVmWithVolume(vmResponse.id, None, migrateTo)
migrationCount = migrationCount - 1
if migrationCount > 0:
time.sleep(self.services["sleep"])
return
@skipTestIf("hypervisorNotSupported")
@attr(tags=["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"], required_hardware="false")
def test_04_migrate_stopped_vm_with_disk_and_iso(self):
"""Test Stopped Virtual Machine Migration With DATA disk or ISO
"""
# Validate the following:
# 1. Start VM if not running
# 2. Add disks and ISO to the VM
# 3. Stop the VM
# 4. Migrate VM to a different pod multiple times with volume to pool mapping
# 5. Start VM and remove disks and ISO from the VM
vmResponse = self.getVmVerifiedResponse(self.virtual_machine.id)
if vmResponse.state != 'Running':
self.startVm(vmResponse.id)
vol1 = self.addVolumeToVm(vmResponse.id, self.tagged_disk_offering)
vol2 = self.addVolumeToVm(vmResponse.id, self.untagged_disk_offering)
# self.addIsoToVm(vmResponse.id)
self.stopVm(vmResponse.id)
migrationCount = 3
while migrationCount > 0:
vmResponse = self.getVmVerifiedResponse(self.virtual_machine.id, 'Stopped')
migrateTo = self.getDifferentPodVolumeStoragePoolMapping(vmResponse.id)
self.debug("#%d migration, mapping: %s" % ((4-migrationCount), migrateTo))
self.migrateVmWithVolume(vmResponse.id, None, migrateTo)
migrationCount = migrationCount - 1
if migrationCount > 0:
time.sleep(self.services["sleep"])
self.removeVolumeFromVm(vol1.id)
self.removeVolumeFromVm(vol2.id)
# self.removeIsoFromVm(vmResponse.id, vmResponse.isoid)
return
def startVm(self, vm_id):
startVirtualMachineCmd = startVirtualMachine.startVirtualMachineCmd()
startVirtualMachineCmd.id = vm_id
self.apiclient.startVirtualMachine(startVirtualMachineCmd)
def stopVm(self, vm_id):
stopVirtualMachineCmd = stopVirtualMachine.stopVirtualMachineCmd()
stopVirtualMachineCmd.id = vm_id
self.apiclient.stopVirtualMachine(stopVirtualMachineCmd)
def addVolumeToVm(self, vm_id, disk_offering):
volume = Volume.create(
self.apiclient,
self.services["volume"],
zoneid=self.zone.id,
diskofferingid=disk_offering.id,
account=self.account.name,
domainid=self.account.domainid)
cmd = attachVolume.attachVolumeCmd()
cmd.id = volume.id
cmd.virtualmachineid = vm_id
attachedVolume = self.apiclient.attachVolume(cmd)
return attachedVolume
def removeVolumeFromVm(self, volume_id):
cmd = detachVolume.detachVolumeCmd()
cmd.id = volume_id
detachedVolume = self.apiclient.detachVolume(cmd)
cmd = deleteVolume.deleteVolumeCmd()
cmd.id = volume_id
self.apiclient.deleteVolume(cmd)
return
def addIsoToVm(self, vm_id):
iso = Iso.create(
self.apiclient,
self.services["iso"],
account=self.account.name,
domainid=self.account.domainid)
cmd = attachIso.attachIsoCmd()
cmd.id = iso.id
cmd.virtualmachineid = vm_id
attachedIso = self.apiclient.attachIso(cmd)
return
def removeIsoFromVm(self, vm_id, iso_id):
cmd = detachIso.detachIsoCmd()
cmd.virtualmachineid = vm_id
self.apiclient.detachIso(cmd)
cmd = deleteIso.deleteIsoCmd()
cmd.id = iso_id
self.apiclient.deleteIso(cmd)
return
def getVmVerifiedResponse(self, vm_id, state=None):
list_vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s" \
% self.virtual_machine.id)
self.assertEqual(
isinstance(list_vm_response, list),
True,
"Check list response returns a valid list")
self.assertNotEqual(
len(list_vm_response),
0,
"Check VM available in List Virtual Machines")
vmResponse = list_vm_response[0]
if state != None:
self.assertEqual(
vmResponse.state,
state,
"VM not in state: %s" % state)
return vmResponse
def getDifferentPodHost(self, vm_id, host_id):
host = None
currentHost = Host.list(self.apiclient, id=host_id)
self.assertEqual(
isinstance(currentHost, list),
True,
"Check host list response returns a valid list")
self.assertNotEqual(
len(currentHost),
0,
"Check current host for VM ID: %s available in List Hosts" % vm_id)
currentHost = currentHost[0]
hosts = Host.listForMigration(self.apiclient, virtualmachineid=vm_id)
self.assertEqual(
isinstance(hosts, list),
True,
"Check host list response returns a valid list")
self.assertNotEqual(
len(hosts),
0,
"Hosts suitable for migration for VM ID: %s not found" % vm_id)
for hostForMigration in hosts:
if hostForMigration.podid != currentHost.podid:
host = hostForMigration
break
self.assertNotEqual(
host,
None,
"Host suitable for migration for VM ID: %s in a different pod not found" % vm_id)
return host
def getPodStoragePoolWithTags(self, pod_id, tags=None):
pool = None
storage_pools = StoragePool.list(
self.apiclient,
podid=pod_id,
listall=True)
if isinstance(storage_pools, list) and len(storage_pools) > 0:
if tags != None:
for storage_pool in storage_pools:
if storage_pool.tags == tags:
pool = storage_pool
break
else:
pool = storage_pool[0]
return pool
def getDifferentPodVolumeStoragePoolMapping(self, vm_id):
rootVolume = Volume.list(self.apiclient, virtualmachineid=vm_id, listall=True, type='ROOT')
self.assertEqual(
isinstance(rootVolume, list),
True,
"Check VM volumes list response returns a valid list")
self.assertNotEqual(
len(rootVolume),
0,
"Check VM ROOT volume available in List Volumes")
rootVolume = rootVolume[0]
volumeStoragePool = StoragePool.list(
self.apiclient,
id=rootVolume.storageid)
self.assertEqual(
isinstance(volumeStoragePool, list),
True,
"Check VM ROOT Volume storage list response returns a valid list")
self.assertNotEqual(
len(volumeStoragePool),
0,
"Check VM ROOT Volume storage available in List Storage Pools")
volumeStoragePool = volumeStoragePool[0]
podId = self.pods[0].id
if volumeStoragePool.podid == podId:
podId = self.pods[1].id
pool = self.getPodStoragePoolWithTags(podId, self.computeOfferingStorageTags)
self.assertNotEqual(
pool,
None,
"Target storage pool mapping for VM ID: %s failed" % vm_id)
migrateTo = { "volume": rootVolume.id, "pool": pool.id}
return [migrateTo]
def migrateVmWithVolume(self, vm_id, host_id, migrate_to=None):
migrateVirtualMachineWithVolumeCmd = migrateVirtualMachineWithVolume.migrateVirtualMachineWithVolumeCmd()
migrateVirtualMachineWithVolumeCmd.virtualmachineid = vm_id
if host_id != None:
migrateVirtualMachineWithVolumeCmd.hostid = host_id
if migrate_to != None:
migrateVirtualMachineWithVolumeCmd.migrateto = migrate_to
response = self.apiclient.migrateVirtualMachineWithVolume(migrateVirtualMachineWithVolumeCmd)
return response
| [
"marvin.cloudstackAPI.attachVolume.attachVolumeCmd",
"marvin.lib.base.VirtualMachine.list",
"marvin.cloudstackAPI.deleteIso.deleteIsoCmd",
"marvin.lib.base.Host.list",
"marvin.lib.base.StoragePool.list",
"marvin.lib.decoratorGenerators.skipTestIf",
"marvin.cloudstackAPI.startVirtualMachine.startVirtualM... | [((7907, 7943), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (7917, 7943), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((7949, 8053), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'advanced', 'advancedns', 'smoke', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['devcloud', 'advanced', 'advancedns', 'smoke', 'basic', 'sg'],\n required_hardware='false')\n", (7953, 8053), False, 'from nose.plugins.attrib import attr\n'), ((9038, 9074), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (9048, 9074), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((9080, 9184), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'advanced', 'advancedns', 'smoke', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['devcloud', 'advanced', 'advancedns', 'smoke', 'basic', 'sg'],\n required_hardware='false')\n", (9084, 9184), False, 'from nose.plugins.attrib import attr\n'), ((10613, 10649), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (10623, 10649), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((10655, 10759), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'advanced', 'advancedns', 'smoke', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['devcloud', 'advanced', 'advancedns', 'smoke', 'basic', 'sg'],\n required_hardware='false')\n", (10659, 10759), False, 'from nose.plugins.attrib import attr\n'), ((11747, 11783), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (11757, 11783), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((11789, 11893), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'advanced', 'advancedns', 'smoke', 'basic', 'sg']", 'required_hardware': '"""false"""'}), "(tags=['devcloud', 'advanced', 'advancedns', 'smoke', 'basic', 'sg'],\n required_hardware='false')\n", (11793, 11893), False, 'from nose.plugins.attrib import attr\n'), ((2425, 2450), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2435, 2450), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((7245, 7300), 'marvin.lib.base.Host.list', 'Host.list', (['cls.apiclient'], {'type': '"""Routing"""', 'podid': 'pod1_id'}), "(cls.apiclient, type='Routing', podid=pod1_id)\n", (7254, 7300), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((7321, 7376), 'marvin.lib.base.Host.list', 'Host.list', (['cls.apiclient'], {'type': '"""Routing"""', 'podid': 'pod2_id'}), "(cls.apiclient, type='Routing', podid=pod2_id)\n", (7330, 7376), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((13449, 13493), 'marvin.cloudstackAPI.startVirtualMachine.startVirtualMachineCmd', 'startVirtualMachine.startVirtualMachineCmd', ([], {}), '()\n', (13491, 13493), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((13665, 13707), 'marvin.cloudstackAPI.stopVirtualMachine.stopVirtualMachineCmd', 'stopVirtualMachine.stopVirtualMachineCmd', ([], {}), '()\n', (13705, 13707), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((13883, 14059), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'diskofferingid': 'disk_offering.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n diskofferingid=disk_offering.id, account=self.account.name, domainid=\n self.account.domainid)\n", (13896, 14059), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((14138, 14168), 'marvin.cloudstackAPI.attachVolume.attachVolumeCmd', 'attachVolume.attachVolumeCmd', ([], {}), '()\n', (14166, 14168), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((14381, 14411), 'marvin.cloudstackAPI.detachVolume.detachVolumeCmd', 'detachVolume.detachVolumeCmd', ([], {}), '()\n', (14409, 14411), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((14511, 14541), 'marvin.cloudstackAPI.deleteVolume.deleteVolumeCmd', 'deleteVolume.deleteVolumeCmd', ([], {}), '()\n', (14539, 14541), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((14673, 14784), 'marvin.lib.base.Iso.create', 'Iso.create', (['self.apiclient', "self.services['iso']"], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['iso'], account=self.account.name,\n domainid=self.account.domainid)\n", (14683, 14784), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((14840, 14864), 'marvin.cloudstackAPI.attachIso.attachIsoCmd', 'attachIso.attachIsoCmd', ([], {}), '()\n', (14862, 14864), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((15054, 15078), 'marvin.cloudstackAPI.detachIso.detachIsoCmd', 'detachIso.detachIsoCmd', ([], {}), '()\n', (15076, 15078), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((15168, 15192), 'marvin.cloudstackAPI.deleteIso.deleteIsoCmd', 'deleteIso.deleteIsoCmd', ([], {}), '()\n', (15190, 15192), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((15354, 15417), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (15373, 15417), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((16185, 16222), 'marvin.lib.base.Host.list', 'Host.list', (['self.apiclient'], {'id': 'host_id'}), '(self.apiclient, id=host_id)\n', (16194, 16222), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((16579, 16640), 'marvin.lib.base.Host.listForMigration', 'Host.listForMigration', (['self.apiclient'], {'virtualmachineid': 'vm_id'}), '(self.apiclient, virtualmachineid=vm_id)\n', (16600, 16640), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((17372, 17432), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['self.apiclient'], {'podid': 'pod_id', 'listall': '(True)'}), '(self.apiclient, podid=pod_id, listall=True)\n', (17388, 17432), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((17906, 17984), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'vm_id', 'listall': '(True)', 'type': '"""ROOT"""'}), "(self.apiclient, virtualmachineid=vm_id, listall=True, type='ROOT')\n", (17917, 17984), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((18336, 18393), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['self.apiclient'], {'id': 'rootVolume.storageid'}), '(self.apiclient, id=rootVolume.storageid)\n', (18352, 18393), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((19337, 19405), 'marvin.cloudstackAPI.migrateVirtualMachineWithVolume.migrateVirtualMachineWithVolumeCmd', 'migrateVirtualMachineWithVolume.migrateVirtualMachineWithVolumeCmd', ([], {}), '()\n', (19403, 19405), False, 'from marvin.cloudstackAPI import attachVolume, detachVolume, deleteVolume, attachIso, detachIso, deleteIso, startVirtualMachine, stopVirtualMachine, migrateVirtualMachineWithVolume\n'), ((2876, 2933), 'marvin.lib.base.Pod.list', 'Pod.list', (['cls.apiclient'], {'zoneid': 'cls.zone.id', 'listall': '(True)'}), '(cls.apiclient, zoneid=cls.zone.id, listall=True)\n', (2884, 2933), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((4090, 4154), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (4102, 4154), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((4603, 4681), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (4617, 4681), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((4971, 5034), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', 'compute_offering_service'], {}), '(cls.apiclient, compute_offering_service)\n', (4993, 5034), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((5232, 5289), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.apiclient', 'disk_offering_service'], {}), '(cls.apiclient, disk_offering_service)\n', (5251, 5289), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((5434, 5491), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.apiclient', 'disk_offering_service'], {}), '(cls.apiclient, disk_offering_service)\n', (5453, 5491), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((5956, 6001), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls.cleanup'], {}), '(cls.apiclient, cls.cleanup)\n', (5973, 6001), False, 'from marvin.lib.utils import cleanup_resources\n'), ((6363, 6587), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['small']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'mode': "self.services['mode']", 'hostid': 'self.hostId'}), "(self.apiclient, self.services['small'], accountid=\n self.account.name, domainid=self.account.domainid, serviceofferingid=\n self.service_offering.id, mode=self.services['mode'], hostid=self.hostId)\n", (6384, 6587), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((6968, 7015), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (6985, 7015), False, 'from marvin.lib.utils import cleanup_resources\n'), ((3207, 3269), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['cls.apiclient'], {'scope': '"""CLUSTER"""', 'podid': 'pod.id'}), "(cls.apiclient, scope='CLUSTER', podid=pod.id)\n", (3223, 3269), False, 'from marvin.lib.base import Account, Host, Pod, StoragePool, ServiceOffering, DiskOffering, VirtualMachine, Iso, Volume\n'), ((8982, 9016), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (8992, 9016), False, 'import time\n'), ((10411, 10445), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (10421, 10445), False, 'import time\n'), ((11691, 11725), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (11701, 11725), False, 'import time\n'), ((13189, 13223), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (13199, 13223), False, 'import time\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for Kubernetes supported version """
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.cloudstackAPI import (listInfrastructure,
listTemplates,
listKubernetesSupportedVersions,
addKubernetesSupportedVersion,
deleteKubernetesSupportedVersion,
listKubernetesClusters,
createKubernetesCluster,
stopKubernetesCluster,
startKubernetesCluster,
deleteKubernetesCluster,
upgradeKubernetesCluster,
scaleKubernetesCluster,
destroyVirtualMachine,
deleteNetwork)
from marvin.cloudstackException import CloudstackAPIException
from marvin.codes import PASS, FAILED
from marvin.lib.base import (Template,
ServiceOffering,
Account,
StoragePool,
Configurations)
from marvin.lib.utils import (cleanup_resources,
validateList,
random_gen)
from marvin.lib.common import (get_zone,
get_domain)
from marvin.sshClient import SshClient
from nose.plugins.attrib import attr
from marvin.lib.decoratorGenerators import skipTestIf
import time
_multiprocess_shared_ = True
k8s_cluster = None
class TestKubernetesCluster(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestKubernetesCluster, cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
cls.cks_template_name_key = "cloud.kubernetes.cluster.template.name." + cls.hypervisor.lower()
cls.hypervisorNotSupported = False
if cls.hypervisor.lower() not in ["kvm", "vmware", "xenserver"]:
cls.hypervisorNotSupported = True
cls.setup_failed = False
cls._cleanup = []
cls.kubernetes_version_ids = []
if cls.hypervisorNotSupported == False:
cls.endpoint_url = Configurations.list(cls.apiclient, name="endpointe.url")[0].value
if "localhost" in cls.endpoint_url:
endpoint_url = "http://%s:%d/client/api " %(cls.mgtSvrDetails["mgtSvrIp"], cls.mgtSvrDetails["port"])
cls.debug("Setting endpointe.url to %s" %(endpoint_url))
Configurations.update(cls.apiclient, "endpointe.url", endpoint_url)
cls.initial_configuration_cks_enabled = Configurations.list(cls.apiclient, name="cloud.kubernetes.service.enabled")[0].value
if cls.initial_configuration_cks_enabled not in ["true", True]:
cls.debug("Enabling CloudStack Kubernetes Service plugin and restarting management server")
Configurations.update(cls.apiclient,
"cloud.kubernetes.service.enabled",
"true")
cls.restartServer()
cls.updateVmwareSettings(False)
cls.cks_template = None
cls.initial_configuration_cks_template_name = None
cls.cks_service_offering = None
if cls.setup_failed == False:
try:
cls.kubernetes_version_1 = cls.addKubernetesSupportedVersion(cls.services["cks_kubernetes_versions"]["1.14.9"])
cls.kubernetes_version_ids.append(cls.kubernetes_version_1.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, version=%s, url=%s, %s" %
(cls.services["cks_kubernetes_versions"]["1.14.9"]["semanticversion"], cls.services["cks_kubernetes_versions"]["1.14.9"]["url"], e))
if cls.setup_failed == False:
try:
cls.kubernetes_version_2 = cls.addKubernetesSupportedVersion(cls.services["cks_kubernetes_versions"]["1.15.0"])
cls.kubernetes_version_ids.append(cls.kubernetes_version_2.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, version=%s, url=%s, %s" %
(cls.services["cks_kubernetes_versions"]["1.15.0"]["semanticversion"], cls.services["cks_kubernetes_versions"]["1.15.0"]["url"], e))
if cls.setup_failed == False:
try:
cls.kubernetes_version_3 = cls.addKubernetesSupportedVersion(cls.services["cks_kubernetes_versions"]["1.16.0"])
cls.kubernetes_version_ids.append(cls.kubernetes_version_3.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, version=%s, url=%s, %s" %
(cls.services["cks_kubernetes_versions"]["1.16.0"]["semanticversion"], cls.services["cks_kubernetes_versions"]["1.16.0"]["url"], e))
if cls.setup_failed == False:
try:
cls.kubernetes_version_4 = cls.addKubernetesSupportedVersion(cls.services["cks_kubernetes_versions"]["1.16.3"])
cls.kubernetes_version_ids.append(cls.kubernetes_version_4.id)
except Exception as e:
cls.setup_failed = True
cls.debug("Failed to get Kubernetes version ISO in ready state, version=%s, url=%s, %s" %
(cls.services["cks_kubernetes_versions"]["1.16.3"]["semanticversion"], cls.services["cks_kubernetes_versions"]["1.16.3"]["url"], e))
if cls.setup_failed == False:
cls.cks_template, existAlready = cls.getKubernetesTemplate()
if cls.cks_template == FAILED:
assert False, "getKubernetesTemplate() failed to return template for hypervisor %s" % cls.hypervisor
cls.setup_failed = True
else:
if not existAlready:
cls._cleanup.append(cls.cks_template)
if cls.setup_failed == False:
cls.initial_configuration_cks_template_name = Configurations.list(cls.apiclient,
name=cls.cks_template_name_key)[0].value
Configurations.update(cls.apiclient,
cls.cks_template_name_key,
cls.cks_template.name)
cks_offering_data = cls.services["cks_service_offering"]
cks_offering_data["name"] = 'CKS-Instance-' + random_gen()
cls.cks_service_offering = ServiceOffering.create(
cls.apiclient,
cks_offering_data
)
cls._cleanup.append(cls.cks_service_offering)
cls.domain = get_domain(cls.apiclient)
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
return
@classmethod
def tearDownClass(cls):
version_delete_failed = False
# Delete added Kubernetes supported version
for version_id in cls.kubernetes_version_ids:
try:
cls.deleteKubernetesSupportedVersion(version_id)
except Exception as e:
version_delete_failed = True
cls.debug("Error: Exception during cleanup for added Kubernetes supported versions: %s" % e)
try:
# Restore original CKS template
if cls.hypervisorNotSupported == False and cls.initial_configuration_cks_template_name != None:
Configurations.update(cls.apiclient,
cls.cks_template_name_key,
cls.initial_configuration_cks_template_name)
# Restore CKS enabled
if cls.initial_configuration_cks_enabled not in ["true", True]:
cls.debug("Restoring Kubernetes Service enabled value")
Configurations.update(cls.apiclient,
"cloud.kubernetes.service.enabled",
"false")
cls.restartServer()
cls.updateVmwareSettings(True)
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
if version_delete_failed == True:
raise Exception("Warning: Exception during cleanup, unable to delete Kubernetes supported versions")
return
@classmethod
def updateVmwareSettings(cls, tearDown):
value = "false"
if not tearDown:
value = "true"
if cls.hypervisor.lower() == 'vmware':
Configurations.update(cls.apiclient,
"vmware.create.full.clone",
value)
allStoragePools = StoragePool.list(
cls.apiclient
)
for pool in allStoragePools:
Configurations.update(cls.apiclient,
storageid=pool.id,
name="vmware.create.full.clone",
value=value)
@classmethod
def restartServer(cls):
"""Restart management server"""
cls.debug("Restarting management server")
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-management stop"
sshClient.execute(command)
command = "service cloudstack-management start"
sshClient.execute(command)
#Waits for management to come up in 5 mins, when it's up it will continue
timeout = time.time() + 300
while time.time() < timeout:
if cls.isManagementUp() is True: return
time.sleep(5)
cls.setup_failed = True
cls.debug("Management server did not come up, failing")
return
@classmethod
def isManagementUp(cls):
try:
cls.apiclient.listInfrastructure(listInfrastructure.listInfrastructureCmd())
return True
except Exception:
return False
@classmethod
def getKubernetesTemplate(cls, cks_templates=None):
if cks_templates is None:
cks_templates = cls.services["cks_templates"]
hypervisor = cls.hypervisor.lower()
if hypervisor not in list(cks_templates.keys()):
cls.debug("Provided hypervisor has no CKS template")
return FAILED, False
cks_template = cks_templates[hypervisor]
cmd = listTemplates.listTemplatesCmd()
cmd.name = cks_template['name']
cmd.templatefilter = 'all'
cmd.zoneid = cls.zone.id
cmd.hypervisor = hypervisor
templates = cls.apiclient.listTemplates(cmd)
if validateList(templates)[0] != PASS:
details = None
if hypervisor in ["vmware"] and "details" in cks_template:
details = cks_template["details"]
template = Template.register(cls.apiclient, cks_template, zoneid=cls.zone.id, hypervisor=hypervisor.lower(), randomize_name=False, details=details)
template.download(cls.apiclient)
return template, False
for template in templates:
if template.isready and template.ispublic:
return Template(template.__dict__), True
return FAILED, False
@classmethod
def waitForKubernetesSupportedVersionIsoReadyState(cls, version_id, retries=30, interval=60):
"""Check if Kubernetes supported version ISO is in Ready state"""
while retries > 0:
time.sleep(interval)
list_versions_response = cls.listKubernetesSupportedVersion(version_id)
if not hasattr(list_versions_response, 'isostate') or not list_versions_response or not list_versions_response.isostate:
retries = retries - 1
continue
if 'Ready' == list_versions_response.isostate:
return
elif 'Failed' == list_versions_response.isostate:
raise Exception( "Failed to download template: status - %s" % template.status)
retries = retries - 1
raise Exception("Kubernetes supported version Ready state timed out")
@classmethod
def listKubernetesSupportedVersion(cls, version_id):
listKubernetesSupportedVersionsCmd = listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd()
listKubernetesSupportedVersionsCmd.id = version_id
versionResponse = cls.apiclient.listKubernetesSupportedVersions(listKubernetesSupportedVersionsCmd)
return versionResponse[0]
@classmethod
def addKubernetesSupportedVersion(cls, version_service):
addKubernetesSupportedVersionCmd = addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd()
addKubernetesSupportedVersionCmd.semanticversion = version_service["semanticversion"]
addKubernetesSupportedVersionCmd.name = 'v' + version_service["semanticversion"] + '-' + random_gen()
addKubernetesSupportedVersionCmd.url = version_service["url"]
addKubernetesSupportedVersionCmd.mincpunumber = version_service["mincpunumber"]
addKubernetesSupportedVersionCmd.minmemory = version_service["minmemory"]
kubernetes_version = cls.apiclient.addKubernetesSupportedVersion(addKubernetesSupportedVersionCmd)
cls.debug("Waiting for Kubernetes version with ID %s to be ready" % kubernetes_version.id)
cls.waitForKubernetesSupportedVersionIsoReadyState(kubernetes_version.id)
kubernetes_version = cls.listKubernetesSupportedVersion(kubernetes_version.id)
return kubernetes_version
@classmethod
def deleteKubernetesSupportedVersion(cls, version_id):
deleteKubernetesSupportedVersionCmd = deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd()
deleteKubernetesSupportedVersionCmd.id = version_id
deleteKubernetesSupportedVersionCmd.deleteiso = True
cls.apiclient.deleteKubernetesSupportedVersion(deleteKubernetesSupportedVersionCmd)
def setUp(self):
self.services = self.testClient.getParsedTestDataConfig()
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_01_invalid_upgrade_kubernetes_cluster(self):
"""Test to check for failure while tying to upgrade a Kubernetes cluster to a lower version
# Validate the following:
# 1. upgradeKubernetesCluster should fail
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster()
self.debug("Upgrading Kubernetes cluster with ID: %s to a lower version" % k8s_cluster.id)
try:
k8s_cluster = self.upgradeKubernetesCluster(k8s_cluster.id, self.kubernetes_version_1.id)
self.debug("Invalid CKS Kubernetes HA cluster deployed with ID: %s. Deleting it and failing test." % kubernetes_version_1.id)
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Kubernetes cluster upgraded to a lower Kubernetes supported version. Must be an error.")
except Exception as e:
self.debug("Upgrading Kubernetes cluster with invalid Kubernetes supported version check successful, API failure: %s" % e)
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_02_deploy_and_upgrade_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster and upgrade it to newer version
# Validate the following:
# 1. upgradeKubernetesCluster should return valid info for the cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster()
time.sleep(self.services["sleep"])
self.debug("Upgrading Kubernetes cluster with ID: %s" % k8s_cluster.id)
try:
k8s_cluster = self.upgradeKubernetesCluster(k8s_cluster.id, self.kubernetes_version_3.id)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to upgrade Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterUpgrade(k8s_cluster, self.kubernetes_version_3.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_03_deploy_and_scale_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster and check for failure while tying to scale it
# Validate the following:
# 1. scaleKubernetesCluster should return valid info for the cluster when it is scaled up
# 2. scaleKubernetesCluster should return valid info for the cluster when it is scaled down
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster()
self.debug("Upscaling Kubernetes cluster with ID: %s" % k8s_cluster.id)
try:
k8s_cluster = self.scaleKubernetesCluster(k8s_cluster.id, 2)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to upscale Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterScale(k8s_cluster, 2)
self.debug("Kubernetes cluster with ID: %s successfully upscaled, now downscaling it" % k8s_cluster.id)
try:
k8s_cluster = self.scaleKubernetesCluster(k8s_cluster.id, 1)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to downscale Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterScale(k8s_cluster)
self.debug("Kubernetes cluster with ID: %s successfully downscaled" % k8s_cluster.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_04_basic_lifecycle_kubernetes_cluster(self):
"""Test to deploy a new Kubernetes cluster
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
# 3. stopKubernetesCluster should stop the cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster()
self.debug("Kubernetes cluster with ID: %s successfully deployed, now stopping it" % k8s_cluster.id)
self.stopAndVerifyKubernetesCluster(k8s_cluster.id)
self.debug("Kubernetes cluster with ID: %s successfully stopped, now starting it again" % k8s_cluster.id)
try:
k8s_cluster = self.startKubernetesCluster(k8s_cluster.id)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to start Kubernetes cluster due to: %s" % e)
self.verifyKubernetesClusterState(k8s_cluster, 'Running')
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_05_delete_kubernetes_cluster(self):
"""Test to delete an existing Kubernetes cluster
# Validate the following:
# 1. deleteKubernetesCluster should delete an existing Kubernetes cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster()
self.debug("Deleting Kubernetes cluster with ID: %s" % k8s_cluster.id)
self.deleteKubernetesClusterAndVerify(k8s_cluster.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % k8s_cluster.id)
k8s_cluster = None
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_06_deploy_invalid_kubernetes_ha_cluster(self):
"""Test to deploy an invalid HA Kubernetes cluster
# Validate the following:
# 1. createKubernetesCluster should fail as version doesn't support HA
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
try:
cluster_response = self.createKubernetesCluster(name, self.kubernetes_version_2.id, 1, 2)
self.debug("Invalid CKS Kubernetes HA cluster deployed with ID: %s. Deleting it and failing test." % cluster_response.id)
self.deleteKubernetesClusterAndVerify(cluster_response.id, False, True)
self.fail("HA Kubernetes cluster deployed with Kubernetes supported version below version 1.16.0. Must be an error.")
except CloudstackAPIException as e:
self.debug("HA Kubernetes cluster with invalid Kubernetes supported version check successful, API failure: %s" % e)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_07_deploy_kubernetes_ha_cluster(self):
"""Test to deploy a new Kubernetes cluster
# Validate the following:
# 1. createKubernetesCluster should return valid info for new cluster
# 2. The Cloud Database contains the valid information
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(1, 2)
self.debug("HA Kubernetes cluster with ID: %s successfully deployed" % k8s_cluster.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_08_deploy_and_upgrade_kubernetes_ha_cluster(self):
"""Test to deploy a new HA Kubernetes cluster and upgrade it to newer version
# Validate the following:
# 1. upgradeKubernetesCluster should return valid info for the cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(1, 2)
time.sleep(self.services["sleep"])
self.debug("Upgrading HA Kubernetes cluster with ID: %s" % k8s_cluster.id)
try:
k8s_cluster = self.upgradeKubernetesCluster(k8s_cluster.id, self.kubernetes_version_4.id)
except Exception as e:
self.deleteKubernetesClusterAndVerify(k8s_cluster.id, False, True)
self.fail("Failed to upgrade Kubernetes HA cluster due to: %s" % e)
self.verifyKubernetesClusterUpgrade(k8s_cluster, self.kubernetes_version_4.id)
self.debug("Kubernetes cluster with ID: %s successfully upgraded" % k8s_cluster.id)
return
@attr(tags=["advanced", "smoke"], required_hardware="true")
@skipTestIf("hypervisorNotSupported")
def test_09_delete_kubernetes_ha_cluster(self):
"""Test to delete a HA Kubernetes cluster
# Validate the following:
# 1. deleteKubernetesCluster should delete an existing HA Kubernetes cluster
"""
if self.setup_failed == True:
self.fail("Setup incomplete")
global k8s_cluster
k8s_cluster = self.getValidKubernetesCluster(1, 2)
self.debug("Deleting Kubernetes cluster with ID: %s" % k8s_cluster.id)
self.deleteKubernetesClusterAndVerify(k8s_cluster.id)
self.debug("Kubernetes cluster with ID: %s successfully deleted" % k8s_cluster.id)
return
def listKubernetesCluster(self, cluster_id = None):
listKubernetesClustersCmd = listKubernetesClusters.listKubernetesClustersCmd()
if cluster_id != None:
listKubernetesClustersCmd.id = cluster_id
clusterResponse = self.apiclient.listKubernetesClusters(listKubernetesClustersCmd)
if cluster_id != None and clusterResponse != None:
return clusterResponse[0]
return clusterResponse
def createKubernetesCluster(self, name, version_id, size=1, control_nodes=1):
createKubernetesClusterCmd = createKubernetesCluster.createKubernetesClusterCmd()
createKubernetesClusterCmd.name = name
createKubernetesClusterCmd.description = name + "-description"
createKubernetesClusterCmd.kubernetesversionid = version_id
createKubernetesClusterCmd.size = size
createKubernetesClusterCmd.controlnodes = control_nodes
createKubernetesClusterCmd.serviceofferingid = self.cks_service_offering.id
createKubernetesClusterCmd.zoneid = self.zone.id
createKubernetesClusterCmd.noderootdisksize = 10
createKubernetesClusterCmd.account = self.account.name
createKubernetesClusterCmd.domainid = self.domain.id
clusterResponse = self.apiclient.createKubernetesCluster(createKubernetesClusterCmd)
if not clusterResponse:
self.cleanup.append(clusterResponse)
return clusterResponse
def stopKubernetesCluster(self, cluster_id):
stopKubernetesClusterCmd = stopKubernetesCluster.stopKubernetesClusterCmd()
stopKubernetesClusterCmd.id = cluster_id
response = self.apiclient.stopKubernetesCluster(stopKubernetesClusterCmd)
return response
def startKubernetesCluster(self, cluster_id):
startKubernetesClusterCmd = startKubernetesCluster.startKubernetesClusterCmd()
startKubernetesClusterCmd.id = cluster_id
response = self.apiclient.startKubernetesCluster(startKubernetesClusterCmd)
return response
def deleteKubernetesCluster(self, cluster_id):
deleteKubernetesClusterCmd = deleteKubernetesCluster.deleteKubernetesClusterCmd()
deleteKubernetesClusterCmd.id = cluster_id
response = self.apiclient.deleteKubernetesCluster(deleteKubernetesClusterCmd)
return response
def upgradeKubernetesCluster(self, cluster_id, version_id):
upgradeKubernetesClusterCmd = upgradeKubernetesCluster.upgradeKubernetesClusterCmd()
upgradeKubernetesClusterCmd.id = cluster_id
upgradeKubernetesClusterCmd.kubernetesversionid = version_id
response = self.apiclient.upgradeKubernetesCluster(upgradeKubernetesClusterCmd)
return response
def scaleKubernetesCluster(self, cluster_id, size):
scaleKubernetesClusterCmd = scaleKubernetesCluster.scaleKubernetesClusterCmd()
scaleKubernetesClusterCmd.id = cluster_id
scaleKubernetesClusterCmd.size = size
response = self.apiclient.scaleKubernetesCluster(scaleKubernetesClusterCmd)
return response
def getValidKubernetesCluster(self, size=1, control_nodes=1):
cluster = k8s_cluster
version = self.kubernetes_version_2
if control_nodes != 1:
version = self.kubernetes_version_3
valid = True
if cluster == None:
valid = False
self.debug("No existing cluster available, k8s_cluster: %s" % cluster)
if valid == True and cluster.id == None:
valid = False
self.debug("ID for existing cluster not found, k8s_cluster ID: %s" % cluster.id)
if valid == True:
cluster_id = cluster.id
cluster = self.listKubernetesCluster(cluster_id)
if cluster == None:
valid = False
self.debug("Existing cluster, k8s_cluster ID: %s not returned by list API" % cluster_id)
if valid == True:
try:
self.verifyKubernetesCluster(cluster, cluster.name, None, size, control_nodes)
self.debug("Existing Kubernetes cluster available with name %s" % cluster.name)
except AssertionError as error:
valid = False
self.debug("Existing cluster failed verification due to %s, need to deploy a new one" % error)
if valid == False:
name = 'testcluster-' + random_gen()
self.debug("Creating for Kubernetes cluster with name %s" % name)
try:
self.deleteAllLeftoverClusters()
cluster = self.createKubernetesCluster(name, version.id, size, control_nodes)
self.verifyKubernetesCluster(cluster, name, version.id, size, control_nodes)
except Exception as ex:
self.fail("Kubernetes cluster deployment failed: %s" % ex)
except AssertionError as err:
self.fail("Kubernetes cluster deployment failed during cluster verification: %s" % err)
return cluster
def verifyKubernetesCluster(self, cluster_response, name, version_id=None, size=1, control_nodes=1):
"""Check if Kubernetes cluster is valid"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
if name != None:
self.assertEqual(
cluster_response.name,
name,
"Check KubernetesCluster name {}, {}".format(cluster_response.name, name)
)
if version_id != None:
self.verifyKubernetesClusterVersion(cluster_response, version_id)
self.assertEqual(
cluster_response.zoneid,
self.zone.id,
"Check KubernetesCluster zone {}, {}".format(cluster_response.zoneid, self.zone.id)
)
self.verifyKubernetesClusterSize(cluster_response, size, control_nodes)
db_cluster_name = self.dbclient.execute("select name from kubernetes_cluster where uuid = '%s';" % cluster_response.id)[0][0]
self.assertEqual(
str(db_cluster_name),
name,
"Check KubernetesCluster name in DB {}, {}".format(db_cluster_name, name)
)
def verifyKubernetesClusterState(self, cluster_response, state):
"""Check if Kubernetes cluster state is Running"""
self.assertEqual(
cluster_response.state,
'Running',
"Check KubernetesCluster state {}, {}".format(cluster_response.state, state)
)
def verifyKubernetesClusterVersion(self, cluster_response, version_id):
"""Check if Kubernetes cluster node sizes are valid"""
self.assertEqual(
cluster_response.kubernetesversionid,
version_id,
"Check KubernetesCluster version {}, {}".format(cluster_response.kubernetesversionid, version_id)
)
def verifyKubernetesClusterSize(self, cluster_response, size=1, control_nodes=1):
"""Check if Kubernetes cluster node sizes are valid"""
self.assertEqual(
cluster_response.size,
size,
"Check KubernetesCluster size {}, {}".format(cluster_response.size, size)
)
self.assertEqual(
cluster_response.controlnodes,
control_nodes,
"Check KubernetesCluster control nodes {}, {}".format(cluster_response.controlnodes, control_nodes)
)
def verifyKubernetesClusterUpgrade(self, cluster_response, version_id):
"""Check if Kubernetes cluster state and version are valid after upgrade"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
self.verifyKubernetesClusterVersion(cluster_response, version_id)
def verifyKubernetesClusterScale(self, cluster_response, size=1, control_nodes=1):
"""Check if Kubernetes cluster state and node sizes are valid after upgrade"""
self.verifyKubernetesClusterState(cluster_response, 'Running')
self.verifyKubernetesClusterSize(cluster_response, size, control_nodes)
def stopAndVerifyKubernetesCluster(self, cluster_id):
"""Stop Kubernetes cluster and check if it is really stopped"""
stop_response = self.stopKubernetesCluster(cluster_id)
self.assertEqual(
stop_response.success,
True,
"Check KubernetesCluster stop response {}, {}".format(stop_response.success, True)
)
db_cluster_state = self.dbclient.execute("select state from kubernetes_cluster where uuid = '%s';" % cluster_id)[0][0]
self.assertEqual(
db_cluster_state,
'Stopped',
"KubernetesCluster not stopped in DB, {}".format(db_cluster_state)
)
def deleteKubernetesClusterAndVerify(self, cluster_id, verify = True, forced = False):
"""Delete Kubernetes cluster and check if it is really deleted"""
forceDeleted = False
try:
delete_response = self.deleteKubernetesCluster(cluster_id)
except Exception as e:
if forced:
cluster = self.listKubernetesCluster(cluster_id)
if cluster != None:
if cluster.state in ['Starting', 'Running', 'Upgrading', 'Scaling']:
self.stopKubernetesCluster(cluster_id)
self.deleteKubernetesCluster(cluster_id)
else:
forceDeleted = True
for cluster_vm in cluster.virtualmachines:
cmd = destroyVirtualMachine.destroyVirtualMachineCmd()
cmd.id = cluster_vm.id
cmd.expunge = True
self.apiclient.destroyVirtualMachine(cmd)
cmd = deleteNetwork.deleteNetworkCmd()
cmd.id = cluster.networkid
cmd.forced = True
self.apiclient.deleteNetwork(cmd)
self.dbclient.execute("update kubernetes_cluster set state='Destroyed', removed=now() where uuid = '%s';" % cluster.id)
else:
raise Exception("Error: Exception during delete cluster : %s" % e)
if verify == True and forceDeleted == False:
self.assertEqual(
delete_response.success,
True,
"Check KubernetesCluster delete response {}, {}".format(delete_response.success, True)
)
db_cluster_removed = self.dbclient.execute("select removed from kubernetes_cluster where uuid = '%s';" % cluster_id)[0][0]
self.assertNotEqual(
db_cluster_removed,
None,
"KubernetesCluster not removed in DB, {}".format(db_cluster_removed)
)
def deleteAllLeftoverClusters(self):
clusters = self.listKubernetesCluster()
if clusters != None:
for cluster in clusters:
self.deleteKubernetesClusterAndVerify(cluster.id, False, True)
| [
"marvin.cloudstackAPI.listKubernetesClusters.listKubernetesClustersCmd",
"marvin.lib.base.StoragePool.list",
"marvin.lib.decoratorGenerators.skipTestIf",
"marvin.lib.utils.random_gen",
"marvin.cloudstackAPI.scaleKubernetesCluster.scaleKubernetesClusterCmd",
"marvin.lib.base.Template",
"marvin.lib.common... | [((16582, 16640), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (16586, 16640), False, 'from nose.plugins.attrib import attr\n'), ((16646, 16682), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (16656, 16682), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((17912, 17970), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (17916, 17970), False, 'from nose.plugins.attrib import attr\n'), ((17976, 18012), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (17986, 18012), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((18982, 19040), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (18986, 19040), False, 'from nose.plugins.attrib import attr\n'), ((19046, 19082), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (19056, 19082), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((20622, 20680), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (20626, 20680), False, 'from nose.plugins.attrib import attr\n'), ((20686, 20722), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (20696, 20722), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((21884, 21942), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (21888, 21942), False, 'from nose.plugins.attrib import attr\n'), ((21948, 21984), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (21958, 21984), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((22667, 22725), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (22671, 22725), False, 'from nose.plugins.attrib import attr\n'), ((22731, 22767), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (22741, 22767), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((23870, 23928), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (23874, 23928), False, 'from nose.plugins.attrib import attr\n'), ((23934, 23970), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (23944, 23970), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((24546, 24604), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (24550, 24604), False, 'from nose.plugins.attrib import attr\n'), ((24610, 24646), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (24620, 24646), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((25724, 25782), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (25728, 25782), False, 'from nose.plugins.attrib import attr\n'), ((25788, 25824), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (25798, 25824), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((11201, 11306), 'marvin.sshClient.SshClient', 'SshClient', (["cls.mgtSvrDetails['mgtSvrIp']", '(22)', "cls.mgtSvrDetails['user']", "cls.mgtSvrDetails['passwd']"], {}), "(cls.mgtSvrDetails['mgtSvrIp'], 22, cls.mgtSvrDetails['user'], cls\n .mgtSvrDetails['passwd'])\n", (11210, 11306), False, 'from marvin.sshClient import SshClient\n'), ((12552, 12584), 'marvin.cloudstackAPI.listTemplates.listTemplatesCmd', 'listTemplates.listTemplatesCmd', ([], {}), '()\n', (12582, 12584), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((14398, 14466), 'marvin.cloudstackAPI.listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd', 'listKubernetesSupportedVersions.listKubernetesSupportedVersionsCmd', ([], {}), '()\n', (14464, 14466), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((14790, 14854), 'marvin.cloudstackAPI.addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd', 'addKubernetesSupportedVersion.addKubernetesSupportedVersionCmd', ([], {}), '()\n', (14852, 14854), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((15831, 15901), 'marvin.cloudstackAPI.deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd', 'deleteKubernetesSupportedVersion.deleteKubernetesSupportedVersionCmd', ([], {}), '()\n', (15899, 15901), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((18453, 18487), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (18463, 18487), False, 'import time\n'), ((25097, 25131), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (25107, 25131), False, 'import time\n'), ((26569, 26619), 'marvin.cloudstackAPI.listKubernetesClusters.listKubernetesClustersCmd', 'listKubernetesClusters.listKubernetesClustersCmd', ([], {}), '()\n', (26617, 26619), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((27044, 27096), 'marvin.cloudstackAPI.createKubernetesCluster.createKubernetesClusterCmd', 'createKubernetesCluster.createKubernetesClusterCmd', ([], {}), '()\n', (27094, 27096), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((28006, 28054), 'marvin.cloudstackAPI.stopKubernetesCluster.stopKubernetesClusterCmd', 'stopKubernetesCluster.stopKubernetesClusterCmd', ([], {}), '()\n', (28052, 28054), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((28297, 28347), 'marvin.cloudstackAPI.startKubernetesCluster.startKubernetesClusterCmd', 'startKubernetesCluster.startKubernetesClusterCmd', ([], {}), '()\n', (28345, 28347), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((28595, 28647), 'marvin.cloudstackAPI.deleteKubernetesCluster.deleteKubernetesClusterCmd', 'deleteKubernetesCluster.deleteKubernetesClusterCmd', ([], {}), '()\n', (28645, 28647), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((28912, 28966), 'marvin.cloudstackAPI.upgradeKubernetesCluster.upgradeKubernetesClusterCmd', 'upgradeKubernetesCluster.upgradeKubernetesClusterCmd', ([], {}), '()\n', (28964, 28966), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((29293, 29343), 'marvin.cloudstackAPI.scaleKubernetesCluster.scaleKubernetesClusterCmd', 'scaleKubernetesCluster.scaleKubernetesClusterCmd', ([], {}), '()\n', (29341, 29343), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((10019, 10065), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (10036, 10065), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((10539, 10610), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""vmware.create.full.clone"""', 'value'], {}), "(cls.apiclient, 'vmware.create.full.clone', value)\n", (10560, 10610), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((10709, 10740), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['cls.apiclient'], {}), '(cls.apiclient)\n', (10725, 10740), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((11651, 11662), 'time.time', 'time.time', ([], {}), '()\n', (11660, 11662), False, 'import time\n'), ((11683, 11694), 'time.time', 'time.time', ([], {}), '()\n', (11692, 11694), False, 'import time\n'), ((11770, 11783), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (11780, 11783), False, 'import time\n'), ((13626, 13646), 'time.sleep', 'time.sleep', (['interval'], {}), '(interval)\n', (13636, 13646), False, 'import time\n'), ((15046, 15058), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (15056, 15058), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((16408, 16455), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (16425, 16455), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((23125, 23137), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (23135, 23137), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((3730, 3797), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""endpointe.url"""', 'endpoint_url'], {}), "(cls.apiclient, 'endpointe.url', endpoint_url)\n", (3751, 3797), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((4135, 4220), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""cloud.kubernetes.service.enabled"""', '"""true"""'], {}), "(cls.apiclient, 'cloud.kubernetes.service.enabled', 'true'\n )\n", (4156, 4220), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((7764, 7855), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', 'cls.cks_template_name_key', 'cls.cks_template.name'], {}), '(cls.apiclient, cls.cks_template_name_key, cls.\n cks_template.name)\n', (7785, 7855), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((8119, 8175), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', 'cks_offering_data'], {}), '(cls.apiclient, cks_offering_data)\n', (8141, 8175), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((8466, 8491), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (8476, 8491), False, 'from marvin.lib.common import get_zone, get_domain\n'), ((8522, 8600), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (8536, 8600), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((9385, 9498), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', 'cls.cks_template_name_key', 'cls.initial_configuration_cks_template_name'], {}), '(cls.apiclient, cls.cks_template_name_key, cls.\n initial_configuration_cks_template_name)\n', (9406, 9498), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((9768, 9853), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient', '"""cloud.kubernetes.service.enabled"""', '"""false"""'], {}), "(cls.apiclient, 'cloud.kubernetes.service.enabled',\n 'false')\n", (9789, 9853), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((10828, 10934), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient'], {'storageid': 'pool.id', 'name': '"""vmware.create.full.clone"""', 'value': 'value'}), "(cls.apiclient, storageid=pool.id, name=\n 'vmware.create.full.clone', value=value)\n", (10849, 10934), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((12000, 12042), 'marvin.cloudstackAPI.listInfrastructure.listInfrastructureCmd', 'listInfrastructure.listInfrastructureCmd', ([], {}), '()\n', (12040, 12042), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((12794, 12817), 'marvin.lib.utils.validateList', 'validateList', (['templates'], {}), '(templates)\n', (12806, 12817), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((30867, 30879), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (30877, 30879), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((3409, 3465), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""endpointe.url"""'}), "(cls.apiclient, name='endpointe.url')\n", (3428, 3465), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((3850, 3925), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""cloud.kubernetes.service.enabled"""'}), "(cls.apiclient, name='cloud.kubernetes.service.enabled')\n", (3869, 3925), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((8063, 8075), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (8073, 8075), False, 'from marvin.lib.utils import cleanup_resources, validateList, random_gen\n'), ((13332, 13359), 'marvin.lib.base.Template', 'Template', (['template.__dict__'], {}), '(template.__dict__)\n', (13340, 13359), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((7590, 7656), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': 'cls.cks_template_name_key'}), '(cls.apiclient, name=cls.cks_template_name_key)\n', (7609, 7656), False, 'from marvin.lib.base import Template, ServiceOffering, Account, StoragePool, Configurations\n'), ((36239, 36271), 'marvin.cloudstackAPI.deleteNetwork.deleteNetworkCmd', 'deleteNetwork.deleteNetworkCmd', ([], {}), '()\n', (36269, 36271), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n'), ((35992, 36040), 'marvin.cloudstackAPI.destroyVirtualMachine.destroyVirtualMachineCmd', 'destroyVirtualMachine.destroyVirtualMachineCmd', ([], {}), '()\n', (36038, 36040), False, 'from marvin.cloudstackAPI import listInfrastructure, listTemplates, listKubernetesSupportedVersions, addKubernetesSupportedVersion, deleteKubernetesSupportedVersion, listKubernetesClusters, createKubernetesCluster, stopKubernetesCluster, startKubernetesCluster, deleteKubernetesCluster, upgradeKubernetesCluster, scaleKubernetesCluster, destroyVirtualMachine, deleteNetwork\n')] |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Filename: MPL11.py
# Project: dap
# Author: <NAME>
# Created: Friday, 26th February 2021 9:23:41 am
# License: BSD 3-clause "New" or "Revised" License
# Copyright (c) 2021 <NAME>
# Last Modified: Friday, 26th February 2021 9:23:42 am
# Modified By: <NAME>
from __future__ import print_function, division, absolute_import
import copy
from .base import DAPDataModel, Template
from .MPL10 import MILESHC_MASTARHC2, SPX, HYB10, VOR10, MPL10_maps, MPL10_models, binid_properties
from marvin.utils.datamodel.maskbit import get_maskbits
# update Template for MPL-11
MILESHC_MASTARSSP = Template('MILESHC-MASTARSSP',
description=('Stellar kinematic templates from the MILES library. '
'Stellar continuum template derived from a subset of the'
'MaStar Simple Stellar Population models; '
'used during emission-line fits.'))
MPL11_maps = copy.deepcopy(MPL10_maps)
MPL11_models = copy.deepcopy(MPL10_models)
# MPL-11 DapDataModel goes here
MPL11 = DAPDataModel('3.1.0', aliases=['MPL-11', 'MPL11', 'DR17'],
bintypes=[SPX, HYB10, VOR10],
templates=[MILESHC_MASTARHC2, MILESHC_MASTARSSP],
excluded_daptypes=['SPX-MILESHC-MASTARHC2', 'VOR10-MILESHC-MASTARHC2'],
properties=MPL11_maps,
models=MPL11_models,
bitmasks=get_maskbits('MPL-11'),
default_bintype='HYB10',
default_template='MILESHC-MASTARSSP',
property_table='SpaxelProp11',
default_binid=copy.deepcopy(binid_properties[0]),
default_mapmask=['NOCOV', 'UNRELIABLE', 'DONOTUSE'],
qual_flag='DAPQUAL')
| [
"marvin.utils.datamodel.maskbit.get_maskbits"
] | [((1042, 1067), 'copy.deepcopy', 'copy.deepcopy', (['MPL10_maps'], {}), '(MPL10_maps)\n', (1055, 1067), False, 'import copy\n'), ((1083, 1110), 'copy.deepcopy', 'copy.deepcopy', (['MPL10_models'], {}), '(MPL10_models)\n', (1096, 1110), False, 'import copy\n'), ((1543, 1565), 'marvin.utils.datamodel.maskbit.get_maskbits', 'get_maskbits', (['"""MPL-11"""'], {}), "('MPL-11')\n", (1555, 1565), False, 'from marvin.utils.datamodel.maskbit import get_maskbits\n'), ((1759, 1793), 'copy.deepcopy', 'copy.deepcopy', (['binid_properties[0]'], {}), '(binid_properties[0])\n', (1772, 1793), False, 'import copy\n')] |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Filename: MPL9.py
# Project: dap
# Author: <NAME>
# Created: Monday, 4th November 2019 2:32:54 pm
# License: BSD 3-clause "New" or "Revised" License
# Copyright (c) 2019 <NAME>
# Last Modified: Monday, 11th November 2019 3:56:19 pm
# Modified By: <NAME>
from __future__ import print_function, division, absolute_import
import copy
from astropy import units as u
from marvin.utils.datamodel.maskbit import get_maskbits
from .base import DAPDataModel, Template, spaxel as spaxel_unit, reindex_channels
from .base import Model, Channel, MultiChannelProperty
from .MPL6 import SPX, HYB10, VOR10, MPL6_maps, binid_properties
from .MPL6 import MPL6_emline_channels, oii_channel, oiid_channel
from .MPL6 import MPL6_specindex_channels
from .MPL8 import SPX, HYB10, VOR10, MPL8_maps
from .MPL8 import MPL8_models, MPL8_emline_channels
# update Template for MPL-8
MILESHC_MASTARHC = Template('MILESHC-MASTARHC',
description=('Stellar kinematic templates from the MILES library. '
'Stellar continuum template derived from high-res spectra '
'from the MaStar stellary library, used during emission-line fits.'))
emline_channels = copy.deepcopy(MPL8_emline_channels)
MPL8_specindex_channels = copy.deepcopy(MPL6_specindex_channels)
updated_maps = copy.deepcopy(MPL8_maps)
# new coo channels
coo_channel = Channel('r_h_kpc', formats={'string': 'R/(h/kpc)'}, idx=2)
for t in updated_maps:
if t.name in ['spx_ellcoo', 'bin_lwellcoo']:
t.append_channel(coo_channel, at_index=2, unit=u.kpc / u.h)
# new emission line channels
new_channels = [
Channel('ariii_7137', formats={'string': 'ArIII 7137',
'latex': r'$\forb{Ar\,III}\;\lambda 7137$'}, idx=28),
Channel('ariii_7753', formats={'string': 'ArIII 7753',
'latex': r'$\forb{Ar\,III}\;\lambda 7753$'}, idx=29),
Channel('hei_7067', formats={'string': 'HeI 7067',
'latex': r'$\forb{He\,I}\;\lambda 7067$'}, idx=27),
Channel('h11_3771', formats={'string': 'H11 3771',
'latex': r'$\forb{H\,11}\;\lambda 3771$'}, idx=3),
Channel('h12_3751', formats={'string': 'H12 3751',
'latex': r'$\forb{H\,12}\;\lambda 3751$'}, idx=2),
Channel('siii_9071', formats={'string': 'SIII 9071',
'latex': r'$\forb{S\,III}\;\lambda 9071$'}, idx=31),
Channel('siii_9533', formats={'string': 'SIII 9533',
'latex': r'$\forb{S\,III}\;\lambda 9533$'}, idx=33),
Channel('peps_9548', formats={'string': 'P-epsilon 9548',
'latex': r'P$\epsilon\;\lambda 9548$'}, idx=34),
Channel('peta_9017', formats={'string': 'P-eta 9017',
'latex': r'P$\eta\;\lambda 9017$'}, idx=30),
Channel('pzet_9231', formats={'string': 'P-zeta 9231',
'latex': r'P$\zeta\;\lambda 9231$'}, idx=32),
]
# create new MPL9 channels and reindex
tmp = emline_channels + new_channels
idx_list = ['oii_3729', 'h12_3751', 'h11_3771', 'hthe_3798', 'heta_3836', 'neiii_3869', 'hei_3889',
'hzet_3890', 'neiii_3968', 'heps_3971', 'hdel_4102', 'hgam_4341', 'heii_4687', 'hb_4862',
'oiii_4960', 'oiii_5008', 'ni_5199', 'ni_5201', 'hei_5877', 'oi_6302', 'oi_6365',
'nii_6549', 'ha_6564', 'nii_6585', 'sii_6718', 'sii_6732', 'hei_7067', 'ariii_7137',
'ariii_7753', 'peta_9017', 'siii_9071', 'pzet_9231', 'siii_9533', 'peps_9548']
MPL9_emline_channels = reindex_channels(tmp, names=idx_list, starting_idx=1)
# update existing emline properties with new channel list
for m in updated_maps:
if 'emline' in m.name and '_fom' not in m.name:
unit, scale = m[0].unit, m[0].unit.scale
params = {'ivar': m[0].ivar, 'mask': m[0].mask, 'formats': m[0].formats,
'pixmask_flag': m[0].pixmask_flag}
scale = unit.scale
oii = oiid_channel if 'd' in m.channels[0].name else oii_channel
chans = [oii] + MPL9_emline_channels
m.update_channels(chans, unit=unit, scale=scale, **params)
# new properties
new_properties = [
# New Emission Line extensions
MultiChannelProperty('emline_sew_cnt', ivar=False, mask=False,
channels=[oiid_channel] + MPL9_emline_channels,
formats={'string': 'Continuum of Summed EW'},
unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit, scale=1e-17,
binid=binid_properties[3],
description='Continuum used for summed-flux equivalent width measurement'),
MultiChannelProperty('emline_gew_cnt', ivar=False, mask=False,
channels=[oii_channel] + MPL9_emline_channels,
formats={'string': 'Continuum of Gaussian-fit EW'},
unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit, scale=1e-17,
binid=binid_properties[3],
description='Continuum used for Gaussian-fit equivalent width measurement'),
# New Spectral Index extensions
MultiChannelProperty('specindex_bcen', ivar=False, mask=False,
channels=MPL8_specindex_channels,
formats={'string': 'Flux-weighted center: blue sideband',
'latex': r'Flux-weighted center: blue sideband'},
description='Flux-weighted center of the blue sideband in '
'the spectral-index measurement'),
MultiChannelProperty('specindex_bcnt', ivar=False, mask=False,
channels=MPL8_specindex_channels,
formats={'string': 'Continuum: blue sideband',
'latex': r'Continuum: blue sideband'},
description='Continuum level in the blue sideband used in '
'the spectral-index measurement'),
MultiChannelProperty('specindex_rcen', ivar=False, mask=False,
channels=MPL8_specindex_channels,
formats={'string': 'Flux-weighted center: red sideband',
'latex': r'Flux-weighted center: red sideband'},
description='Flux-weighted center of the red sideband in '
'the spectral-index measurement'),
MultiChannelProperty('specindex_rcnt', ivar=False, mask=False,
channels=MPL8_specindex_channels,
formats={'string': 'Continuum: red sideband',
'latex': r'Continuum: red sideband'},
description='Continuum level in the red sideband used in '
'the spectral-index measurement'),
MultiChannelProperty('specindex_model', ivar=False, mask=False,
channels=MPL8_specindex_channels,
formats={'string': 'Best-fit Index Measurement',
'latex': r'Best-fit Index Measurement'},
description='Index measurement made using the best-fitting '
'stellar continuum model')
]
MPL9_maps = updated_maps + new_properties
# MPL-9 DapDataModel goes here
MPL9 = DAPDataModel('2.4.1', aliases=['MPL-9', 'MPL9'],
bintypes=[SPX, HYB10, VOR10],
db_only=[HYB10],
templates=[MILESHC_MASTARHC],
properties=MPL9_maps,
models=MPL8_models,
bitmasks=get_maskbits('MPL-9'),
default_bintype='HYB10',
default_template='MILESHC-MASTARHC',
property_table='SpaxelProp9',
default_binid=copy.deepcopy(binid_properties[0]),
default_mapmask=['NOCOV', 'UNRELIABLE', 'DONOTUSE'],
qual_flag='DAPQUAL')
| [
"marvin.utils.datamodel.maskbit.get_maskbits"
] | [((1287, 1322), 'copy.deepcopy', 'copy.deepcopy', (['MPL8_emline_channels'], {}), '(MPL8_emline_channels)\n', (1300, 1322), False, 'import copy\n'), ((1349, 1387), 'copy.deepcopy', 'copy.deepcopy', (['MPL6_specindex_channels'], {}), '(MPL6_specindex_channels)\n', (1362, 1387), False, 'import copy\n'), ((1403, 1427), 'copy.deepcopy', 'copy.deepcopy', (['MPL8_maps'], {}), '(MPL8_maps)\n', (1416, 1427), False, 'import copy\n'), ((7893, 7914), 'marvin.utils.datamodel.maskbit.get_maskbits', 'get_maskbits', (['"""MPL-9"""'], {}), "('MPL-9')\n", (7905, 7914), False, 'from marvin.utils.datamodel.maskbit import get_maskbits\n'), ((8102, 8136), 'copy.deepcopy', 'copy.deepcopy', (['binid_properties[0]'], {}), '(binid_properties[0])\n', (8115, 8136), False, 'import copy\n')] |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# @Author: <NAME> (<EMAIL>)
# @Date: 2018-07-08
# @Filename: vacs.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: <NAME>
# @Last modified time: 2018-07-09 17:27:59
import importlib
import astropy.io.fits
import pytest
from marvin.contrib.vacs import VACMixIn
from marvin.tools.maps import Maps
class TestVACs(object):
def test_subclasses(self):
assert len(VACMixIn.__subclasses__()) > 0
def test_mangahi(self):
my_map = Maps('7443-12701')
assert hasattr(my_map, 'vacs')
#assert my_map.vacs.mangahi is not None # figure out how to test based on release
def test_vac_container(self):
my_map = Maps('8485-1901')
assert my_map.vacs.__class__.__name__ == 'VACContainer'
assert list(my_map.vacs) is not None
def test_vacs_return(self, plateifu, release):
if release in ['MPL-4', 'MPL-5', 'MPL-6', 'MPL-8']:
pytest.skip()
vacs = VACMixIn.__subclasses__()
for vac in vacs:
for include_class in vac.include:
__ = importlib.import_module(str(include_class.__module__))
obj = include_class(plateifu, release=release)
assert hasattr(obj, 'vacs')
assert hasattr(obj.vacs, vac.name)
assert getattr(obj.vacs, vac.name) is not None
@pytest.mark.xfail(reason="will not work with tested releases it does not have")
class TestMangaHI(object):
def test_return_type(self, plateifu):
my_map = Maps(plateifu)
assert isinstance(my_map.vacs.HI, object)
| [
"marvin.contrib.vacs.VACMixIn.__subclasses__",
"marvin.tools.maps.Maps"
] | [((1440, 1519), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""will not work with tested releases it does not have"""'}), "(reason='will not work with tested releases it does not have')\n", (1457, 1519), False, 'import pytest\n'), ((555, 573), 'marvin.tools.maps.Maps', 'Maps', (['"""7443-12701"""'], {}), "('7443-12701')\n", (559, 573), False, 'from marvin.tools.maps import Maps\n'), ((758, 775), 'marvin.tools.maps.Maps', 'Maps', (['"""8485-1901"""'], {}), "('8485-1901')\n", (762, 775), False, 'from marvin.tools.maps import Maps\n'), ((1041, 1066), 'marvin.contrib.vacs.VACMixIn.__subclasses__', 'VACMixIn.__subclasses__', ([], {}), '()\n', (1064, 1066), False, 'from marvin.contrib.vacs import VACMixIn\n'), ((1608, 1622), 'marvin.tools.maps.Maps', 'Maps', (['plateifu'], {}), '(plateifu)\n', (1612, 1622), False, 'from marvin.tools.maps import Maps\n'), ((1011, 1024), 'pytest.skip', 'pytest.skip', ([], {}), '()\n', (1022, 1024), False, 'import pytest\n'), ((477, 502), 'marvin.contrib.vacs.VACMixIn.__subclasses__', 'VACMixIn.__subclasses__', ([], {}), '()\n', (500, 502), False, 'from marvin.contrib.vacs import VACMixIn\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Network migration test with Nuage VSP SDN plugin
"""
# Import Local Modules
from nuageTestCase import nuageTestCase
from marvin.lib.base import (Account, Host)
from marvin.lib.utils import is_server_ssh_ready
from marvin.cloudstackAPI import updateZone
# Import System Modules
from nose.plugins.attrib import attr
import time
import base64
import unittest
import re
class Services:
"""Test network services
"""
def __init__(self):
self.services = {
"shared_network_offering": {
"name": "MySharedOffering-shared",
"displaytext": "MySharedOffering",
"guestiptype": "Shared",
"supportedservices": "Dhcp,Dns,UserData",
"specifyVlan": "True",
"specifyIpRanges": "True",
"traffictype": "GUEST",
"tags": "native",
"serviceProviderList": {
"Dhcp": "VirtualRouter",
"Dns": "VirtualRouter",
"UserData": "VirtualRouter"
}
}
}
class TestNuageMigration(nuageTestCase):
"""Test Native to Nuage Migration
"""
@classmethod
def setUpClass(cls):
super(TestNuageMigration, cls).setUpClass()
cls.services = Services().services
if not hasattr(cls.vsp_physical_network, "tags") \
or cls.vsp_physical_network.tags != 'nuage':
raise unittest.SkipTest("Require migrateACS configuration - skip")
# create a native vpc offering
cls.native_vpc_offering = cls.create_VpcOffering(cls.test_data
["vpc_offering"])
# create a nuage vpc offering
cls.nuage_vpc_offering = \
cls.create_VpcOffering(cls.test_data["nuagevsp"]["vpc_offering"])
# tier network offerings
cls.nuage_vpc_network_offering = \
cls.create_NetworkOffering(cls.test_data["nuagevsp"]
["vpc_network_offering"])
cls.native_vpc_network_offering = \
cls.create_NetworkOffering(cls.test_data
["nw_offering_isolated_vpc"])
# create a Nuage isolated network offering with vr
cls.nuage_isolated_network_offering = cls.create_NetworkOffering(
cls.test_data["nuagevsp"]["isolated_network_offering"], True)
# create a Nuage isolated network offering with vr and persistent
cls.nuage_isolated_network_offering_persistent = \
cls.create_NetworkOffering(
cls.test_data["nuagevsp"]
["isolated_network_offering_persistent"],
True)
# create a Nuage isolated network offering without vr
cls.nuage_isolated_network_offering_without_vr = \
cls.create_NetworkOffering(
cls.test_data["nuagevsp"]
["isolated_network_offering_without_vr"],
True)
# create a Nuage isolated network offering without vr but persistent
cls.nuage_isolated_network_offering_without_vr_persistent = \
cls.create_NetworkOffering(
cls.test_data["nuagevsp"]
["isolated_network_offering_without_vr_persistent"],
True)
# create a native isolated network offering
cls.native_isolated_network_offering = cls.create_NetworkOffering(
cls.test_data["isolated_network_offering"], True)
# create a native persistent isolated network offering
cls.native_isolated_network_offering_persistent = \
cls.create_NetworkOffering(
cls.test_data["nw_off_isolated_persistent"], True)
# create a native persistent staticNat isolated network offering
cls.native_isolated_network_staticnat_offering_persistent = \
cls.create_NetworkOffering(
cls.test_data["isolated_staticnat_network_offering"], True)
# create a Native shared network offering
cls.native_shared_network_offering = cls.create_NetworkOffering(
cls.services["shared_network_offering"], False)
# create a Nuage shared network offering
cls.nuage_shared_network_offering = cls.create_NetworkOffering(
cls.test_data["nuagevsp"]["shared_nuage_network_offering"],
False)
cls._cleanup = [
cls.nuage_isolated_network_offering,
cls.nuage_isolated_network_offering_persistent,
cls.nuage_isolated_network_offering_without_vr,
cls.nuage_isolated_network_offering_without_vr_persistent,
cls.native_isolated_network_offering,
cls.native_isolated_network_offering_persistent,
cls.native_vpc_offering,
cls.nuage_vpc_offering,
cls.nuage_vpc_network_offering,
cls.native_vpc_network_offering,
cls.native_shared_network_offering,
cls.nuage_shared_network_offering
]
return
def setUp(self):
# Create an account
self.account = Account.create(self.api_client,
self.test_data["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account]
return
def migrate_network(self, nw_off, network, resume=False):
return network.migrate(self.api_client, nw_off.id, resume)
def migrate_vpc(self, vpc, vpc_offering,
network_offering_map, resume=False):
return vpc.migrate(self.api_client,
vpc_offering.id,
network_offering_map, resume)
def verify_pingtovmipaddress(self, ssh, pingtovmipaddress):
"""verify ping to ipaddress of the vm and retry 3 times"""
successfull_ping = False
nbr_retries = 0
max_retries = 5
cmd = 'ping -c 2 ' + pingtovmipaddress
while not successfull_ping and nbr_retries < max_retries:
self.debug("ping vm by ipaddress with command: " + cmd)
outputlist = ssh.execute(cmd)
self.debug("command is executed properly " + cmd)
completeoutput = str(outputlist).strip('[]')
self.debug("complete output is " + completeoutput)
if '2 received' in completeoutput:
self.debug("PASS as vm is pingeable: " + completeoutput)
successfull_ping = True
else:
self.debug("FAIL as vm is not pingeable: " + completeoutput)
time.sleep(3)
nbr_retries = nbr_retries + 1
if not successfull_ping:
self.fail("FAILED TEST as excepted value not found in vm")
def verify_pingtovmhostname(self, ssh, pingtovmhostname):
"""verify ping to hostname of the vm and retry 3 times"""
successfull_ping = False
nbr_retries = 0
max_retries = 5
cmd = 'ping -c 2 ' + pingtovmhostname
while not successfull_ping and nbr_retries < max_retries:
self.debug("ping vm by hostname with command: " + cmd)
outputlist = ssh.execute(cmd)
self.debug("command is executed properly " + cmd)
completeoutput = str(outputlist).strip('[]')
self.debug("complete output is " + completeoutput)
if '2 received' in completeoutput:
self.debug("PASS as vm is pingeable: " + completeoutput)
successfull_ping = True
else:
self.debug("FAIL as vm is not pingeable: " + completeoutput)
time.sleep(3)
nbr_retries = nbr_retries + 1
if not successfull_ping:
self.fail("FAILED TEST as excepted value not found in vm")
def update_userdata(self, vm, expected_user_data):
updated_user_data = base64.b64encode(expected_user_data)
vm.update(self.api_client, userdata=updated_user_data)
return expected_user_data
def get_userdata_url(self, vm):
self.debug("Getting user data url")
nic = vm.nic[0]
gateway = str(nic.gateway)
self.debug("Gateway: " + gateway)
user_data_url = 'curl "http://' + gateway + ':80/latest/user-data"'
return user_data_url
def define_cloudstack_managementip(self):
# get cloudstack managementips from cfg file
config = self.getClsConfig()
return [config.mgtSvr[0].mgtSvrIp, config.mgtSvr[1].mgtSvrIp]
def cloudstack_connection_vsd(self, connection="up",
cscip=["csc-1", "csc-2"]):
self.debug("SSH into cloudstack management server(s), setting "
"connection to VSD as %s " % connection)
try:
for ip in cscip:
csc_ssh_client = is_server_ssh_ready(
ipaddress=ip,
port=22,
username="root",
password="<PASSWORD>",
retries=2
)
self.debug("SSH is successful for cloudstack management "
"server with IP %s" % ip)
if connection == "down":
cmd = "iptables -A OUTPUT -p tcp --dport 8443 -j DROP"
else:
cmd = "iptables -D OUTPUT -p tcp --dport 8443 -j DROP"
self.execute_cmd(csc_ssh_client, cmd)
except Exception as e:
self.debug("Setting cloudstack management server(s) connection %s "
"to VSD fails with exception %s" % (connection, e))
def verify_cloudstack_host_state_up(self, state):
nbr_retries = 0
max_retries = 30
self.debug("Verify state by list hosts type=L2Networking")
result = Host.list(self.api_client, type="L2Networking")
while result[0].state != state and nbr_retries < max_retries:
time.sleep(5)
result = Host.list(self.api_client, type="L2Networking")
nbr_retries = nbr_retries + 1
if nbr_retries == max_retries:
self.debug("TIMEOUT - state of list hosts unchanged")
def verifymigrationerrortext(self, errortext, expectstr):
if expectstr in errortext:
self.debug("Migrate_network fails with expected errortext %s",
errortext)
else:
self.fail("Migrate_network fails but test expects "
"other errortext %s", expectstr)
@attr(tags=["migrateACS", "novms"],
required_hardware="false")
def test_01_native_to_nuage_network_migration_novms(self):
"""
Verify Migration for an isolated network without VMs
1. create multiple native non-persistent isolated network
2. move to nuage non-persistent isolated network
3. move to native persistent network, check VR state
4. move to nuage persistent network, check VR state
"""
isolated_network = self.create_Network(
self.native_isolated_network_offering, gateway="10.0.0.1",
netmask="255.255.255.0")
isolated_network2 = self.create_Network(
self.native_isolated_network_offering, gateway="10.1.0.1",
netmask="255.255.255.0")
shared_network = self.create_Network(
self.native_shared_network_offering, gateway="10.3.0.1",
netmask="255.255.255.0", vlan=1201)
try:
self.migrate_network(
self.nuage_shared_network_offering,
shared_network, resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "NetworkOfferingId can be upgraded only for the " \
"network of type Isolated"
self.verifymigrationerrortext(errortext, expectstr)
try:
self.migrate_network(
self.nuage_shared_network_offering,
isolated_network, resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Can't upgrade from network offering"
self.verifymigrationerrortext(errortext, expectstr)
self.nuage_isolated_network_offering.update(self.api_client,
state="Disabled")
self.validate_NetworkOffering(
self.nuage_isolated_network_offering, state="Disabled")
try:
self.migrate_network(
self.nuage_isolated_network_offering,
isolated_network, resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate network as the specified network " \
"offering is not enabled."
self.verifymigrationerrortext(errortext, expectstr)
self.nuage_isolated_network_offering.update(self.api_client,
state="Enabled")
self.validate_NetworkOffering(
self.nuage_isolated_network_offering, state="Enabled")
self.migrate_network(
self.nuage_isolated_network_offering, isolated_network,
resume=True)
self.verify_vsd_network_not_present(isolated_network, None)
self.migrate_network(
self.native_isolated_network_offering_persistent, isolated_network)
self.verify_vsd_network_not_present(isolated_network, None)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
try:
self.migrate_network(
self.nuage_vpc_offering, isolated_network, resume=False)
except Exception as e:
self.debug("Migration fails with %s" % e)
try:
self.migrate_network(
self.nuage_vpc_network_offering, isolated_network,
resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate network as the specified network " \
"offering is a VPC offering"
self.verifymigrationerrortext(errortext, expectstr)
self.migrate_network(
self.nuage_isolated_network_offering_persistent, isolated_network)
self.verify_vsd_network(self.domain.id, isolated_network, None)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
self.verify_vsd_router(vr)
with self.assertRaises(Exception):
self.verify_vsd_network(self.domain.id, isolated_network2, None)
self.add_resource_tag(
self.native_isolated_network_offering_persistent.id,
"NetworkOffering", "RelatedNetworkOffering",
self.native_isolated_network_offering.id)
result = self.list_resource_tag(
self.native_isolated_network_offering_persistent.id,
"NetworkOffering", "RelatedNetworkOffering")
if result[0].value != self.native_isolated_network_offering.id:
self.fail("Listed resource value does not match with stored"
" resource value!")
self.delete_resource_tag(
self.native_isolated_network_offering_persistent.id,
"NetworkOffering")
empty = self.list_resource_tag(
self.native_isolated_network_offering_persistent.id,
"NetworkOffering", "RelatedNetworkOffering")
if empty:
self.fail("clean up of resource values did was not successful!")
@attr(tags=["migrateACS", "stoppedvms"],
required_hardware="false")
def test_02_native_to_nuage_network_migration_stoppedvms(self):
"""
Verify Migration for an isolated network with stopped VMs
1. create multiple native non-persistent isolated network
2. deploy vm and stop vm
3. move to nuage non-persistent isolated network
4. deploy vm and stop vm
5. move to native persistent network, check VR state
6. deploy vm and stop vm
7. move to nuage persistent network, check VR state
"""
isolated_network = self.create_Network(
self.native_isolated_network_offering, gateway="10.0.0.1",
netmask="255.255.255.0")
vm_1 = self.create_VM(isolated_network)
vm_1.stop(self.api_client)
self.migrate_network(
self.nuage_isolated_network_offering, isolated_network)
vm_1.delete(self.api_client, expunge=True)
vm_2 = self.create_VM(isolated_network)
vm_2.stop(self.api_client)
self.verify_vsd_network(self.domain.id, isolated_network, None)
self.migrate_network(
self.native_isolated_network_offering_persistent, isolated_network)
self.verify_vsd_network_not_present(isolated_network, None)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
vm_2.delete(self.api_client, expunge=True)
vm_3 = self.create_VM(isolated_network)
vm_3.stop(self.api_client)
self.migrate_network(
self.nuage_isolated_network_offering_persistent, isolated_network)
self.verify_vsd_network(self.domain.id, isolated_network, None)
vr2 = self.get_Router(isolated_network)
self.check_Router_state(vr2, "Running")
self.verify_vsd_router(vr2)
self.verify_vsd_network(self.domain.id, isolated_network, None)
@attr(tags=["migrateACS", "nonpersist"],
required_hardware="false")
def test_03_migrate_native_nonpersistent_network_to_nuage_traffic(self):
"""
Verify traffic after Migration of a non-persistent isolated network
1. create native non-persistent isolated network
2. move to nuage non-persistent isolated network
3. Spin VM's and verify traffic provided by Nuage
"""
for i in range(1, 3):
isolated_network = self.create_Network(
self.native_isolated_network_offering, gateway="10.1.0.1",
netmask="255.255.255.0", account=self.account)
try:
self.migrate_network(
self.nuage_vpc_network_offering,
isolated_network, resume=False)
except Exception as e:
errortext = re.search(".*errortext\s*:\s*u?'([^']+)'.*",
e.message).group(1)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate network as the specified network " \
"offering is a VPC offering"
self.verifymigrationerrortext(errortext, expectstr)
self.migrate_network(
self.nuage_isolated_network_offering_without_vr,
isolated_network, resume=True)
self.migrate_network(
self.nuage_isolated_network_offering_without_vr,
isolated_network, resume=False)
self.verify_vsd_network_not_present(isolated_network, None)
self.debug("Deploying a VM in the created Isolated network...")
vm_1 = self.create_VM(isolated_network)
self.validate_Network(isolated_network, state="Implemented")
self.check_VM_state(vm_1, state="Running")
vm_2 = self.create_VM(isolated_network)
self.check_VM_state(vm_2, state="Running")
# VSD verification
self.verify_vsd_network(self.domain.id, isolated_network)
# self.verify_vsd_router(vr_1)
self.verify_vsd_vm(vm_1)
self.verify_vsd_vm(vm_2)
# Creating Static NAT rule
self.debug("Creating Static NAT rule for the deployed VM in the "
"created Isolated network...")
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.validate_PublicIPAddress(public_ip, isolated_network)
self.create_StaticNatRule_For_VM(vm_1, public_ip, isolated_network)
self.validate_PublicIPAddress(
public_ip, isolated_network, static_nat=True, vm=vm_1)
fw_rule = self.create_FirewallRule(
public_ip, self.test_data["ingress_rule"])
# VSD verification for Static NAT functionality
self.verify_vsd_floating_ip(isolated_network, vm_1,
public_ip.ipaddress)
self.verify_vsd_firewall_rule(fw_rule)
# Ssh into the VM via floating ip
vm_public_ip = public_ip.ipaddress.ipaddress
try:
vm_1.ssh_ip = vm_public_ip
vm_1.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_1.username = self.test_data["virtual_machine"]["username"]
vm_1.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_1.ssh_ip, vm_1.password))
ssh = vm_1.get_ssh_client(ipaddress=vm_public_ip)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, vm_2.ipaddress)
vm_1.delete(self.api_client, expunge=True)
vm_2.delete(self.api_client, expunge=True)
isolated_network.delete(self.api_client)
self.debug("Number of loops %s" % i)
@attr(tags=["migrateACS", "persist"],
required_hardware="false")
def test_04_migrate_native_persistentnetwork_to_nuage_traffic(self):
"""
Verify traffic after Migration of a persistent isolated network
1. create native persistent isolated network
2. move to nuage persistent isolated network without VR
3. Spin VM's and verify traffic provided by Nuage
"""
for i in range(1, 3):
isolated_network = self.create_Network(
self.native_isolated_network_offering_persistent,
gateway="10.2.0.1",
netmask="255.255.255.0", account=self.account)
self.verify_vsd_network_not_present(isolated_network, None)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
csc_ips = self.define_cloudstack_managementip()
self.cloudstack_connection_vsd(connection="down", cscip=csc_ips)
self.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
self.debug("Migrate_network fails if connection ACS VSD is down")
self.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
self.verify_cloudstack_host_state_up("Alert")
try:
self.migrate_network(
self.nuage_isolated_network_offering_without_vr_persistent,
isolated_network, resume=False)
except Exception as e:
errortext = re.search(".*errortext\s*:\s*u?'([^']+)'.*",
e.message).group(1)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to implement network (with specified id) " \
"elements and resources as a part of network update"
self.verifymigrationerrortext(errortext, expectstr)
self.cloudstack_connection_vsd(connection="up", cscip=csc_ips)
self.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
self.debug("Migrate_network resumes if connection ACS VSD is up")
self.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
self.verify_cloudstack_host_state_up("Up")
try:
self.migrate_network(
self.nuage_isolated_network_offering_without_vr_persistent,
isolated_network, resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate network as previous migration " \
"left this network in transient condition. " \
"Specify resume as true."
self.verifymigrationerrortext(errortext, expectstr)
self.migrate_network(
self.nuage_isolated_network_offering_without_vr_persistent,
isolated_network, resume=True)
self.verify_vsd_network(self.domain.id, isolated_network, None)
with self.assertRaises(Exception):
self.get_Router(isolated_network)
self.debug("Deploying a VM in the created Isolated network...")
vm_1 = self.create_VM(isolated_network)
self.validate_Network(isolated_network, state="Implemented")
with self.assertRaises(Exception):
self.get_Router(isolated_network)
self.check_VM_state(vm_1, state="Running")
vm_2 = self.create_VM(isolated_network)
self.check_VM_state(vm_2, state="Running")
# VSD verification
self.verify_vsd_network(self.domain.id, isolated_network)
self.verify_vsd_vm(vm_1)
self.verify_vsd_vm(vm_2)
# Creating Static NAT rule
self.debug("Creating Static NAT rule for the deployed VM in the "
"created Isolated network...")
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.validate_PublicIPAddress(public_ip, isolated_network)
self.create_StaticNatRule_For_VM(vm_1, public_ip, isolated_network)
self.validate_PublicIPAddress(
public_ip, isolated_network, static_nat=True, vm=vm_1)
fw_rule = self.create_FirewallRule(
public_ip, self.test_data["ingress_rule"])
# VSD verification for Static NAT functionality
self.verify_vsd_floating_ip(isolated_network, vm_1,
public_ip.ipaddress)
self.verify_vsd_firewall_rule(fw_rule)
# Ssh into the VM via floating ip
vm_public_ip = public_ip.ipaddress.ipaddress
try:
vm_1.ssh_ip = vm_public_ip
vm_1.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_1.username = self.test_data["virtual_machine"]["username"]
vm_1.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_1.ssh_ip, vm_1.password))
ssh = vm_1.get_ssh_client(ipaddress=vm_public_ip)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, vm_2.ipaddress)
vm_1.delete(self.api_client, expunge=True)
vm_2.delete(self.api_client, expunge=True)
isolated_network.delete(self.api_client)
self.debug("Number of loops %s" % i)
@attr(tags=["migrateACS", "nicmigration"],
required_hardware="false")
def test_05_native_to_nuage_nic_migration(self):
"""
Verify Nic migration of GuestVm in an isolated network
1. create multiple native non-persistent isolated network
2. populate network with 2 vm's
3. enable static nat + create FW rule
4. move to nuage non-persistent isolated network, check:
- public ip
- FW rules
- VR
- VM's
"""
isolated_network = self.create_Network(
self.native_isolated_network_offering, gateway="10.0.0.1",
netmask="255.255.255.0")
isolated_network2 = self.create_Network(
self.native_isolated_network_offering, gateway="10.1.0.1",
netmask="255.255.255.0")
vm1 = self.create_VM(isolated_network)
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.create_StaticNatRule_For_VM(vm1, public_ip, isolated_network)
firewall_rule = self.create_FirewallRule(public_ip)
vm2 = self.create_VM(isolated_network)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
self.migrate_network(
self.nuage_isolated_network_offering, isolated_network)
self.verify_vsd_network(self.domain.id, isolated_network, None)
self.verify_vsd_vm(vm1)
self.verify_vsd_floating_ip(isolated_network, vm1, public_ip.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule)
self.verify_vsd_vm(vm2)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
self.verify_vsd_router(vr)
with self.assertRaises(Exception):
self.verify_vsd_network(self.domain.id, isolated_network2, None)
@attr(tags=["migrateACS", "nonpersistnic"],
required_hardware="false")
def test_06_migrate_native_nonpersistent_nic_to_nuage_traffic(self):
"""
Verify Nic migration of GuestVm in a non-persistent isolated network
1. create two native non-persistent isolated networks
2. Deploy 2 vm's in first network
3. enable static nat + create FW rule
4. move first network to nuage non-persistent isolated network,
check:
- public ip
- FW rules
- VR
- VM's
5. Destroy and expunge 1 VM in first network
6. Deploy a new VM in first network and check traffic
7. Move second network to nuage non-persistent isolated network,
check:
- public ip
- FW rules
- VR
- VM's
8. Deploy 2 vm in second network , move it and check
9. Cleanup
"""
isolated_network = self.create_Network(
self.native_isolated_network_offering, gateway="10.3.0.1",
netmask="255.255.255.0")
isolated_network2 = self.create_Network(
self.native_isolated_network_offering, gateway="10.4.0.1",
netmask="255.255.255.0")
vm_1 = self.create_VM(isolated_network)
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.create_StaticNatRule_For_VM(vm_1, public_ip, isolated_network)
firewall_rule = self.create_FirewallRule(public_ip)
vm_2 = self.create_VM(isolated_network)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
self.migrate_network(
self.nuage_isolated_network_offering, isolated_network)
self.verify_vsd_network(self.domain.id, isolated_network, None)
self.verify_vsd_vm(vm_1)
self.verify_vsd_floating_ip(isolated_network, vm_1,
public_ip.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule)
self.verify_vsd_vm(vm_2)
vr_3 = self.get_Router(isolated_network)
self.check_Router_state(vr_3, "Running")
self.verify_vsd_router(vr_3)
# VSD verification for Static NAT functionality
self.verify_vsd_floating_ip(isolated_network, vm_1,
public_ip.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule)
# Ssh into the VM via floating ip
vm_public_ip = public_ip.ipaddress.ipaddress
try:
vm_1.ssh_ip = vm_public_ip
vm_1.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_1.username = self.test_data["virtual_machine"]["username"]
vm_1.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_1.ssh_ip, vm_1.password))
ssh = vm_1.get_ssh_client(ipaddress=vm_public_ip)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, vm_2.ipaddress)
vm_2.delete(self.api_client, expunge=True)
with self.assertRaises(Exception):
self.verify_vsd_vm(vm_2)
vm_4 = self.create_VM(isolated_network)
self.verify_vsd_vm(vm_4)
with self.assertRaises(Exception):
self.verify_vsd_network(self.domain.id, isolated_network2, None)
vm_3 = self.create_VM(isolated_network2)
vr_2 = self.get_Router(isolated_network2)
self.check_Router_state(vr_2, "Running")
# Ssh into the VM via floating ip
vm_public_ip = public_ip.ipaddress.ipaddress
try:
vm_1.ssh_ip = vm_public_ip
vm_1.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_1.username = self.test_data["virtual_machine"]["username"]
vm_1.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_1.ssh_ip, vm_1.password))
ssh = vm_1.get_ssh_client(ipaddress=vm_public_ip)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, vm_4.ipaddress)
vm_1.delete(self.api_client, expunge=True)
vm_4.delete(self.api_client, expunge=True)
isolated_network.delete(self.api_client)
self.migrate_network(
self.nuage_isolated_network_offering_without_vr,
isolated_network2)
public_ip_2 = self.acquire_PublicIPAddress(isolated_network2)
self.create_StaticNatRule_For_VM(vm_3, public_ip_2, isolated_network2)
firewall_rule_2 = self.create_FirewallRule(public_ip_2)
self.verify_vsd_floating_ip(isolated_network2, vm_3,
public_ip_2.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule_2)
self.verify_vsd_network(self.domain.id, isolated_network2, None)
self.verify_vsd_vm(vm_3)
self.verify_vsd_floating_ip(isolated_network2, vm_3,
public_ip_2.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule_2)
with self.assertRaises(Exception):
self.get_Router(isolated_network2)
vm_5 = self.create_VM(isolated_network2)
self.verify_vsd_vm(vm_5)
# Ssh into the VM via floating ip
vm_public_ip_2 = public_ip_2.ipaddress.ipaddress
try:
vm_3.ssh_ip = vm_public_ip_2
vm_3.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_3.username = self.test_data["virtual_machine"]["username"]
vm_3.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_3.ssh_ip, vm_3.password))
ssh = vm_3.get_ssh_client(ipaddress=vm_public_ip_2)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, vm_5.ipaddress)
@attr(tags=["migrateACS", "persistnic"],
required_hardware="false")
def test_07_migrate_native_persistent_nic_to_nuage_traffic(self):
"""
Verify Nic migration of GuestVm in a persistent isolated network
1. create two native persistent isolated networks
2. deploy 2 vm's in this network
3. move to nuage non-persistent isolated network,
4. enable static nat + create FW rule
check:
- public ip
- FW rules
- VR
- VM's
"""
isolated_network = self.create_Network(
self.native_isolated_network_offering_persistent,
gateway="10.5.0.1",
netmask="255.255.255.0")
isolated_network2 = self.create_Network(
self.native_isolated_network_offering_persistent,
gateway="10.6.0.1",
netmask="255.255.255.0")
vm_1 = self.create_VM(isolated_network)
vm_2 = self.create_VM(isolated_network)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
vm_3 = self.create_VM(isolated_network2)
self.migrate_network(
self.nuage_isolated_network_offering_without_vr_persistent,
isolated_network)
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.create_StaticNatRule_For_VM(vm_1, public_ip, isolated_network)
firewall_rule = self.create_FirewallRule(public_ip)
self.verify_vsd_network(self.domain.id, isolated_network, None)
self.verify_vsd_vm(vm_1)
self.verify_vsd_floating_ip(isolated_network, vm_1,
public_ip.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule)
self.verify_vsd_vm(vm_2)
with self.assertRaises(Exception):
self.get_Router(isolated_network)
# Ssh into the VM via floating ip
vm_public_ip = public_ip.ipaddress.ipaddress
try:
vm_1.ssh_ip = vm_public_ip
vm_1.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_1.username = self.test_data["virtual_machine"]["username"]
vm_1.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_1.ssh_ip, vm_1.password))
ssh = vm_1.get_ssh_client(ipaddress=vm_public_ip)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, vm_2.ipaddress)
vm_1.delete(self.api_client, expunge=True)
self.migrate_network(
self.nuage_isolated_network_offering_without_vr_persistent,
isolated_network2)
vm_2.delete(self.api_client, expunge=True)
isolated_network.delete(self.api_client)
self.verify_vsd_network(self.domain.id, isolated_network2, None)
self.verify_vsd_vm(vm_3)
public_ip_2 = self.acquire_PublicIPAddress(isolated_network2)
self.create_StaticNatRule_For_VM(vm_3, public_ip_2, isolated_network2)
firewall_rule_2 = self.create_FirewallRule(public_ip_2)
vm_4 = self.create_VM(isolated_network2)
self.verify_vsd_floating_ip(isolated_network2, vm_3,
public_ip_2.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule_2)
self.verify_vsd_vm(vm_4)
# Ssh into the VM via floating ip
vm_public_ip_2 = public_ip_2.ipaddress.ipaddress
try:
vm_3.ssh_ip = vm_public_ip_2
vm_3.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_3.username = self.test_data["virtual_machine"]["username"]
vm_3.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_3.ssh_ip, vm_3.password))
ssh = vm_3.get_ssh_client(ipaddress=vm_public_ip_2)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh, vm_4.ipaddress)
@attr(tags=["migrateACS", "isomultinic"],
required_hardware="false")
def test_08_migrate_native_multinic_to_nuage_traffic(self):
"""
Verify MultiNic migration of GuestVm with multiple isolated networks
1. create one native non-persistent isolated network
2. create one native persistent isolated network
3. deploy 2 vm's in both these network
4. move non-persist to nuage non-persistent isolated network,
5. move persist to nuage persistent isolated network
6. enable static nat + create FW rule
check:
- public ip
- FW rules
- VR
- VM's
"""
isolated_network = self.create_Network(
self.native_isolated_network_offering,
gateway="10.7.0.1",
netmask="255.255.255.0")
isolated_network2 = self.create_Network(
self.native_isolated_network_offering_persistent,
gateway="10.8.0.1",
netmask="255.255.255.0")
vm_1 = self.create_VM([isolated_network, isolated_network2])
vm_2 = self.create_VM([isolated_network2, isolated_network])
vr = self.get_Router(isolated_network2)
self.check_Router_state(vr, "Running")
self.migrate_network(
self.nuage_isolated_network_offering_without_vr,
isolated_network)
vm_3 = self.create_VM(isolated_network)
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.create_StaticNatRule_For_VM(vm_3, public_ip, isolated_network)
firewall_rule = self.create_FirewallRule(public_ip)
self.verify_vsd_network(self.domain.id, isolated_network, None)
self.verify_vsd_vm(vm_3)
self.verify_vsd_floating_ip(isolated_network, vm_3,
public_ip.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule)
# Ssh into the VM via floating ip
vm_public_ip = public_ip.ipaddress.ipaddress
try:
vm_3.ssh_ip = vm_public_ip
vm_3.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_3.username = self.test_data["virtual_machine"]["username"]
vm_3.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_3.ssh_ip, vm_3.password))
ssh = vm_3.get_ssh_client(ipaddress=vm_public_ip)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
defaultipaddress = \
[nic.ipaddress for nic in vm_1.nic if nic.isdefault][0]
self.verify_pingtovmipaddress(ssh, defaultipaddress)
self.migrate_network(
self.nuage_isolated_network_offering_without_vr_persistent,
isolated_network2)
vm_3.delete(self.api_client, expunge=True)
public_ip.delete(self.api_client)
vm_4 = self.create_VM(isolated_network2)
public_ip_2 = self.acquire_PublicIPAddress(isolated_network2)
self.create_StaticNatRule_For_VM(vm_4, public_ip_2, isolated_network2)
firewall_rule_2 = self.create_FirewallRule(public_ip_2)
self.verify_vsd_floating_ip(isolated_network2, vm_4,
public_ip_2.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule_2)
self.verify_vsd_vm(vm_4)
# Ssh into the VM via floating ip
vm_public_ip_2 = public_ip_2.ipaddress.ipaddress
try:
vm_4.ssh_ip = vm_public_ip_2
vm_4.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_4.username = self.test_data["virtual_machine"]["username"]
vm_4.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_4.ssh_ip, vm_4.password))
ssh = vm_4.get_ssh_client(ipaddress=vm_public_ip_2)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
defaultipaddress2 = \
[nic.ipaddress for nic in vm_2.nic if nic.isdefault][0]
self.verify_pingtovmipaddress(ssh, defaultipaddress2)
@attr(tags=["migrateACS", "persiststaticnat"],
required_hardware="false")
def test_09_migrate_native_persist_staticnat_to_nuage_traffic(self):
"""
Verify StaticNat migration of GuestVm in a persistent isolated network
1. create one native persistent isolated network offering
2. with Dhcp,SourceNat,StaticNat,Dns,Userdata and Firewall
3. create one native persistent isolated network with above
4. deploy 2 vm's in this network
5. In a loop
enable staticnat on first vm and open port 22 for ssh
login to vm1 and ping vm2
verify userdata in Native
move to nuage persistent isolated network,
deploy 2 new vm's in this network
enable staticnat on new vm and open port 22 for ssh
check:
- public ips
- FW rules
- VR
- VM's ping old and new VM's
- verify userdata in Nuage
- Release public ips
move back to native persistent isolated network,
"""
isolated_network = self.create_Network(
self.native_isolated_network_staticnat_offering_persistent,
gateway="10.9.0.1",
netmask="255.255.255.0", account=self.account)
vm_1 = self.create_VM(isolated_network)
vm_2 = self.create_VM(isolated_network)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
for i in range(1, 3):
self.debug("+++++Starting again as Native in Loop+++++")
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.create_StaticNatRule_For_VM(vm_1, public_ip, isolated_network)
firewall_rule = self.create_FirewallRule(public_ip)
self.migrate_network(
self.nuage_isolated_network_offering_persistent,
isolated_network)
self.verify_vsd_network(self.domain.id, isolated_network, None)
self.verify_vsd_vm(vm_1)
self.verify_vsd_floating_ip(isolated_network, vm_1,
public_ip.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule)
self.verify_vsd_vm(vm_2)
vm_3 = self.create_VM(isolated_network)
public_ip_2 = self.acquire_PublicIPAddress(isolated_network)
self.create_StaticNatRule_For_VM(vm_3,
public_ip_2,
isolated_network)
firewall_rule_2 = self.create_FirewallRule(public_ip_2)
vm_4 = self.create_VM(isolated_network)
self.verify_vsd_floating_ip(isolated_network, vm_3,
public_ip_2.ipaddress)
self.verify_vsd_firewall_rule(firewall_rule_2)
self.verify_vsd_vm(vm_3)
self.verify_vsd_vm(vm_4)
# Ssh into the VM via floating ip
vm_public_ip_2 = public_ip_2.ipaddress.ipaddress
try:
vm_3.ssh_ip = vm_public_ip_2
vm_3.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_3.username = self.test_data["virtual_machine"]["username"]
vm_3.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_3.ssh_ip, vm_3.password))
ssh2 = vm_3.get_ssh_client(ipaddress=vm_public_ip_2)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh2, vm_1.ipaddress)
self.verify_pingtovmipaddress(ssh2, vm_4.ipaddress)
self.verify_pingtovmipaddress(ssh2, vm_2.ipaddress)
self.debug("Updating the running vm_3 with new user data...")
expected_user_data2 = self.update_userdata(vm_3, "hellonuage vm3")
self.debug("SSHing into the vm_3 for verifying its user data...")
user_data_cmd = self.get_userdata_url(vm_3)
self.debug("Getting user data with command: " + user_data_cmd)
actual_user_data2 = self.execute_cmd(ssh2, user_data_cmd)
self.debug("Actual user data - " + actual_user_data2 +
", Expected user data - " + expected_user_data2)
self.assertEqual(actual_user_data2, expected_user_data2,
"Un-expected VM (VM_3) user data")
vm_3.delete(self.api_client, expunge=True)
vm_4.delete(self.api_client, expunge=True)
public_ip_2.delete(self.api_client)
# ReleaseIP as get_ssh_client fails when migrating back to native
public_ip.delete(self.api_client)
self.debug("++++++++Migrating network back to native+++++++")
self.migrate_network(
self.native_isolated_network_staticnat_offering_persistent,
isolated_network)
@attr(tags=["migrateACS", "vpcnovms"],
required_hardware="false")
def test_10_migrate_native_vpc(self):
vpc = self.create_Vpc(self.native_vpc_offering)
network = self.create_Network(self.native_vpc_network_offering,
vpc=vpc)
self.create_VM(network)
network_offering_map = \
[{"networkid": network.id,
"networkofferingid":
self.nuage_isolated_network_offering_without_vr.id}]
try:
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=False)
except Exception as e:
errortext = re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "can't be used for VPC networks"
self.verifymigrationerrortext(errortext, expectstr)
network_offering_map = \
[{"networkid": network.id,
"networkofferingid": self.nuage_vpc_network_offering.id}]
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map)
self.verify_vsd_network(self.domain.id, network, vpc)
@attr(tags=["migrateACS", "vpcstaticnat"],
required_hardware="false")
def test_11_migrate_native_vpc_staticnat_to_nuage_traffic(self):
"""
Verify StaticNat migration of GuestVm in a vpc network
1. create one native vpc network offering
2. create one native vpc tier network offering
3. with Dhcp,SourceNat,StaticNat,Dns,Userdata and NetworkACL
4. create one vpc with above native vpc network offering
5. create one native vpc tier network in above vpc
6. deploy 2 vm's in this tier network
7. In a loop
enable staticnat on first vm and ssh into vm
login to vm1 and ping vm2
verify userdata in Native
move to nuage vpc tier networkoffering,
deploy 2 new vm's in this network
enable staticnat on new vm and ssh into vm
check:
- public ips
- NetworkACL rules
- VR
- VM's ping old and new VM's
- verify userdata in Nuage
- Release public ips
move back to native vpc tier network offering,
"""
cmd = updateZone.updateZoneCmd()
cmd.id = self.zone.id
cmd.domain = "vpc.com"
self.api_client.updateZone(cmd)
self.debug("Creating Native VSP VPC offering with Static NAT service "
"provider as VPCVR...")
native_vpc_off = self.create_VpcOffering(
self.test_data["vpc_offering_reduced"])
self.validate_VpcOffering(native_vpc_off, state="Enabled")
self.debug("Creating a VPC with Static NAT service provider as "
"VpcVirtualRouter")
vpc = self.create_Vpc(native_vpc_off, cidr='10.1.0.0/16')
self.validate_Vpc(vpc, state="Enabled")
self.debug("Creating native VPC Network Tier offering "
"with Static NAT service provider as VPCVR")
native_tiernet_off = self.create_NetworkOffering(
self.test_data["nw_offering_reduced_vpc"])
self.validate_NetworkOffering(native_tiernet_off, state="Enabled")
acl_list = self.create_NetworkAclList(
name="acl", description="acl", vpc=vpc)
acl_item = self.create_NetworkAclRule(
self.test_data["ingress_rule"], acl_list=acl_list)
self.create_NetworkAclRule(
self.test_data["icmprule"], acl_list=acl_list)
self.debug("Creating a VPC tier network with Static NAT service")
vpc_tier = self.create_Network(native_tiernet_off,
gateway='10.1.0.1',
vpc=vpc,
acl_list=acl_list)
self.validate_Network(vpc_tier, state="Implemented")
self.debug("Creating 2nd VPC tier network with Static NAT service")
vpc_2ndtier = self.create_Network(native_tiernet_off,
gateway='10.1.128.1',
vpc=vpc,
acl_list=acl_list)
self.validate_Network(vpc_2ndtier, state="Implemented")
vpc_vr = self.get_Router(vpc_tier)
self.check_Router_state(vpc_vr, state="Running")
self.debug("Deploying a VM in the created VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm1"
self.test_data["virtual_machine"]["name"] = "vpcvm1"
vpc_vm_1 = self.create_VM(vpc_tier)
self.check_VM_state(vpc_vm_1, state="Running")
self.debug("Deploying another VM in the created VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm2"
self.test_data["virtual_machine"]["name"] = "vpcvm2"
vpc_vm_2 = self.create_VM(vpc_tier)
self.check_VM_state(vpc_vm_2, state="Running")
self.debug("Deploying a VM in the 2nd VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm12"
self.test_data["virtual_machine"]["name"] = "vpcvm12"
vpc_vm_12 = self.create_VM(vpc_2ndtier)
self.check_VM_state(vpc_vm_2, state="Running")
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
for i in range(1, 3):
self.debug("+++++Starting again as Native in Loop+++++")
self.debug("Creating Static NAT rule for the deployed VM "
"in the created VPC network...")
public_ip_1 = self.acquire_PublicIPAddress(vpc_tier, vpc=vpc)
self.validate_PublicIPAddress(public_ip_1, vpc_tier)
self.create_StaticNatRule_For_VM(vpc_vm_1, public_ip_1, vpc_tier)
self.validate_PublicIPAddress(
public_ip_1, vpc_tier, static_nat=True, vm=vpc_vm_1)
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.nuage_vpc_network_offering.id},
{"networkid": vpc_2ndtier.id,
"networkofferingid": self.nuage_vpc_network_offering.id}]
csc_ips = self.define_cloudstack_managementip()
self.cloudstack_connection_vsd(connection="down",
cscip=csc_ips)
self.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
self.debug("Migrate_vpc fails when connection ACS VSD is down")
self.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
self.verify_cloudstack_host_state_up("Alert")
try:
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to implement network (with specified id) " \
"elements and resources as a part of network update"
self.verifymigrationerrortext(errortext, expectstr)
self.cloudstack_connection_vsd(connection="up",
cscip=csc_ips)
self.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
self.debug("Migrate_vpc resumes when connection ACS VSD is up")
self.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
self.verify_cloudstack_host_state_up("Up")
try:
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate VPC as previous migration " \
"left this VPC in transient condition. " \
"Specify resume as true."
self.verifymigrationerrortext(errortext, expectstr)
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.nuage_vpc_network_offering.id},
{"networkid": vpc_2ndtier.id,
"networkofferingid":
self.nuage_isolated_network_offering.id}]
try:
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=True)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "can't be used for VPC networks for network"
self.verifymigrationerrortext(errortext, expectstr)
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.nuage_vpc_network_offering.id},
{"networkid": vpc_2ndtier.id,
"networkofferingid": self.nuage_vpc_network_offering.id}]
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=True)
# checking after successful migrate vpc, migrate still succeeds
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=True)
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=False)
# VSD verification after VPC migration functionality
self.verify_vsd_network(self.domain.id, vpc_tier, vpc)
self.verify_vsd_vm(vpc_vm_1)
self.verify_vsd_vm(vpc_vm_2)
self.verify_vsd_floating_ip(
vpc_tier, vpc_vm_1, public_ip_1.ipaddress, vpc=vpc)
self.verify_vsd_firewall_rule(acl_item)
# self.verify_vsd_firewall_rule(acl_item2)
self.verify_vsd_vm(vpc_vm_12)
self.test_data["virtual_machine"]["displayname"] = "vpcvm3"
self.test_data["virtual_machine"]["name"] = "vpcvm3"
vpc_vm_3 = self.create_VM(vpc_tier)
public_ip_2 = self.acquire_PublicIPAddress(vpc_tier, vpc=vpc)
self.create_StaticNatRule_For_VM(vpc_vm_3,
public_ip_2,
vpc_tier)
self.test_data["virtual_machine"]["displayname"] = "vpcvm4"
self.test_data["virtual_machine"]["name"] = "vpcvm4"
vpc_vm_4 = self.create_VM(vpc_tier)
self.verify_vsd_floating_ip(vpc_tier, vpc_vm_3,
public_ip_2.ipaddress, vpc=vpc)
self.verify_vsd_vm(vpc_vm_3)
self.verify_vsd_vm(vpc_vm_4)
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
vm_public_ip_2 = public_ip_2.ipaddress.ipaddress
try:
vpc_vm_3.ssh_ip = vm_public_ip_2
vpc_vm_3.ssh_port = \
self.test_data["virtual_machine"]["ssh_port"]
vpc_vm_3.username = \
self.test_data["virtual_machine"]["username"]
vpc_vm_3.password = \
self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vpc_vm_3.ssh_ip, vpc_vm_3.password))
ssh2 = vpc_vm_3.get_ssh_client(ipaddress=vm_public_ip_2)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
self.verify_pingtovmipaddress(ssh2, vpc_vm_1.ipaddress)
self.verify_pingtovmhostname(ssh2, "vpcvm1")
self.verify_pingtovmipaddress(ssh2, vpc_vm_4.ipaddress)
self.verify_pingtovmhostname(ssh2, "vpcvm4")
self.verify_pingtovmipaddress(ssh2, vpc_vm_2.ipaddress)
self.verify_pingtovmhostname(ssh2, "vpcvm2")
self.debug("Updating the running vm_3 with new user data...")
expected_user_data2 = self.update_userdata(vpc_vm_3,
"hellonuage vm3")
self.debug("SSHing into the vm_3 for verifying its user data...")
user_data_cmd = self.get_userdata_url(vpc_vm_3)
self.debug("Getting user data with command: " + user_data_cmd)
actual_user_data2 = self.execute_cmd(ssh2, user_data_cmd)
self.debug("Actual user data - " + actual_user_data2 +
", Expected user data - " + expected_user_data2)
self.assertEqual(actual_user_data2, expected_user_data2,
"Un-expected VM (VM_3) user data")
self.verify_pingtovmipaddress(ssh2, vpc_vm_12.ipaddress)
self.verify_pingtovmhostname(ssh2, "vpcvm12")
vpc_vm_3.delete(self.api_client, expunge=True)
vpc_vm_4.delete(self.api_client, expunge=True)
public_ip_2.delete(self.api_client)
# ReleaseIP as get_ssh_client fails when migrating back to native
public_ip_1.delete(self.api_client)
self.debug("++++++++Migrating network back to native+++++++")
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": native_tiernet_off.id},
{"networkid": vpc_2ndtier.id,
"networkofferingid": native_tiernet_off.id}]
self.migrate_vpc(vpc, native_vpc_off,
network_offering_map)
@attr(tags=["migrateACS", "vpcmultinic"],
required_hardware="false")
def test_12_migrate_native_vpc_multinic_to_nuage_traffic(self):
"""
Verify MultiNic migration of GuestVm in multiple networks
1. create one native vpc network offering
2. create one native vpc tier network offering
3. with Dhcp,SourceNat,StaticNat,Dns,Userdata and NetworkACL
4. create one vpc with above native vpc network offering
5. create one native vpc tier network in above vpc
6. create 2nd isolated network
7. deploy 2 vm's in both networks
8. move to nuage vpc tier networkoffering,
9. deploy vm3 in vpc tier network
10. enable staticnat on first vm and ssh into vm
11. login to vm3 and ping vm1 nic1
12. move isolated network to nuage networkoffering,
13. deploy vm4 in 2nd vpc tier network
14. enable staticnat on new vm4 and ssh into vm
15. login to vm4 and ping vm2 nic1
"""
cmd = updateZone.updateZoneCmd()
cmd.id = self.zone.id
cmd.domain = "vpc.com"
self.api_client.updateZone(cmd)
self.debug("Creating Native VSP VPC offering with Static NAT service "
"provider as VPCVR...")
native_vpc_off = self.create_VpcOffering(
self.test_data["vpc_offering_reduced"])
self.validate_VpcOffering(native_vpc_off, state="Enabled")
self.debug("Creating a VPC with Static NAT service provider as "
"VpcVirtualRouter")
vpc = self.create_Vpc(native_vpc_off, cidr='10.1.0.0/16')
self.validate_Vpc(vpc, state="Enabled")
self.debug("Creating native VPC Network Tier offering "
"with Static NAT service provider as VPCVR")
native_tiernet_off = self.create_NetworkOffering(
self.test_data["nw_offering_reduced_vpc"])
self.validate_NetworkOffering(native_tiernet_off, state="Enabled")
acl_list = self.create_NetworkAclList(
name="acl", description="acl", vpc=vpc)
acl_item = self.create_NetworkAclRule(
self.test_data["ingress_rule"], acl_list=acl_list)
self.create_NetworkAclRule(
self.test_data["icmprule"], acl_list=acl_list)
self.debug("Creating a VPC tier network with Static NAT service")
vpc_tier = self.create_Network(native_tiernet_off,
gateway='10.1.0.1',
vpc=vpc,
acl_list=acl_list)
self.validate_Network(vpc_tier, state="Implemented")
self.debug("Creating 2nd VPC tier network with Static NAT service")
vpc_2ndtier = self.create_Network(native_tiernet_off,
gateway='10.1.128.1',
vpc=vpc,
acl_list=acl_list)
self.validate_Network(vpc_2ndtier, state="Implemented")
vpc_vr = self.get_Router(vpc_tier)
self.check_Router_state(vpc_vr, state="Running")
isolated_network = self.create_Network(
self.native_isolated_network_staticnat_offering_persistent,
gateway="10.10.0.1",
netmask="255.255.255.0", account=self.account)
self.debug("Creating isolated network with Static NAT service")
self.debug("Deploying a multinic VM in both networks")
self.test_data["virtual_machine"]["displayname"] = "vpcvm1"
self.test_data["virtual_machine"]["name"] = "vpcvm1"
vpc_vm_1 = self.create_VM([vpc_tier, isolated_network])
self.check_VM_state(vpc_vm_1, state="Running")
self.debug("Deploying another VM in both networks other defaultnic")
self.test_data["virtual_machine"]["displayname"] = "vpcvm2"
self.test_data["virtual_machine"]["name"] = "vpcvm2"
vpc_vm_2 = self.create_VM([isolated_network, vpc_tier])
self.check_VM_state(vpc_vm_2, state="Running")
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
network_offering_map_fault = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.nuage_vpc_network_offering.id}]
try:
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map_fault, resume=False)
except Exception as e:
errortext = re.search(".*errortext\s*:\s*u?'([^']+)'.*",
e.message).group(1)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate VPC as the specified " \
"tierNetworkOfferings is not complete"
self.verifymigrationerrortext(errortext, expectstr)
try:
self.migrate_network(self.nuage_isolated_network_offering,
vpc_tier, resume=False)
except Exception as e:
errortext = re.search(".*errortext\s*:\s*u?'([^']+)'.*",
e.message).group(1)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate network as the specified " \
"network is a vpc tier. Use migrateVpc."
self.verifymigrationerrortext(errortext, expectstr)
network_offering_map_fault2 = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.nuage_vpc_network_offering.id},
{"networkid": vpc_2ndtier.id,
"networkofferingid": self.nuage_isolated_network_offering.id}]
try:
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map_fault2, resume=True)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "can't be used for VPC networks for network"
self.verifymigrationerrortext(errortext, expectstr)
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.nuage_vpc_network_offering.id},
{"networkid": vpc_2ndtier.id,
"networkofferingid": self.nuage_vpc_network_offering.id}]
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=True)
self.debug("Deploying another VM in the created VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm3"
self.test_data["virtual_machine"]["name"] = "vpcvm3"
vpc_vm_3 = self.create_VM(vpc_tier)
self.check_VM_state(vpc_vm_3, state="Running")
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
self.debug("Creating Static NAT rule for the deployed VM "
"in the created VPC network...")
public_ip_1 = self.acquire_PublicIPAddress(vpc_tier, vpc=vpc)
self.validate_PublicIPAddress(public_ip_1, vpc_tier)
self.create_StaticNatRule_For_VM(vpc_vm_3, public_ip_1, vpc_tier)
self.validate_PublicIPAddress(
public_ip_1, vpc_tier, static_nat=True, vm=vpc_vm_3)
# VSD verification after VPC migration functionality
self.verify_vsd_network(self.domain.id, vpc_tier, vpc)
self.verify_vsd_vm(vpc_vm_3)
self.verify_vsd_floating_ip(
vpc_tier, vpc_vm_3, public_ip_1.ipaddress, vpc=vpc)
self.verify_vsd_firewall_rule(acl_item)
# self.verify_vsd_vm(vpc_vm_1)
vm_public_ip_1 = public_ip_1.ipaddress.ipaddress
try:
vpc_vm_3.ssh_ip = vm_public_ip_1
vpc_vm_3.ssh_port = \
self.test_data["virtual_machine"]["ssh_port"]
vpc_vm_3.username = \
self.test_data["virtual_machine"]["username"]
vpc_vm_3.password = \
self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vpc_vm_3.ssh_ip, vpc_vm_1.password))
ssh = vpc_vm_3.get_ssh_client(ipaddress=vm_public_ip_1)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
defaultipaddress = \
[nic.ipaddress for nic in vpc_vm_1.nic if nic.isdefault][0]
self.verify_pingtovmipaddress(ssh, defaultipaddress)
vpc_vm_3.delete(self.api_client, expunge=True)
public_ip_1.delete(self.api_client)
self.migrate_network(
self.nuage_isolated_network_offering_without_vr,
isolated_network)
self.test_data["virtual_machine"]["displayname"] = "vm4"
self.test_data["virtual_machine"]["name"] = "vm4"
vm_4 = self.create_VM(isolated_network)
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
self.debug("Creating Static NAT rule for the deployed VM "
"in the created VPC network...")
public_ip_2 = self.acquire_PublicIPAddress(isolated_network)
self.validate_PublicIPAddress(public_ip_1, isolated_network)
self.create_StaticNatRule_For_VM(vm_4, public_ip_2, isolated_network)
self.validate_PublicIPAddress(
public_ip_2, isolated_network, static_nat=True, vm=vm_4)
firewall_rule_2 = self.create_FirewallRule(public_ip_2)
self.verify_vsd_network(self.domain.id, isolated_network)
self.verify_vsd_floating_ip(isolated_network, vm_4,
public_ip_2.ipaddress)
self.verify_vsd_vm(vm_4)
self.verify_vsd_firewall_rule(firewall_rule_2)
# self.verify_vsd_vm(vpc_vm_2)
vm_public_ip_2 = public_ip_2.ipaddress.ipaddress
try:
vm_4.ssh_ip = vm_public_ip_2
vm_4.ssh_port = self.test_data["virtual_machine"]["ssh_port"]
vm_4.username = self.test_data["virtual_machine"]["username"]
vm_4.password = self.test_data["virtual_machine"]["password"]
self.debug("SSHing into VM: %s with %s" %
(vm_4.ssh_ip, vm_4.password))
ssh2 = vm_4.get_ssh_client(ipaddress=vm_public_ip_2)
except Exception as e:
self.fail("SSH into VM failed with exception %s" % e)
defaultipaddress2 = \
[nic.ipaddress for nic in vpc_vm_2.nic if nic.isdefault][0]
self.verify_pingtovmipaddress(ssh2, defaultipaddress2)
@attr(tags=["migrateACS", "guestvmip2"],
required_hardware="false")
def test_13_verify_guestvmip2_when_migrating_to_nuage(self):
"""
Verify migration of GuestVm with ip .2 still works
when migrating isolated or vpc tier networks
"""
isolated_network = self.create_Network(
self.native_isolated_network_offering,
gateway="10.13.0.1",
netmask="255.255.255.248", account=self.account)
self.test_data["virtual_machine"]["ipaddress"] = "10.13.0.2"
vm_11 = self.create_VM(isolated_network)
self.test_data["virtual_machine"]["ipaddress"] = "10.13.0.3"
vm_12 = self.create_VM(isolated_network)
self.test_data["virtual_machine"]["ipaddress"] = "10.13.0.4"
vm_13 = self.create_VM(isolated_network)
self.test_data["virtual_machine"]["ipaddress"] = "10.13.0.5"
vm_14 = self.create_VM(isolated_network)
self.test_data["virtual_machine"]["ipaddress"] = None
vm_15 = self.create_VM(isolated_network)
try:
self.migrate_network(
self.nuage_isolated_network_offering_persistent,
isolated_network, resume=False)
except Exception as e:
errortext = re.search(".*errortext\s*:\s*u?'([^']+)'.*",
e.message).group(1)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to implement network (with specified id) " \
"elements and resources as a part of network update"
self.verifymigrationerrortext(errortext, expectstr)
try:
self.migrate_network(
self.nuage_isolated_network_offering_without_vr,
isolated_network, resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate network as previous migration " \
"left this network in transient condition. " \
"Specify resume as true."
self.verifymigrationerrortext(errortext, expectstr)
try:
self.migrate_network(
self.nuage_isolated_network_offering_without_vr,
isolated_network, resume=True)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to resume migrating network as network offering " \
"does not match previously specified network offering"
self.verifymigrationerrortext(errortext, expectstr)
vm_13.delete(self.api_client, expunge=True)
try:
self.migrate_network(
self.nuage_isolated_network_offering_without_vr,
isolated_network, resume=True)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to resume migrating network as network offering " \
"does not match previously specified network offering"
self.verifymigrationerrortext(errortext, expectstr)
try:
self.migrate_network(
self.nuage_isolated_network_offering_persistent,
isolated_network, resume=False)
except Exception as e:
errortext = \
re.search(".*errortext\s*:\s*u?(['\"])([^\\1]+)\\1.*",
e.message).group(2)
self.debug("Migration fails with %s" % errortext)
expectstr = "Failed to migrate network as previous migration " \
"left this network in transient condition. " \
"Specify resume as true."
self.verifymigrationerrortext(errortext, expectstr)
self.migrate_network(
self.nuage_isolated_network_offering_persistent,
isolated_network, resume=True)
self.verify_vsd_network(self.domain.id, isolated_network, None)
self.verify_vsd_vm(vm_11)
self.verify_vsd_vm(vm_12)
self.verify_vsd_vm(vm_14)
self.verify_vsd_vm(vm_15)
cmd = updateZone.updateZoneCmd()
cmd.id = self.zone.id
cmd.domain = "vpc.com"
self.api_client.updateZone(cmd)
self.debug("Creating Native VSP VPC offering with Static NAT service "
"provider as VPCVR...")
native_vpc_off = self.create_VpcOffering(
self.test_data["vpc_offering_reduced"])
self.validate_VpcOffering(native_vpc_off, state="Enabled")
self.debug("Creating a VPC with Static NAT service provider as "
"VpcVirtualRouter")
vpc = self.create_Vpc(native_vpc_off, cidr='10.1.0.0/16')
self.validate_Vpc(vpc, state="Enabled")
self.debug("Creating native VPC Network Tier offering "
"with Static NAT service provider as VPCVR")
native_tiernet_off = self.create_NetworkOffering(
self.test_data["nw_offering_reduced_vpc"])
self.validate_NetworkOffering(native_tiernet_off, state="Enabled")
acl_list = self.create_NetworkAclList(
name="acl", description="acl", vpc=vpc)
self.create_NetworkAclRule(
self.test_data["ingress_rule"], acl_list=acl_list)
self.create_NetworkAclRule(
self.test_data["icmprule"], acl_list=acl_list)
self.debug("Creating a VPC tier network with Static NAT service")
vpc_tier = self.create_Network(native_tiernet_off,
gateway='10.1.1.1',
vpc=vpc,
acl_list=acl_list)
self.validate_Network(vpc_tier, state="Implemented")
vpc_vr = self.get_Router(vpc_tier)
self.check_Router_state(vpc_vr, state="Running")
self.debug("Deploying a VM in a vpc tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm1"
self.test_data["virtual_machine"]["name"] = "vpcvm1"
self.test_data["virtual_machine"]["ipaddress"] = "10.1.1.2"
vpc_vm_1 = self.create_VM(vpc_tier)
self.test_data["virtual_machine"]["ipaddress"] = None
self.check_VM_state(vpc_vm_1, state="Running")
self.debug("Deploying another VM in vpc tier")
self.test_data["virtual_machine"]["displayname"] = "vpcvm2"
self.test_data["virtual_machine"]["name"] = "vpcvm2"
vpc_vm_2 = self.create_VM(vpc_tier)
self.check_VM_state(vpc_vm_2, state="Running")
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.nuage_vpc_network_offering.id}]
self.migrate_vpc(vpc, self.nuage_vpc_offering,
network_offering_map, resume=False)
self.verify_vsd_network(self.domain.id, vpc_tier, vpc)
self.verify_vsd_vm(vpc_vm_1)
self.verify_vsd_vm(vpc_vm_2)
@attr(tags=["migrateACS", "nativeisoonly"],
required_hardware="false")
def test_14_native_to_native_network_migration(self):
"""
Verify Migration for an isolated network nativeOnly
1. create native non-persistent isolated network
2. migrate to native persistent isolated network, check VR state
3. migrate back to native non-persistent network
4. deploy VM in non-persistent isolated network
5. acquire ip and enable staticnat
6. migrate to native persistent isolated network
7. migrate back to native non-persistent network
"""
isolated_network = self.create_Network(
self.native_isolated_network_offering, gateway="10.0.0.1",
netmask="255.255.255.0")
self.migrate_network(
self.native_isolated_network_offering_persistent,
isolated_network, resume=False)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
self.migrate_network(
self.native_isolated_network_offering,
isolated_network, resume=False)
vm_1 = self.create_VM(isolated_network)
vr = self.get_Router(isolated_network)
self.check_Router_state(vr, "Running")
public_ip = self.acquire_PublicIPAddress(isolated_network)
self.create_StaticNatRule_For_VM(vm_1, public_ip, isolated_network)
self.create_FirewallRule(public_ip)
self.migrate_network(
self.native_isolated_network_offering_persistent,
isolated_network, resume=False)
self.migrate_network(
self.native_isolated_network_offering,
isolated_network, resume=False)
@attr(tags=["migrateACS", "nativevpconly"],
required_hardware="false")
def test_15_native_to_native_vpc_migration(self):
"""
Verify Migration for a vpc network nativeOnly
1. create native vpc with 2 tier networks
2. migrate to native vpc, check VR state
3. deploy VM in vpc tier network
4. acquire ip and enable staticnat
5. migrate to native vpc network
"""
cmd = updateZone.updateZoneCmd()
cmd.id = self.zone.id
cmd.domain = "vpc.com"
self.api_client.updateZone(cmd)
self.debug("Creating Native VSP VPC offering with Static NAT service "
"provider as VPCVR...")
native_vpc_off = self.create_VpcOffering(
self.test_data["vpc_offering_reduced"])
self.validate_VpcOffering(native_vpc_off, state="Enabled")
self.debug("Creating a VPC with Static NAT service provider as "
"VpcVirtualRouter")
vpc = self.create_Vpc(native_vpc_off, cidr='10.1.0.0/16')
self.validate_Vpc(vpc, state="Enabled")
self.debug("Creating native VPC Network Tier offering "
"with Static NAT service provider as VPCVR")
native_tiernet_off = self.create_NetworkOffering(
self.test_data["nw_offering_reduced_vpc"])
self.validate_NetworkOffering(native_tiernet_off, state="Enabled")
acl_list = self.create_NetworkAclList(
name="acl", description="acl", vpc=vpc)
self.create_NetworkAclRule(
self.test_data["ingress_rule"], acl_list=acl_list)
self.create_NetworkAclRule(
self.test_data["icmprule"], acl_list=acl_list)
self.debug("Creating a VPC tier network with Static NAT service")
vpc_tier = self.create_Network(native_tiernet_off,
gateway='10.1.0.1',
vpc=vpc,
acl_list=acl_list)
self.validate_Network(vpc_tier, state="Implemented")
self.debug("Creating 2nd VPC tier network with Static NAT service")
vpc_2ndtier = self.create_Network(native_tiernet_off,
gateway='10.1.128.1',
vpc=vpc,
acl_list=acl_list)
self.validate_Network(vpc_2ndtier, state="Implemented")
vpc_vr = self.get_Router(vpc_tier)
self.check_Router_state(vpc_vr, state="Running")
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.native_vpc_network_offering.id},
{"networkid": vpc_2ndtier.id,
"networkofferingid": self.native_vpc_network_offering.id}]
self.migrate_vpc(vpc, self.native_vpc_offering,
network_offering_map, resume=False)
self.debug("Deploying a VM in the created VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm1"
self.test_data["virtual_machine"]["name"] = "vpcvm1"
vpc_vm_1 = self.create_VM(vpc_tier)
self.check_VM_state(vpc_vm_1, state="Running")
self.debug("Deploying another VM in the created VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm2"
self.test_data["virtual_machine"]["name"] = "vpcvm2"
vpc_vm_2 = self.create_VM(vpc_tier)
self.check_VM_state(vpc_vm_2, state="Running")
self.debug("Deploying a VM in the 2nd VPC tier network")
self.test_data["virtual_machine"]["displayname"] = "vpcvm12"
self.test_data["virtual_machine"]["name"] = "vpcvm12"
self.create_VM(vpc_2ndtier)
self.check_VM_state(vpc_vm_2, state="Running")
self.test_data["virtual_machine"]["displayname"] = None
self.test_data["virtual_machine"]["name"] = None
self.debug("Creating Static NAT rule for the deployed VM "
"in the created VPC network...")
public_ip_1 = self.acquire_PublicIPAddress(vpc_tier, vpc=vpc)
self.validate_PublicIPAddress(public_ip_1, vpc_tier)
self.create_StaticNatRule_For_VM(vpc_vm_1, public_ip_1, vpc_tier)
self.validate_PublicIPAddress(
public_ip_1, vpc_tier, static_nat=True, vm=vpc_vm_1)
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.native_vpc_network_offering.id},
{"networkid": vpc_2ndtier.id,
"networkofferingid": self.native_vpc_network_offering.id}]
self.migrate_vpc(vpc, self.native_vpc_offering,
network_offering_map, resume=False)
| [
"marvin.cloudstackAPI.updateZone.updateZoneCmd",
"marvin.lib.base.Account.create",
"marvin.lib.utils.is_server_ssh_ready",
"marvin.lib.base.Host.list"
] | [((11465, 11526), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'novms']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'novms'], required_hardware='false')\n", (11469, 11526), False, 'from nose.plugins.attrib import attr\n'), ((17237, 17303), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'stoppedvms']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'stoppedvms'], required_hardware='false')\n", (17241, 17303), False, 'from nose.plugins.attrib import attr\n'), ((19173, 19239), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'nonpersist']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'nonpersist'], required_hardware='false')\n", (19177, 19239), False, 'from nose.plugins.attrib import attr\n'), ((23214, 23277), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'persist']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'persist'], required_hardware='false')\n", (23218, 23277), False, 'from nose.plugins.attrib import attr\n'), ((28985, 29053), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'nicmigration']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'nicmigration'], required_hardware='false')\n", (28989, 29053), False, 'from nose.plugins.attrib import attr\n'), ((30834, 30903), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'nonpersistnic']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'nonpersistnic'], required_hardware='false')\n", (30838, 30903), False, 'from nose.plugins.attrib import attr\n'), ((37030, 37096), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'persistnic']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'persistnic'], required_hardware='false')\n", (37034, 37096), False, 'from nose.plugins.attrib import attr\n'), ((41224, 41291), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'isomultinic']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'isomultinic'], required_hardware='false')\n", (41228, 41291), False, 'from nose.plugins.attrib import attr\n'), ((45494, 45566), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'persiststaticnat']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'persiststaticnat'], required_hardware='false')\n", (45498, 45566), False, 'from nose.plugins.attrib import attr\n'), ((50609, 50673), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'vpcnovms']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'vpcnovms'], required_hardware='false')\n", (50613, 50673), False, 'from nose.plugins.attrib import attr\n'), ((51901, 51969), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'vpcstaticnat']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'vpcstaticnat'], required_hardware='false')\n", (51905, 51969), False, 'from nose.plugins.attrib import attr\n'), ((65006, 65073), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'vpcmultinic']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'vpcmultinic'], required_hardware='false')\n", (65010, 65073), False, 'from nose.plugins.attrib import attr\n'), ((75801, 75867), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'guestvmip2']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'guestvmip2'], required_hardware='false')\n", (75805, 75867), False, 'from nose.plugins.attrib import attr\n'), ((83273, 83342), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'nativeisoonly']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'nativeisoonly'], required_hardware='false')\n", (83277, 83342), False, 'from nose.plugins.attrib import attr\n'), ((85048, 85117), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['migrateACS', 'nativevpconly']", 'required_hardware': '"""false"""'}), "(tags=['migrateACS', 'nativevpconly'], required_hardware='false')\n", (85052, 85117), False, 'from nose.plugins.attrib import attr\n'), ((5935, 6034), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.test_data['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.test_data['account'], admin=True,\n domainid=self.domain.id)\n", (5949, 6034), False, 'from marvin.lib.base import Account, Host\n'), ((8804, 8840), 'base64.b64encode', 'base64.b64encode', (['expected_user_data'], {}), '(expected_user_data)\n', (8820, 8840), False, 'import base64\n'), ((10758, 10805), 'marvin.lib.base.Host.list', 'Host.list', (['self.api_client'], {'type': '"""L2Networking"""'}), "(self.api_client, type='L2Networking')\n", (10767, 10805), False, 'from marvin.lib.base import Account, Host\n'), ((53099, 53125), 'marvin.cloudstackAPI.updateZone.updateZoneCmd', 'updateZone.updateZoneCmd', ([], {}), '()\n', (53123, 53125), False, 'from marvin.cloudstackAPI import updateZone\n'), ((66035, 66061), 'marvin.cloudstackAPI.updateZone.updateZoneCmd', 'updateZone.updateZoneCmd', ([], {}), '()\n', (66059, 66061), False, 'from marvin.cloudstackAPI import updateZone\n'), ((80424, 80450), 'marvin.cloudstackAPI.updateZone.updateZoneCmd', 'updateZone.updateZoneCmd', ([], {}), '()\n', (80448, 80450), False, 'from marvin.cloudstackAPI import updateZone\n'), ((85499, 85525), 'marvin.cloudstackAPI.updateZone.updateZoneCmd', 'updateZone.updateZoneCmd', ([], {}), '()\n', (85523, 85525), False, 'from marvin.cloudstackAPI import updateZone\n'), ((2246, 2306), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Require migrateACS configuration - skip"""'], {}), "('Require migrateACS configuration - skip')\n", (2263, 2306), False, 'import unittest\n'), ((10888, 10901), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (10898, 10901), False, 'import time\n'), ((10923, 10970), 'marvin.lib.base.Host.list', 'Host.list', (['self.api_client'], {'type': '"""L2Networking"""'}), "(self.api_client, type='L2Networking')\n", (10932, 10970), False, 'from marvin.lib.base import Account, Host\n'), ((7505, 7518), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (7515, 7518), False, 'import time\n'), ((8555, 8568), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (8565, 8568), False, 'import time\n'), ((9758, 9856), 'marvin.lib.utils.is_server_ssh_ready', 'is_server_ssh_ready', ([], {'ipaddress': 'ip', 'port': '(22)', 'username': '"""root"""', 'password': '"""<PASSWORD>"""', 'retries': '(2)'}), "(ipaddress=ip, port=22, username='root', password=\n '<PASSWORD>', retries=2)\n", (9777, 9856), False, 'from marvin.lib.utils import is_server_ssh_ready\n'), ((12634, 12701), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (12643, 12701), False, 'import re\n'), ((13206, 13273), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (13215, 13273), False, 'import re\n'), ((13970, 14037), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (13979, 14037), False, 'import re\n'), ((15468, 15535), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (15477, 15535), False, 'import re\n'), ((51301, 51368), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (51310, 51368), False, 'import re\n'), ((69571, 69628), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*"""', 'e.message'], {}), '(".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*", e.message)\n', (69580, 69628), False, 'import re\n'), ((70113, 70170), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*"""', 'e.message'], {}), '(".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*", e.message)\n', (70122, 70170), False, 'import re\n'), ((70954, 71021), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (70963, 71021), False, 'import re\n'), ((77092, 77149), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*"""', 'e.message'], {}), '(".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*", e.message)\n', (77101, 77149), False, 'import re\n'), ((77702, 77769), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (77711, 77769), False, 'import re\n'), ((78353, 78420), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (78362, 78420), False, 'import re\n'), ((79026, 79093), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (79035, 79093), False, 'import re\n'), ((79647, 79714), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (79656, 79714), False, 'import re\n'), ((20051, 20108), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*"""', 'e.message'], {}), '(".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*", e.message)\n', (20060, 20108), False, 'import re\n'), ((24731, 24788), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*"""', 'e.message'], {}), '(".*errortext\\\\s*:\\\\s*u?\'([^\']+)\'.*", e.message)\n', (24740, 24788), False, 'import re\n'), ((25754, 25821), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (25763, 25821), False, 'import re\n'), ((57796, 57863), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (57805, 57863), False, 'import re\n'), ((58824, 58891), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (58833, 58891), False, 'import re\n'), ((59791, 59858), 're.search', 're.search', (['""".*errortext\\\\s*:\\\\s*u?([\'"])([^\\\\1]+)\\\\1.*"""', 'e.message'], {}), '(\'.*errortext\\\\s*:\\\\s*u?([\\\'"])([^\\\\1]+)\\\\1.*\', e.message)\n', (59800, 59858), False, 'import re\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Test cases for VM/Volume snapshot Test Path
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.lib.utils import (cleanup_resources,
is_snapshot_on_nfs,
validateList)
from marvin.lib.base import (Account,
Cluster,
StoragePool,
DiskOffering,
ServiceOffering,
Host,
Configurations,
Template,
VirtualMachine,
Snapshot,
SnapshotPolicy,
Volume
)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
list_volumes,
list_snapshots,
list_virtual_machines,
createChecksum,
compareChecksum
)
from marvin.sshClient import SshClient
import time
from marvin.codes import (
CLUSTERTAG1,
CLUSTERTAG2,
PASS,
BACKED_UP,
UP)
from threading import Thread
def checkIntegrityOfSnapshot(
self,
snapshotsToRestore,
checksumToCompare,
disk_type="root"):
if disk_type == "root":
# Create template from snapshot
template_from_snapshot = Template.create_from_snapshot(
self.apiclient,
snapshotsToRestore,
self.testdata["template_2"])
self.assertNotEqual(
template_from_snapshot,
None,
"Check if result exists in list item call"
)
time.sleep(60)
# Deploy VM
vm_from_temp = VirtualMachine.create(
self.apiclient,
self.testdata["small"],
templateid=template_from_snapshot.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
self.assertNotEqual(
vm_from_temp,
None,
"Check if result exists in list item call"
)
time.sleep(60)
# Verify contents of ROOT disk match with snapshot
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=checksumToCompare,
disk_type="rootdiskdevice",
virt_machine=vm_from_temp
)
vm_from_temp.delete(self.apiclient)
template_from_snapshot.delete(self.apiclient)
else:
volumeFormSnap = Volume.create_from_snapshot(
self.apiclient,
snapshotsToRestore.id,
self.testdata["volume"],
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
temp_vm = VirtualMachine.create(
self.apiclient,
self.testdata["small"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
temp_vm.attach_volume(
self.apiclient,
volumeFormSnap
)
temp_vm.reboot(self.apiclient)
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=checksumToCompare,
disk_type="datadiskdevice_1",
virt_machine=temp_vm
)
temp_vm.delete(self.apiclient)
volumeFormSnap.delete(self.apiclient)
return
def GetDestinationHost(self,
hostid,
currentHosts,
hostList
):
""" Get destination host in same cluster to migrate
vm to
"""
destinationHost = None
clusterid = None
for host in self.Hosts:
if host.id == hostid:
clusterid = host.clusterid
break
for host in hostList:
if host.clusterid == clusterid:
destinationHost = host
break
return destinationHost
def MigrateRootVolume(self,
vm,
destinationHost,
expectexception=False):
""" Migrate given volume to type of storage pool mentioned in migrateto:
Inputs:
1. volume: Volume to be migrated
2. migrate_to: Scope of desired Storage pool to which volume
is to be migrated
3. expectexception: If exception is expected while migration
"""
if expectexception:
with self.assertRaises(Exception):
VirtualMachine.migrate(
vm,
self.apiclient,
hostid=destinationHost.id,
)
else:
VirtualMachine.migrate(
vm,
self.apiclient,
hostid=destinationHost.id,
)
migrated_vm_response = list_virtual_machines(
self.apiclient,
id=vm.id
)
self.assertEqual(
isinstance(migrated_vm_response, list),
True,
"Check list virtual machines response for valid list"
)
self.assertNotEqual(
migrated_vm_response,
None,
"Check if virtual machine exists in ListVirtualMachines"
)
migrated_vm = migrated_vm_response[0]
vm_list = VirtualMachine.list(
self.apiclient,
id=migrated_vm.id
)
self.assertEqual(
vm_list[0].hostid,
destinationHost.id,
"Check volume is on migrated pool"
)
return
class TestSnapshotsHardning(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestSnapshotsHardning, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
cls.hypervisor = cls.testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
cls._cleanup = []
cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
try:
# Create an account
cls.account = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
# Create user api client of the account
cls.userapiclient = testClient.getUserApiClient(
UserName=cls.account.name,
DomainName=cls.account.domain
)
# Create Service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
)
cls._cleanup.append(cls.service_offering)
cls.service_offering_ha = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
offerha=True
)
cls.disk_offering = DiskOffering.create(
cls.apiclient,
cls.testdata["disk_offering"],
)
cls._cleanup.append(cls.disk_offering)
cls.vm = VirtualMachine.create(
cls.apiclient,
cls.testdata["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
zoneid=cls.zone.id,
diskofferingid=cls.disk_offering.id,
mode=cls.zone.networktype
)
cls._cleanup.append(cls.vm)
cls.root_volume = list_volumes(
cls.userapiclient,
virtualmachineid=cls.vm.id,
type='ROOT',
listall=True
)
cls.data_volume = list_volumes(
cls.userapiclient,
virtualmachineid=cls.vm.id,
type='DATA',
listall=True
)
cls.vm_ha = VirtualMachine.create(
cls.apiclient,
cls.testdata["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering_ha.id,
zoneid=cls.zone.id,
diskofferingid=cls.disk_offering.id,
mode=cls.zone.networktype
)
cls._cleanup.append(cls.vm_ha)
cls._cleanup.append(cls.account)
cls.root_volume_ha = list_volumes(
cls.userapiclient,
virtualmachineid=cls.vm_ha.id,
type='ROOT',
listall=True
)
cls.clusterList = Cluster.list(cls.apiclient)
cls.Hosts = Host.list(cls.apiclient)
cls.exceptionList = []
configs = Configurations.list(
cls.apiclient,
name="snapshot.delta.max")
cls.delta_max = configs[0].value
try:
cls.pools = StoragePool.list(cls.apiclient, zoneid=cls.zone.id)
except Exception as e:
raise unittest.SkipTest(e)
except Exception as e:
cls.tearDownClass()
raise e
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def RestartServer(cls):
"""Restart management server"""
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-management restart"
sshClient.execute(command)
return
def EnableMaintenance(self, hostid):
Host.enableMaintenance(self.apiclient, id=hostid)
return
def StartVM(self, vm):
vm.start(self.apiclient)
return
def RebootVM(self, vm):
vm.reboot(self.apiclient)
return
def StopVM(self, vm):
vm.stop(self.apiclient)
return
def ClearSnapshots(self, snapshots):
if snapshots:
for snap in snapshots:
snap.delete(self.apiclient)
return
def CreateSnapshot(self, root_volume, is_recurring):
"""Create Snapshot"""
try:
if is_recurring:
recurring_snapshot = SnapshotPolicy.create(
self.apiclient,
root_volume.id,
self.testdata["recurring_snapshot"]
)
self.rec_policy_pool.append(recurring_snapshot)
else:
root_vol_snap = Snapshot.create(
self.apiclient,
root_volume.id)
self.snapshot_pool.append(root_vol_snap)
except Exception as e:
self.exceptionList = []
self.exceptionList.append(e)
return
def CreateDeltaSnapshot(self, volume):
for i in range(int(self.delta_max)):
Snapshot.create(
self.apiclient,
volume.id)
return
@attr(tags=["advanced", "basic"], required_hardware="true")
def test_01_snapshot_hardning_kvm(self):
"""snapshot hardning
1. Take VM snapshot then migrate the VM to another host
and again take volume snapshot and check its integrity
2. Verify that snapshot gets created successfully while VM
is getting Migrated to another host
3. Verify that snapshot should succeed after vm's are HA-ed
to different host and also check its integrity
4. Take ROOT volume snapshot and when snapshot is in progress
bring the host down then once the VM is HA-ed
to different host take snapshot of root volume and
Check the integrity of this snapshot
5. Stop the VM, initiate VM snapshot and while snapshot
is still in progress start the VM and check
the integrity of the snapshot
6. Initiate ROOT volume snapshot and while snapshot is
in pregress Stop the VM Verify that the VM stops
successfully and check integrity of snapshot
7. Initiate ROOT volume snapshot and while snapshot is
in pregress Reboot the VM
Verify that the VM reboot successfully and
check integrity of snapshot
8. Initiate ROOT volume snapshot and while snapshot is
in progress create snapshot of the same volume
and check integrity of both the snapshots
9. Initiate snapshot of DATA volume and while snapshot is
in progress detach the volume verify that volume
gets detached successfully also check integrity of snapshot
10. Initiate snapshot of a detached volume and while snapshot is
in progress attach the volume to A VM verify that volume
gets attached successfully also check integrity of snapshot
"""
if self.hypervisor.lower() != "kvm":
self.skipTest("Skip test for Hypervisor other than KVM")
# Step 1
root_volume = list_volumes(
self.userapiclient,
virtualmachineid=self.vm.id,
type='ROOT',
listall=True
)
checksum_root = createChecksum(
service=self.testdata,
virtual_machine=self.vm,
disk=root_volume[0],
disk_type="rootdiskdevice")
Snapshot.create(
self.apiclient,
root_volume[0].id)
snapshots = list_snapshots(
self.apiclient,
volumeid=root_volume[0].id,
listall=True)
destinationHost = Host.listForMigration(
self.apiclient,
virtualmachineid=self.vm.id)
sameClusHosts = Host.list(self.apiclient, virtualmachineid=self.vm.id)
current_host = self.vm.hostid
hostToMigarte = GetDestinationHost(
self,
current_host,
sameClusHosts,
destinationHost)
MigrateRootVolume(self,
self.vm,
hostToMigarte)
Snapshot.create(
self.apiclient,
root_volume[0].id)
snapshots = list_snapshots(
self.apiclient,
volumeid=root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
# Step 2
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume[0],
False))
destinationHost = Host.listForMigration(
self.apiclient,
virtualmachineid=self.vm.id)
migrate_rootvolume_thread = Thread(target=MigrateRootVolume,
args=(self,
self.vm,
destinationHost[0]))
create_snapshot_thread.start()
migrate_rootvolume_thread.start()
create_snapshot_thread.join()
migrate_rootvolume_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
# Step 3
vm_host_id = self.vm_ha.hostid
checksum_root_ha = createChecksum(
service=self.testdata,
virtual_machine=self.vm_ha,
disk=self.root_volume_ha[0],
disk_type="rootdiskdevice")
self.CreateSnapshot(
self.root_volume_ha[0],
False)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume_ha[0].id,
listall=True)
Host.enableMaintenance(self.apiclient, id=vm_host_id)
time.sleep(180)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume_ha[0].id,
listall=True)
Host.cancelMaintenance(self.apiclient, id=vm_host_id)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root_ha)
# Step 4
# Scenario to be tested
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume_ha[0],
False))
host_enable_maint_thread = Thread(
target=Host.enableMaintenance,
args=(
self.apiclient,
vm_host_id))
create_snapshot_thread.start()
host_enable_maint_thread.start()
create_snapshot_thread.join()
host_enable_maint_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
self.CreateSnapshot(self.root_volume_ha[0], False)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume_ha[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root_ha)
Host.cancelMaintenance(self.apiclient, vm_host_id)
# Step 5
self.vm.stop(self.apiclient)
time.sleep(90)
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume[0],
False))
start_vm_thread = Thread(target=self.StartVM,
args=([self.vm]))
create_snapshot_thread.start()
start_vm_thread.start()
create_snapshot_thread.join()
start_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
state = self.dbclient.execute(
"select state from vm_instance where name='%s'" %
self.vm.name)[0][0]
self.assertEqual(
state,
"Running",
"Check if vm has started properly")
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
# Step 6
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume[0],
False))
stop_vm_thread = Thread(target=self.StopVM,
args=([self.vm]))
create_snapshot_thread.start()
stop_vm_thread.start()
create_snapshot_thread.join()
stop_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
state = self.dbclient.execute(
"select state from vm_instance where name='%s'" %
self.vm.name)[0][0]
self.assertEqual(
state,
"Stopped",
"Check if vm has started properly")
self.vm.start(self.apiclient)
time.sleep(180)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
# Step 7
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume[0],
False))
reboot_vm_thread = Thread(target=self.RebootVM,
args=([self.vm]))
create_snapshot_thread.start()
reboot_vm_thread.start()
create_snapshot_thread.join()
reboot_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
state = self.dbclient.execute(
"select state from vm_instance where name='%s'" %
self.vm.name)[0][0]
self.assertEqual(
state,
"Running",
"Check if vm has started properly")
time.sleep(180)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
# Step 8 pending(actual 9)
# Step 9
checksum_data = createChecksum(
service=self.testdata,
virtual_machine=self.vm,
disk=self.data_volume[0],
disk_type="datadiskdevice_1")
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.data_volume[0],
False))
detach_vm_thread = Thread(
target=self.vm.detach_volume,
args=(
self.apiclient,
self.data_volume[0]))
create_snapshot_thread.start()
detach_vm_thread.start()
create_snapshot_thread.join()
detach_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
self.vm.reboot(self.apiclient)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.data_volume[0].id,
listall=True)
data_volume_list = list_volumes(
self.apiclient,
virtualmachineid=self.vm.id,
type='DATA',
listall=True
)
self.assertEqual(
data_volume_list,
None,
"check if volume is detached"
)
checkIntegrityOfSnapshot(
self,
snapshots[0],
checksum_data,
disk_type="data")
# Step 10
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.data_volume[0],
False))
attach_vm_thread = Thread(
target=self.vm.attach_volume,
args=(
self.apiclient,
self.data_volume[0]))
create_snapshot_thread.start()
attach_vm_thread.start()
create_snapshot_thread.join()
attach_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
self.vm.reboot(self.apiclient)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.data_volume[0].id,
listall=True)
data_volume_list = list_volumes(
self.apiclient,
virtualmachineid=self.vm.id,
type='DATA',
listall=True
)
self.assertNotEqual(
data_volume_list,
[],
"check if volume is detached"
)
checkIntegrityOfSnapshot(
self,
snapshots[0],
checksum_root,
disk_type="data")
@attr(tags=["advanced", "basic"], required_hardware="true")
def test_02_snapshot_hardning_xenserver(self):
"""snapshot hardning
1. Take VM snapshot then migrate the VM to another
host and again take
volume snapshot and check its intigrity
2. Verify that snapshot gets created successfully
while VM is getting
Migrated to another host
3. Verify that snapshot should succeed after vm's are
HA-ed to different host
and also check its integrity
4. Take ROOT volume snapshot and when snapshot is
in progress bring the host down
then once the VM is HA-ed to different host
take snapshot of root volume
and Check the integrity of this snapshot
5. Stop the VM, initiate VM snapshot and
while snapshot is still in progress
start the VM and check the integrity of the snapshot
6. Initiate ROOT volume snapshot and while snapshot is
in pregress Stop the VM
Verify that the VM stops successfully and
check integrity of snapshot
7. Initiate ROOT volume snapshot and while snapshot is
in pregress Reboot the VM
Verify that the VM reboot successfully and
check integrity of snapshot
8. Initiate ROOT volume snapshot and while snapshot is
in pregress create snapshot of the same volume
and check integrity of both the snapshots
9. Initiate snapshot of DATA volume and while snapshot
is in progress detach the volume
verify that volume gets detached successfully
also check integrity of snapshot
10. Initiate snapshot of a detached volume and
while snapshot is in progress attach the volume
to A VM verify that volume gets attached
successfully also check integrity of snapshot
"""
if self.hypervisor != "xenserver":
self.skipTest("Skip test for server other than XenServer")
# Step 1
root_volume = list_volumes(
self.userapiclient,
virtualmachineid=self.vm.id,
type='ROOT',
listall=True
)
checksum_root = createChecksum(
service=self.testdata,
virtual_machine=self.vm,
disk=root_volume[0],
disk_type="rootdiskdevice")
Snapshot.create(
self.apiclient,
root_volume[0].id)
snapshots = list_snapshots(
self.apiclient,
volumeid=root_volume[0].id,
listall=True)
destinationHost = Host.listForMigration(
self.apiclient,
virtualmachineid=self.vm.id)
sameClusHosts = Host.list(self.apiclient, virtualmachineid=self.vm.id)
current_host = self.vm.hostid
hostToMigarte = GetDestinationHost(
self,
current_host,
sameClusHosts,
destinationHost)
MigrateRootVolume(self,
self.vm,
hostToMigarte)
self.CreateDeltaSnapshot(root_volume[0])
Snapshot.create(
self.apiclient,
root_volume[0].id)
snapshots = list_snapshots(
self.apiclient,
volumeid=root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
self.CreateDeltaSnapshot(root_volume[0])
# Step 2
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume[0],
False))
destinationHost = Host.listForMigration(
self.apiclient,
virtualmachineid=self.vm.id)
migrate_rootvolume_thread = Thread(target=MigrateRootVolume,
args=(self,
self.vm,
destinationHost[0]))
create_snapshot_thread.start()
migrate_rootvolume_thread.start()
create_snapshot_thread.join()
migrate_rootvolume_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
self.CreateDeltaSnapshot(root_volume[0])
# Step 3
vm_host_id = self.vm_ha.hostid
checksum_root_ha = createChecksum(
service=self.testdata,
virtual_machine=self.vm_ha,
disk=self.root_volume_ha[0],
disk_type="rootdiskdevice")
self.CreateSnapshot(
self.root_volume_ha[0],
False)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume_ha[0].id,
listall=True)
self.CreateDeltaSnapshot(self.root_volume_ha[0])
Host.enableMaintenance(self.apiclient, id=vm_host_id)
time.sleep(180)
self.CreateSnapshot(self.root_volume[0], False)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume_ha[0].id,
listall=True)
Host.cancelMaintenance(self.apiclient, id=vm_host_id)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root_ha)
self.CreateDeltaSnapshot(self.root_volume_ha[0])
# Step 4
# Scenario to be tested
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume_ha[0],
False))
host_enable_maint_thread = Thread(
target=Host.enableMaintenance,
args=(
self.apiclient,
vm_host_id))
create_snapshot_thread.start()
host_enable_maint_thread.start()
create_snapshot_thread.join()
host_enable_maint_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
self.CreateDeltaSnapshot(self.root_volume_ha[0])
self.CreateSnapshot(self.root_volume_ha[0], False)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume_ha[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root_ha)
Host.cancelMaintenance(self.apiclient, vm_host_id)
# Step 5
self.vm.stop(self.apiclient)
time.sleep(90)
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume[0],
False))
start_vm_thread = Thread(target=self.StartVM,
args=([self.vm]))
create_snapshot_thread.start()
start_vm_thread.start()
create_snapshot_thread.join()
start_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
state = self.dbclient.execute(
"select state from vm_instance where name='%s'" %
self.vm.name)[0][0]
self.assertEqual(
state,
"Running",
"Check if vm has started properly")
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
self.CreateDeltaSnapshot(root_volume[0])
# Step 6
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume[0],
False))
stop_vm_thread = Thread(target=self.StopVM,
args=([self.vm]))
create_snapshot_thread.start()
stop_vm_thread.start()
create_snapshot_thread.join()
stop_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
state = self.dbclient.execute(
"select state from vm_instance where name='%s'" %
self.vm.name)[0][0]
self.assertEqual(
state,
"Stopped",
"Check if vm has started properly")
self.vm.start(self.apiclient)
time.sleep(180)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
self.CreateDeltaSnapshot(root_volume[0])
# Step 7
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.root_volume[0],
False))
reboot_vm_thread = Thread(target=self.RebootVM,
args=([self.vm]))
create_snapshot_thread.start()
reboot_vm_thread.start()
create_snapshot_thread.join()
reboot_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
state = self.dbclient.execute(
"select state from vm_instance where name='%s'" %
self.vm.name)[0][0]
self.assertEqual(
state,
"Running",
"Check if vm has started properly")
time.sleep(180)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.root_volume[0].id,
listall=True)
checkIntegrityOfSnapshot(self, snapshots[0], checksum_root)
self.CreateDeltaSnapshot(root_volume[0])
# Step 8 pending(actual 9)
# Step 9
checksum_data = createChecksum(
service=self.testdata,
virtual_machine=self.vm,
disk=self.data_volume[0],
disk_type="datadiskdevice_1")
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.data_volume[0],
False))
detach_vm_thread = Thread(
target=self.vm.detach_volume,
args=(
self.apiclient,
self.data_volume[0]))
create_snapshot_thread.start()
detach_vm_thread.start()
create_snapshot_thread.join()
detach_vm_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
self.vm.reboot(self.apiclient)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.data_volume[0].id,
listall=True)
data_volume_list = list_volumes(
self.apiclient,
virtualmachineid=self.vm.id,
type='DATA',
listall=True
)
self.assertEqual(
data_volume_list,
None,
"check if volume is detached"
)
checkIntegrityOfSnapshot(
self,
snapshots[0],
checksum_data,
disk_type="data")
self.CreateDeltaSnapshot(self.data_volume[0])
# Step 10
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self.data_volume[0],
False))
attach_volume_thread = Thread(
target=self.vm.attach_volume,
args=(
self.apiclient,
self.data_volume[0]))
create_snapshot_thread.start()
attach_volume_thread.start()
create_snapshot_thread.join()
attach_volume_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
self.vm.reboot(self.apiclient)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.data_volume[0].id,
listall=True)
data_volume_list = list_volumes(
self.apiclient,
virtualmachineid=self.vm.id,
type='DATA',
listall=True
)
self.assertNotEqual(
data_volume_list,
[],
"check if volume is detached"
)
checkIntegrityOfSnapshot(
self,
snapshots[0],
checksum_root,
disk_type="data")
self.CreateDeltaSnapshot(self.data_volume[0])
return
def test_03_snapshot_hardning_configuration(self):
"""snapshot hardning
1. Verify the snapshot failuar for smaller value of
backup.snapshot.wait then snapshot success for
larger value of backup.snapshot.wait
and check the integrity of the snapshot
2.
"""
# Step 1
if not self.testdata["configurableData"][
"restartManagementServerThroughTestCase"]:
self.skipTest(
"Skip test if restartManagementServerThroughTestCase\
is not provided")
configs = Configurations.list(
self.apiclient,
name="backup.snapshot.wait")
orig_backup = configs[0].value
Configurations.update(self.apiclient,
name="backup.snapshot.wait",
value="10"
)
# Restart management server
self.RestartServer()
time.sleep(120)
checksum_root = createChecksum(
service=self.testdata,
virtual_machine=self.vm,
disk=self.root_volume,
disk_type="rootdiskdevice")
with self.assertRaises(Exception):
Snapshot.create(
self.apiclient,
self.root_volume[0].id)
Configurations.update(self.apiclient,
name="backup.snapshot.wait",
value=orig_backup
)
# Restart management server
self.RestartServer()
time.sleep(120)
configs = Configurations.list(
self.apiclient,
name="backup.snapshot.wait")
orig_backup = configs[0].value
snapshot_2 = Snapshot.create(
self.apiclient,
self.root_volume[0].id)
time.sleep(360)
self.assertEqual(
self.dbclient.execute(
"select status from snapshots where id='%s'" %
snapshot_2.id)[0][0],
"BackedUp"
)
checkIntegrityOfSnapshot(self, snapshot_2, checksum_root)
return
class TestHardening(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestHardening, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
cls.hypervisor = cls.testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
cls._cleanup = []
configs = Configurations.list(
cls.apiclient,
name="snapshot.delta.max")
cls.delta_max = configs[0].value
clusterid_tag_mapping = {}
cwps_no = 0
cls.unsupportedHypervisor = False
if cls.hypervisor.lower() not in [
"vmware",
"kvm",
"xenserver",
"hyper-v"]:
cls.unsupportedHypervisor = True
return
try:
cls.pools = StoragePool.list(
cls.apiclient,
zoneid=cls.zone.id,
scope="CLUSTER")
for storagePool in cls.pools:
if storagePool.state.lower() == UP:
if storagePool.clusterid not in clusterid_tag_mapping:
cwps_no += 1
StoragePool.update(
cls.apiclient,
id=storagePool.id,
tags=['cwps' + repr(cwps_no)])
clusterid_tag_mapping[
storagePool.clusterid] = [cwps_no]
else:
cwps_no = clusterid_tag_mapping[
storagePool.clusterid][0]
StoragePool.update(
cls.apiclient,
id=storagePool.id,
tags=['cwps' + repr(cwps_no)])
clusterid_tag_mapping[
storagePool.clusterid].append(cwps_no)
cls.pools = StoragePool.list(
cls.apiclient,
zoneid=cls.zone.id,
scope="CLUSTER")
# Check clusterid count is 2
# Check each clusterid has two Storage Pool Tags
# which indicate two Storage Pools exist.
assert (len(clusterid_tag_mapping)) >= 2 and\
(len(tags) for tags in clusterid_tag_mapping.values(
)) >= 2, "There must be atleast two Clusters and\
each must have atleast two cluster wide storage pools in\
Up state in the setup"
except Exception as e:
raise unittest.SkipTest(e)
try:
# Create an account
cls.account = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
# Create user api client of the account
cls.userapiclient = testClient.getUserApiClient(
UserName=cls.account.name,
DomainName=cls.account.domain
)
# Create Service offering
cls.service_offering_cluster1 = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
tags=CLUSTERTAG1
)
cls._cleanup.append(cls.service_offering_cluster1)
cls.service_offering_cluster2 = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
tags=CLUSTERTAG2
)
cls._cleanup.append(cls.service_offering_cluster1)
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"]
)
cls._cleanup.append(cls.service_offering)
# Create Disk offering
cls.disk_offering_cluster1 = DiskOffering.create(
cls.apiclient,
cls.testdata["disk_offering"],
tags=CLUSTERTAG1
)
cls._cleanup.append(cls.disk_offering_cluster1)
# Create VM on CWPS
cls.vm = VirtualMachine.create(
cls.apiclient,
cls.testdata["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering_cluster1.id,
zoneid=cls.zone.id,
mode=cls.zone.networktype
)
except Exception as e:
cls.tearDownClass()
raise e
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
if self.unsupportedHypervisor:
self.skipTest("VM migration is not supported on %s" % self.hypervisor)
def tearDown(self):
try:
for storagePool in self.pools:
StoragePool.update(self.apiclient, id=storagePool.id, tags="")
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def GetStoragePoolTag(self, rootVolume):
storagePoolTag = None
# Storage Pool Id to migrate to
for storagePool in self.pools:
if storagePool.id == rootVolume.storageid:
storagePoolTag = storagePool.tags
return storagePoolTag
def GetDestinationPool(
self,
currentStoragePoolTag,
poolsToavoid,
migrateToDiffCluster=False):
destinationPool = None
# Storage Pool Id to migrate to
if migrateToDiffCluster:
for storagePool in self.pools:
if storagePool.tags != currentStoragePoolTag:
destinationPool = storagePool
break
else:
for storagePool in self.pools:
if storagePool.name not in poolsToavoid:
if storagePool.tags == currentStoragePoolTag:
destinationPool = storagePool
break
return destinationPool
def CreateSnapshot(self, root_volume, is_recurring):
"""Create Snapshot"""
try:
if is_recurring:
recurring_snapshot = SnapshotPolicy.create(
self.apiclient,
root_volume.id,
self.testdata["recurring_snapshot"]
)
self.rec_policy_pool.append(recurring_snapshot)
else:
root_vol_snap = Snapshot.create(
self.apiclient,
root_volume.id)
self.snapshot_pool.append(root_vol_snap)
except Exception as e:
self.exceptionList = []
self.exceptionList.append(e)
return
def CreateDeltaSnapshot(self, volume):
for i in range(int(self.delta_max)):
Snapshot.create(
self.apiclient,
volume.id)
return
def GetUpdatedRootVolume(self):
"""
Return Updated Root Volume.
The storage pool of ROOT Volume
changes after migration.
"""
# Get ROOT Volume
root_volumes_list = Volume.list(
self.apiclient,
virtualmachineid=self.vm.id,
type='ROOT',
listall=True
)
status = validateList(root_volumes_list)
self.assertEqual(status[0], PASS, "Check list of ROOT Volumes.")
rootVolume = root_volumes_list[0]
return rootVolume
def LiveMigrateVolume(self,
volume,
destinationPool,
islive=False,
expectexception=False
):
""" Migrate given volume to type of storage pool mentioned in migrateto:
Inputs:
1. volume: Volume to be migrated
2. migrate_to: Scope of desired Storage pool
to which volume is
to be migrated
3. expectexception: If exception is expected while migration
"""
if expectexception:
with self.assertRaises(Exception):
Volume.migrate(
self.apiclient,
volumeid=volume.id,
storageid=destinationPool.id,
livemigrate=islive
)
else:
Volume.migrate(
self.apiclient,
volumeid=volume.id,
storageid=destinationPool.id,
livemigrate=islive
)
migrated_volume_response = list_volumes(
self.apiclient,
id=volume.id
)
self.assertEqual(
isinstance(migrated_volume_response, list),
True,
"Check list volumes response for valid list"
)
self.assertNotEqual(
migrated_volume_response,
None,
"Check if volume exists in ListVolumes"
)
migrated_volume = migrated_volume_response[0]
self.assertEqual(
str(migrated_volume.state).lower(),
'ready',
"Check migrated volume is in Ready state"
)
self.assertEqual(
migrated_volume.storage,
destinationPool.name,
"Check volume is on migrated pool"
)
return
@attr(tags=["basic", "advanced"], required_hardware="true")
def test_06_hardening(self):
""" Hardening
1. Attach Volume when snapshot on this volume is
still in progress to a VM in different cluster.
2. Volume Snapshot after Vms have migrated to
a different storage pool in same cluster.
3. Volume Snapshot after Vms have migrated to
a different cluster.
4. Volume Snapshot after Vm has live migrated to
a different storage with in the same cluster.
5. Volume Snapshot after Vm has live migrated to
a different cluster.
6. Volume migration when snapshot is in progress.
7. Storage live migration when snapshot is in progress.
"""
# Get ROOT Volume
root_volume = self.GetUpdatedRootVolume()
checksum_root = createChecksum(
service=self.testdata,
virtual_machine=self.vm,
disk=root_volume,
disk_type="rootdiskdevice")
data_volume_created = Volume.create(
self.apiclient,
self.testdata["volume"],
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid,
diskofferingid=self.disk_offering_cluster1.id
)
self.vm.attach_volume(
self.apiclient,
data_volume_created
)
self.vm.reboot(self.apiclient)
data_volumes_list = Volume.list(
self.apiclient,
id=data_volume_created.id
)
data_volume = data_volumes_list[0]
checksum_data = createChecksum(
service=self.testdata,
virtual_machine=self.vm,
disk=data_volume,
disk_type="datadiskdevice_1")
# Detach DATA Volume
self.vm.detach_volume(
self.apiclient,
data_volume
)
self.vm.reboot(self.apiclient)
current_storagepool_tag = self.GetStoragePoolTag(root_volume)
# Create VM on CWPS
vm_in_cluster2 = VirtualMachine.create(
self.apiclient,
self.testdata["small"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_cluster2.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
# Step 1
self.CreateSnapshot(data_volume, False)
vm_in_cluster2.attach_volume(self.apiclient, data_volume)
vm_in_cluster2.reboot(self.apiclient)
snapshots_list = list_snapshots(
self.apiclient,
volumeid=data_volume.id,
listall=True)
data_volume_list = list_volumes(
self.apiclient,
virtualmachineid=vm_in_cluster2.id,
type='DATA',
listall=True
)
self.assertNotEqual(
data_volume_list,
[],
"check if volume is detached"
)
self.CreateDeltaSnapshot(data_volume)
self.CreateSnapshot(data_volume,
False)
snapshots_list = list_snapshots(
self.apiclient,
volumeid=data_volume_list[0].id,
listall=True)
status = validateList(snapshots_list)
self.assertEqual(status[0], PASS, "Snapshots List Validation Failed")
# Verify Snapshot state
self.assertEqual(
snapshots_list[0].state.lower() in [
BACKED_UP,
],
True,
"Snapshot state is not as expected. It is %s" %
snapshots_list[0].state
)
checkIntegrityOfSnapshot(
self,
snapshots_list[0],
checksum_data,
disk_type="data")
# Detach DATA Volume
vm_in_cluster2.detach_volume(
self.apiclient,
data_volume_list[0]
)
vm_in_cluster2.reboot(self.apiclient)
# Step 2
self.CreateSnapshot(self,
root_volume,
False)
snapshots_list = Snapshot.list(
self.userapiclient,
volumeid=root_volume.id)
status = validateList(snapshots_list)
self.assertEqual(status[0], PASS, "Snapshots List Validation Failed")
# Verify Snapshot state
self.assertEqual(
snapshots_list[0].state.lower() in [
BACKED_UP,
],
True,
"Snapshot state is not as expected. It is %s" %
snapshots_list[0].state
)
self.vm.stop(self.apiclient)
# Migration
destination_storage_pool = self.GetDestinationPool(
self,
current_storagepool_tag,
root_volume.storage,
migrateToDiffCluster=False)
MigrateRootVolume(self, self.vm, destination_storage_pool)
self.vm.start(self.apiclient)
self.CreateSnapshot(self,
root_volume,
False)
new_snapshots_list = list_snapshots(
self.userapiclient,
volumeid=root_volume.id)
status = validateList(new_snapshots_list)
self.assertEqual(status[0], PASS, "Snapshots List Validation Failed")
# Verify Snapshot state
self.assertEqual(
new_snapshots_list[0].state.lower() in [
BACKED_UP,
],
True,
"Snapshot state is not as expected. It is %s" %
new_snapshots_list[0].state
)
checkIntegrityOfSnapshot(
self,
new_snapshots_list[0],
checksum_root,
disk_type="root")
# Step 3
self.vm.stop(self.apiclient)
# Get Updated ROOT Volume
root_volume = self.GetUpdatedRootVolume(self)
current_storagepool_tag = self.GetStoragePoolTag(self, root_volume)
destination_storage_pool = self.GetDestinationPool(
self,
current_storagepool_tag,
[],
migrateToDiffCluster=True)
# Migration
MigrateRootVolume(self, self.vm, destination_storage_pool)
self.vm.start(self.apiclient)
self.CreateSnapshot(self,
root_volume,
False)
snapshots_list = list_snapshots(
self.userapiclient,
volumeid=root_volume.id)
checkIntegrityOfSnapshot(
self,
snapshots_list[0],
checksum_root,
disk_type="root")
# Get Updated ROOT Volume
root_volume = self.GetUpdatedRootVolume(self)
current_storagepool_tag = self.GetStoragePoolTag(self, root_volume)
# Step 4
# Migration
destination_storage_pool = self.GetDestinationPool(
self,
current_storagepool_tag,
root_volume.storage,
migrateToDiffCluster=False)
# Migrate
self.LiveMigrateVolume(
self,
root_volume,
destination_storage_pool,
islive=True)
self.CreateSnapshot(self,
root_volume,
False)
snapshots_list = list_snapshots(
self.userapiclient,
volumeid=root_volume.id)
checkIntegrityOfSnapshot(
self,
snapshots_list[0],
checksum_root,
disk_type="root")
# Step 5
# Live Migration
# Get Updated ROOT Volume
root_volume = self.GetUpdatedRootVolume(self)
current_storagepool_tag = self.GetStoragePoolTag(self, root_volume)
destination_storage_pool = self.GetDestinationPool(
self,
current_storagepool_tag,
[],
migrateToDiffCluster=True)
# Migrate
self.LiveMigrateVolume(
self,
root_volume,
destination_storage_pool,
islive=True)
current_storagepool_tag = self.GetStoragePoolTag(self, data_volume)
destination_storage_pool = self.GetDestinationPool(
self,
current_storagepool_tag,
[],
migrateToDiffCluster=True)
# Migrate
self.LiveMigrateVolume(
self,
data_volume,
destination_storage_pool,
islive=True)
self.CreateSnapshot(self,
root_volume,
False)
snapshots_list = list_snapshots(
self.userapiclient,
volumeid=root_volume.id)
checkIntegrityOfSnapshot(
self,
snapshots_list[0],
checksum_root,
disk_type="root")
self.vm.stop(self.apiclient)
# Get Updated ROOT Volume
root_volume = self.GetUpdatedRootVolume(self)
current_storagepool_tag = self.GetStoragePoolTag(self, root_volume)
# Step 6
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self,
root_volume,
False))
destination_storage_pool = self.GetDestinationPool(
self,
current_storagepool_tag,
root_volume.storage,
migrateToDiffCluster=False)
migrate_volume_thread = Thread(target=MigrateRootVolume,
args=(self,
self.vm,
destination_storage_pool))
create_snapshot_thread.start()
migrate_volume_thread.start()
create_snapshot_thread.join()
migrate_volume_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
snapshots_list = list_snapshots(
self.userapiclient,
volumeid=root_volume.id)
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snapshots_list[0].id),
"Snapshot is not on Secondary Storage.")
checkIntegrityOfSnapshot(self, snapshots_list[0], checksum_root)
# Step 7
self.vm.start(self.apiclient)
# Get Updated ROOT Volume
root_volume = self.GetUpdatedRootVolume(self)
current_storagepool_tag = self.GetStoragePoolTag(self, root_volume)
# live
try:
create_snapshot_thread = Thread(
target=self.CreateSnapshot,
args=(
self,
root_volume,
False))
destination_storage_pool = self.GetDestinationPool(
self,
current_storagepool_tag,
root_volume.storage,
migrateToDiffCluster=False)
live_migrate_volume_thread = Thread(target=self.LiveMigrateVolume,
args=(self,
root_volume,
destination_storage_pool,
True))
create_snapshot_thread.start()
live_migrate_volume_thread.start()
create_snapshot_thread.join()
live_migrate_volume_thread.join()
except Exception as e:
raise Exception(
"Warning: Exception unable to start thread : %s" %
e)
snapshots_list = list_snapshots(
self.userapiclient,
volumeid=root_volume.id)
checkIntegrityOfSnapshot(
self,
snapshots_list[0],
checksum_root,
disk_type="root")
data_volume_created.delete(self.apiclient)
return
| [
"marvin.lib.common.list_snapshots",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.Host.cancelMaintenance",
"marvin.lib.base.Host.list",
"marvin.lib.base.VirtualMachine.migrate",
"marvin.lib.base.StoragePool.list",
"marvin.lib.utils.is_snapshot_on_nfs",
"marvin.lib.base.Cluster.list",
"marv... | [((13349, 13407), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (13353, 13407), False, 'from nose.plugins.attrib import attr\n'), ((26170, 26228), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (26174, 26228), False, 'from nose.plugins.attrib import attr\n'), ((52328, 52386), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['basic', 'advanced']", 'required_hardware': '"""true"""'}), "(tags=['basic', 'advanced'], required_hardware='true')\n", (52332, 52386), False, 'from nose.plugins.attrib import attr\n'), ((2421, 2520), 'marvin.lib.base.Template.create_from_snapshot', 'Template.create_from_snapshot', (['self.apiclient', 'snapshotsToRestore', "self.testdata['template_2']"], {}), "(self.apiclient, snapshotsToRestore, self.\n testdata['template_2'])\n", (2450, 2520), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((2711, 2725), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (2721, 2725), False, 'import time\n'), ((2769, 3037), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['small']"], {'templateid': 'template_from_snapshot.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.testdata['small'], templateid=\n template_from_snapshot.id, accountid=self.account.name, domainid=self.\n account.domainid, serviceofferingid=self.service_offering.id, zoneid=\n self.zone.id, mode=self.zone.networktype)\n", (2790, 3037), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((3276, 3290), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (3286, 3290), False, 'import time\n'), ((3359, 3510), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'checksumToCompare', 'disk_type': '"""rootdiskdevice"""', 'virt_machine': 'vm_from_temp'}), "(self.apiclient, service=self.testdata, original_checksum=\n checksumToCompare, disk_type='rootdiskdevice', virt_machine=vm_from_temp)\n", (3374, 3510), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((3710, 3891), 'marvin.lib.base.Volume.create_from_snapshot', 'Volume.create_from_snapshot', (['self.apiclient', 'snapshotsToRestore.id', "self.testdata['volume']"], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), "(self.apiclient, snapshotsToRestore.id, self.\n testdata['volume'], account=self.account.name, domainid=self.account.\n domainid, zoneid=self.zone.id)\n", (3737, 3891), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((3983, 4242), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['small']"], {'templateid': 'self.template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.testdata['small'], templateid=\n self.template.id, accountid=self.account.name, domainid=self.account.\n domainid, serviceofferingid=self.service_offering.id, zoneid=self.zone.\n id, mode=self.zone.networktype)\n", (4004, 4242), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((4479, 4627), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'checksumToCompare', 'disk_type': '"""datadiskdevice_1"""', 'virt_machine': 'temp_vm'}), "(self.apiclient, service=self.testdata, original_checksum=\n checksumToCompare, disk_type='datadiskdevice_1', virt_machine=temp_vm)\n", (4494, 4627), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((6067, 6136), 'marvin.lib.base.VirtualMachine.migrate', 'VirtualMachine.migrate', (['vm', 'self.apiclient'], {'hostid': 'destinationHost.id'}), '(vm, self.apiclient, hostid=destinationHost.id)\n', (6089, 6136), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((6216, 6263), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'id': 'vm.id'}), '(self.apiclient, id=vm.id)\n', (6237, 6263), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((6698, 6752), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'migrated_vm.id'}), '(self.apiclient, id=migrated_vm.id)\n', (6717, 6752), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((7347, 7372), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (7357, 7372), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((7470, 7534), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.testdata['ostype'])\n", (7482, 7534), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((11658, 11763), 'marvin.sshClient.SshClient', 'SshClient', (["cls.mgtSvrDetails['mgtSvrIp']", '(22)', "cls.mgtSvrDetails['user']", "cls.mgtSvrDetails['passwd']"], {}), "(cls.mgtSvrDetails['mgtSvrIp'], 22, cls.mgtSvrDetails['user'], cls\n .mgtSvrDetails['passwd'])\n", (11667, 11763), False, 'from marvin.sshClient import SshClient\n'), ((11976, 12025), 'marvin.lib.base.Host.enableMaintenance', 'Host.enableMaintenance', (['self.apiclient'], {'id': 'hostid'}), '(self.apiclient, id=hostid)\n', (11998, 12025), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((15505, 15597), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.userapiclient'], {'virtualmachineid': 'self.vm.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.userapiclient, virtualmachineid=self.vm.id, type='ROOT',\n listall=True)\n", (15517, 15597), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((15677, 15793), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm', 'disk': 'root_volume[0]', 'disk_type': '"""rootdiskdevice"""'}), "(service=self.testdata, virtual_machine=self.vm, disk=\n root_volume[0], disk_type='rootdiskdevice')\n", (15691, 15793), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((15847, 15897), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume[0].id'], {}), '(self.apiclient, root_volume[0].id)\n', (15862, 15897), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((15944, 16016), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=root_volume[0].id, listall=True)\n', (15958, 16016), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((16081, 16147), 'marvin.lib.base.Host.listForMigration', 'Host.listForMigration', (['self.apiclient'], {'virtualmachineid': 'self.vm.id'}), '(self.apiclient, virtualmachineid=self.vm.id)\n', (16102, 16147), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((16197, 16251), 'marvin.lib.base.Host.list', 'Host.list', (['self.apiclient'], {'virtualmachineid': 'self.vm.id'}), '(self.apiclient, virtualmachineid=self.vm.id)\n', (16206, 16251), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((16553, 16603), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume[0].id'], {}), '(self.apiclient, root_volume[0].id)\n', (16568, 16603), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((16650, 16722), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=root_volume[0].id, listall=True)\n', (16664, 16722), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((17786, 17863), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume[0].id, listall=True)\n', (17800, 17863), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((18056, 18183), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm_ha', 'disk': 'self.root_volume_ha[0]', 'disk_type': '"""rootdiskdevice"""'}), "(service=self.testdata, virtual_machine=self.vm_ha, disk=self\n .root_volume_ha[0], disk_type='rootdiskdevice')\n", (18070, 18183), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((18334, 18419), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume_ha[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume_ha[0].id, listall=True\n )\n', (18348, 18419), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((18461, 18514), 'marvin.lib.base.Host.enableMaintenance', 'Host.enableMaintenance', (['self.apiclient'], {'id': 'vm_host_id'}), '(self.apiclient, id=vm_host_id)\n', (18483, 18514), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((18523, 18538), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (18533, 18538), False, 'import time\n'), ((18560, 18645), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume_ha[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume_ha[0].id, listall=True\n )\n', (18574, 18645), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((18687, 18740), 'marvin.lib.base.Host.cancelMaintenance', 'Host.cancelMaintenance', (['self.apiclient'], {'id': 'vm_host_id'}), '(self.apiclient, id=vm_host_id)\n', (18709, 18740), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((19649, 19734), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume_ha[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume_ha[0].id, listall=True\n )\n', (19663, 19734), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((19848, 19898), 'marvin.lib.base.Host.cancelMaintenance', 'Host.cancelMaintenance', (['self.apiclient', 'vm_host_id'], {}), '(self.apiclient, vm_host_id)\n', (19870, 19898), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((19962, 19976), 'time.sleep', 'time.sleep', (['(90)'], {}), '(90)\n', (19972, 19976), False, 'import time\n'), ((20861, 20938), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume[0].id, listall=True)\n', (20875, 20938), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((21968, 21983), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (21978, 21983), False, 'import time\n'), ((22004, 22081), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume[0].id, listall=True)\n', (22018, 22081), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((23084, 23099), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (23094, 23099), False, 'import time\n'), ((23120, 23197), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume[0].id, listall=True)\n', (23134, 23197), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((23382, 23505), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm', 'disk': 'self.data_volume[0]', 'disk_type': '"""datadiskdevice_1"""'}), "(service=self.testdata, virtual_machine=self.vm, disk=self.\n data_volume[0], disk_type='datadiskdevice_1')\n", (23396, 23505), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((24298, 24375), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.data_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.data_volume[0].id, listall=True)\n', (24312, 24375), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((24441, 24529), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm.id', 'type': '"""DATA"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.vm.id, type='DATA',\n listall=True)\n", (24453, 24529), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((25614, 25691), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.data_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.data_volume[0].id, listall=True)\n', (25628, 25691), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((25757, 25845), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm.id', 'type': '"""DATA"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.vm.id, type='DATA',\n listall=True)\n", (25769, 25845), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((28445, 28537), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.userapiclient'], {'virtualmachineid': 'self.vm.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.userapiclient, virtualmachineid=self.vm.id, type='ROOT',\n listall=True)\n", (28457, 28537), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((28617, 28733), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm', 'disk': 'root_volume[0]', 'disk_type': '"""rootdiskdevice"""'}), "(service=self.testdata, virtual_machine=self.vm, disk=\n root_volume[0], disk_type='rootdiskdevice')\n", (28631, 28733), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((28787, 28837), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume[0].id'], {}), '(self.apiclient, root_volume[0].id)\n', (28802, 28837), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((28884, 28956), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=root_volume[0].id, listall=True)\n', (28898, 28956), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((29021, 29087), 'marvin.lib.base.Host.listForMigration', 'Host.listForMigration', (['self.apiclient'], {'virtualmachineid': 'self.vm.id'}), '(self.apiclient, virtualmachineid=self.vm.id)\n', (29042, 29087), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((29137, 29191), 'marvin.lib.base.Host.list', 'Host.list', (['self.apiclient'], {'virtualmachineid': 'self.vm.id'}), '(self.apiclient, virtualmachineid=self.vm.id)\n', (29146, 29191), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((29543, 29593), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume[0].id'], {}), '(self.apiclient, root_volume[0].id)\n', (29558, 29593), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((29640, 29712), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=root_volume[0].id, listall=True)\n', (29654, 29712), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((30825, 30902), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume[0].id, listall=True)\n', (30839, 30902), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((31144, 31271), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm_ha', 'disk': 'self.root_volume_ha[0]', 'disk_type': '"""rootdiskdevice"""'}), "(service=self.testdata, virtual_machine=self.vm_ha, disk=self\n .root_volume_ha[0], disk_type='rootdiskdevice')\n", (31158, 31271), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((31422, 31507), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume_ha[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume_ha[0].id, listall=True\n )\n', (31436, 31507), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((31607, 31660), 'marvin.lib.base.Host.enableMaintenance', 'Host.enableMaintenance', (['self.apiclient'], {'id': 'vm_host_id'}), '(self.apiclient, id=vm_host_id)\n', (31629, 31660), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((31669, 31684), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (31679, 31684), False, 'import time\n'), ((31763, 31848), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume_ha[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume_ha[0].id, listall=True\n )\n', (31777, 31848), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((31890, 31943), 'marvin.lib.base.Host.cancelMaintenance', 'Host.cancelMaintenance', (['self.apiclient'], {'id': 'vm_host_id'}), '(self.apiclient, id=vm_host_id)\n', (31912, 31943), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((32967, 33052), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume_ha[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume_ha[0].id, listall=True\n )\n', (32981, 33052), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((33166, 33216), 'marvin.lib.base.Host.cancelMaintenance', 'Host.cancelMaintenance', (['self.apiclient', 'vm_host_id'], {}), '(self.apiclient, vm_host_id)\n', (33188, 33216), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((33280, 33294), 'time.sleep', 'time.sleep', (['(90)'], {}), '(90)\n', (33290, 33294), False, 'import time\n'), ((34179, 34256), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume[0].id, listall=True)\n', (34193, 34256), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((35335, 35350), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (35345, 35350), False, 'import time\n'), ((35371, 35448), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume[0].id, listall=True)\n', (35385, 35448), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((36500, 36515), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (36510, 36515), False, 'import time\n'), ((36536, 36613), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.root_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.root_volume[0].id, listall=True)\n', (36550, 36613), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((36847, 36970), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm', 'disk': 'self.data_volume[0]', 'disk_type': '"""datadiskdevice_1"""'}), "(service=self.testdata, virtual_machine=self.vm, disk=self.\n data_volume[0], disk_type='datadiskdevice_1')\n", (36861, 36970), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((37763, 37840), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.data_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.data_volume[0].id, listall=True)\n', (37777, 37840), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((37906, 37994), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm.id', 'type': '"""DATA"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.vm.id, type='DATA',\n listall=True)\n", (37918, 37994), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((39145, 39222), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.data_volume[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=self.data_volume[0].id, listall=True)\n', (39159, 39222), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((39288, 39376), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm.id', 'type': '"""DATA"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.vm.id, type='DATA',\n listall=True)\n", (39300, 39376), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((40399, 40463), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""backup.snapshot.wait"""'}), "(self.apiclient, name='backup.snapshot.wait')\n", (40418, 40463), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((40537, 40615), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""backup.snapshot.wait"""', 'value': '"""10"""'}), "(self.apiclient, name='backup.snapshot.wait', value='10')\n", (40558, 40615), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((40781, 40796), 'time.sleep', 'time.sleep', (['(120)'], {}), '(120)\n', (40791, 40796), False, 'import time\n'), ((40822, 40940), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm', 'disk': 'self.root_volume', 'disk_type': '"""rootdiskdevice"""'}), "(service=self.testdata, virtual_machine=self.vm, disk=self.\n root_volume, disk_type='rootdiskdevice')\n", (40836, 40940), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((41139, 41229), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""backup.snapshot.wait"""', 'value': 'orig_backup'}), "(self.apiclient, name='backup.snapshot.wait', value=\n orig_backup)\n", (41160, 41229), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((41390, 41405), 'time.sleep', 'time.sleep', (['(120)'], {}), '(120)\n', (41400, 41405), False, 'import time\n'), ((41425, 41489), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""backup.snapshot.wait"""'}), "(self.apiclient, name='backup.snapshot.wait')\n", (41444, 41489), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((41576, 41631), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'self.root_volume[0].id'], {}), '(self.apiclient, self.root_volume[0].id)\n', (41591, 41631), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((41666, 41681), 'time.sleep', 'time.sleep', (['(360)'], {}), '(360)\n', (41676, 41681), False, 'import time\n'), ((42347, 42372), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (42357, 42372), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((42470, 42534), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.testdata['ostype'])\n", (42482, 42534), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((42618, 42679), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""snapshot.delta.max"""'}), "(cls.apiclient, name='snapshot.delta.max')\n", (42637, 42679), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((49924, 50011), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.vm.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.vm.id, type='ROOT',\n listall=True)\n", (49935, 50011), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((50084, 50115), 'marvin.lib.utils.validateList', 'validateList', (['root_volumes_list'], {}), '(root_volumes_list)\n', (50096, 50115), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((53240, 53353), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm', 'disk': 'root_volume', 'disk_type': '"""rootdiskdevice"""'}), "(service=self.testdata, virtual_machine=self.vm, disk=\n root_volume, disk_type='rootdiskdevice')\n", (53254, 53353), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((53429, 53618), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.testdata['volume']"], {'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'diskofferingid': 'self.disk_offering_cluster1.id'}), "(self.apiclient, self.testdata['volume'], zoneid=self.zone.id,\n account=self.account.name, domainid=self.account.domainid,\n diskofferingid=self.disk_offering_cluster1.id)\n", (53442, 53618), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((53864, 53918), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'data_volume_created.id'}), '(self.apiclient, id=data_volume_created.id)\n', (53875, 53918), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((54022, 54137), 'marvin.lib.common.createChecksum', 'createChecksum', ([], {'service': 'self.testdata', 'virtual_machine': 'self.vm', 'disk': 'data_volume', 'disk_type': '"""datadiskdevice_1"""'}), "(service=self.testdata, virtual_machine=self.vm, disk=\n data_volume, disk_type='datadiskdevice_1')\n", (54036, 54137), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((54470, 54738), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['small']"], {'templateid': 'self.template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_cluster2.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.testdata['small'], templateid=\n self.template.id, accountid=self.account.name, domainid=self.account.\n domainid, serviceofferingid=self.service_offering_cluster2.id, zoneid=\n self.zone.id, mode=self.zone.networktype)\n", (54491, 54738), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((55037, 55106), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'data_volume.id', 'listall': '(True)'}), '(self.apiclient, volumeid=data_volume.id, listall=True)\n', (55051, 55106), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((55172, 55268), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'vm_in_cluster2.id', 'type': '"""DATA"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=vm_in_cluster2.id, type=\n 'DATA', listall=True)\n", (55184, 55268), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((55600, 55677), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'data_volume_list[0].id', 'listall': '(True)'}), '(self.apiclient, volumeid=data_volume_list[0].id, listall=True)\n', (55614, 55677), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((55733, 55761), 'marvin.lib.utils.validateList', 'validateList', (['snapshots_list'], {}), '(snapshots_list)\n', (55745, 55761), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((56594, 56652), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.userapiclient'], {'volumeid': 'root_volume.id'}), '(self.userapiclient, volumeid=root_volume.id)\n', (56607, 56652), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((56696, 56724), 'marvin.lib.utils.validateList', 'validateList', (['snapshots_list'], {}), '(snapshots_list)\n', (56708, 56724), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((57572, 57631), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.userapiclient'], {'volumeid': 'root_volume.id'}), '(self.userapiclient, volumeid=root_volume.id)\n', (57586, 57631), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((57675, 57707), 'marvin.lib.utils.validateList', 'validateList', (['new_snapshots_list'], {}), '(new_snapshots_list)\n', (57687, 57707), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((58868, 58927), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.userapiclient'], {'volumeid': 'root_volume.id'}), '(self.userapiclient, volumeid=root_volume.id)\n', (58882, 58927), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((59780, 59839), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.userapiclient'], {'volumeid': 'root_volume.id'}), '(self.userapiclient, volumeid=root_volume.id)\n', (59794, 59839), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((61085, 61144), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.userapiclient'], {'volumeid': 'root_volume.id'}), '(self.userapiclient, volumeid=root_volume.id)\n', (61099, 61144), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((62555, 62614), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.userapiclient'], {'volumeid': 'root_volume.id'}), '(self.userapiclient, volumeid=root_volume.id)\n', (62569, 62614), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((64347, 64406), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.userapiclient'], {'volumeid': 'root_volume.id'}), '(self.userapiclient, volumeid=root_volume.id)\n', (64361, 64406), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((5916, 5985), 'marvin.lib.base.VirtualMachine.migrate', 'VirtualMachine.migrate', (['vm', 'self.apiclient'], {'hostid': 'destinationHost.id'}), '(vm, self.apiclient, hostid=destinationHost.id)\n', (5938, 5985), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((7743, 7821), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.testdata['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.testdata['account'], domainid=cls.domain.id)\n", (7757, 7821), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((8175, 8246), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {}), "(cls.apiclient, cls.testdata['service_offering'])\n", (8197, 8246), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((8387, 8476), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {'offerha': '(True)'}), "(cls.apiclient, cls.testdata['service_offering'],\n offerha=True)\n", (8409, 8476), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((8568, 8633), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.apiclient', "cls.testdata['disk_offering']"], {}), "(cls.apiclient, cls.testdata['disk_offering'])\n", (8587, 8633), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((8754, 9040), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.testdata['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id', 'zoneid': 'cls.zone.id', 'diskofferingid': 'cls.disk_offering.id', 'mode': 'cls.zone.networktype'}), "(cls.apiclient, cls.testdata['small'], templateid=cls.\n template.id, accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering.id, zoneid=cls.zone.id,\n diskofferingid=cls.disk_offering.id, mode=cls.zone.networktype)\n", (8775, 9040), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((9257, 9347), 'marvin.lib.common.list_volumes', 'list_volumes', (['cls.userapiclient'], {'virtualmachineid': 'cls.vm.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(cls.userapiclient, virtualmachineid=cls.vm.id, type='ROOT',\n listall=True)\n", (9269, 9347), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((9452, 9542), 'marvin.lib.common.list_volumes', 'list_volumes', (['cls.userapiclient'], {'virtualmachineid': 'cls.vm.id', 'type': '"""DATA"""', 'listall': '(True)'}), "(cls.userapiclient, virtualmachineid=cls.vm.id, type='DATA',\n listall=True)\n", (9464, 9542), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((9642, 9931), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.testdata['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering_ha.id', 'zoneid': 'cls.zone.id', 'diskofferingid': 'cls.disk_offering.id', 'mode': 'cls.zone.networktype'}), "(cls.apiclient, cls.testdata['small'], templateid=cls.\n template.id, accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering_ha.id, zoneid=cls.zone.id,\n diskofferingid=cls.disk_offering.id, mode=cls.zone.networktype)\n", (9663, 9931), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((10199, 10292), 'marvin.lib.common.list_volumes', 'list_volumes', (['cls.userapiclient'], {'virtualmachineid': 'cls.vm_ha.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(cls.userapiclient, virtualmachineid=cls.vm_ha.id, type='ROOT',\n listall=True)\n", (10211, 10292), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((10398, 10425), 'marvin.lib.base.Cluster.list', 'Cluster.list', (['cls.apiclient'], {}), '(cls.apiclient)\n', (10410, 10425), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((10450, 10474), 'marvin.lib.base.Host.list', 'Host.list', (['cls.apiclient'], {}), '(cls.apiclient)\n', (10459, 10474), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((10533, 10594), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""snapshot.delta.max"""'}), "(cls.apiclient, name='snapshot.delta.max')\n", (10552, 10594), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((11019, 11065), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (11036, 11065), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((11383, 11430), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (11400, 11430), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((13252, 13294), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'volume.id'], {}), '(self.apiclient, volume.id)\n', (13267, 13294), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((16897, 16966), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume[0], False))\n', (16903, 16966), False, 'from threading import Thread\n'), ((17072, 17138), 'marvin.lib.base.Host.listForMigration', 'Host.listForMigration', (['self.apiclient'], {'virtualmachineid': 'self.vm.id'}), '(self.apiclient, virtualmachineid=self.vm.id)\n', (17093, 17138), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((17213, 17287), 'threading.Thread', 'Thread', ([], {'target': 'MigrateRootVolume', 'args': '(self, self.vm, destinationHost[0])'}), '(target=MigrateRootVolume, args=(self, self.vm, destinationHost[0]))\n', (17219, 17287), False, 'from threading import Thread\n'), ((18912, 18984), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume_ha[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume_ha[0], False))\n', (18918, 18984), False, 'from threading import Thread\n'), ((19099, 19171), 'threading.Thread', 'Thread', ([], {'target': 'Host.enableMaintenance', 'args': '(self.apiclient, vm_host_id)'}), '(target=Host.enableMaintenance, args=(self.apiclient, vm_host_id))\n', (19105, 19171), False, 'from threading import Thread\n'), ((20027, 20096), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume[0], False))\n', (20033, 20096), False, 'from threading import Thread\n'), ((20202, 20245), 'threading.Thread', 'Thread', ([], {'target': 'self.StartVM', 'args': '[self.vm]'}), '(target=self.StartVM, args=[self.vm])\n', (20208, 20245), False, 'from threading import Thread\n'), ((21113, 21182), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume[0], False))\n', (21119, 21182), False, 'from threading import Thread\n'), ((21287, 21329), 'threading.Thread', 'Thread', ([], {'target': 'self.StopVM', 'args': '[self.vm]'}), '(target=self.StopVM, args=[self.vm])\n', (21293, 21329), False, 'from threading import Thread\n'), ((22257, 22326), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume[0], False))\n', (22263, 22326), False, 'from threading import Thread\n'), ((22433, 22477), 'threading.Thread', 'Thread', ([], {'target': 'self.RebootVM', 'args': '[self.vm]'}), '(target=self.RebootVM, args=[self.vm])\n', (22439, 22477), False, 'from threading import Thread\n'), ((23601, 23670), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.data_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.data_volume[0], False))\n', (23607, 23670), False, 'from threading import Thread\n'), ((23777, 23862), 'threading.Thread', 'Thread', ([], {'target': 'self.vm.detach_volume', 'args': '(self.apiclient, self.data_volume[0])'}), '(target=self.vm.detach_volume, args=(self.apiclient, self.data_volume[0])\n )\n', (23783, 23862), False, 'from threading import Thread\n'), ((24917, 24986), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.data_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.data_volume[0], False))\n', (24923, 24986), False, 'from threading import Thread\n'), ((25093, 25178), 'threading.Thread', 'Thread', ([], {'target': 'self.vm.attach_volume', 'args': '(self.apiclient, self.data_volume[0])'}), '(target=self.vm.attach_volume, args=(self.apiclient, self.data_volume[0])\n )\n', (25099, 25178), False, 'from threading import Thread\n'), ((29937, 30006), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume[0], False))\n', (29943, 30006), False, 'from threading import Thread\n'), ((30112, 30178), 'marvin.lib.base.Host.listForMigration', 'Host.listForMigration', (['self.apiclient'], {'virtualmachineid': 'self.vm.id'}), '(self.apiclient, virtualmachineid=self.vm.id)\n', (30133, 30178), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((30252, 30326), 'threading.Thread', 'Thread', ([], {'target': 'MigrateRootVolume', 'args': '(self, self.vm, destinationHost[0])'}), '(target=MigrateRootVolume, args=(self, self.vm, destinationHost[0]))\n', (30258, 30326), False, 'from threading import Thread\n'), ((32172, 32244), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume_ha[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume_ha[0], False))\n', (32178, 32244), False, 'from threading import Thread\n'), ((32359, 32431), 'threading.Thread', 'Thread', ([], {'target': 'Host.enableMaintenance', 'args': '(self.apiclient, vm_host_id)'}), '(target=Host.enableMaintenance, args=(self.apiclient, vm_host_id))\n', (32365, 32431), False, 'from threading import Thread\n'), ((33345, 33414), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume[0], False))\n', (33351, 33414), False, 'from threading import Thread\n'), ((33520, 33563), 'threading.Thread', 'Thread', ([], {'target': 'self.StartVM', 'args': '[self.vm]'}), '(target=self.StartVM, args=[self.vm])\n', (33526, 33563), False, 'from threading import Thread\n'), ((34480, 34549), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume[0], False))\n', (34486, 34549), False, 'from threading import Thread\n'), ((34654, 34696), 'threading.Thread', 'Thread', ([], {'target': 'self.StopVM', 'args': '[self.vm]'}), '(target=self.StopVM, args=[self.vm])\n', (34660, 34696), False, 'from threading import Thread\n'), ((35673, 35742), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.root_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.root_volume[0], False))\n', (35679, 35742), False, 'from threading import Thread\n'), ((35849, 35893), 'threading.Thread', 'Thread', ([], {'target': 'self.RebootVM', 'args': '[self.vm]'}), '(target=self.RebootVM, args=[self.vm])\n', (35855, 35893), False, 'from threading import Thread\n'), ((37066, 37135), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.data_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.data_volume[0], False))\n', (37072, 37135), False, 'from threading import Thread\n'), ((37242, 37327), 'threading.Thread', 'Thread', ([], {'target': 'self.vm.detach_volume', 'args': '(self.apiclient, self.data_volume[0])'}), '(target=self.vm.detach_volume, args=(self.apiclient, self.data_volume[0])\n )\n', (37248, 37327), False, 'from threading import Thread\n'), ((38436, 38505), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self.data_volume[0], False)'}), '(target=self.CreateSnapshot, args=(self.data_volume[0], False))\n', (38442, 38505), False, 'from threading import Thread\n'), ((38616, 38701), 'threading.Thread', 'Thread', ([], {'target': 'self.vm.attach_volume', 'args': '(self.apiclient, self.data_volume[0])'}), '(target=self.vm.attach_volume, args=(self.apiclient, self.data_volume[0])\n )\n', (38622, 38701), False, 'from threading import Thread\n'), ((41041, 41096), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'self.root_volume[0].id'], {}), '(self.apiclient, self.root_volume[0].id)\n', (41056, 41096), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((43095, 43163), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['cls.apiclient'], {'zoneid': 'cls.zone.id', 'scope': '"""CLUSTER"""'}), "(cls.apiclient, zoneid=cls.zone.id, scope='CLUSTER')\n", (43111, 43163), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((44196, 44264), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['cls.apiclient'], {'zoneid': 'cls.zone.id', 'scope': '"""CLUSTER"""'}), "(cls.apiclient, zoneid=cls.zone.id, scope='CLUSTER')\n", (44212, 44264), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((44921, 44999), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.testdata['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.testdata['account'], domainid=cls.domain.id)\n", (44935, 44999), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((45406, 45499), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {'tags': 'CLUSTERTAG1'}), "(cls.apiclient, cls.testdata['service_offering'],\n tags=CLUSTERTAG1)\n", (45428, 45499), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((45666, 45759), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {'tags': 'CLUSTERTAG2'}), "(cls.apiclient, cls.testdata['service_offering'],\n tags=CLUSTERTAG2)\n", (45688, 45759), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((45918, 45989), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {}), "(cls.apiclient, cls.testdata['service_offering'])\n", (45940, 45989), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((46167, 46255), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.apiclient', "cls.testdata['disk_offering']"], {'tags': 'CLUSTERTAG1'}), "(cls.apiclient, cls.testdata['disk_offering'], tags=\n CLUSTERTAG1)\n", (46186, 46255), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((46427, 46685), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.testdata['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering_cluster1.id', 'zoneid': 'cls.zone.id', 'mode': 'cls.zone.networktype'}), "(cls.apiclient, cls.testdata['small'], templateid=cls.\n template.id, accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering_cluster1.id, zoneid=cls.zone.id,\n mode=cls.zone.networktype)\n", (46448, 46685), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((46985, 47031), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (47002, 47031), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((47593, 47640), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (47610, 47640), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((49607, 49649), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'volume.id'], {}), '(self.apiclient, volume.id)\n', (49622, 49649), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((51229, 51334), 'marvin.lib.base.Volume.migrate', 'Volume.migrate', (['self.apiclient'], {'volumeid': 'volume.id', 'storageid': 'destinationPool.id', 'livemigrate': 'islive'}), '(self.apiclient, volumeid=volume.id, storageid=\n destinationPool.id, livemigrate=islive)\n', (51243, 51334), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((51448, 51490), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (51460, 51490), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_virtual_machines, createChecksum, compareChecksum\n'), ((61583, 61650), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self, root_volume, False)'}), '(target=self.CreateSnapshot, args=(self, root_volume, False))\n', (61589, 61650), False, 'from threading import Thread\n'), ((61991, 62076), 'threading.Thread', 'Thread', ([], {'target': 'MigrateRootVolume', 'args': '(self, self.vm, destination_storage_pool)'}), '(target=MigrateRootVolume, args=(self, self.vm, destination_storage_pool)\n )\n', (61997, 62076), False, 'from threading import Thread\n'), ((62678, 62780), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snapshots_list[0].id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snapshots_list[0].id)\n', (62696, 62780), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((63276, 63343), 'threading.Thread', 'Thread', ([], {'target': 'self.CreateSnapshot', 'args': '(self, root_volume, False)'}), '(target=self.CreateSnapshot, args=(self, root_volume, False))\n', (63282, 63343), False, 'from threading import Thread\n'), ((63689, 63788), 'threading.Thread', 'Thread', ([], {'target': 'self.LiveMigrateVolume', 'args': '(self, root_volume, destination_storage_pool, True)'}), '(target=self.LiveMigrateVolume, args=(self, root_volume,\n destination_storage_pool, True))\n', (63695, 63788), False, 'from threading import Thread\n'), ((10719, 10770), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['cls.apiclient'], {'zoneid': 'cls.zone.id'}), '(cls.apiclient, zoneid=cls.zone.id)\n', (10735, 10770), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((12598, 12693), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'root_volume.id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, root_volume.id, self.testdata[\n 'recurring_snapshot'])\n", (12619, 12693), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((12881, 12928), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume.id'], {}), '(self.apiclient, root_volume.id)\n', (12896, 12928), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((44827, 44847), 'unittest.SkipTest', 'unittest.SkipTest', (['e'], {}), '(e)\n', (44844, 44847), False, 'import unittest\n'), ((47518, 47580), 'marvin.lib.base.StoragePool.update', 'StoragePool.update', (['self.apiclient'], {'id': 'storagePool.id', 'tags': '""""""'}), "(self.apiclient, id=storagePool.id, tags='')\n", (47536, 47580), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((48953, 49048), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'root_volume.id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, root_volume.id, self.testdata[\n 'recurring_snapshot'])\n", (48974, 49048), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((49236, 49283), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume.id'], {}), '(self.apiclient, root_volume.id)\n', (49251, 49283), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((51004, 51109), 'marvin.lib.base.Volume.migrate', 'Volume.migrate', (['self.apiclient'], {'volumeid': 'volume.id', 'storageid': 'destinationPool.id', 'livemigrate': 'islive'}), '(self.apiclient, volumeid=volume.id, storageid=\n destinationPool.id, livemigrate=islive)\n', (51018, 51109), False, 'from marvin.lib.base import Account, Cluster, StoragePool, DiskOffering, ServiceOffering, Host, Configurations, Template, VirtualMachine, Snapshot, SnapshotPolicy, Volume\n'), ((10828, 10848), 'unittest.SkipTest', 'unittest.SkipTest', (['e'], {}), '(e)\n', (10845, 10848), False, 'import unittest\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" tests for Volume improvement (Destroy/Recover) in cloudstack 4.14.0.0
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import (deleteVolume, extractVolume, recoverVolume)
from marvin.lib.utils import (validateList,
cleanup_resources)
from marvin.lib.base import (Resources,
Volume,
Account,
Domain,
Network,
NetworkOffering,
VirtualMachine,
ServiceOffering,
DiskOffering,
Zone)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
matchResourceCount,
isAccountResourceCountEqualToExpectedCount)
from marvin.codes import (PASS, FAILED, RESOURCE_PRIMARY_STORAGE, RESOURCE_VOLUME)
import logging
import random
import time
class TestVolumeDestroyRecover(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(
TestVolumeDestroyRecover,
cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.zone = Zone(zone.__dict__)
cls._cleanup = []
cls.logger = logging.getLogger("TestVolumeDestroyRecover")
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
# Get Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.template = get_template(cls.apiclient, cls.zone.id, hypervisor="KVM")
if cls.template == FAILED:
sys.exit(1)
cls.templatesize = (cls.template.size / (1024 ** 3))
cls.services['mode'] = cls.zone.networktype
# Create Account
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls._cleanup.append(cls.account);
accounts = Account.list(cls.apiclient, id=cls.account.id)
cls.expectedCount = int(accounts[0].primarystoragetotal)
cls.volumeTotal = int(accounts[0].volumetotal)
if cls.zone.securitygroupsenabled:
cls.services["shared_network_offering"]["specifyVlan"] = 'True'
cls.services["shared_network_offering"]["specifyIpRanges"] = 'True'
cls.network_offering = NetworkOffering.create(
cls.apiclient,
cls.services["shared_network_offering"]
)
cls._cleanup.append(cls.network_offering)
cls.network_offering.update(cls.apiclient, state='Enabled')
cls.account_network = Network.create(
cls.apiclient,
cls.services["network2"],
networkofferingid=cls.network_offering.id,
zoneid=cls.zone.id,
accountid=cls.account.name,
domainid=cls.account.domainid
)
cls._cleanup.append(cls.account_network)
else:
cls.network_offering = NetworkOffering.create(
cls.apiclient,
cls.services["isolated_network_offering"],
)
cls._cleanup.append(cls.network_offering)
# Enable Network offering
cls.network_offering.update(cls.apiclient, state='Enabled')
# Create account network
cls.services["network"]["zoneid"] = cls.zone.id
cls.services["network"]["networkoffering"] = cls.network_offering.id
cls.account_network = Network.create(
cls.apiclient,
cls.services["network"],
cls.account.name,
cls.account.domainid
)
cls._cleanup.append(cls.account_network)
# Create small service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["small"]
)
cls._cleanup.append(cls.service_offering)
# Create disk offering
cls.disk_offering = DiskOffering.create(
cls.apiclient,
cls.services["disk_offering"],
)
cls._cleanup.append(cls.disk_offering)
@classmethod
def tearDownClass(cls):
super(TestVolumeDestroyRecover, cls).tearDownClass()
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
return
def tearDown(self):
super(TestVolumeDestroyRecover, self).tearDown()
def verify_resource_count_primary_storage(self, expectedCount, volumeTotal):
response = matchResourceCount(
self.apiclient, expectedCount,
RESOURCE_PRIMARY_STORAGE,
accountid=self.account.id)
self.assertEqual(response[0], PASS, response[1])
result = isAccountResourceCountEqualToExpectedCount(
self.apiclient, self.account.domainid, self.account.name,
expectedCount, RESOURCE_PRIMARY_STORAGE)
self.assertFalse(result[0], result[1])
self.assertTrue(result[2], "Resource count of primary storage does not match")
response = matchResourceCount(
self.apiclient, volumeTotal,
RESOURCE_VOLUME,
accountid=self.account.id)
self.assertEqual(response[0], PASS, response[1])
result = isAccountResourceCountEqualToExpectedCount(
self.apiclient, self.account.domainid, self.account.name,
volumeTotal, RESOURCE_VOLUME)
self.assertFalse(result[0], result[1])
self.assertTrue(result[2], "Resource count of volume does not match")
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_01_create_vm_with_data_disk(self):
"""Create VM with DATA disk, then destroy it (expunge=False) and expunge it
Steps:
# 1. create vm with root disk and data disk
# 2. destroy vm, resource count of primary storage is not changed
# 3. expunge vm, resource count of primary storage decreased with size of root disk.
# 4. delete volume (data disk), resource count of primary storage decreased with size of data disk
"""
try:
virtual_machine_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
diskofferingid=self.disk_offering.id,
templateid=self.template.id,
zoneid=self.zone.id
)
self.cleanup.append(virtual_machine_1)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCount = self.expectedCount + self.templatesize + self.disk_offering.disksize
self.volumeTotal = self.volumeTotal + 2
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
root_volumes_list = Volume.list(
self.apiclient,
virtualmachineid=virtual_machine_1.id,
type='ROOT',
listall=True
)
status = validateList(root_volumes_list)
self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
root_volume_id = root_volumes_list[0].id
data_volumes_list = Volume.list(
self.apiclient,
virtualmachineid=virtual_machine_1.id,
type='DATADISK',
listall=True
)
status = validateList(data_volumes_list)
self.assertEqual(status[0], PASS, "DATADISK Volume List Validation Failed")
data_volume_id = data_volumes_list[0].id
# destroy vm
virtual_machine_1.delete(self.apiclient, expunge=False)
self.cleanup.remove(virtual_machine_1)
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal)
# expunge vm
virtual_machine_1.expunge(self.apiclient)
self.expectedCount = self.expectedCount - self.templatesize
self.volumeTotal = self.volumeTotal - 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal)
# delete datadisk
cmd = deleteVolume.deleteVolumeCmd()
cmd.id = data_volume_id
self.apiclient.deleteVolume(cmd)
self.expectedCount = self.expectedCount - self.disk_offering.disksize
self.volumeTotal = self.volumeTotal - 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal)
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_02_destroy_allocated_volume(self):
"""Create volume, destroy it when expunge=false and expunge=true
Steps:
# 1. create volume, resource count increases.
# 2. destroy volume (expunge = false), Exception happened. resource count no changes
# 3. destroy volume (expunge = True), resource count of primary storage decreased with size of volume.
"""
# Create volume
volume = Volume.create(
self.apiclient, self.services["volume"],
zoneid=self.zone.id, account=self.account.name,
domainid=self.account.domainid, diskofferingid=self.disk_offering.id
)
self.cleanup.append(volume)
self.expectedCount = self.expectedCount + self.disk_offering.disksize
self.volumeTotal = self.volumeTotal + 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# Destroy volume (expunge=False)
with self.assertRaises(Exception):
volume.destroy(self.apiclient)
# Destroy volume (expunge=True)
volume.destroy(self.apiclient, expunge=True)
self.cleanup.remove(volume)
self.expectedCount = self.expectedCount - self.disk_offering.disksize
self.volumeTotal = self.volumeTotal - 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_03_destroy_detached_volume(self):
"""Create volume, attach/detach it, then destroy it when expunge=false and expunge=true
Steps:
# 1. create vm without data disk, resource count increases.
# 2. create volume, resource count increases.
# 3. attach volume to a vm. resource count no changes.
# 4. detach volume from a vm. resource count no changes.
# 5. destroy volume (expunge = false), volume is Destroy. resource count decreased with size of volume.
# 6. destroy volume (expunge = true), volume is not found. resource count no changes.
# 7. destroy vm (expunge=True). resource count decreased with size of root disk
"""
# Create vm
try:
virtual_machine_2 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id
)
self.cleanup.append(virtual_machine_2)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCount = self.expectedCount + self.templatesize
self.volumeTotal = self.volumeTotal + 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# Create volume
volume = Volume.create(
self.apiclient, self.services["volume"],
zoneid=self.zone.id, account=self.account.name,
domainid=self.account.domainid, diskofferingid=self.disk_offering.id
)
self.cleanup.append(volume)
self.expectedCount = self.expectedCount + self.disk_offering.disksize
self.volumeTotal = self.volumeTotal + 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# Attach volume to vm
virtual_machine_2.attach_volume(self.apiclient, volume)
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# Detach volume from vm
virtual_machine_2.stop(self.apiclient)
virtual_machine_2.detach_volume(self.apiclient, volume)
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# save id for later recovery and expunge
volumeUuid = volume.id
# Destroy volume (expunge=False)
volume.destroy(self.apiclient, expunge=False)
self.cleanup.remove(volume)
self.expectedCount = self.expectedCount - self.disk_offering.disksize
self.volumeTotal = self.volumeTotal - 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# Destroy volume (expunge=True)
volume.destroy(self.apiclient, expunge=True)
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# Destroy VM (expunge=True)
virtual_machine_2.delete(self.apiclient, expunge=True)
self.cleanup.remove(virtual_machine_2)
self.expectedCount = self.expectedCount - self.templatesize
self.volumeTotal = self.volumeTotal - 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_04_recover_root_volume_after_restorevm(self):
"""Restore VM, recover/delete old root disk
Steps:
# 1. create vm without data disk, resource count increases.
# 2. restore vm. resource count no changes.
# 3. check old root disk , should be Destroy state
# 4. recover old root disk. resource count increases.
# 5. delete old root disk . resource count decreases.
# 6. destroy vm (expunge=True). resource count decreased with size of root disk
"""
# Create vm
try:
virtual_machine_3 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id
)
self.cleanup.append(virtual_machine_3)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCount = self.expectedCount + self.templatesize
self.volumeTotal = self.volumeTotal + 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# Get id of root disk
root_volumes_list = Volume.list(
self.apiclient,
virtualmachineid=virtual_machine_3.id,
type='ROOT',
listall=True
)
status = validateList(root_volumes_list)
self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
root_volume_id = root_volumes_list[0].id
# restore vm
virtual_machine_3.restore(self.apiclient)
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# check old root disk state
root_volumes_list = Volume.list(
self.apiclient,
id=root_volume_id,
listall=True
)
status = validateList(root_volumes_list)
self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
root_volume = root_volumes_list[0]
self.assertEqual(root_volume['state'], 'Destroy', "ROOT volume should be Destroy after restorevm")
# recover old root disk
cmd = recoverVolume.recoverVolumeCmd()
cmd.id = root_volume.id
self.apiclient.recoverVolume(cmd)
self.expectedCount = self.expectedCount + self.templatesize
self.volumeTotal = self.volumeTotal + 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# delete old root disk
cmd = deleteVolume.deleteVolumeCmd()
cmd.id = root_volume.id
self.apiclient.deleteVolume(cmd)
self.expectedCount = self.expectedCount - self.templatesize
self.volumeTotal = self.volumeTotal - 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal)
# Destroy VM (expunge=True)
virtual_machine_3.delete(self.apiclient, expunge=True)
self.cleanup.remove(virtual_machine_3)
self.expectedCount = self.expectedCount - self.templatesize
self.volumeTotal = self.volumeTotal - 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_05_extract_root_volume_and_destroy_vm(self):
"""Create VM, extract root volume, then destroy vm and volume
Steps:
# 1. create vm without data disk, resource count increases.
# 2. stop vm
# 3. extract root volume
# 4. expunge vm, root volume in Expunged state. resource count decreased with size of root disk.
# 5. destroy volume (expunge = false), Exception happened. resource count no changes
# 6. destroy volume (expunge = true). volume is not found. resource count no changes.
"""
# Create vm
try:
virtual_machine_4 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id
)
self.cleanup.append(virtual_machine_4)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCount = self.expectedCount + self.templatesize
self.volumeTotal = self.volumeTotal + 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# Get id of root disk
root_volumes_list = Volume.list(
self.apiclient,
virtualmachineid=virtual_machine_4.id,
type='ROOT',
listall=True
)
status = validateList(root_volumes_list)
self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
root_volume_id = root_volumes_list[0].id
# Stop vm
virtual_machine_4.stop(self.apiclient)
# extract root volume
cmd = extractVolume.extractVolumeCmd()
cmd.id = root_volume_id
cmd.mode = "HTTP_DOWNLOAD"
cmd.zoneid = self.zone.id
self.apiclient.extractVolume(cmd)
# Destroy VM (expunge=True)
virtual_machine_4.delete(self.apiclient, expunge=True)
self.cleanup.remove(virtual_machine_4)
self.expectedCount = self.expectedCount - self.templatesize
self.volumeTotal = self.volumeTotal - 1
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal);
# check root disk state
root_volumes_list = Volume.list(
self.apiclient,
id=root_volume_id,
listall=True
)
status = validateList(root_volumes_list)
self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
root_volume = root_volumes_list[0]
self.assertEqual(root_volume['state'], 'Expunged', "ROOT volume should be Destroy after restorevm")
# delete root disk
cmd = deleteVolume.deleteVolumeCmd()
cmd.id = root_volume.id
self.apiclient.deleteVolume(cmd)
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal)
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_06_delete_network(self):
"""Delete account network, resource count should not be changed
Steps:
# 1. Delete account network
# 2. resource count should not be changed
"""
self.account_network.delete(self.apiclient)
self._cleanup.remove(self.account_network)
self.verify_resource_count_primary_storage(self.expectedCount, self.volumeTotal)
| [
"marvin.lib.base.Zone",
"marvin.lib.base.Network.create",
"marvin.lib.common.get_domain",
"marvin.cloudstackAPI.extractVolume.extractVolumeCmd",
"marvin.cloudstackAPI.deleteVolume.deleteVolumeCmd",
"marvin.lib.base.Volume.create",
"marvin.lib.base.Account.list",
"marvin.lib.common.get_template",
"ma... | [((6967, 7031), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (6971, 7031), False, 'from nose.plugins.attrib import attr\n'), ((9976, 10040), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (9980, 10040), False, 'from nose.plugins.attrib import attr\n'), ((11458, 11522), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (11462, 11522), False, 'from nose.plugins.attrib import attr\n'), ((14958, 15022), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (14962, 15022), False, 'from nose.plugins.attrib import attr\n'), ((18450, 18514), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (18454, 18514), False, 'from nose.plugins.attrib import attr\n'), ((21622, 21686), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (21626, 21686), False, 'from nose.plugins.attrib import attr\n'), ((2347, 2366), 'marvin.lib.base.Zone', 'Zone', (['zone.__dict__'], {}), '(zone.__dict__)\n', (2351, 2366), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((2415, 2460), 'logging.getLogger', 'logging.getLogger', (['"""TestVolumeDestroyRecover"""'], {}), "('TestVolumeDestroyRecover')\n", (2432, 2460), False, 'import logging\n'), ((2490, 2513), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2511, 2513), False, 'import logging\n'), ((2664, 2689), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2674, 2689), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((2714, 2772), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id'], {'hypervisor': '"""KVM"""'}), "(cls.apiclient, cls.zone.id, hypervisor='KVM')\n", (2726, 2772), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((2993, 3088), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (3007, 3088), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((3203, 3249), 'marvin.lib.base.Account.list', 'Account.list', (['cls.apiclient'], {'id': 'cls.account.id'}), '(cls.apiclient, id=cls.account.id)\n', (3215, 3249), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((5085, 5171), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['small']"], {}), "(cls.apiclient, cls.services['service_offerings'][\n 'small'])\n", (5107, 5171), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((5311, 5376), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.apiclient', "cls.services['disk_offering']"], {}), "(cls.apiclient, cls.services['disk_offering'])\n", (5330, 5376), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((5868, 5974), 'marvin.lib.common.matchResourceCount', 'matchResourceCount', (['self.apiclient', 'expectedCount', 'RESOURCE_PRIMARY_STORAGE'], {'accountid': 'self.account.id'}), '(self.apiclient, expectedCount, RESOURCE_PRIMARY_STORAGE,\n accountid=self.account.id)\n', (5886, 5974), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((6119, 6265), 'marvin.lib.common.isAccountResourceCountEqualToExpectedCount', 'isAccountResourceCountEqualToExpectedCount', (['self.apiclient', 'self.account.domainid', 'self.account.name', 'expectedCount', 'RESOURCE_PRIMARY_STORAGE'], {}), '(self.apiclient, self.account.\n domainid, self.account.name, expectedCount, RESOURCE_PRIMARY_STORAGE)\n', (6161, 6265), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((6440, 6536), 'marvin.lib.common.matchResourceCount', 'matchResourceCount', (['self.apiclient', 'volumeTotal', 'RESOURCE_VOLUME'], {'accountid': 'self.account.id'}), '(self.apiclient, volumeTotal, RESOURCE_VOLUME, accountid=\n self.account.id)\n', (6458, 6536), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((6680, 6815), 'marvin.lib.common.isAccountResourceCountEqualToExpectedCount', 'isAccountResourceCountEqualToExpectedCount', (['self.apiclient', 'self.account.domainid', 'self.account.name', 'volumeTotal', 'RESOURCE_VOLUME'], {}), '(self.apiclient, self.account.\n domainid, self.account.name, volumeTotal, RESOURCE_VOLUME)\n', (6722, 6815), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((8414, 8512), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine_1.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=virtual_machine_1.id, type=\n 'ROOT', listall=True)\n", (8425, 8512), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((8583, 8614), 'marvin.lib.utils.validateList', 'validateList', (['root_volumes_list'], {}), '(root_volumes_list)\n', (8595, 8614), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((8773, 8875), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine_1.id', 'type': '"""DATADISK"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=virtual_machine_1.id, type=\n 'DATADISK', listall=True)\n", (8784, 8875), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((8946, 8977), 'marvin.lib.utils.validateList', 'validateList', (['data_volumes_list'], {}), '(data_volumes_list)\n', (8958, 8977), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((9651, 9681), 'marvin.cloudstackAPI.deleteVolume.deleteVolumeCmd', 'deleteVolume.deleteVolumeCmd', ([], {}), '()\n', (9679, 9681), False, 'from marvin.cloudstackAPI import deleteVolume, extractVolume, recoverVolume\n'), ((10506, 10686), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'diskofferingid': 'self.disk_offering.id'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n account=self.account.name, domainid=self.account.domainid,\n diskofferingid=self.disk_offering.id)\n", (10519, 10686), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((13096, 13276), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'diskofferingid': 'self.disk_offering.id'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n account=self.account.name, domainid=self.account.domainid,\n diskofferingid=self.disk_offering.id)\n", (13109, 13276), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((16433, 16531), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine_3.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=virtual_machine_3.id, type=\n 'ROOT', listall=True)\n", (16444, 16531), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((16602, 16633), 'marvin.lib.utils.validateList', 'validateList', (['root_volumes_list'], {}), '(root_volumes_list)\n', (16614, 16633), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((16990, 17050), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'root_volume_id', 'listall': '(True)'}), '(self.apiclient, id=root_volume_id, listall=True)\n', (17001, 17050), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((17114, 17145), 'marvin.lib.utils.validateList', 'validateList', (['root_volumes_list'], {}), '(root_volumes_list)\n', (17126, 17145), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((17423, 17455), 'marvin.cloudstackAPI.recoverVolume.recoverVolumeCmd', 'recoverVolume.recoverVolumeCmd', ([], {}), '()\n', (17453, 17455), False, 'from marvin.cloudstackAPI import deleteVolume, extractVolume, recoverVolume\n'), ((17782, 17812), 'marvin.cloudstackAPI.deleteVolume.deleteVolumeCmd', 'deleteVolume.deleteVolumeCmd', ([], {}), '()\n', (17810, 17812), False, 'from marvin.cloudstackAPI import deleteVolume, extractVolume, recoverVolume\n'), ((19963, 20061), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine_4.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=virtual_machine_4.id, type=\n 'ROOT', listall=True)\n", (19974, 20061), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((20132, 20163), 'marvin.lib.utils.validateList', 'validateList', (['root_volumes_list'], {}), '(root_volumes_list)\n', (20144, 20163), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((20404, 20436), 'marvin.cloudstackAPI.extractVolume.extractVolumeCmd', 'extractVolume.extractVolumeCmd', ([], {}), '()\n', (20434, 20436), False, 'from marvin.cloudstackAPI import deleteVolume, extractVolume, recoverVolume\n'), ((20994, 21054), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'root_volume_id', 'listall': '(True)'}), '(self.apiclient, id=root_volume_id, listall=True)\n', (21005, 21054), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((21118, 21149), 'marvin.lib.utils.validateList', 'validateList', (['root_volumes_list'], {}), '(root_volumes_list)\n', (21130, 21149), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((21423, 21453), 'marvin.cloudstackAPI.deleteVolume.deleteVolumeCmd', 'deleteVolume.deleteVolumeCmd', ([], {}), '()\n', (21451, 21453), False, 'from marvin.cloudstackAPI import deleteVolume, extractVolume, recoverVolume\n'), ((3606, 3684), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['shared_network_offering']"], {}), "(cls.apiclient, cls.services['shared_network_offering'])\n", (3628, 3684), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((3892, 4078), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network2']"], {'networkofferingid': 'cls.network_offering.id', 'zoneid': 'cls.zone.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid'}), "(cls.apiclient, cls.services['network2'], networkofferingid=\n cls.network_offering.id, zoneid=cls.zone.id, accountid=cls.account.name,\n domainid=cls.account.domainid)\n", (3906, 4078), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((4282, 4367), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['isolated_network_offering']"], {}), "(cls.apiclient, cls.services['isolated_network_offering']\n )\n", (4304, 4367), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((4787, 4885), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network']", 'cls.account.name', 'cls.account.domainid'], {}), "(cls.apiclient, cls.services['network'], cls.account.name,\n cls.account.domainid)\n", (4801, 4885), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((7584, 7861), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'diskofferingid': 'self.disk_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, diskofferingid=self.\n disk_offering.id, templateid=self.template.id, zoneid=self.zone.id)\n", (7605, 7861), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((12337, 12575), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, templateid=self.template.id,\n zoneid=self.zone.id)\n", (12358, 12575), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((15656, 15894), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, templateid=self.template.id,\n zoneid=self.zone.id)\n", (15677, 15894), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n'), ((19187, 19425), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, templateid=self.template.id,\n zoneid=self.zone.id)\n", (19208, 19425), False, 'from marvin.lib.base import Resources, Volume, Account, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, DiskOffering, Zone\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for Templates
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.cloudstackAPI import listZones
from marvin.lib.utils import (cleanup_resources)
from marvin.lib.base import (Account,
Domain,
Template,
ServiceOffering,
VirtualMachine,
Snapshot,
Volume)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
get_builtin_template_info,
list_volumes,
list_snapshots)
# Import System modules
import time
class Services:
"""Test Templates Services
"""
def __init__(self):
self.services = {
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended for unique
# username
"password": "password",
},
"testdomain": {"name": "test"},
"service_offering": {
"name": "Tiny Instance",
"displaytext": "Tiny Instance",
"cpunumber": 1,
"cpuspeed": 100, # in MHz
"memory": 128, # In MBs
},
"disk_offering": {
"displaytext": "Small",
"name": "Small",
"disksize": 1
},
"virtual_machine": {
"displayname": "testVM",
"hypervisor": 'XenServer',
"protocol": 'TCP',
"ssh_port": 22,
"username": "root",
"password": "password",
"privateport": 22,
"publicport": 22,
},
"volume": {
"diskname": "Test Volume",
},
"templates": {
# Configs for different Template formats
# For Eg. raw image, zip etc
0: {
"displaytext": "Public Template",
"name": "Public template",
"ostype": 'CentOS 5.3 (64-bit)',
"url": "http://download.cloudstack.org/releases/2.0.0/UbuntuServer-10-04-64bit.vhd.bz2",
"hypervisor": 'XenServer',
"format": 'VHD',
"isfeatured": True,
"ispublic": True,
"isextractable": True,
},
},
"template": {
"displaytext": "Cent OS Template",
"name": "Cent OS Template",
"ostype": 'CentOS 5.3 (64-bit)',
"templatefilter": 'self',
"isfeatured": True,
"ispublic": True,
},
"templatefilter": 'self',
"ostype": 'CentOS 5.3 (64-bit)',
"sleep": 60,
"timeout": 10,
}
class TestCreateTemplate(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
if self.unsupportedHypervisor:
self.skipTest(
"Template creation from root volume is not supported in LXC")
return
def tearDown(self):
try:
# Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def setUpClass(cls):
cls.testClient = super(TestCreateTemplate, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
cls._cleanup = []
cls.unsupportedHypervisor = False
cls.hypervisor = cls.testClient.getHypervisorInfo()
if cls.hypervisor.lower() in ['lxc']:
cls.unsupportedHypervisor = True
return
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup.append(cls.service_offering)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
cls.services["account"] = cls.account.name
return
@classmethod
def tearDownClass(cls):
try:
cls.api_client = super(
TestCreateTemplate,
cls).getClsTestClient().getApiClient()
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "advancedns"], required_hardware="true")
def test_01_create_template_snampshot(self):
builtin_info = get_builtin_template_info(self.apiclient, self.zone.id)
self.services["templates"][0]["url"] = builtin_info[0]
self.services["templates"][0]["hypervisor"] = builtin_info[1]
self.services["templates"][0]["format"] = builtin_info[2]
# Register new template
template = Template.register(
self.apiclient,
self.services["templates"][0],
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid,
hypervisor=self.hypervisor,
details=[{"keyboard":"us","nicAdapter":"e1000","rootDiskController":"scsi"}]
)
self.debug(
"Registered a template of format: %s with ID: %s" % (
self.services["templates"][0]["format"],
template.id
))
# Wait for template to download
template.download(self.apiclient)
self.cleanup.append(template)
# Wait for template status to be changed across
time.sleep(self.services["sleep"])
timeout = self.services["timeout"]
while True:
list_template_response = Template.list(
self.apiclient,
templatefilter='all',
id=template.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid)
if isinstance(list_template_response, list):
break
elif timeout == 0:
raise Exception("List template failed!")
time.sleep(5)
timeout = timeout - 1
# Verify template response to check whether template added successfully
self.assertEqual(
isinstance(list_template_response, list),
True,
"Check for list template response return valid data"
)
self.assertNotEqual(
len(list_template_response),
0,
"Check template available in List Templates"
)
template_response = list_template_response[0]
self.assertEqual(
template_response.isready,
True,
"Template state is not ready, it is %s" % template_response.isready
)
self.assertIsNotNone(
template_response.details,
"Template details is %s" % template_response.details
)
# Deploy new virtual machine using template
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
mode=self.services["mode"]
)
self.debug("creating an instance with template ID: %s" % template.id)
vm_response = VirtualMachine.list(self.apiclient,
id=virtual_machine.id,
account=self.account.name,
domainid=self.account.domainid)
self.assertEqual(
isinstance(vm_response, list),
True,
"Check for list VMs response after VM deployment"
)
# Verify VM response to check whether VM deployment was successful
self.assertNotEqual(
len(vm_response),
0,
"Check VMs available in List VMs response"
)
vm = vm_response[0]
self.assertEqual(
vm.state,
'Running',
"Check the state of VM created from Template"
)
volumes = list_volumes(
self.apiclient,
virtualmachineid=vm.id,
type='ROOT',
listall=True
)
snapshot = Snapshot.create(
self.apiclient,
volumes[0].id,
account=self.account.name,
domainid=self.account.domainid
)
time.sleep(self.services["sleep"])
self.cleanup.append(snapshot)
self.debug("Snapshot created: ID - %s" % snapshot.id)
snapshots = list_snapshots(
self.apiclient,
id=snapshot.id
)
self.assertEqual(
isinstance(snapshots, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
snapshots,
None,
"Check if result exists in list item call"
)
self.assertEqual(
snapshots[0].id,
snapshot.id,
"Check resource id in list resources call"
)
virtual_machine.delete(self.apiclient, expunge=False)
list_vm_response = VirtualMachine.list(
self.apiclient,
id=virtual_machine.id
)
self.assertEqual(
isinstance(list_vm_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_vm_response),
0,
"Check VM avaliable in List Virtual Machines"
)
template = Template.create_from_snapshot(
self.apiclient,
snapshot,
self.services["template"]
)
self.cleanup.append(template)
# Verify created template
templates = Template.list(
self.apiclient ,
templatefilter=self.services["template"]["templatefilter"],
id=template.id
)
self.assertNotEqual(
templates,
None,
"Check if result exists in list item call"
)
self.assertEqual(
templates[0].id,
template.id,
"Check new template id in list resources call"
)
self.assertIsNotNone(
templates[0].details,
"Template details is %s" % template_response.details
)
return
| [
"marvin.lib.common.list_snapshots",
"marvin.lib.common.list_volumes",
"marvin.lib.common.get_builtin_template_info",
"marvin.lib.base.Template.list",
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.Snapshot.create",
"marvin.li... | [((6269, 6332), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns'], required_hardware='true')\n", (6273, 6332), False, 'from nose.plugins.attrib import attr\n'), ((4956, 4982), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (4966, 4982), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, list_volumes, list_snapshots\n'), ((5447, 5519), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (5469, 5519), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((5626, 5705), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], domainid=cls.domain.id)\n", (5640, 5705), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((6406, 6461), 'marvin.lib.common.get_builtin_template_info', 'get_builtin_template_info', (['self.apiclient', 'self.zone.id'], {}), '(self.apiclient, self.zone.id)\n', (6431, 6461), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, list_volumes, list_snapshots\n'), ((6713, 6981), 'marvin.lib.base.Template.register', 'Template.register', (['self.apiclient', "self.services['templates'][0]"], {'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid', 'hypervisor': 'self.hypervisor', 'details': "[{'keyboard': 'us', 'nicAdapter': 'e1000', 'rootDiskController': 'scsi'}]"}), "(self.apiclient, self.services['templates'][0], zoneid=\n self.zone.id, account=self.account.name, domainid=self.account.domainid,\n hypervisor=self.hypervisor, details=[{'keyboard': 'us', 'nicAdapter':\n 'e1000', 'rootDiskController': 'scsi'}])\n", (6730, 6981), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((7429, 7463), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (7439, 7463), False, 'import time\n'), ((8895, 9137), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'mode': "self.services['mode']"}), "(self.apiclient, self.services['virtual_machine'],\n templateid=template.id, accountid=self.account.name, domainid=self.\n account.domainid, serviceofferingid=self.service_offering.id, mode=self\n .services['mode'])\n", (8916, 9137), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((9318, 9440), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, id=virtual_machine.id, account=self.\n account.name, domainid=self.account.domainid)\n', (9337, 9440), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((10121, 10200), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'vm.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=vm.id, type='ROOT', listall=True)\n", (10133, 10200), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, list_volumes, list_snapshots\n'), ((10279, 10388), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'volumes[0].id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volumes[0].id, account=self.account.name,\n domainid=self.account.domainid)\n', (10294, 10388), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((10451, 10485), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (10461, 10485), False, 'import time\n'), ((10607, 10653), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'id': 'snapshot.id'}), '(self.apiclient, id=snapshot.id)\n', (10621, 10653), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, list_volumes, list_snapshots\n'), ((11210, 11268), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine.id'}), '(self.apiclient, id=virtual_machine.id)\n', (11229, 11268), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((11629, 11716), 'marvin.lib.base.Template.create_from_snapshot', 'Template.create_from_snapshot', (['self.apiclient', 'snapshot', "self.services['template']"], {}), "(self.apiclient, snapshot, self.services[\n 'template'])\n", (11658, 11716), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((11850, 11960), 'marvin.lib.base.Template.list', 'Template.list', (['self.apiclient'], {'templatefilter': "self.services['template']['templatefilter']", 'id': 'template.id'}), "(self.apiclient, templatefilter=self.services['template'][\n 'templatefilter'], id=template.id)\n", (11863, 11960), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((4508, 4555), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (4525, 4555), False, 'from marvin.lib.utils import cleanup_resources\n'), ((6094, 6141), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (6111, 6141), False, 'from marvin.lib.utils import cleanup_resources\n'), ((7564, 7716), 'marvin.lib.base.Template.list', 'Template.list', (['self.apiclient'], {'templatefilter': '"""all"""', 'id': 'template.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, templatefilter='all', id=template.id, zoneid=\n self.zone.id, account=self.account.name, domainid=self.account.domainid)\n", (7577, 7716), False, 'from marvin.lib.base import Account, Domain, Template, ServiceOffering, VirtualMachine, Snapshot, Volume\n'), ((7989, 8002), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (7999, 8002), False, 'import time\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" NIC tests for VM """
from marvin.codes import FAILED
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import (Account,
ServiceOffering,
Network,
VirtualMachine,
NetworkOffering)
from marvin.lib.common import (get_zone,
get_suitable_test_template,
get_domain)
from marvin.lib.utils import validateList
from marvin.codes import PASS
from nose.plugins.attrib import attr
import signal
import sys
import logging
import time
import threading
import Queue
class TestNic(cloudstackTestCase):
def setUp(self):
self.cleanup = []
self.logger = logging.getLogger('TestNIC')
self.stream_handler = logging.StreamHandler()
self.logger.setLevel(logging.DEBUG)
self.logger.addHandler(self.stream_handler)
def signal_handler(signal, frame):
self.tearDown()
sys.exit(0)
# assign the signal handler immediately
signal.signal(signal.SIGINT, signal_handler)
self.hypervisor = self.testClient.getHypervisorInfo()
if self.hypervisor.lower() == "hyperv":
self.skipTest("Not supported on Hyper-V")
try:
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.services = self.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
domain = get_domain(self.apiclient)
self.zone = get_zone(
self.apiclient,
self.testClient.getZoneForTests()
)
# if local storage is enabled, alter the offerings to use
# localstorage
# this step is needed for devcloud
if self.zone.localstorageenabled:
self.services["service_offerings"][
"tiny"]["storagetype"] = 'local'
template = get_suitable_test_template(
self.apiclient,
self.zone.id,
self.services["ostype"],
self.hypervisor
)
if template == FAILED:
assert False, "get_suitable_test_template() failed to return template with description %s" % self.services["ostype"]
# Set Zones and disk offerings
self.services["small"]["zoneid"] = self.zone.id
self.services["small"]["template"] = template.id
self.services["iso1"]["zoneid"] = self.zone.id
self.services["network"]["zoneid"] = self.zone.id
# Create Account, VMs, NAT Rules etc
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=domain.id
)
self.cleanup.insert(0, self.account)
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["tiny"]
)
self.cleanup.insert(0, self.service_offering)
####################
# Network offering
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
)
self.cleanup.insert(0, self.network_offering)
self.network_offering.update(
self.apiclient,
state='Enabled') # Enable Network offering
self.services["network"][
"networkoffering"] = self.network_offering.id
self.network_offering_shared = NetworkOffering.create(
self.apiclient,
self.services["network_offering_shared"],
)
self.cleanup.insert(0, self.network_offering_shared)
self.network_offering_shared.update(
self.apiclient,
state='Enabled') # Enable Network offering
self.services["network2"][
"networkoffering"] = self.network_offering_shared.id
################
# Test Network
self.test_network = Network.create(
self.apiclient,
self.services["network"],
self.account.name,
self.account.domainid,
)
self.cleanup.insert(0, self.test_network)
self.test_network2 = Network.create(
self.apiclient,
self.services["network2"],
self.account.name,
self.account.domainid,
zoneid=self.services["network"]["zoneid"]
)
self.cleanup.insert(0, self.test_network2)
except Exception as ex:
self.debug("Exception during NIC test SETUP!: " + str(ex))
@attr(
tags=[
"devcloud",
"smoke",
"advanced",
"advancedns"],
required_hardware="true")
def test_01_nic(self):
# TODO: SIMENH: add validation
"""Test to add and update added nic to a virtual machine"""
hypervisorIsVmware = False
isVmwareToolInstalled = False
if self.hypervisor.lower() == "vmware":
hypervisorIsVmware = True
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["small"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[self.test_network.id],
mode=self.zone.networktype if hypervisorIsVmware else "default"
)
self.cleanup.insert(0, self.virtual_machine)
vms = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
validateList(vms)[0],
PASS,
"vms list validation failed")
vm_response = vms[0]
self.assertEqual(
len(vm_response.nic),
1,
"Verify we only start with one nic"
)
self.assertEqual(
vm_response.nic[0].isdefault,
True,
"Verify initial adapter is set to default"
)
existing_nic_ip = vm_response.nic[0].ipaddress
existing_nic_id = vm_response.nic[0].id
self.virtual_machine.add_nic(
self.apiclient,
self.test_network2.id)
list_vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
len(list_vm_response[0].nic),
2,
"Verify we have 2 NIC's now"
)
# If hypervisor is Vmware, then check if
# the vmware tools are installed and the process is running
# Vmware tools are necessary for remove nic operations (vmware 5.5+)
if hypervisorIsVmware:
sshClient = self.virtual_machine.get_ssh_client()
result = str(
sshClient.execute("service vmware-tools status")).lower()
self.debug("and result is: %s" % result)
if "running" in result:
isVmwareToolInstalled = True
goForUnplugOperation = True
# If Vmware tools are not installed in case of vmware hypervisor
# then don't go further for unplug operation (remove nic) as it won't
# be supported
if hypervisorIsVmware and not isVmwareToolInstalled:
goForUnplugOperation = False
if goForUnplugOperation:
new_nic_id = ""
for nc in list_vm_response[0].nic:
if nc.ipaddress != existing_nic_ip:
new_nic_id = nc.id
self.virtual_machine.update_default_nic(self.apiclient, new_nic_id)
time.sleep(5)
list_vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
# iterate as we don't know for sure what order our NIC's will be
# returned to us.
for nc in list_vm_response[0].nic:
if nc.ipaddress == existing_nic_ip:
self.assertEqual(
nc.isdefault,
False,
"Verify initial adapter is NOT set to default"
)
else:
self.assertEqual(
nc.isdefault,
True,
"Verify second adapter is set to default"
)
with self.assertRaises(Exception):
self.virtual_machine.remove_nic(self.apiclient, new_nic_id)
self.virtual_machine.update_default_nic(
self.apiclient,
existing_nic_id)
time.sleep(5)
self.virtual_machine.remove_nic(self.apiclient, new_nic_id)
time.sleep(5)
list_vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
len(list_vm_response[0].nic),
1,
"Verify we are back to a signle NIC"
)
return
def test_02_nic_with_mac(self):
"""Test to add and update added nic to a virtual machine with specific mac"""
hypervisorIsVmware = False
isVmwareToolInstalled = False
if self.hypervisor.lower() == "vmware":
hypervisorIsVmware = True
self.virtual_machine2 = VirtualMachine.create(
self.apiclient,
self.services["small"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[self.test_network.id],
macaddress="aa:bb:cc:dd:ee:ff",
mode=self.zone.networktype if hypervisorIsVmware else "default"
)
self.cleanup.insert(0, self.virtual_machine2)
self.assertEqual(self.virtual_machine2.nic[0].macaddress, "aa:bb:cc:dd:ee:ff", "Mac address not honored")
vmdata = self.virtual_machine2.add_nic(
self.apiclient,
self.test_network2.id,
macaddress="ee:ee:dd:cc:bb:aa")
found = False
for n in vmdata.nic:
if n.macaddress == "ee:ee:dd:cc:bb:aa":
found = True
break
self.assertTrue(found, "Nic not successfully added with specified mac address")
@attr(tags = ["devcloud", "advanced", "advancedns", "smoke"], required_hardware="true")
def test_03_nic_multiple_vmware(self):
"""Test to adding multiple nics to a VMware VM and restarting VM
Refer to CLOUDSTACK-10107 for details, in this test we add 8 nics to
a VM and stop, start it to show that VMware VMs are not limited to
having up to 7 nics.
"""
if self.hypervisor.lower() != "vmware":
self.skipTest("Skipping test applicable for VMware")
network_offering = NetworkOffering.create(
self.apiclient,
self.services["nw_off_isolated_persistent"]
)
self.cleanup.insert(0, network_offering)
network_offering.update(self.apiclient, state='Enabled')
offering = dict(self.services["network"])
offering["networkoffering"] = network_offering.id
networks = []
def createNetwork(idx):
offering["name"] = "Test Network%s" % idx
network = Network.create(
self.apiclient,
offering,
self.account.name,
self.account.domainid,
zoneid=self.services["network"]["zoneid"]
)
networks.append(network)
self.cleanup.insert(0, network)
class NetworkMaker(threading.Thread):
def __init__(self, queue=None, createNetwork=None):
threading.Thread.__init__(self)
self.queue = queue
self.createNetwork = createNetwork
def run(self):
while True:
idx = self.queue.get()
if idx is not None:
self.createNetwork(idx)
self.queue.task_done()
# Start multiple networks
tsize = 8
queue = Queue.Queue()
for _ in range(tsize):
worker = NetworkMaker(queue, createNetwork)
worker.setDaemon(True)
worker.start()
for idx in range(tsize):
queue.put(idx)
queue.join()
# Deploy a VM
vm = VirtualMachine.create(
self.apiclient,
self.services["small"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[networks[0].id],
mode=self.zone.networktype
)
self.cleanup.insert(0, vm)
# Add nics to networks
for network in networks[1:]:
response = vm.add_nic(self.apiclient, network.id)
found = False
for nic in response.nic:
if nic.networkid == network.id:
found = True
break
self.assertTrue(found, "Nic not successfully added for the specific network")
# Stop VM
vm.stop(self.apiclient, forced=True)
vms = VirtualMachine.list(
self.apiclient,
id=vm.id
)
self.assertEqual(
validateList(vms)[0],
PASS,
"vms list validation failed")
vm_response = vms[0]
self.assertEqual(
vm_response.state,
"Stopped",
"Verify the VM is stopped"
)
# Start VM
vm.start(self.apiclient)
vms = VirtualMachine.list(
self.apiclient,
id=vm.id
)
self.assertEqual(
validateList(vms)[0],
PASS,
"vms list validation failed")
vm_response = vms[0]
self.assertEqual(
vm_response.state,
"Running",
"Verify the VM is running"
)
self.assertTrue(len(vm_response.nic) == len(networks), "Number of nics on VM not 8")
# Validate nics exist on each of the network
for network in networks:
found = False
for nic in vm_response.nic:
if nic.networkid == network.id:
found = True
break
self.assertTrue(found, "Nic not found for the specific network")
def tearDown(self):
try:
for obj in self.cleanup:
try:
obj.delete(self.apiclient)
time.sleep(10)
except Exception as ex:
self.debug(
"Error deleting: " +
str(obj) +
", exception: " +
str(ex))
except Exception as e:
self.debug("Warning! Exception in tearDown: %s" % e)
| [
"marvin.lib.utils.validateList",
"marvin.lib.base.Network.create",
"marvin.lib.base.Account.create",
"marvin.lib.common.get_domain",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.NetworkOffering.create",
"ma... | [((5725, 5813), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'smoke', 'advanced', 'advancedns']", 'required_hardware': '"""true"""'}), "(tags=['devcloud', 'smoke', 'advanced', 'advancedns'],\n required_hardware='true')\n", (5729, 5813), False, 'from nose.plugins.attrib import attr\n'), ((11578, 11666), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['devcloud', 'advanced', 'advancedns', 'smoke'],\n required_hardware='true')\n", (11582, 11666), False, 'from nose.plugins.attrib import attr\n'), ((1554, 1582), 'logging.getLogger', 'logging.getLogger', (['"""TestNIC"""'], {}), "('TestNIC')\n", (1571, 1582), False, 'import logging\n'), ((1613, 1636), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1634, 1636), False, 'import logging\n'), ((1887, 1931), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal_handler'], {}), '(signal.SIGINT, signal_handler)\n', (1900, 1931), False, 'import signal\n'), ((6202, 6483), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['small']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'networkids': '[self.test_network.id]', 'mode': "(self.zone.networktype if hypervisorIsVmware else 'default')"}), "(self.apiclient, self.services['small'], accountid=\n self.account.name, domainid=self.account.domainid, serviceofferingid=\n self.service_offering.id, networkids=[self.test_network.id], mode=self.\n zone.networktype if hypervisorIsVmware else 'default')\n", (6223, 6483), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((6631, 6694), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (6650, 6694), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((7426, 7489), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (7445, 7489), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((10600, 10917), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['small']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'networkids': '[self.test_network.id]', 'macaddress': '"""aa:bb:cc:dd:ee:ff"""', 'mode': "(self.zone.networktype if hypervisorIsVmware else 'default')"}), "(self.apiclient, self.services['small'], accountid=\n self.account.name, domainid=self.account.domainid, serviceofferingid=\n self.service_offering.id, networkids=[self.test_network.id], macaddress\n ='aa:bb:cc:dd:ee:ff', mode=self.zone.networktype if hypervisorIsVmware else\n 'default')\n", (10621, 10917), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((12126, 12214), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['nw_off_isolated_persistent']"], {}), "(self.apiclient, self.services[\n 'nw_off_isolated_persistent'])\n", (12148, 12214), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((13445, 13458), 'Queue.Queue', 'Queue.Queue', ([], {}), '()\n', (13456, 13458), False, 'import Queue\n'), ((13726, 13964), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['small']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'networkids': '[networks[0].id]', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['small'], accountid=\n self.account.name, domainid=self.account.domainid, serviceofferingid=\n self.service_offering.id, networkids=[networks[0].id], mode=self.zone.\n networktype)\n", (13747, 13964), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((14549, 14594), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'vm.id'}), '(self.apiclient, id=vm.id)\n', (14568, 14594), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((14988, 15033), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'vm.id'}), '(self.apiclient, id=vm.id)\n', (15007, 15033), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((1818, 1829), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1826, 1829), False, 'import sys\n'), ((2370, 2396), 'marvin.lib.common.get_domain', 'get_domain', (['self.apiclient'], {}), '(self.apiclient)\n', (2380, 2396), False, 'from marvin.lib.common import get_zone, get_suitable_test_template, get_domain\n'), ((2850, 2953), 'marvin.lib.common.get_suitable_test_template', 'get_suitable_test_template', (['self.apiclient', 'self.zone.id', "self.services['ostype']", 'self.hypervisor'], {}), "(self.apiclient, self.zone.id, self.services[\n 'ostype'], self.hypervisor)\n", (2876, 2953), False, 'from marvin.lib.common import get_zone, get_suitable_test_template, get_domain\n'), ((3558, 3634), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'domain.id'}), "(self.apiclient, self.services['account'], domainid=domain.id)\n", (3572, 3634), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((3783, 3870), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['tiny']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'tiny'])\n", (3805, 3870), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((4071, 4144), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {}), "(self.apiclient, self.services['network_offering'])\n", (4093, 4144), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((4528, 4613), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering_shared']"], {}), "(self.apiclient, self.services['network_offering_shared']\n )\n", (4550, 4613), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((5059, 5161), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']", 'self.account.name', 'self.account.domainid'], {}), "(self.apiclient, self.services['network'], self.account.name,\n self.account.domainid)\n", (5073, 5161), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((5324, 5470), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network2']", 'self.account.name', 'self.account.domainid'], {'zoneid': "self.services['network']['zoneid']"}), "(self.apiclient, self.services['network2'], self.account.name,\n self.account.domainid, zoneid=self.services['network']['zoneid'])\n", (5338, 5470), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((8817, 8830), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (8827, 8830), False, 'import time\n'), ((8863, 8926), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (8882, 8926), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((9851, 9864), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (9861, 9864), False, 'import time\n'), ((9949, 9962), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (9959, 9962), False, 'import time\n'), ((9995, 10058), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (10014, 10058), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((12599, 12729), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', 'offering', 'self.account.name', 'self.account.domainid'], {'zoneid': "self.services['network']['zoneid']"}), "(self.apiclient, offering, self.account.name, self.account.\n domainid, zoneid=self.services['network']['zoneid'])\n", (12613, 12729), False, 'from marvin.lib.base import Account, ServiceOffering, Network, VirtualMachine, NetworkOffering\n'), ((6772, 6789), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (6784, 6789), False, 'from marvin.lib.utils import validateList\n'), ((13028, 13059), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (13053, 13059), False, 'import threading\n'), ((14671, 14688), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (14683, 14688), False, 'from marvin.lib.utils import validateList\n'), ((15110, 15127), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (15122, 15127), False, 'from marvin.lib.utils import validateList\n'), ((15954, 15968), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (15964, 15968), False, 'import time\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for Nuage VSP SDN plugin
"""
# Import Local Modules
from nuageTestCase import nuageTestCase
from marvin.lib.base import Account
# Import System Modules
from nose.plugins.attrib import attr
class TestNuageVsp(nuageTestCase):
""" Test Nuage VSP SDN plugin
"""
@classmethod
def setUpClass(cls):
super(TestNuageVsp, cls).setUpClass()
return
def setUp(self):
# Create an account
self.account = Account.create(self.api_client,
self.test_data["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account]
return
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_nuage_vsp(self):
""" Test Nuage VSP SDN plugin with basic Isolated Network functionality
"""
# 1. Verify that the Nuage VSP network service provider is successfully created and enabled.
# 2. Create and enable Nuage VSP Isolated Network offering, check if it is successfully created and enabled.
# 3. Create an Isolated Network with Nuage VSP Isolated Network offering, check if it is successfully created
# and is in the "Allocated" state.
# 4. Deploy a VM in the created Isolated network, check if the Isolated network state is changed to
# "Implemented", and both the VM & VR are successfully deployed and are in the "Running" state.
# 5. Deploy one more VM in the created Isolated network, check if the VM is successfully deployed and is in the
# "Running" state.
# 6. Delete the created Isolated Network after destroying its VMs, check if the Isolated network is successfully
# deleted.
self.debug("Validating the Nuage VSP network service provider...")
self.validate_NetworkServiceProvider("NuageVsp", state="Enabled")
# Creating a network offering
self.debug("Creating and enabling Nuage VSP Isolated Network offering...")
network_offering = self.create_NetworkOffering(
self.test_data["nuagevsp"]["isolated_network_offering"])
self.validate_NetworkOffering(network_offering, state="Enabled")
# Creating a network
self.debug("Creating an Isolated Network with Nuage VSP Isolated Network offering...")
network = self.create_Network(network_offering)
self.validate_Network(network, state="Allocated")
# Deploying a VM in the network
vm_1 = self.create_VM(network)
self.validate_Network(network, state="Implemented")
vr = self.get_Router(network)
self.check_Router_state(vr, state="Running")
self.check_VM_state(vm_1, state="Running")
# VSD verification
self.verify_vsp_network(self.domain.id, network)
self.verify_vsp_router(vr)
self.verify_vsp_vm(vm_1)
# Deploying one more VM in the network
vm_2 = self.create_VM(network)
self.check_VM_state(vm_2, state="Running")
# VSD verification
self.verify_vsp_vm(vm_2)
# Deleting the network
self.debug("Deleting the Isolated Network with Nuage VSP Isolated Network offering...")
self.delete_VM(vm_1)
self.delete_VM(vm_2)
self.delete_Network(network)
with self.assertRaises(Exception):
self.validate_Network(network)
self.debug("Isolated Network successfully deleted in CloudStack")
# VSD verification
with self.assertRaises(Exception):
self.verify_vsp_network(self.domain.id, network)
self.debug("Isolated Network successfully deleted in VSD")
| [
"marvin.lib.base.Account.create"
] | [((1552, 1614), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (1556, 1614), False, 'from nose.plugins.attrib import attr\n'), ((1244, 1343), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.test_data['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.test_data['account'], admin=True,\n domainid=self.domain.id)\n", (1258, 1343), False, 'from marvin.lib.base import Account\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for shared networks
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.cloudstackAPI import rebootRouter, stopRouter, startRouter
from marvin.lib.base import (Account,
Network,
NetworkOffering,
VirtualMachine,
Project,
PhysicalNetwork,
Domain,
StaticNATRule,
FireWallRule,
ServiceOffering,
PublicIPAddress,
Router,
NATRule)
from marvin.lib.utils import (cleanup_resources,
validateList)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
get_free_vlan,
wait_for_cleanup,
verifyRouterState,
verifyGuestTrafficPortGroups)
from marvin.sshClient import SshClient
from marvin.codes import PASS
from ddt import ddt, data
import time
import random
import netaddr
@ddt
class TestSharedNetworks(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestSharedNetworks, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.testdata = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testdata["ostype"]
)
cls.testdata["virtual_machine"]["zoneid"] = cls.zone.id
cls.testdata["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testdata["service_offering"]
)
cls.testdata["shared_network_offering"]["specifyVlan"] = "True"
cls.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
cls.shared_network_offering = NetworkOffering.create(
cls.api_client,
cls.testdata["shared_network_offering"],
conservemode=False
)
NetworkOffering.update(
cls.shared_network_offering,
cls.api_client,
id=cls.shared_network_offering.id,
state="enabled"
)
cls.testdata["shared_network_offering_all_services"]["specifyVlan"] = "True"
cls.testdata["shared_network_offering_all_services"]["specifyIpRanges"] = "True"
cls.shared_network_offering_all_services = NetworkOffering.create(
cls.api_client,
cls.testdata["shared_network_offering_all_services"],
conservemode=False
)
NetworkOffering.update(
cls.shared_network_offering_all_services,
cls.api_client,
id=cls.shared_network_offering_all_services.id,
state="enabled"
)
cls._cleanup = [
cls.service_offering
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.api_client = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
# Set the subnet number of shared networks randomly prior to execution
# of each test case to avoid overlapping of ip addresses
shared_network_subnet_number = random.randrange(1, 254)
self.testdata["shared_network"]["netmask"] = "255.255.255.0"
self.testdata["shared_network"]["gateway"] = "172.16." + \
str(shared_network_subnet_number) + ".1"
self.testdata["shared_network"]["startip"] = "172.16." + \
str(shared_network_subnet_number) + ".2"
self.testdata["shared_network"]["endip"] = "172.16." + \
str(shared_network_subnet_number) + ".20"
self.cleanup = []
self.cleanup_networks = []
self.cleanup_accounts = []
self.cleanup_domains = []
self.cleanup_projects = []
self.cleanup_vms = []
return
def tearDown(self):
try:
# Clean up, terminate the created network offerings
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
# below components is not a part of cleanup because to mandate the
# order and to cleanup network
try:
for vm in self.cleanup_vms:
vm.delete(self.api_client)
except Exception as e:
raise Exception(
"Warning: Exception during virtual machines cleanup : %s" %
e)
try:
for project in self.cleanup_projects:
project.delete(self.api_client)
except Exception as e:
raise Exception(
"Warning: Exception during project cleanup : %s" %
e)
try:
for account in self.cleanup_accounts:
account.delete(self.api_client)
except Exception as e:
raise Exception(
"Warning: Exception during account cleanup : %s" %
e)
# Wait till all resources created are cleaned up completely and then
# attempt to delete domains
wait_for_cleanup(self.api_client, ["account.cleanup.interval"])
try:
for network in self.cleanup_networks:
network.delete(self.api_client)
except Exception:
self.debug("Network %s failed to delete. Moving on" % network.id)
pass # because domain/account deletion will get rid of the network
try:
for domain in self.cleanup_domains:
domain.delete(self.api_client)
except Exception as e:
raise Exception(
"Warning: Exception during domain cleanup : %s" %
e)
return
def verifyRouterResponse(self, router_response, ip):
if (router_response) and (isinstance(router_response, list)) and \
(router_response[0].state == "Running") and \
(router_response[0].publicip == ip):
return True
return False
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_sharedNetworkOffering_01(self):
""" Test shared network Offering 01 """
# Steps,
# 1. create an Admin Account - admin-XABU1
# 2. listPhysicalNetworks in available zone
# 3. createNetworkOffering:
# - name = "MySharedOffering"
# - guestiptype="shared"
# - services = {Dns, Dhcp, UserData}
# - conservemode = false
# - specifyVlan = true
# - specifyIpRanges = true
# 4. Enable network offering - updateNetworkOffering - state=Enabled
# 5. delete the admin account
# Validations,
# 1. listAccounts name=admin-XABU1, state=enabled returns your account
# 2. listPhysicalNetworks should return at least one active physical
# network
# 3. listNetworkOfferings - name=mysharedoffering , should list
# offering in disabled state
# 4. listNetworkOfferings - name=mysharedoffering, should list
# enabled offering
# Create an account
self.account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin Type account created: %s" % self.account.name)
# Verify that there should be at least one physical network present in
# zone.
list_physical_networks_response = PhysicalNetwork.list(
self.api_client,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_physical_networks_response, list),
True,
"listPhysicalNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_physical_networks_response),
0,
"listPhysicalNetworks should return at least one physical network."
)
physical_network = list_physical_networks_response[0]
self.debug("Physical network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
self.debug(
"NetworkOffering created and enabled: %s" %
self.shared_network_offering.id)
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_sharedNetworkOffering_02(self):
""" Test Shared Network Offering 02 """
# Steps,
# 1. create an Admin Account - admin-XABU1
# 2. listPhysicalNetworks in available zone
# 3. createNetworkOffering:
# - name = "MySharedOffering"
# - guestiptype="shared"
# - services = {Dns, Dhcp, UserData}
# - conservemode = false
# - specifyVlan = false
# - specifyIpRanges = false
# 4. delete the admin account
# Validations,
# 1. listAccounts name=admin-XABU1, state=enabled returns your account
# 2. listPhysicalNetworks should return at least one active physical
# network
# 3. createNetworkOffering fails - vlan should be specified in
# advanced zone
# Create an account
self.account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin type account created: %s" % self.account.name)
# Verify that there should be at least one physical network present in
# zone.
list_physical_networks_response = PhysicalNetwork.list(
self.api_client,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_physical_networks_response, list),
True,
"listPhysicalNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_physical_networks_response),
0,
"listPhysicalNetworks should return at least one physical network."
)
physical_network = list_physical_networks_response[0]
self.debug("Physical network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "False"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "False"
try:
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
self.fail(
"Network offering got created with vlan as False in advance\
mode and shared guest type, which is invalid case.")
except Exception as e:
self.debug(
"Network Offering creation failed with vlan as False\
in advance mode and shared guest type. Exception: %s" %
e)
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_sharedNetworkOffering_03(self):
""" Test Shared Network Offering 03 """
# Steps,
# 1. create an Admin Account - admin-XABU1
# 2. listPhysicalNetworks in available zone
# 3. createNetworkOffering:
# - name = "MySharedOffering"
# - guestiptype="shared"
# - services = {Dns, Dhcp, UserData}
# - conservemode = false
# - specifyVlan = true
# - specifyIpRanges = false
# 4. delete the admin account
# Validations,
# 1. listAccounts name=admin-XABU1, state=enabled returns your account
# 2. listPhysicalNetworks should return at least one active physical
# network
# 3. createNetworkOffering fails - ip ranges should be specified when
# creating shared network offering
# Create an account
self.account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin Type account created: %s" % self.account.name)
# Verify that there should be at least one physical network present in
# zone.
list_physical_networks_response = PhysicalNetwork.list(
self.api_client,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_physical_networks_response, list),
True,
"listPhysicalNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_physical_networks_response),
0,
"listPhysicalNetworks should return at least one physical network."
)
physical_network = list_physical_networks_response[0]
self.debug("Physical Network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "False"
try:
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
self.fail(
"Network offering got created with vlan as True and ip ranges\
as False in advance mode and with shared guest type,\
which is invalid case.")
except Exception as e:
self.debug(
"Network Offering creation failed with vlan as true and ip\
ranges as False in advance mode and with shared guest type.\
Exception : %s" % e)
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_createSharedNetwork_All(self):
""" Test Shared Network ALL """
# Steps,
# 1. create an Admin Account - admin-XABU1
# 2. listPhysicalNetworks in available zone
# 3. createNetworkOffering:
# - name = "MySharedOffering"
# - guestiptype="shared"
# - services = {Dns, Dhcp, UserData}
# - conservemode = false
# - specifyVlan = true
# - specifyIpRanges = true
# 4. Create network offering - updateNetworkOffering - state=Enabled
# 5. createNetwork
# - name = mysharednetwork, displaytext = mysharednetwork
# - vlan = 123 (say)
# - networkofferingid = <mysharedoffering>
# - gw = 172.16.15.1, startip = 172.16.15.2 , endip = 172.16.15.200
# - netmask=255.255.255.0
# - scope = all
# 6. create User account - user-ASJDK
# 7. deployVirtualMachine in this account and in admin account &
# within networkid = <mysharednetwork>
# 8. delete the admin account and the user account
# Validations,
# 1. listAccounts name=admin-XABU1, state=enabled returns account
# 2. listPhysicalNetworks should return at least one active
# physical network
# 3. listNetworkOfferings - name=mysharedoffering , should list
# offering in disabled state
# 4. listNetworkOfferings - name=mysharedoffering, should list
# enabled offering
# 5. listNetworks - name = mysharednetwork should list the
# successfully created network, verify the guestIp ranges and
# CIDR are as given in the createNetwork call
# 6. No checks reqd
# 7. a. listVirtualMachines should show both VMs in running state
# in the user account and the admin account
# b. VM's IPs shoud be in the range of the shared network ip ranges
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin type account created: %s" % self.admin_account.name)
# Create an user account
self.user_account = Account.create(
self.api_client,
self.testdata["account"],
admin=False,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.user_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.user_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The user account created is not enabled."
)
self.debug("User type account created: %s" % self.user_account.name)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
self.debug(
"Shared Network offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network)
list_networks_response = Network.list(
self.api_client,
id=self.network.id
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False.")
self.debug(
"Shared Network created for scope domain: %s" %
self.network.id)
self.admin_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
networkids=self.network.id,
serviceofferingid=self.service_offering.id
)
self.cleanup_vms.append(self.admin_account_virtual_machine)
vms = VirtualMachine.list(
self.api_client,
id=self.admin_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
self.debug(
"Virtual Machine created: %s" %
self.admin_account_virtual_machine.id)
ip_range = list(
netaddr.iter_iprange(
str(
self.testdata["shared_network"]["startip"]), str(
self.testdata["shared_network"]["endip"])))
if netaddr.IPAddress(str(vms[0].nic[0].ipaddress)) not in ip_range:
self.fail(
"Virtual machine ip should be from the ip range assigned to\
network created.")
self.user_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.user_account.name,
domainid=self.user_account.domainid,
serviceofferingid=self.service_offering.id,
networkids=self.network.id
)
vms = VirtualMachine.list(
self.api_client,
id=self.user_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
self.debug(
"Virtual Machine created: %s" %
self.user_account_virtual_machine.id)
ip_range = list(
netaddr.iter_iprange(
str(
self.testdata["shared_network"]["startip"]), str(
self.testdata["shared_network"]["endip"])))
if netaddr.IPAddress(str(vms[0].nic[0].ipaddress)) not in ip_range:
self.fail(
"Virtual machine ip should be from the ip range assigned to\
network created.")
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_createSharedNetwork_accountSpecific(self):
""" Test Shared Network with scope account """
# Steps,
# 1. create an Admin Account - admin-XABU1
# create a user account = user-SOPJD
# 2. listPhysicalNetworks in available zone
# 3. createNetworkOffering:
# - name = "MySharedOffering"
# - guestiptype="shared"
# - services = {Dns, Dhcp, UserData}
# - conservemode = false
# - specifyVlan = true
# - specifyIpRanges = true
# 4. Enable network offering - updateNetworkOffering - state=Enabled
# 5. createNetwork
# - name = mysharednetwork, displaytext = mysharednetwork
# - vlan = 123 (say)
# - networkofferingid = <mysharedoffering>
# - gw = 172.16.15.1, startip = 172.16.15.2 , endip = 172.16.15.200
# - netmask=255.255.255.0
# - scope = account, account = user-SOPJD, domain = ROOT
# 6. deployVirtualMachine in this account and in admin account
# & within networkid = <mysharednetwork>
# 7. delete the admin account and the user account
# Validations,
# 1. listAccounts name=admin-XABU1 and user-SOPJD, state=enabled
# returns your account
# 2. listPhysicalNetworks should return at least one active
# physical network
# 3. listNetworkOfferings - name=mysharedoffering , should list
# offering in disabled state
# 4. listNetworkOfferings - name=mysharedoffering, should list
# enabled offering
# 5. listNetworks - name = mysharednetwork should list the
# successfully created network, verify the guestIp ranges and CIDR
# are as given in the createNetwork call
# 6. VM deployed in admin account should FAIL to deploy
# VM should be deployed in user account only
# verify VM's IP is within shared network range
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin type account created: %s" % self.admin_account.name)
# Create an user account
self.user_account = Account.create(
self.api_client,
self.testdata["account"],
admin=False,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.user_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.user_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The user account created is not enabled."
)
self.debug("User type account created: %s" % self.user_account.name)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical Network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be by default disabled."
)
self.debug(
"Shared Network Offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Account"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
accountid=self.user_account.name,
domainid=self.user_account.domainid,
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id
)
self.cleanup_networks.append(self.network)
list_networks_response = Network.list(
self.api_client,
id=self.network.id
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False.")
self.debug("Network created: %s" % self.network.id)
try:
self.admin_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkids=self.network.id,
serviceofferingid=self.service_offering.id
)
self.fail(
"Virtual Machine got created in admin account with network\
created but the network used is of scope account and for\
user account.")
except Exception as e:
self.debug(
"Virtual Machine creation failed as network used have scoped\
only for user account. Exception: %s" % e)
self.user_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.user_account.name,
domainid=self.user_account.domainid,
networkids=self.network.id,
serviceofferingid=self.service_offering.id
)
vms = VirtualMachine.list(
self.api_client,
id=self.user_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
ip_range = list(
netaddr.iter_iprange(
str(
self.testdata["shared_network"]["startip"]), str(
self.testdata["shared_network"]["endip"])))
if netaddr.IPAddress(str(vms[0].nic[0].ipaddress)) not in ip_range:
self.fail(
"Virtual machine ip should be from the ip range assigned\
to network created.")
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_createSharedNetwork_domainSpecific(self):
""" Test Shared Network with scope domain """
# Steps,
# 1. create an Admin Account - admin-XABU1
# create a domain - DOM
# create a domain admin account = domadmin-SOPJD
# create a user in domain - DOM
# 2. listPhysicalNetworks in available zone
# 3. createNetworkOffering:
# - name = "MySharedOffering"
# - guestiptype="shared"
# - services = {Dns, Dhcp, UserData}
# - conservemode = false
# - specifyVlan = true
# - specifyIpRanges = true
# 4. Enable network offering - updateNetworkOffering - state=Enabled
# 5. createNetwork
# - name = mysharednetwork, displaytext = mysharednetwork
# - vlan = 123 (say)
# - networkofferingid = <mysharedoffering>
# - gw = 172.16.15.1, startip = 172.16.15.2 , endip = 172.16.15.200
# - netmask=255.255.255.0
# - scope = domain, domain = DOM
# 6. deployVirtualMachine in this admin, domainadmin and user account
# & within networkid = <mysharednetwork>
# 7. delete all the accounts
# Validations,
# 1. listAccounts state=enabled returns your accounts,
# listDomains - DOM should be created
# 2. listPhysicalNetworks should return at least one
# active physical network
# 3. listNetworkOfferings - name=mysharedoffering , should list
# offering in disabled state
# 4. listNetworkOfferings - name=mysharedoffering, should list
# enabled offering
# 5. listNetworks - name = mysharednetwork should list the
# successfully created network, verify the guestIp ranges and
# CIDR are as given in the createNetwork call
# 6. VM should NOT be deployed in admin account
# VM should be deployed in user account and domain admin account
# verify VM's IP are within shared network range
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin type account created: %s" % self.admin_account.id)
# create domain
self.dom_domain = Domain.create(
self.api_client,
self.testdata["domain"],
)
self.cleanup_domains.append(self.dom_domain)
# verify that the account got created with state enabled
list_domains_response = Domain.list(
self.api_client,
id=self.dom_domain.id
)
self.assertEqual(
isinstance(list_domains_response, list),
True,
"listDomains returned invalid object in response."
)
self.assertNotEqual(
len(list_domains_response),
0,
"listDomains returned empty list."
)
self.debug("Domain created: %s" % self.dom_domain.id)
# Create admin account
self.domain_admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.dom_domain.id
)
self.cleanup_accounts.append(self.domain_admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.domain_admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The domain admin account created is not enabled."
)
self.debug(
"Domain admin account created: %s" %
self.domain_admin_account.id)
# Create an user account
self.domain_user_account = Account.create(
self.api_client,
self.testdata["account"],
admin=False,
domainid=self.dom_domain.id
)
self.cleanup_accounts.append(self.domain_user_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.domain_user_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The domain user account created is not enabled."
)
self.debug(
"Domain user account created: %s" %
self.domain_user_account.id)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical Network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be by default disabled."
)
self.debug(
"Shared Network Offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
accountid=self.domain_admin_account.name,
domainid=self.dom_domain.id,
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id
)
self.cleanup_networks.append(self.network)
list_networks_response = Network.list(
self.api_client,
id=self.network.id,
listall=True
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False.")
self.debug("Shared Network created: %s" % self.network.id)
try:
self.admin_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkids=self.network.id,
serviceofferingid=self.service_offering.id
)
self.fail(
"Virtual Machine got created in admin account with network\
specified but the network used is of scope domain and admin\
account is not part of this domain.")
except Exception as e:
self.debug(
"Virtual Machine creation failed as network used have scoped\
only for DOM domain. Exception: %s" % e)
self.domain_user_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.domain_user_account.name,
domainid=self.domain_user_account.domainid,
networkids=self.network.id,
serviceofferingid=self.service_offering.id
)
self.cleanup_vms.append(self.domain_user_account_virtual_machine)
vms = VirtualMachine.list(
self.api_client,
id=self.domain_user_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
ip_range = list(
netaddr.iter_iprange(
str(
self.testdata["shared_network"]["startip"]), str(
self.testdata["shared_network"]["endip"])))
if netaddr.IPAddress(str(vms[0].nic[0].ipaddress)) not in ip_range:
self.fail(
"Virtual machine ip should be from the ip range\
assigned to network created.")
self.domain_admin_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.domain_admin_account.name,
domainid=self.domain_admin_account.domainid,
networkids=self.network.id,
serviceofferingid=self.service_offering.id
)
self.cleanup_vms.append(self.domain_admin_account_virtual_machine)
vms = VirtualMachine.list(
self.api_client,
id=self.domain_admin_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
ip_range = list(
netaddr.iter_iprange(
str(
self.testdata["shared_network"]["startip"]), str(
self.testdata["shared_network"]["endip"])))
if netaddr.IPAddress(str(vms[0].nic[0].ipaddress)) not in ip_range:
self.fail(
"Virtual machine ip should be from the ip range assigne\
to network created.")
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_createSharedNetwork_projectSpecific(self):
""" Test Shared Network with scope project """
# Steps,
# 1. create an Admin Account - admin-XABU1
# create a project - proj-SADJKS
# create another project - proj-SLDJK
# 2. listPhysicalNetworks in available zone
# 3. createNetworkOffering:
# - name = "MySharedOffering"
# - guestiptype="shared"
# - services = {Dns, Dhcp, UserData}
# - conservemode = false
# - specifyVlan = true
# - specifyIpRanges = true
# 4. Enable network offering - updateNetworkOffering - state=Enabled
# 5. createNetwork
# - name = mysharednetwork, displaytext = mysharednetwork
# - vlan = 123 (say)
# - networkofferingid = <mysharedoffering>
# - gw = 172.16.15.1, startip = 172.16.15.2 , endip = 172.16.15.200
# - netmask=255.255.255.0
# - scope = project, project = proj-SLDJK
# 6. deployVirtualMachine in admin, project and user account & within
# networkid = <mysharednetwork>
# 7. delete all the accounts
# Validations,
# 1. listAccounts state=enabled returns your accounts, listDomains
# - DOM should be created
# 2. listPhysicalNetworks should return at least one active physical
# network
# 3. listNetworkOfferings - name=mysharedoffering , should list
# offering in disabled state
# 4. listNetworkOfferings - name=mysharedoffering, should list
# enabled offering
# 5. listNetworks - name = mysharednetwork should list the
# successfully created network, verify the guestIp ranges
# and CIDR are as given in the createNetwork call
# 6. VM should NOT be deployed in admin account and user account
# VM should be deployed in project account only
# verify VM's IP are within shared network range
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin account created: %s" % self.admin_account.id)
self.testdata["project"]["name"] = "proj-SADJKS"
self.testdata["project"]["displaytext"] = "proj-SADJKS"
self.project1 = Project.create(
self.api_client,
self.testdata["project"],
account=self.admin_account.name,
domainid=self.admin_account.domainid
)
self.cleanup_projects.append(self.project1)
list_projects_response = Project.list(
self.api_client,
id=self.project1.id,
listall=True
)
self.assertEqual(
isinstance(list_projects_response, list),
True,
"listProjects returned invalid object in response."
)
self.assertNotEqual(
len(list_projects_response),
0,
"listProjects should return at least one."
)
self.debug("Project created: %s" % self.project1.id)
self.testdata["project"]["name"] = "proj-SLDJK"
self.testdata["project"]["displaytext"] = "proj-SLDJK"
self.project2 = Project.create(
self.api_client,
self.testdata["project"],
account=self.admin_account.name,
domainid=self.admin_account.domainid
)
self.cleanup_projects.append(self.project2)
list_projects_response = Project.list(
self.api_client,
id=self.project2.id,
listall=True
)
self.assertEqual(
isinstance(list_projects_response, list),
True,
"listProjects returned invalid object in response."
)
self.assertNotEqual(
len(list_projects_response),
0,
"listProjects should return at least one."
)
self.debug("Project2 created: %s" % self.project2.id)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical Network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be by default disabled."
)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
self.debug(
"Shared Network found: %s" %
self.shared_network_offering.id)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "account"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
projectid=self.project1.id,
domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id
)
self.cleanup_networks.append(self.network)
list_networks_response = Network.list(
self.api_client,
id=self.network.id,
projectid=self.project1.id,
listall=True
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False")
self.debug("Shared Network created: %s" % self.network.id)
with self.assertRaises(Exception):
self.project2_admin_account_virtual_machine =\
VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
networkids=self.network.id,
projectid=self.project2.id,
serviceofferingid=self.service_offering.id)
self.debug("Deploying a vm to project other than the one in which \
network is created raised an Exception as expected")
self.project1_admin_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
networkids=self.network.id,
projectid=self.project1.id,
serviceofferingid=self.service_offering.id
)
vms = VirtualMachine.list(
self.api_client,
id=self.project1_admin_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
ip_range = list(
netaddr.iter_iprange(
str(
self.testdata["shared_network"]["startip"]), str(
self.testdata["shared_network"]["endip"])))
if netaddr.IPAddress(str(vms[0].nic[0].ipaddress)) not in ip_range:
self.fail(
"Virtual machine ip should be from the ip range assigned\
to network created.")
@unittest.skip(
"skipped - This is a redundant case and also this\
is causing issue for rest fo the cases ")
@attr(tags=["advanced", "advancedns", "NA"])
def test_createSharedNetwork_usedVlan(self):
""" Test Shared Network with used vlan 01 """
# Steps,
# 1. create an Admin account
# 2. create a shared NetworkOffering
# 3. enable the network offering
# 4. listPhysicalNetworks
# - vlan = guest VLAN range = 10-90 (say)
# 5. createNetwork
# - name = mysharednetwork, displaytext = mysharednetwork
# - vlan = any vlan between 10-90
# - networkofferingid = <mysharedoffering>
# - gw = 172.16.15.1, startip = 172.16.15.2 , endip = 172.16.15.200
# - netmask=255.255.255.0
# - scope = all
# 6. delete admin account
# Validations,
# 1. listAccounts state=enabled returns your account
# 2. listNetworkOfferings - name=mysharedoffering , should list
# offering in disabled state
# 3. listNetworkOfferings - name=mysharedoffering, should list
# enabled offering
# 4. listPhysicalNetworks should return at least one active
# physical network
# 5. network creation should FAIL since VLAN is used for
# guest networks
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Domain admin account created: %s" % self.admin_account.id)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
self.debug(
"Shared Network Offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["vlan"] = str.split(
str(physical_network.vlan), "-")[0]
self.testdata["shared_network"]["acltype"] = "domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
try:
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.fail(
"Network created with used vlan %s id, which is invalid" %
shared_vlan)
except Exception as e:
self.debug(
"Network creation failed because the valn id being used by\
another network. Exception: %s" % e)
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_createSharedNetwork_usedVlan2(self):
""" Test Shared Network with used vlan 02 """
# Steps,
# 1. create an Admin account
# 2. create a shared NetworkOffering
# 3. enable the network offering
# 4. listPhysicalNetworks
# - vlan = guest VLAN range = 10-90 (say)
# 5. createNetwork
# - name = mysharednetwork, displaytext = mysharednetwork
# - vlan = any vlan beyond 10-90 (123 for eg)
# - networkofferingid = <mysharedoffering>
# - gw = 172.16.15.1, startip = 172.16.15.2 , endip = 172.16.15.200
# - netmask=255.255.255.0
# - scope = all
# 6. createNetwork again with same VLAN but different IP ranges and
# gateway
# 7. delete admin account
# Validations,
# 1. listAccounts state=enabled returns your account
# 2. listNetworkOfferings - name=mysharedoffering , should list
# offering in disabled state
# 3. listNetworkOfferings - name=mysharedoffering, should list
# enabled offering
# 4. listPhysicalNetworks should return at least one active
# physical network
# 5. network creation shoud PASS
# 6. network creation should FAIL since VLAN is already used by
# previously created network
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin account created: %s" % self.admin_account.id)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical Network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
self.debug(
"Shared Network Offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.debug(
"Creating a shared network in non-cloudstack VLAN %s" %
shared_vlan)
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network)
list_networks_response = Network.list(
self.api_client,
id=self.network.id
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False.")
self.debug("Network created: %s" % self.network.id)
shared_network_subnet_number = random.randrange(1, 254)
self.testdata["shared_network"]["gateway"] = "172.16." + \
str(shared_network_subnet_number) + ".1"
self.testdata["shared_network"]["startip"] = "172.16." + \
str(shared_network_subnet_number) + ".2"
self.testdata["shared_network"]["endip"] = "172.16." + \
str(shared_network_subnet_number) + ".20"
self.testdata["shared_network"]["acltype"] = "domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
try:
self.network1 = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network1)
self.fail(
"Network got created with used vlan id, which is invalid")
except Exception as e:
self.debug(
"Network creation failed because the valn id being used by\
another network. Exception: %s" % e)
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_deployVM_multipleSharedNetwork(self):
""" Test Vm deployment with multiple shared networks """
# Steps,
# 0. create a user account
# 1. Create two shared Networks (scope=ALL, different IP ranges)
# 2. deployVirtualMachine in both the above networkids within the
# user account
# 3. delete the user account
# Validations,
# 1. shared networks should be created successfully
# 2. a. VM should deploy successfully
# b. VM should be deployed in both networks and have IP in both the
# networks
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin account created: %s" % self.admin_account.id)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical Network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
self.debug(
"Shared Network offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network)
list_networks_response = Network.list(
self.api_client,
id=self.network.id
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False.")
self.debug("Shared Network created: %s" % self.network.id)
shared_network_subnet_number = random.randrange(1, 254)
self.testdata["shared_network"]["gateway"] = "172.16." + \
str(shared_network_subnet_number) + ".1"
self.testdata["shared_network"]["startip"] = "172.16." + \
str(shared_network_subnet_number) + ".2"
self.testdata["shared_network"]["endip"] = "172.16." + \
str(shared_network_subnet_number) + ".20"
self.testdata["shared_network"]["acltype"] = "domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
shared_vlan = get_free_vlan(self.api_client, self.zone.id)[1]
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.testdata["shared_network"]["vlan"] = shared_vlan
self.network1 = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network1)
list_networks_response = Network.list(
self.api_client,
id=self.network1.id
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False.")
self.debug("Network created: %s" % self.network1.id)
self.network_admin_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkids=self.network.id,
serviceofferingid=self.service_offering.id
)
vms = VirtualMachine.list(
self.api_client,
id=self.network_admin_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
self.debug(
"Virtual Machine created: %s" %
self.network_admin_account_virtual_machine.id)
self.assertTrue(
self.network_admin_account_virtual_machine.nic[0].ipaddress
is not None,
"ip should be assigned to running virtual machine")
self.network1_admin_account_virtual_machine = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkids=self.network1.id,
serviceofferingid=self.service_offering.id
)
vms = VirtualMachine.list(
self.api_client,
id=self.network1_admin_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
self.debug(
"Virtual Machine created: %s" %
self.network1_admin_account_virtual_machine.id)
self.assertTrue(
self.network1_admin_account_virtual_machine.nic[0].ipaddress
is not None,
"ip should be assigned to running virtual machine")
@attr(tags=["advanced", "advancedns"], required_hardware="true")
def test_deployVM_isolatedAndShared(self):
""" Test VM deployment in shared and isolated networks """
# Steps,
# 0. create a user account
# 1. Create one shared Network (scope=ALL, different IP ranges)
# 2. Create one Isolated Network
# 3. deployVirtualMachine in both the above networkids within
# the user account
# 4. apply FW rule and enable PF for port 22 for guest VM on
# isolated network
# 5. delete the user account
# Validations,
# 1. shared network should be created successfully
# 2. isolated network should be created successfully
# 3.
# a. VM should deploy successfully
# b. VM should be deployed in both networks and have IP in both
# the networks
# 4. FW and PF should apply successfully, ssh into the VM should work
# over isolated network
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin type account created: %s" % self.admin_account.name)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
self.debug(
"Shared Network offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
self.isolated_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["isolated_network_offering"],
conservemode=False
)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.isolated_network_offering,
self.api_client,
id=self.isolated_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.isolated_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The isolated network offering state should get\
updated to Enabled.")
self.debug(
"Isolated Network Offering created: %s" %
self.isolated_network_offering.id)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.shared_network = Network.create(
self.api_client,
self.testdata["shared_network"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id
)
self.cleanup_networks.append(self.shared_network)
list_networks_response = Network.list(
self.api_client,
id=self.shared_network.id
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False.")
self.debug("Shared Network created: %s" % self.shared_network.id)
self.isolated_network = Network.create(
self.api_client,
self.testdata["isolated_network"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkofferingid=self.isolated_network_offering.id,
zoneid=self.zone.id
)
self.cleanup_networks.append(self.isolated_network)
list_networks_response = Network.list(
self.api_client,
id=self.isolated_network.id
)
self.assertEqual(
isinstance(list_networks_response, list),
True,
"listNetworks returned invalid object in response."
)
self.assertNotEqual(
len(list_networks_response),
0,
"listNetworks returned empty list."
)
self.debug("Isolated Network created: %s" % self.isolated_network.id)
self.shared_network_admin_account_virtual_machine = \
VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkids=self.shared_network.id,
serviceofferingid=self.service_offering.id
)
vms = VirtualMachine.list(
self.api_client,
id=self.shared_network_admin_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
self.debug(
"Virtual Machine created: %s" %
self.shared_network_admin_account_virtual_machine.id)
self.assertTrue(
self.shared_network_admin_account_virtual_machine.nic[0].ipaddress
is not None,
"ip should be assigned to running virtual machine")
self.isolated_network_admin_account_virtual_machine = \
VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkids=self.isolated_network.id,
serviceofferingid=self.service_offering.id
)
vms = VirtualMachine.list(
self.api_client,
id=self.isolated_network_admin_account_virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"listVirtualMachines returned invalid object in response."
)
self.assertNotEqual(
len(vms),
0,
"listVirtualMachines returned empty list."
)
self.debug(
"Virtual Machine created: %s" %
self.isolated_network_admin_account_virtual_machine.id)
self.assertTrue(
self.isolated_network_admin_account_virtual_machine.nic[0].ipaddress
is not None,
"ip should be assigned to running virtual machine")
self.debug(
"Associating public IP for account: %s" %
self.admin_account.name)
self.public_ip = PublicIPAddress.create(
self.api_client,
accountid=self.admin_account.name,
zoneid=self.zone.id,
domainid=self.admin_account.domainid,
networkid=self.isolated_network.id
)
self.debug(
"Associated %s with network %s" %
(self.public_ip.ipaddress.ipaddress, self.isolated_network.id))
self.debug(
"Creating PF rule for IP address: %s" %
self.public_ip.ipaddress.ipaddress)
public_ip = self.public_ip.ipaddress
# Enable Static NAT for VM
StaticNATRule.enable(
self.api_client,
public_ip.id,
self.isolated_network_admin_account_virtual_machine.id
)
self.debug("Enabled static NAT for public IP ID: %s" % public_ip.id)
# Create Firewall rule on source NAT
fw_rule = FireWallRule.create(
self.api_client,
ipaddressid=self.public_ip.ipaddress.id,
protocol='TCP',
cidrlist=[self.testdata["fwrule"]["cidr"]],
startport=self.testdata["fwrule"]["startport"],
endport=self.testdata["fwrule"]["endport"]
)
self.debug("Created firewall rule: %s" % fw_rule.id)
fw_rules = FireWallRule.list(
self.api_client,
id=fw_rule.id
)
self.assertEqual(
isinstance(fw_rules, list),
True,
"List fw rules should return a valid firewall rules"
)
self.assertNotEqual(
len(fw_rules),
0,
"Length of fw rules response should not be zero"
)
# Should be able to SSH VM
try:
self.debug(
"SSH into VM: %s" %
self.isolated_network_admin_account_virtual_machine.id)
self.isolated_network_admin_account_virtual_machine.get_ssh_client(
ipaddress=self.public_ip.ipaddress.ipaddress)
except Exception as e:
self.fail(
"SSH Access failed for %s: %s" %
(self.isolated_network_admin_account_virtual_machine.ipaddress,
e))
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_networkWithsubdomainaccessTrue(self):
""" Test Shared Network with subdomainaccess=True """
# Steps,
# 1. create Network using shared network offering for scope=Account
# and subdomainaccess=true.
# Validations,
# (Expected) API should fail saying that subdomainaccess cannot be
# given when scope is Account
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin type account created: %s" % self.admin_account.id)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical Network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
self.debug(
"Shared Network Offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Account"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.testdata["shared_network"]["subdomainaccess"] = "True"
try:
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id
)
self.fail("Network creation should fail.")
except:
self.debug(
"Network creation failed because subdomainaccess parameter was\
passed when scope was account.")
@attr(tags=["advanced", "advancedns"], required_hardware="false")
def test_networkWithsubdomainaccessFalse(self):
""" Test shared Network with subdomainaccess=False """
# Steps,
# 1. create Network using shared network offering for scope=Account
# and subdomainaccess=false
# Validations,
# (Expected) API should fail saying that subdomainaccess cannot be
# given when scope is Account
# Create admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
self.assertEqual(
isinstance(list_accounts_response, list),
True,
"listAccounts returned invalid object in response."
)
self.assertNotEqual(
len(list_accounts_response),
0,
"listAccounts returned empty list."
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin type account created: %s" % self.admin_account.id)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical Network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
self.debug(
"Shared Network Offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
self.assertEqual(
isinstance(list_network_offerings_response, list),
True,
"listNetworkOfferings returned invalid object in response."
)
self.assertNotEqual(
len(list_network_offerings_response),
0,
"listNetworkOfferings returned empty list."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Account"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.testdata["shared_network"]["subdomainaccess"] = "False"
try:
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
accountid=self.admin_account.name,
domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id
)
self.fail("Network creation should fail.")
except:
self.debug(
"Network creation failed because subdomainaccess parameter\
was passed when scope was account.")
@attr(tags=["advanced"], required_hardware="false")
def test_escalation_ES1621(self):
"""
@summary: ES1621:Allow creating shared networks with overlapping
ip ranges in different vlans
@steps:
Step1: Create an Admin account for the test
Step2: Create shared network offering
Step3: Update the network offering to Enabled state
Step4: list network offering
Step5: Create network with above offering
Step6: List netwokrs and verify the network created in
step5 in the response
Step7: Create another network with offering,vlan and ip range
same as in step6
Step8: Verify that network creationin Step7 should fail
Step9: Repeat step6 with diff vlan but same ip range and network
offering
Step10: List netwokrs and verify the network created in step9
in the response
Step11: Dislable network offering for the cleanup to delete at
the end of the test
"""
# Creating Admin account
self.admin_account = Account.create(
self.api_client,
self.testdata["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup_accounts.append(self.admin_account)
# verify that the account got created with state enabled
list_accounts_response = Account.list(
self.api_client,
id=self.admin_account.id,
listall=True
)
status = validateList(list_accounts_response)
self.assertEqual(
PASS,
status[0],
"listAccounts returned invalid object in response"
)
self.assertEqual(
list_accounts_response[0].state,
"enabled",
"The admin account created is not enabled."
)
self.debug("Admin type account created: %s" % self.admin_account.name)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical network found: %s" % physical_network.id)
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Verify that the network offering got created
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
status = validateList(list_network_offerings_response)
self.assertEqual(
PASS,
status[0],
"listNetworkOfferings returned invalid object in response."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Disabled",
"The network offering created should be bydefault disabled."
)
self.debug(
"Shared Network offering created: %s" %
self.shared_network_offering.id)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# Verify that the state of the network offering is updated
list_network_offerings_response = NetworkOffering.list(
self.api_client,
id=self.shared_network_offering.id
)
status = validateList(list_network_offerings_response)
self.assertEqual(
PASS,
status[0],
"listNetworkOfferings returned invalid object in\
response after enabling it."
)
self.assertEqual(
list_network_offerings_response[0].state,
"Enabled",
"The network offering state should get updated to Enabled."
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network)
list_networks_response = Network.list(
self.api_client,
id=self.network.id
)
status = validateList(list_accounts_response)
self.assertEqual(
PASS,
status[0],
"listNetworks returned invalid object in response."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is\
set to False.")
self.debug(
"Shared Network created for scope domain: %s" %
self.network.id)
# Create another network with same ip range and vlan. It should fail
try:
self.network1 = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network1)
self.fail(
"CS is allowing to create shared network with ip range and\
vlan same as used by another shared network")
except Exception as e:
self.debug("Network Creation Exception Raised: %s" % e)
# Create another shared network with overlapped ip range but different
# vlan
physical_network, shared_vlan1 = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan1 is None:
self.fail("Failed to get free vlan id for shared network")
self.testdata["shared_network"]["vlan"] = shared_vlan1
self.network2 = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network2)
list_networks_response = Network.list(
self.api_client,
id=self.network2.id
)
status = validateList(list_networks_response)
self.assertEqual(
PASS,
status[0],
"listNetworks returned invalid object in response after\
creating with overlapped ip range in diff vlan."
)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is set to\
False after creating with overlapped ip range in diff vlan")
self.debug(
"Shared Network created for scope domain: %s" %
self.network2.id)
# Update network offering state from enabled to disabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="disabled"
)
self.cleanup_networks.append(self.shared_network_offering)
return
@data(True, False)
@attr(tags=["advanced", "advancedns", "dvs"], required_hardware="false")
def test_restart_network(self, cleanup):
""" Test restart shared Network
# Steps
# 1. Create a shared network in an account
# 2. Deploy a VM in the network
# 3. Restart the network with cleanup true and false
# 4. List the router for the network and verify that publicip of
the router remain the same
"""
# Create admin account
account = Account.create(
self.api_client,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup_accounts.append(account)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical network found: %s" % physical_network.id)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
shared_network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(shared_network)
self.debug(
"Shared Network created for scope domain: %s" %
shared_network.id)
VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
networkids=shared_network.id,
serviceofferingid=self.service_offering.id
)
list_router_response = Router.list(
self.api_client,
networkid=shared_network.id,
listall=True
)
self.assertEqual(
validateList(list_router_response)[0],
PASS,
"Router list validation failed"
)
router = list_router_response[0]
# Store old values before restart
old_publicip = router.publicip
shared_network.restart(self.api_client, cleanup=cleanup)
# Get router details after restart
list_router_response = Router.list(
self.api_client,
networkid=shared_network.id,
listall=True
)
self.assertEqual(
validateList(list_router_response)[0],
PASS,
"Router list validation failed"
)
router = list_router_response[0]
self.assertEqual(
router.publicip,
old_publicip,
"Public IP of the router should remain same after network restart"
)
return
@attr(tags=["advanced", "advancedns", "dvs"], required_hardware="false")
def test_reboot_router(self):
"""Test reboot router
# Steps
# 1. Create a shared network in an account
# 2. Deploy a VM in the network
# 3. Restart the router related to shared network
# 4. List the router for the network and verify that publicip of
the router remain the same
"""
# Create admin account
account = Account.create(
self.api_client,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup_accounts.append(account)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical network found: %s" % physical_network.id)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
shared_network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(shared_network)
self.debug(
"Shared Network created for scope domain: %s" %
shared_network.id)
vm = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
networkids=shared_network.id,
serviceofferingid=self.service_offering.id
)
self.cleanup_vms.append(vm)
list_router_response = Router.list(
self.api_client,
networkid=shared_network.id,
listall=True
)
self.assertEqual(
validateList(list_router_response)[0],
PASS,
"Router list validation failed"
)
router = list_router_response[0]
# Store old values before restart
public_ip = router.publicip
self.debug("Rebooting the router with ID: %s" % router.id)
# Stop the router
cmd = rebootRouter.rebootRouterCmd()
cmd.id = router.id
self.api_client.rebootRouter(cmd)
isRouterRunningSuccessfully = False
# List routers to check state of router
retries_cnt = 6
while retries_cnt >= 0:
router_response = Router.list(
self.api_client,
id=router.id
)
if self.verifyRouterResponse(router_response, public_ip):
isRouterRunningSuccessfully = True
break
time.sleep(10)
retries_cnt = retries_cnt - 1
if not isRouterRunningSuccessfully:
self.fail(
"Router response after reboot is either is invalid\
or in stopped state")
return
@attr(tags=["advanced", "advancedns", "dvs"], required_hardware="false")
def test_stop_start_router(self):
"""Test stop and start router
# Steps
# 1. Create a shared network in an account
# 2. Deploy a VM in the network
# 3. Stop the router related to shared network and start it again
# 4. List the router for the network and verify that publicip of
the router remain the same
"""
# Create admin account
account = Account.create(
self.api_client,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup_accounts.append(account)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical network found: %s" % physical_network.id)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
shared_network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(shared_network)
self.debug(
"Shared Network created for scope domain: %s" %
shared_network.id)
vm = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
networkids=shared_network.id,
serviceofferingid=self.service_offering.id
)
self.cleanup_vms.append(vm)
list_router_response = Router.list(
self.api_client,
networkid=shared_network.id,
listall=True
)
self.assertEqual(
validateList(list_router_response)[0],
PASS,
"Router list validation failed"
)
router = list_router_response[0]
self.debug("Stopping the router with ID: %s" % router.id)
# Reboot the router
cmd = stopRouter.stopRouterCmd()
cmd.id = router.id
self.api_client.stopRouter(cmd)
response = verifyRouterState(self.api_client, router.id, "stopped")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
self.debug("Starting the router with ID: %s" % router.id)
# Reboot the router
cmd = startRouter.startRouterCmd()
cmd.id = router.id
self.api_client.startRouter(cmd)
response = verifyRouterState(self.api_client, router.id, "running")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
return
@attr(tags=["advanced", "advancedns", "dvs"], required_hardware="false")
def test_acquire_ip(self):
"""Test acquire IP in shared network
# Steps
# 1. Create a shared network in an account
# 2. Deploy a VM in the network
# 3. Acquire a public IP in the network
# 4. List the public IP by passing the id, it should be listed properly
# 5. Create Firewall and NAT rules for the public IP and verify that
ssh to vm works using the public IP
# 6. Disassociate the public IP and try to list the public IP
# 7. The list should be empty
"""
# Create admin account
account = Account.create(
self.api_client,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup_accounts.append(account)
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.debug("Physical network found: %s" % physical_network.id)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering_all_services.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
shared_network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering_all_services.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(shared_network)
self.debug(
"Shared Network created for scope domain: %s" %
shared_network.id)
vm = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
networkids=shared_network.id,
serviceofferingid=self.service_offering.id
)
self.cleanup_vms.append(vm)
public_ip = PublicIPAddress.create(
self.api_client,
accountid=account.name,
zoneid=self.zone.id,
domainid=account.domainid,
networkid=shared_network.id)
# listPublicIpAddresses should return newly created public IP
list_pub_ip_addr_resp = PublicIPAddress.list(
self.api_client,
id=public_ip.ipaddress.id
)
self.assertEqual(
validateList(list_pub_ip_addr_resp)[0],
PASS,
"IP address list validation failed"
)
self.assertEqual(
list_pub_ip_addr_resp[0].id,
public_ip.ipaddress.id,
"Check Correct IP Address is returned in the List Call"
)
FireWallRule.create(
self.api_client,
ipaddressid=public_ip.ipaddress.id,
protocol='TCP',
cidrlist=[
self.testdata["fwrule"]["cidr"]],
startport=self.testdata["fwrule"]["startport"],
endport=self.testdata["fwrule"]["endport"])
NATRule.create(
self.api_client,
vm,
self.testdata["natrule"],
ipaddressid=public_ip.ipaddress.id,
networkid=shared_network.id)
SshClient(
public_ip.ipaddress.ipaddress,
vm.ssh_port,
vm.username,
vm.password
)
public_ip.delete(self.api_client)
list_pub_ip_addr_resp = PublicIPAddress.list(
self.api_client,
id=public_ip.ipaddress.id
)
self.assertEqual(
list_pub_ip_addr_resp,
None,
"Check if disassociated IP Address is no longer available"
)
return
@attr(tags=["dvs"], required_hardware="true")
def test_guest_traffic_port_groups_shared_network(self):
""" Verify vcenter port groups are created for shared network
# Steps,
# 1. Create a shared network
# 2. Deploy a VM in shared network so that router is
# created
# 3. Verify that corresponding port groups are created
for guest traffic
"""
if self.hypervisor.lower() != "vmware":
self.skipTest("This test is intended for only vmware")
physical_network, shared_vlan = get_free_vlan(
self.api_client, self.zone.id)
if shared_vlan is None:
self.fail("Failed to get free vlan id for shared network")
self.testdata["shared_network_offering"]["specifyVlan"] = "True"
self.testdata["shared_network_offering"]["specifyIpRanges"] = "True"
# Create Network Offering
self.shared_network_offering = NetworkOffering.create(
self.api_client,
self.testdata["shared_network_offering"],
conservemode=False
)
# Update network offering state from disabled to enabled.
NetworkOffering.update(
self.shared_network_offering,
self.api_client,
id=self.shared_network_offering.id,
state="enabled"
)
# create network using the shared network offering created
self.testdata["shared_network"]["acltype"] = "Domain"
self.testdata["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.testdata["shared_network"][
"physicalnetworkid"] = physical_network.id
self.testdata["shared_network"]["vlan"] = shared_vlan
self.network = Network.create(
self.api_client,
self.testdata["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id,
)
self.cleanup_networks.append(self.network)
vm = VirtualMachine.create(
self.api_client,
self.testdata["virtual_machine"],
networkids=self.network.id,
serviceofferingid=self.service_offering.id
)
self.cleanup_vms.append(vm)
routers = Router.list(self.api_client,
networkid=self.network.id,
listall=True)
self.assertEqual(validateList(routers)[0], PASS,
"No Router associated with the network found")
response = verifyGuestTrafficPortGroups(self.api_client,
self.config,
self.zone)
self.assertEqual(response[0], PASS, response[1])
return
| [
"marvin.lib.base.Domain.create",
"marvin.cloudstackAPI.stopRouter.stopRouterCmd",
"marvin.lib.base.VirtualMachine.list",
"marvin.cloudstackAPI.rebootRouter.rebootRouterCmd",
"marvin.lib.base.PublicIPAddress.create",
"marvin.lib.common.get_free_vlan",
"marvin.lib.base.FireWallRule.create",
"marvin.lib.... | [((7694, 7758), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (7698, 7758), False, 'from nose.plugins.attrib import attr\n'), ((12781, 12845), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (12785, 12845), False, 'from nose.plugins.attrib import attr\n'), ((16243, 16307), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (16247, 16307), False, 'from nose.plugins.attrib import attr\n'), ((19795, 19859), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (19799, 19859), False, 'from nose.plugins.attrib import attr\n'), ((30485, 30549), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (30489, 30549), False, 'from nose.plugins.attrib import attr\n'), ((40628, 40692), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (40632, 40692), False, 'from nose.plugins.attrib import attr\n'), ((54244, 54308), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (54248, 54308), False, 'from nose.plugins.attrib import attr\n'), ((64964, 65094), 'unittest.skip', 'unittest.skip', (['"""skipped - This is a redundant case and also this is causing issue for rest fo the cases """'], {}), "(\n 'skipped - This is a redundant case and also this is causing issue for rest fo the cases '\n )\n", (64977, 65094), False, 'import unittest\n'), ((65101, 65144), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'NA']"}), "(tags=['advanced', 'advancedns', 'NA'])\n", (65105, 65144), False, 'from nose.plugins.attrib import attr\n'), ((70916, 70980), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (70920, 70980), False, 'from nose.plugins.attrib import attr\n'), ((78674, 78738), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (78678, 78738), False, 'from nose.plugins.attrib import attr\n'), ((88401, 88464), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns'], required_hardware='true')\n", (88405, 88464), False, 'from nose.plugins.attrib import attr\n'), ((101378, 101442), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (101382, 101442), False, 'from nose.plugins.attrib import attr\n'), ((106441, 106505), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns'], required_hardware='false')\n", (106445, 106505), False, 'from nose.plugins.attrib import attr\n'), ((111514, 111564), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (111518, 111564), False, 'from nose.plugins.attrib import attr\n'), ((119440, 119457), 'ddt.data', 'data', (['(True)', '(False)'], {}), '(True, False)\n', (119444, 119457), False, 'from ddt import ddt, data\n'), ((119463, 119534), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'dvs']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'dvs'], required_hardware='false')\n", (119467, 119534), False, 'from nose.plugins.attrib import attr\n'), ((122473, 122544), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'dvs']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'dvs'], required_hardware='false')\n", (122477, 122544), False, 'from nose.plugins.attrib import attr\n'), ((125744, 125815), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'dvs']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'dvs'], required_hardware='false')\n", (125748, 125815), False, 'from nose.plugins.attrib import attr\n'), ((129119, 129190), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'dvs']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'dvs'], required_hardware='false')\n", (129123, 129190), False, 'from nose.plugins.attrib import attr\n'), ((133200, 133244), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['dvs']", 'required_hardware': '"""true"""'}), "(tags=['dvs'], required_hardware='true')\n", (133204, 133244), False, 'from nose.plugins.attrib import attr\n'), ((2463, 2489), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2473, 2489), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((2651, 2716), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.testdata['ostype'])\n", (2663, 2716), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((2930, 3002), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.testdata['service_offering']"], {}), "(cls.api_client, cls.testdata['service_offering'])\n", (2952, 3002), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((3225, 3329), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(cls.api_client, cls.testdata[\n 'shared_network_offering'], conservemode=False)\n", (3247, 3329), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((3380, 3504), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['cls.shared_network_offering', 'cls.api_client'], {'id': 'cls.shared_network_offering.id', 'state': '"""enabled"""'}), "(cls.shared_network_offering, cls.api_client, id=cls.\n shared_network_offering.id, state='enabled')\n", (3402, 3504), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((3785, 3902), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.testdata['shared_network_offering_all_services']"], {'conservemode': '(False)'}), "(cls.api_client, cls.testdata[\n 'shared_network_offering_all_services'], conservemode=False)\n", (3807, 3902), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((3953, 4108), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['cls.shared_network_offering_all_services', 'cls.api_client'], {'id': 'cls.shared_network_offering_all_services.id', 'state': '"""enabled"""'}), "(cls.shared_network_offering_all_services, cls.\n api_client, id=cls.shared_network_offering_all_services.id, state='enabled'\n )\n", (3975, 4108), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((4838, 4862), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (4854, 4862), False, 'import random\n'), ((6775, 6838), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['account.cleanup.interval']"], {}), "(self.api_client, ['account.cleanup.interval'])\n", (6791, 6838), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((8830, 8928), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (8844, 8928), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((9134, 9197), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.account.id', 'listall': '(True)'}), '(self.api_client, id=self.account.id, listall=True)\n', (9146, 9197), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((9931, 9989), 'marvin.lib.base.PhysicalNetwork.list', 'PhysicalNetwork.list', (['self.api_client'], {'zoneid': 'self.zone.id'}), '(self.api_client, zoneid=self.zone.id)\n', (9951, 9989), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((10757, 10863), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (10779, 10863), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((11003, 11076), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (11023, 11076), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((11722, 11849), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (11744, 11849), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((12012, 12085), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (12032, 12085), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((13729, 13827), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (13743, 13827), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((14033, 14096), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.account.id', 'listall': '(True)'}), '(self.api_client, id=self.account.id, listall=True)\n', (14045, 14096), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((14830, 14888), 'marvin.lib.base.PhysicalNetwork.list', 'PhysicalNetwork.list', (['self.api_client'], {'zoneid': 'self.zone.id'}), '(self.api_client, zoneid=self.zone.id)\n', (14850, 14888), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((17216, 17314), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (17230, 17314), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((17520, 17583), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.account.id', 'listall': '(True)'}), '(self.api_client, id=self.account.id, listall=True)\n', (17532, 17583), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((18317, 18375), 'marvin.lib.base.PhysicalNetwork.list', 'PhysicalNetwork.list', (['self.api_client'], {'zoneid': 'self.zone.id'}), '(self.api_client, zoneid=self.zone.id)\n', (18337, 18375), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((21891, 21989), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (21905, 21989), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((22201, 22270), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (22213, 22270), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((22934, 23033), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(False)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=False,\n domainid=self.domain.id)\n", (22948, 23033), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((23244, 23312), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.user_account.id', 'listall': '(True)'}), '(self.api_client, id=self.user_account.id, listall=True)\n', (23256, 23312), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((23952, 23996), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (23965, 23996), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((24410, 24516), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (24432, 24516), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((24656, 24729), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (24676, 24729), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((25493, 25620), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (25515, 25620), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((25784, 25857), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (25804, 25857), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((26846, 26986), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (26860, 26986), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((27128, 27177), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network.id'}), '(self.api_client, id=self.network.id)\n', (27140, 27177), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((27885, 28033), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'networkids': 'self.network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n networkids=self.network.id, serviceofferingid=self.service_offering.id)\n", (27906, 28033), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((28172, 28269), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.admin_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account_virtual_machine.\n id, listall=True)\n', (28191, 28269), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((29197, 29420), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.user_account.name', 'domainid': 'self.user_account.domainid', 'serviceofferingid': 'self.service_offering.id', 'networkids': 'self.network.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.user_account.name, domainid=self.user_account.domainid,\n serviceofferingid=self.service_offering.id, networkids=self.network.id)\n", (29218, 29420), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((29509, 29605), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.user_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.user_account_virtual_machine.\n id, listall=True)\n', (29528, 29605), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((32625, 32723), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (32639, 32723), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((32935, 33004), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (32947, 33004), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((33668, 33767), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(False)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=False,\n domainid=self.domain.id)\n", (33682, 33767), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((33978, 34046), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.user_account.id', 'listall': '(True)'}), '(self.api_client, id=self.user_account.id, listall=True)\n', (33990, 34046), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((34686, 34730), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (34699, 34730), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((35144, 35250), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (35166, 35250), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((35390, 35463), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (35410, 35463), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((36228, 36355), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (36250, 36355), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((36518, 36591), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (36538, 36591), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((37581, 37797), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'accountid': 'self.user_account.name', 'domainid': 'self.user_account.domainid', 'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'], accountid=\n self.user_account.name, domainid=self.user_account.domainid,\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (37595, 37797), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((37957, 38006), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network.id'}), '(self.api_client, id=self.network.id)\n', (37969, 38006), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((39454, 39677), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.user_account.name', 'domainid': 'self.user_account.domainid', 'networkids': 'self.network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.user_account.name, domainid=self.user_account.domainid,\n networkids=self.network.id, serviceofferingid=self.service_offering.id)\n", (39475, 39677), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((39766, 39862), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.user_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.user_account_virtual_machine.\n id, listall=True)\n', (39785, 39862), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((42835, 42933), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (42849, 42933), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((43145, 43214), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (43157, 43214), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((43865, 43920), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.api_client', "self.testdata['domain']"], {}), "(self.api_client, self.testdata['domain'])\n", (43878, 43920), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((44108, 44159), 'marvin.lib.base.Domain.list', 'Domain.list', (['self.api_client'], {'id': 'self.dom_domain.id'}), '(self.api_client, id=self.dom_domain.id)\n', (44119, 44159), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((44636, 44738), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.dom_domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.dom_domain.id)\n", (44650, 44738), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((44957, 45033), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.domain_admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.domain_admin_account.id, listall=True)\n', (44969, 45033), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((45743, 45846), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(False)', 'domainid': 'self.dom_domain.id'}), "(self.api_client, self.testdata['account'], admin=False,\n domainid=self.dom_domain.id)\n", (45757, 45846), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((46064, 46139), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.domain_user_account.id', 'listall': '(True)'}), '(self.api_client, id=self.domain_user_account.id, listall=True)\n', (46076, 46139), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((46818, 46862), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (46831, 46862), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((47276, 47382), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (47298, 47382), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((47522, 47595), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (47542, 47595), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((48360, 48487), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (48382, 48487), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((48651, 48724), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (48671, 48724), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((49713, 49929), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'accountid': 'self.domain_admin_account.name', 'domainid': 'self.dom_domain.id', 'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'], accountid=\n self.domain_admin_account.name, domainid=self.dom_domain.id,\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (49727, 49929), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((50089, 50152), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network.id', 'listall': '(True)'}), '(self.api_client, id=self.network.id, listall=True)\n', (50101, 50152), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((51649, 51891), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.domain_user_account.name', 'domainid': 'self.domain_user_account.domainid', 'networkids': 'self.network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.domain_user_account.name, domainid=self.\n domain_user_account.domainid, networkids=self.network.id,\n serviceofferingid=self.service_offering.id)\n", (51670, 51891), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((52049, 52152), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.domain_user_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.\n domain_user_account_virtual_machine.id, listall=True)\n', (52068, 52152), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((52972, 53216), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.domain_admin_account.name', 'domainid': 'self.domain_admin_account.domainid', 'networkids': 'self.network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.domain_admin_account.name, domainid=self.\n domain_admin_account.domainid, networkids=self.network.id,\n serviceofferingid=self.service_offering.id)\n", (52993, 53216), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((53375, 53479), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.domain_admin_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.\n domain_admin_account_virtual_machine.id, listall=True)\n', (53394, 53479), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((56412, 56510), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (56426, 56510), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((56722, 56791), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (56734, 56791), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((57533, 57666), 'marvin.lib.base.Project.create', 'Project.create', (['self.api_client', "self.testdata['project']"], {'account': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid'}), "(self.api_client, self.testdata['project'], account=self.\n admin_account.name, domainid=self.admin_account.domainid)\n", (57547, 57666), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((57807, 57871), 'marvin.lib.base.Project.list', 'Project.list', (['self.api_client'], {'id': 'self.project1.id', 'listall': '(True)'}), '(self.api_client, id=self.project1.id, listall=True)\n', (57819, 57871), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((58447, 58580), 'marvin.lib.base.Project.create', 'Project.create', (['self.api_client', "self.testdata['project']"], {'account': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid'}), "(self.api_client, self.testdata['project'], account=self.\n admin_account.name, domainid=self.admin_account.domainid)\n", (58461, 58580), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((58721, 58785), 'marvin.lib.base.Project.list', 'Project.list', (['self.api_client'], {'id': 'self.project2.id', 'listall': '(True)'}), '(self.api_client, id=self.project2.id, listall=True)\n', (58733, 58785), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((59258, 59302), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (59271, 59302), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((59716, 59822), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (59738, 59822), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((59962, 60035), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (59982, 60035), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((60682, 60809), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (60704, 60809), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((60973, 61046), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (60993, 61046), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((62143, 62354), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'projectid': 'self.project1.id', 'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'], projectid=\n self.project1.id, domainid=self.admin_account.domainid,\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (62157, 62354), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((62513, 62609), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network.id', 'projectid': 'self.project1.id', 'listall': '(True)'}), '(self.api_client, id=self.network.id, projectid=self.project1.\n id, listall=True)\n', (62525, 62609), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((63835, 64015), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'networkids': 'self.network.id', 'projectid': 'self.project1.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n networkids=self.network.id, projectid=self.project1.id,\n serviceofferingid=self.service_offering.id)\n", (63856, 64015), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((64092, 64198), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.project1_admin_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.\n project1_admin_account_virtual_machine.id, listall=True)\n', (64111, 64198), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((66412, 66510), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (66426, 66510), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((66722, 66791), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (66734, 66791), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((67434, 67478), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (67447, 67478), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((67820, 67926), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (67842, 67926), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((68066, 68139), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (68086, 68139), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((68903, 69030), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (68925, 69030), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((69194, 69267), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (69214, 69267), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((72422, 72520), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (72436, 72520), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((72731, 72800), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (72743, 72800), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((73436, 73480), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (73449, 73480), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((73894, 74000), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (73916, 74000), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((74140, 74213), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (74160, 74213), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((74977, 75104), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (74999, 75104), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((75268, 75341), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (75288, 75341), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((76442, 76582), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (76456, 76582), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((76724, 76773), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network.id'}), '(self.api_client, id=self.network.id)\n', (76736, 76773), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((77419, 77443), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (77435, 77443), False, 'import random\n'), ((79410, 79508), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (79424, 79508), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((79720, 79789), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (79732, 79789), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((80425, 80469), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (80438, 80469), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((80883, 80989), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (80905, 80989), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((81129, 81202), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (81149, 81202), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((81966, 82093), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (81988, 82093), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((82257, 82330), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (82277, 82330), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((83319, 83459), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (83333, 83459), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((83601, 83650), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network.id'}), '(self.api_client, id=self.network.id)\n', (83613, 83650), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((84303, 84327), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (84319, 84327), False, 'import random\n'), ((85217, 85357), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (85231, 85357), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((85500, 85550), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network1.id'}), '(self.api_client, id=self.network1.id)\n', (85512, 85550), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((86211, 86436), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkids': 'self.network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkids=self.network.id, serviceofferingid=self.service_offering.id)\n", (86232, 86436), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((86525, 86630), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.network_admin_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.\n network_admin_account_virtual_machine.id, listall=True)\n', (86544, 86630), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((87329, 87555), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkids': 'self.network1.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkids=self.network1.id, serviceofferingid=self.service_offering.id)\n", (87350, 87555), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((87644, 87750), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.network1_admin_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.\n network1_admin_account_virtual_machine.id, listall=True)\n', (87663, 87750), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((89469, 89567), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (89483, 89567), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((89779, 89848), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (89791, 89848), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((90675, 90781), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (90697, 90781), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((90921, 90994), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (90941, 90994), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((91758, 91885), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (91780, 91885), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((92049, 92122), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (92069, 92122), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((92733, 92841), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['isolated_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'isolated_network_offering'], conservemode=False)\n", (92755, 92841), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((92958, 93089), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.isolated_network_offering', 'self.api_client'], {'id': 'self.isolated_network_offering.id', 'state': '"""enabled"""'}), "(self.isolated_network_offering, self.api_client, id=\n self.isolated_network_offering.id, state='enabled')\n", (92980, 93089), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((93253, 93328), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.isolated_network_offering.id'}), '(self.api_client, id=self.isolated_network_offering.id)\n', (93273, 93328), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((94074, 94118), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (94087, 94118), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((94662, 94880), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'], accountid=\n self.admin_account.name, domainid=self.admin_account.domainid,\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (94676, 94880), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((95047, 95103), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.shared_network.id'}), '(self.api_client, id=self.shared_network.id)\n', (95059, 95103), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((95763, 95984), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['isolated_network']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.isolated_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['isolated_network'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkofferingid=self.isolated_network_offering.id, zoneid=self.zone.id)\n", (95777, 95984), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((96154, 96212), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.isolated_network.id'}), '(self.api_client, id=self.isolated_network.id)\n', (96166, 96212), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((96716, 96953), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkids': 'self.shared_network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkids=self.shared_network.id, serviceofferingid=self.\n service_offering.id)\n", (96737, 96953), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((97065, 97177), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.shared_network_admin_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.\n shared_network_admin_account_virtual_machine.id, listall=True)\n', (97084, 97177), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((97911, 98150), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkids': 'self.isolated_network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkids=self.isolated_network.id, serviceofferingid=self.\n service_offering.id)\n", (97932, 98150), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((98262, 98376), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'self.isolated_network_admin_account_virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=self.\n isolated_network_admin_account_virtual_machine.id, listall=True)\n', (98281, 98376), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((99175, 99353), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.admin_account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.admin_account.domainid', 'networkid': 'self.isolated_network.id'}), '(self.api_client, accountid=self.admin_account.name,\n zoneid=self.zone.id, domainid=self.admin_account.domainid, networkid=\n self.isolated_network.id)\n', (99197, 99353), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((99768, 99880), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.api_client', 'public_ip.id', 'self.isolated_network_admin_account_virtual_machine.id'], {}), '(self.api_client, public_ip.id, self.\n isolated_network_admin_account_virtual_machine.id)\n', (99788, 99880), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((100063, 100306), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.api_client'], {'ipaddressid': 'self.public_ip.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.testdata['fwrule']['cidr']]", 'startport': "self.testdata['fwrule']['startport']", 'endport': "self.testdata['fwrule']['endport']"}), "(self.api_client, ipaddressid=self.public_ip.ipaddress.\n id, protocol='TCP', cidrlist=[self.testdata['fwrule']['cidr']],\n startport=self.testdata['fwrule']['startport'], endport=self.testdata[\n 'fwrule']['endport'])\n", (100082, 100306), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((100456, 100505), 'marvin.lib.base.FireWallRule.list', 'FireWallRule.list', (['self.api_client'], {'id': 'fw_rule.id'}), '(self.api_client, id=fw_rule.id)\n', (100473, 100505), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((101891, 101989), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (101905, 101989), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((102201, 102270), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (102213, 102270), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((102911, 102955), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (102924, 102955), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((103369, 103475), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (103391, 103475), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((103615, 103688), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (103635, 103688), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((104452, 104579), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (104474, 104579), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((104742, 104815), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (104762, 104815), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((106956, 107054), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (106970, 107054), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((107266, 107335), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (107278, 107335), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((107976, 108020), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (107989, 108020), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((108434, 108540), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (108456, 108540), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((108680, 108753), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (108700, 108753), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((109517, 109644), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (109539, 109644), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((109807, 109880), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (109827, 109880), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((112642, 112740), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], admin=True,\n domainid=self.domain.id)\n", (112656, 112740), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((112950, 113019), 'marvin.lib.base.Account.list', 'Account.list', (['self.api_client'], {'id': 'self.admin_account.id', 'listall': '(True)'}), '(self.api_client, id=self.admin_account.id, listall=True)\n', (112962, 113019), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((113083, 113119), 'marvin.lib.utils.validateList', 'validateList', (['list_accounts_response'], {}), '(list_accounts_response)\n', (113095, 113119), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((113539, 113583), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (113552, 113583), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((113994, 114100), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (114016, 114100), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((114239, 114312), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (114259, 114312), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((114364, 114409), 'marvin.lib.utils.validateList', 'validateList', (['list_network_offerings_response'], {}), '(list_network_offerings_response)\n', (114376, 114409), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((114937, 115064), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (114959, 115064), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((115227, 115300), 'marvin.lib.base.NetworkOffering.list', 'NetworkOffering.list', (['self.api_client'], {'id': 'self.shared_network_offering.id'}), '(self.api_client, id=self.shared_network_offering.id)\n', (115247, 115300), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((115352, 115397), 'marvin.lib.utils.validateList', 'validateList', (['list_network_offerings_response'], {}), '(list_network_offerings_response)\n', (115364, 115397), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((116189, 116329), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (116203, 116329), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((116469, 116518), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network.id'}), '(self.api_client, id=self.network.id)\n', (116481, 116518), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((116570, 116606), 'marvin.lib.utils.validateList', 'validateList', (['list_accounts_response'], {}), '(list_accounts_response)\n', (116582, 116606), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((117852, 117896), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (117865, 117896), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((118101, 118241), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (118115, 118241), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((118382, 118432), 'marvin.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.network2.id'}), '(self.api_client, id=self.network2.id)\n', (118394, 118432), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((118484, 118520), 'marvin.lib.utils.validateList', 'validateList', (['list_networks_response'], {}), '(list_networks_response)\n', (118496, 118520), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((119170, 119298), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""disabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='disabled')\n", (119192, 119298), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((119964, 120051), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], domainid=self.\n domain.id)\n", (119978, 120051), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((120180, 120224), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (120193, 120224), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((120835, 120975), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (120849, 120975), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((121206, 121356), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'networkids': 'shared_network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n networkids=shared_network.id, serviceofferingid=self.service_offering.id)\n", (121227, 121356), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((121443, 121514), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'networkid': 'shared_network.id', 'listall': '(True)'}), '(self.api_client, networkid=shared_network.id, listall=True)\n', (121454, 121514), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((121973, 122044), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'networkid': 'shared_network.id', 'listall': '(True)'}), '(self.api_client, networkid=shared_network.id, listall=True)\n', (121984, 122044), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((122950, 123037), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], domainid=self.\n domain.id)\n", (122964, 123037), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((123166, 123210), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (123179, 123210), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((123821, 123961), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (123835, 123961), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((124197, 124347), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'networkids': 'shared_network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n networkids=shared_network.id, serviceofferingid=self.service_offering.id)\n", (124218, 124347), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((124470, 124541), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'networkid': 'shared_network.id', 'listall': '(True)'}), '(self.api_client, networkid=shared_network.id, listall=True)\n', (124481, 124541), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((124964, 124994), 'marvin.cloudstackAPI.rebootRouter.rebootRouterCmd', 'rebootRouter.rebootRouterCmd', ([], {}), '()\n', (124992, 124994), False, 'from marvin.cloudstackAPI import rebootRouter, stopRouter, startRouter\n'), ((126249, 126336), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], domainid=self.\n domain.id)\n", (126263, 126336), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((126465, 126509), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (126478, 126509), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((127120, 127260), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (127134, 127260), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((127496, 127646), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'networkids': 'shared_network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n networkids=shared_network.id, serviceofferingid=self.service_offering.id)\n", (127517, 127646), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((127769, 127840), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'networkid': 'shared_network.id', 'listall': '(True)'}), '(self.api_client, networkid=shared_network.id, listall=True)\n', (127780, 127840), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((128186, 128212), 'marvin.cloudstackAPI.stopRouter.stopRouterCmd', 'stopRouter.stopRouterCmd', ([], {}), '()\n', (128210, 128212), False, 'from marvin.cloudstackAPI import rebootRouter, stopRouter, startRouter\n'), ((128300, 128356), 'marvin.lib.common.verifyRouterState', 'verifyRouterState', (['self.api_client', 'router.id', '"""stopped"""'], {}), "(self.api_client, router.id, 'stopped')\n", (128317, 128356), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((128695, 128723), 'marvin.cloudstackAPI.startRouter.startRouterCmd', 'startRouter.startRouterCmd', ([], {}), '()\n', (128721, 128723), False, 'from marvin.cloudstackAPI import rebootRouter, stopRouter, startRouter\n'), ((128812, 128868), 'marvin.lib.common.verifyRouterState', 'verifyRouterState', (['self.api_client', 'router.id', '"""running"""'], {}), "(self.api_client, router.id, 'running')\n", (128829, 128868), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((129799, 129886), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.testdata['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.testdata['account'], domainid=self.\n domain.id)\n", (129813, 129886), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((130015, 130059), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (130028, 130059), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((130683, 130841), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering_all_services.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering_all_services.id, zoneid=\n self.zone.id)\n", (130697, 130841), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((131072, 131222), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'networkids': 'shared_network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n networkids=shared_network.id, serviceofferingid=self.service_offering.id)\n", (131093, 131222), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((131334, 131479), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'account.name', 'zoneid': 'self.zone.id', 'domainid': 'account.domainid', 'networkid': 'shared_network.id'}), '(self.api_client, accountid=account.name, zoneid=self\n .zone.id, domainid=account.domainid, networkid=shared_network.id)\n', (131356, 131479), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((131639, 131703), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'id': 'public_ip.ipaddress.id'}), '(self.api_client, id=public_ip.ipaddress.id)\n', (131659, 131703), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((132082, 132320), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.api_client'], {'ipaddressid': 'public_ip.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.testdata['fwrule']['cidr']]", 'startport': "self.testdata['fwrule']['startport']", 'endport': "self.testdata['fwrule']['endport']"}), "(self.api_client, ipaddressid=public_ip.ipaddress.id,\n protocol='TCP', cidrlist=[self.testdata['fwrule']['cidr']], startport=\n self.testdata['fwrule']['startport'], endport=self.testdata['fwrule'][\n 'endport'])\n", (132101, 132320), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((132434, 132565), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'vm', "self.testdata['natrule']"], {'ipaddressid': 'public_ip.ipaddress.id', 'networkid': 'shared_network.id'}), "(self.api_client, vm, self.testdata['natrule'], ipaddressid=\n public_ip.ipaddress.id, networkid=shared_network.id)\n", (132448, 132565), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((132671, 132750), 'marvin.sshClient.SshClient', 'SshClient', (['public_ip.ipaddress.ipaddress', 'vm.ssh_port', 'vm.username', 'vm.password'], {}), '(public_ip.ipaddress.ipaddress, vm.ssh_port, vm.username, vm.password)\n', (132680, 132750), False, 'from marvin.sshClient import SshClient\n'), ((132919, 132983), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.api_client'], {'id': 'public_ip.ipaddress.id'}), '(self.api_client, id=public_ip.ipaddress.id)\n', (132939, 132983), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((133781, 133825), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (133794, 133825), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((134167, 134273), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (134189, 134273), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((134390, 134517), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'id': 'self.shared_network_offering.id', 'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, id=\n self.shared_network_offering.id, state='enabled')\n", (134412, 134517), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((134991, 135131), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (135005, 135131), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((135252, 135400), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'networkids': 'self.network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n networkids=self.network.id, serviceofferingid=self.service_offering.id)\n", (135273, 135400), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((135510, 135579), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'networkid': 'self.network.id', 'listall': '(True)'}), '(self.api_client, networkid=self.network.id, listall=True)\n', (135521, 135579), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((135761, 135830), 'marvin.lib.common.verifyGuestTrafficPortGroups', 'verifyGuestTrafficPortGroups', (['self.api_client', 'self.config', 'self.zone'], {}), '(self.api_client, self.config, self.zone)\n', (135789, 135830), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((4349, 4396), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (4366, 4396), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((5617, 5665), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.api_client', 'self.cleanup'], {}), '(self.api_client, self.cleanup)\n', (5634, 5665), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((15679, 15785), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (15701, 15785), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((19165, 19271), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.testdata['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.testdata[\n 'shared_network_offering'], conservemode=False)\n", (19187, 19271), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((38682, 38907), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkids': 'self.network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkids=self.network.id, serviceofferingid=self.service_offering.id)\n", (38703, 38907), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((50847, 51072), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkids': 'self.network.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkids=self.network.id, serviceofferingid=self.service_offering.id)\n", (50868, 51072), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((63359, 63539), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.testdata['virtual_machine']"], {'networkids': 'self.network.id', 'projectid': 'self.project2.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.testdata['virtual_machine'],\n networkids=self.network.id, projectid=self.project2.id,\n serviceofferingid=self.service_offering.id)\n", (63380, 63539), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((70382, 70522), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (70396, 70522), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((78113, 78253), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (78127, 78253), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((84978, 85022), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (84991, 85022), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_free_vlan, wait_for_cleanup, verifyRouterState, verifyGuestTrafficPortGroups\n'), ((105890, 106108), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'], accountid=\n self.admin_account.name, domainid=self.admin_account.domainid,\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (105904, 106108), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((110956, 111174), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'], accountid=\n self.admin_account.name, domainid=self.admin_account.domainid,\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (110970, 111174), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((117177, 117317), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.testdata['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.testdata['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (117191, 117317), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((125244, 125286), 'marvin.lib.base.Router.list', 'Router.list', (['self.api_client'], {'id': 'router.id'}), '(self.api_client, id=router.id)\n', (125255, 125286), False, 'from marvin.lib.base import Account, Network, NetworkOffering, VirtualMachine, Project, PhysicalNetwork, Domain, StaticNATRule, FireWallRule, ServiceOffering, PublicIPAddress, Router, NATRule\n'), ((125488, 125502), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (125498, 125502), False, 'import time\n'), ((121599, 121633), 'marvin.lib.utils.validateList', 'validateList', (['list_router_response'], {}), '(list_router_response)\n', (121611, 121633), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((122129, 122163), 'marvin.lib.utils.validateList', 'validateList', (['list_router_response'], {}), '(list_router_response)\n', (122141, 122163), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((124626, 124660), 'marvin.lib.utils.validateList', 'validateList', (['list_router_response'], {}), '(list_router_response)\n', (124638, 124660), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((127925, 127959), 'marvin.lib.utils.validateList', 'validateList', (['list_router_response'], {}), '(list_router_response)\n', (127937, 127959), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((131776, 131811), 'marvin.lib.utils.validateList', 'validateList', (['list_pub_ip_addr_resp'], {}), '(list_pub_ip_addr_resp)\n', (131788, 131811), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((135646, 135667), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (135658, 135667), False, 'from marvin.lib.utils import cleanup_resources, validateList\n')] |
#!/usr/bin/env python
# encoding: utf-8
# Licensed under a 3-clause BSD license.
# Revision History:
# Initial Version: 2016-02-17 14:13:28 by <NAME>
# 2016-02-23 - Modified to test a programmatic query using a test sample form - <NAME>
# 2016-03-02 - Generalized to many parameters and many forms - <NAME>
# - Added config drpver info
# 2016-03-12 - Changed parameter input to be a natural language string
from __future__ import print_function, division, unicode_literals
from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb
from marvin.utils.general.structs import string_folding_wrapper
from sqlalchemy_boolean_search import parse_boolean_search, BooleanSearchException
from sqlalchemy import func
from marvin import config, marvindb
from marvin.tools.results import Results
from marvin.utils.datamodel.query import datamodel
from marvin.utils.datamodel.query.base import query_params
from marvin.utils.general import temp_setattr
from marvin.api.api import Interaction
from marvin.core import marvin_pickle
from marvin.tools.results import remote_mode_only
from sqlalchemy import bindparam
from sqlalchemy.orm import aliased
from sqlalchemy.dialects import postgresql
from sqlalchemy.sql.expression import desc
from operator import le, ge, gt, lt, eq, ne
from collections import defaultdict, OrderedDict
import datetime
import numpy as np
import warnings
import os
import re
import six
from functools import wraps
try:
import cPickle as pickle
except:
import pickle
__all__ = ['Query', 'doQuery']
opdict = {'<=': le, '>=': ge, '>': gt, '<': lt, '!=': ne, '=': eq, '==': eq}
breadcrumb = MarvinBreadCrumb()
def tree():
return defaultdict(tree)
def doQuery(*args, **kwargs):
"""Convenience function for building a Query and retrieving the Results.
Parameters:
N/A:
See the :class:`~marvin.tools.query.Query` class for a list
of inputs.
Returns:
query, results:
A tuple containing the built
:class:`~marvin.tools.query.Query` instance, and the
:class:`~marvin.tools.results.Results` instance.
"""
start = kwargs.pop('start', None)
end = kwargs.pop('end', None)
q = Query(*args, **kwargs)
try:
res = q.run(start=start, end=end)
except TypeError as e:
warnings.warn('Cannot run, query object is None: {0}.'.format(e), MarvinUserWarning)
res = None
return q, res
def updateConfig(f):
"""Decorator that updates query object with new config drpver version."""
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.query and self.mode == 'local':
self.query = self.query.params({'drpver': self._drpver, 'dapver': self._dapver})
return f(self, *args, **kwargs)
return wrapper
def makeBaseQuery(f):
"""Decorator that makes the base query if it does not already exist."""
@wraps(f)
def wrapper(self, *args, **kwargs):
if not self.query and self.mode == 'local':
self._createBaseQuery()
return f(self, *args, **kwargs)
return wrapper
def checkCondition(f):
"""Decorator that checks if filter is set, if it does not already exist."""
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.mode == 'local' and self.filterparams and not self._alreadyInFilter(self.filterparams.keys()):
self.add_condition()
return f(self, *args, **kwargs)
return wrapper
class Query(object):
''' A class to perform queries on the MaNGA dataset.
This class is the main way of performing a query. A query works minimally
by specifying a list of desired parameters, along with a string filter
condition in a natural language SQL format.
A local mode query assumes a local database. A remote mode query uses the
API to run a query on the Utah server, and return the results.
By default, the query returns a list of tupled parameters. The parameters
are a combination of user-defined parameters, parameters used in the
filter condition, and a set of pre-defined default parameters. The object
plate-IFU or mangaid is always returned by default.
Parameters:
returnparams (str list):
A list of string parameters names desired to be returned in the query
searchfilter (str):
A (natural language) string containing the filter conditions
in the query; written as you would say it.
returntype (str):
The requested Marvin Tool object that the results are converted into
mode ({'local', 'remote', 'auto'}):
The load mode to use. See :doc:`Mode secision tree</mode_decision>`.
sort (str):
The parameter name to sort the query on
order ({'asc', 'desc'}):
The sort order. Can be either ascending or descending.
limit (int):
The number limit on the number of returned results
Returns:
results:
An instance of the :class:`~marvin.tools.query.results.Results`
class containing the results of your Query.
Example:
>>> # filter of "NSA redshift less than 0.1 and IFU names starting with 19"
>>> searchfilter = 'nsa.z < 0.1 and ifu.name = 19*'
>>> returnparams = ['cube.ra', 'cube.dec']
>>> q = Query(searchfilter=searchfilter, returnparams=returnparams)
>>> results = q.run()
'''
def __init__(self, *args, **kwargs):
self._release = kwargs.pop('release', config.release)
self._drpver, self._dapver = config.lookUpVersions(release=self._release)
self.query = None
self.params = []
self.filterparams = {}
self.queryparams = None
self.myparamtree = tree()
self._paramtree = None
self.session = marvindb.session
self.filter = None
self.joins = []
self.myforms = defaultdict(str)
self.quiet = kwargs.get('quiet', None)
self._errors = []
self._basetable = None
self._modelgraph = marvindb.modelgraph
self._returnparams = []
self._caching = kwargs.get('caching', True)
self.verbose = kwargs.get('verbose', True)
self.count_threshold = kwargs.get('count_threshold', 1000)
self.allspaxels = kwargs.get('allspaxels', None)
self.mode = kwargs.get('mode', None)
self.limit = int(kwargs.get('limit', 100))
self.sort = kwargs.get('sort', 'mangaid')
self.order = kwargs.get('order', 'asc')
self.return_all = kwargs.get('return_all', False)
self.datamodel = datamodel[self._release]
self.marvinform = self.datamodel._marvinform
# drop breadcrumb
breadcrumb.drop(message='Initializing MarvinQuery {0}'.format(self.__class__),
category=self.__class__)
# set the mode
if self.mode is None:
self.mode = config.mode
if self.mode == 'local':
self._doLocal()
if self.mode == 'remote':
self._doRemote()
if self.mode == 'auto':
try:
self._doLocal()
except Exception as e:
warnings.warn('local mode failed. Trying remote now.', MarvinUserWarning)
self._doRemote()
# get return type
self.returntype = kwargs.get('returntype', None)
# set default parameters
self.set_defaultparams()
# get user-defined input parameters
returnparams = kwargs.get('returnparams', [])
if returnparams:
self.set_returnparams(returnparams)
# if searchfilter is set then set the parameters
searchfilter = kwargs.get('searchfilter', None)
if searchfilter:
self.set_filter(searchfilter=searchfilter)
self._isdapquery = self._checkInFilter(name='dapdb')
# Don't do anything if nothing specified
allnot = [not searchfilter, not returnparams]
if not all(allnot) and self.mode == 'local':
# create query parameter ModelClasses
self._create_query_modelclasses()
# this adds spaxel x, y into default for query 1 dap zonal query
self._adjust_defaults()
# join tables
self._join_tables()
# add condition
if searchfilter:
self.add_condition()
# add PipelineInfo
self._addPipeline()
# check if query if a dap query
if self._isdapquery:
self._buildDapQuery()
self._check_dapall_query()
def __repr__(self):
return ('Marvin Query(filter={4}, mode={0}, limit={1}, sort={2}, order={3})'
.format(repr(self.mode), self.limit, self.sort, repr(self.order), self.searchfilter))
def _doLocal(self):
''' Tests if it is possible to perform queries locally. '''
if not config.db or not self.session:
warnings.warn('No local database found. Cannot perform queries.', MarvinUserWarning)
raise MarvinError('No local database found. Query cannot be run in local mode')
else:
self.mode = 'local'
def _doRemote(self):
''' Sets up to perform queries remotely. '''
if not config.urlmap:
raise MarvinError('No URL Map found. Cannot make remote query calls!')
else:
self.mode = 'remote'
def _check_query(self, name):
''' Check if string is inside the query statement '''
qstate = str(self.query.statement.compile(compile_kwargs={'literal_binds':True}))
return name in qstate
def _checkInFilter(self, name='dapdb'):
''' Check if the given name is in the schema of any of the filter params '''
if self.mode == 'local':
fparams = self.marvinform._param_form_lookup.mapToColumn(self.filterparams.keys())
fparams = [fparams] if not isinstance(fparams, list) else fparams
inschema = [name in c.class_.__table__.schema for c in fparams]
elif self.mode == 'remote':
inschema = []
return True if any(inschema) else False
def _check_shortcuts_in_filter(self, strfilter):
''' Check for shortcuts in string filter
Replaces shortcuts in string searchfilter
with the full tables and names.
is there a better way?
'''
# table shortcuts
# for key in self.marvinform._param_form_lookup._tableShortcuts.keys():
# #if key in strfilter:
# if re.search('{0}.[a-z]'.format(key), strfilter):
# strfilter = strfilter.replace(key, self.marvinform._param_form_lookup._tableShortcuts[key])
# name shortcuts
for key in self.marvinform._param_form_lookup._nameShortcuts.keys():
if key in strfilter:
# strfilter = strfilter.replace(key, self.marvinform._param_form_lookup._nameShortcuts[key])
param_form_lookup = self.marvinform._param_form_lookup
strfilter = re.sub(r'\b{0}\b'.format(key),
'{0}'.format(param_form_lookup._nameShortcuts[key]),
strfilter)
return strfilter
def _adjust_defaults(self):
''' Adjust the default parameters to include necessary parameters
For any query involving DAP DB, always return the spaxel index
TODO: change this to spaxel x and y
TODO: change this entirely
'''
dapschema = ['dapdb' in c.class_.__table__.schema for c in self.queryparams]
if any(dapschema):
dapcols = ['spaxelprop.x', 'spaxelprop.y', 'bintype.name', 'template.name']
self.defaultparams.extend(dapcols)
self.params.extend(dapcols)
self.params = list(OrderedDict.fromkeys(self.params))
self._create_query_modelclasses()
# qpdap = self.marvinform._param_form_lookup.mapToColumn(dapcols)
# self.queryparams.extend(qpdap)
# self.queryparams_order.extend([q.key for q in qpdap])
def set_returnparams(self, returnparams):
''' Loads the user input parameters into the query params limit
Adds a list of string parameter names into the main list of
query parameters to return
Parameters:
returnparams (list):
A string list of the parameters you wish to return in the query
'''
if returnparams:
returnparams = [returnparams] if not isinstance(returnparams, list) else returnparams
# look up shortcut names for the return parameters
full_returnparams = [self.marvinform._param_form_lookup._nameShortcuts[rp]
if rp in self.marvinform._param_form_lookup._nameShortcuts else rp
for rp in returnparams]
self._returnparams = full_returnparams
self.params.extend(full_returnparams)
def set_defaultparams(self):
''' Loads the default params for a given return type
TODO - change mangaid to plateifu once plateifu works in
cube, maps, rss, modelcube - file objects
spaxel, map, rssfiber - derived objects (no file)
these are also the default params except
any query on spaxelprop should return spaxel_index (x/y)
Minimum parameters to instantiate a Marvin Tool
cube - return plateifu/mangaid
modelcube - return plateifu/mangaid, bintype, template
rss - return plateifu/mangaid
maps - return plateifu/mangaid, bintype, template
spaxel - return plateifu/mangaid, spaxel x and y
map - do not instantiate directly (plateifu/mangaid, bintype, template, property name, channel)
rssfiber - do not instantiate directly (plateifu/mangaid, fiberid)
return any of our tools
'''
assert self.returntype in [None, 'cube', 'spaxel', 'maps',
'rss', 'modelcube'], 'Query returntype must be either cube, spaxel, maps, modelcube, rss'
self.defaultparams = ['cube.mangaid', 'cube.plate', 'cube.plateifu', 'ifu.name']
if self.returntype == 'spaxel':
pass
#self.defaultparams.extend(['spaxel.x', 'spaxel.y'])
elif self.returntype == 'modelcube':
self.defaultparams.extend(['bintype.name', 'template.name'])
elif self.returntype == 'rss':
pass
elif self.returntype == 'maps':
self.defaultparams.extend(['bintype.name', 'template.name'])
# self.defaultparams.extend(['spaxelprop.x', 'spaxelprop.y'])
# add to main set of params
self.params.extend(self.defaultparams)
def _create_query_modelclasses(self):
''' Creates a list of database ModelClasses from a list of parameter names '''
self.params = [item for item in self.params if item in set(self.params)]
self.queryparams = self.marvinform._param_form_lookup.mapToColumn(self.params)
self.queryparams = [item for item in self.queryparams if item in set(self.queryparams)]
self.queryparams_order = [q.key for q in self.queryparams]
def get_available_params(self, paramdisplay='best'):
''' Retrieve the available parameters to query on
Retrieves a list of the available query parameters.
Can either retrieve a list of all the parameters or only the vetted parameters.
Parameters:
paramdisplay (str {all|best}):
String indicating to grab either all or just the vetted parameters.
Default is to only return 'best', i.e. vetted parameters
Returns:
qparams (list):
a list of all of the available queryable parameters
'''
assert paramdisplay in ['all', 'best'], 'paramdisplay can only be either "all" or "best"!'
if paramdisplay == 'all':
qparams = self.datamodel.groups.list_params('full')
elif paramdisplay == 'best':
qparams = query_params
return qparams
@remote_mode_only
def save(self, path=None, overwrite=False):
''' Save the query as a pickle object
Parameters:
path (str):
Filepath and name of the pickled object
overwrite (bool):
Set this to overwrite an existing pickled file
Returns:
path (str):
The filepath and name of the pickled object
'''
sf = self.searchfilter.replace(' ', '') if self.searchfilter else 'anon'
# set the path
if not path:
path = os.path.expanduser('~/marvin_query_{0}.mpf'.format(sf))
# check for file extension
if not os.path.splitext(path)[1]:
path = os.path.join(path + '.mpf')
path = os.path.realpath(path)
if os.path.isdir(path):
raise MarvinError('path must be a full route, including the filename.')
if os.path.exists(path) and not overwrite:
warnings.warn('file already exists. Not overwriting.', MarvinUserWarning)
return
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
# set bad pickled attributes to None
attrs = ['session', 'datamodel', 'marvinform', 'myform', '_modelgraph']
# pickle the query
try:
with temp_setattr(self, attrs, None):
pickle.dump(self, open(path, 'wb'), protocol=-1)
except Exception as ee:
if os.path.exists(path):
os.remove(path)
raise MarvinError('Error found while pickling: {0}'.format(str(ee)))
return path
@classmethod
def restore(cls, path, delete=False):
''' Restore a pickled object
Parameters:
path (str):
The filename and path to the pickled object
delete (bool):
Turn this on to delete the pickled fil upon restore
Returns:
Query (instance):
The instantiated Marvin Query class
'''
obj = marvin_pickle.restore(path, delete=delete)
obj._modelgraph = marvindb.modelgraph
obj.session = marvindb.session
obj.datamodel = datamodel[obj._release]
# if obj.allspaxels:
# obj.datamodel.use_all_spaxels()
obj.marvinform = obj.datamodel._marvinform
return obj
def set_filter(self, searchfilter=None):
''' Parses a filter string and adds it into the query.
Parses a natural language string filter into the appropriate SQL
filter syntax. String is a boolean join of one or more conditons
of the form "PARAMETER_NAME OPERAND VALUE"
Parameter names must be uniquely specified. For example, nsa.z is
a unique parameter name in the database and can be specified thusly.
On the other hand, name is not a unique parameter name in the database,
and must be clarified with the desired table.
Parameter Naming Convention:
NSA redshift == nsa.z
IFU name == ifu.name
Pipeline name == pipeline_info.name
Allowed Joins:
AND | OR | NOT
In the absence of parantheses, the precedence of
joins follow: NOT > AND > OR
Allowed Operands:
== | != | <= | >= | < | > | =
Notes:
Operand == maps to a strict equality (x == 5 --> x is equal to 5)
Operand = maps to SQL LIKE
(x = 5 --> x contains the string 5; x = '%5%')
(x = 5* --> x starts with the string 5; x = '5%')
(x = *5 --> x ends with the string 5; x = '%5')
Parameters:
searchfilter (str):
A (natural language) string containing the filter conditions
in the query; written as you would say it.
Example:
>>> # Filter string
>>> filter = "nsa.z < 0.012 and ifu.name = 19*"
>>> # Converts to
>>> and_(nsa.z<0.012, ifu.name=19*)
>>> # SQL syntax
>>> mangasampledb.nsa.z < 0.012 AND lower(mangadatadb.ifudesign.name) LIKE lower('19%')
>>> # Filter string
>>> filter = 'cube.plate < 8000 and ifu.name = 19 or not (nsa.z > 0.1 or not cube.ra > 225.)'
>>> # Converts to
>>> or_(and_(cube.plate<8000, ifu.name=19), not_(or_(nsa.z>0.1, not_(cube.ra>225.))))
>>> # SQL syntax
>>> mangadatadb.cube.plate < 8000 AND lower(mangadatadb.ifudesign.name) LIKE lower(('%' || '19' || '%'))
>>> OR NOT (mangasampledb.nsa.z > 0.1 OR mangadatadb.cube.ra <= 225.0)
'''
if searchfilter:
# if params is a string, then parse and filter
if isinstance(searchfilter, six.string_types):
searchfilter = self._check_shortcuts_in_filter(searchfilter)
try:
parsed = parse_boolean_search(searchfilter)
except BooleanSearchException as e:
raise MarvinError('Your boolean expression contained a syntax error: {0}'.format(e))
else:
raise MarvinError('Input parameters must be a natural language string!')
# update the parameters dictionary
self.searchfilter = searchfilter
self._parsed = parsed
self._checkParsed()
self.strfilter = str(parsed)
self.filterparams.update(parsed.params)
filterkeys = [key for key in parsed.uniqueparams if key not in self.params]
self.params.extend(filterkeys)
# print filter
if not self.quiet:
print('Your parsed filter is: ')
print(parsed)
# Perform local vs remote modes
if self.mode == 'local':
# Pass into Marvin Forms
try:
self._setForms()
except KeyError as e:
self.reset()
raise MarvinError('Could not set parameters. Multiple entries found for key. Be more specific: {0}'.format(e))
elif self.mode == 'remote':
# Is it possible to build a query remotely but still allow for user manipulation?
pass
def _setForms(self):
''' Set the appropriate WTForms in myforms and set the parameters '''
self._paramtree = self.marvinform._paramtree
for key in self.filterparams.keys():
self.myforms[key] = self.marvinform.callInstance(self.marvinform._param_form_lookup[key], params=self.filterparams)
self.myparamtree[self.myforms[key].Meta.model.__name__][key]
def _validateForms(self):
''' Validate all the data in the forms '''
formkeys = list(self.myforms.keys())
isgood = [form.validate() for form in self.myforms.values()]
if not all(isgood):
inds = np.where(np.invert(isgood))[0]
for index in inds:
self._errors.append(list(self.myforms.values())[index].errors)
raise MarvinError('Parameters failed to validate: {0}'.format(self._errors))
def add_condition(self):
''' Loop over all input forms and add a filter condition based on the input parameter form data. '''
# validate the forms
self._validateForms()
# build the actual filter
self.build_filter()
# add the filter to the query
if not isinstance(self.filter, type(None)):
self.query = self.query.filter(self.filter)
@makeBaseQuery
def _join_tables(self):
''' Build the join statement from the input parameters '''
self._modellist = [param.class_ for param in self.queryparams]
# Gets the list of joins from ModelGraph. Uses Cube as nexus, so that
# the order of the joins is the correct one.
# TODO: at some point, all the queries should be generalised so that
# we don't assume that we are querying a cube.
joinmodellist = self._modelgraph.getJoins(self._modellist, format_out='models', nexus=marvindb.datadb.Cube)
# sublist = [model for model in modellist if model.__tablename__ not in self._basetable and not self._tableInQuery(model.__tablename__)]
# self.joins.extend([model.__tablename__ for model in sublist])
# self.query = self.query.join(*sublist)
for model in joinmodellist:
name = '{0}.{1}'.format(model.__table__.schema, model.__tablename__)
if not self._tableInQuery(name):
self.joins.append(model.__tablename__)
if 'template' not in model.__tablename__:
self.query = self.query.join(model)
else:
# assume template_kin only now, TODO deal with template_pop later
self.query = self.query.join(model, marvindb.dapdb.Structure.template_kin)
def build_filter(self):
''' Builds a filter condition to load into sqlalchemy filter. '''
try:
self.filter = self._parsed.filter(self._modellist)
except BooleanSearchException as e:
raise MarvinError('Your boolean expression could not me mapped to model: {0}'.format(e))
def update_params(self, param):
''' Update the input parameters '''
# param = {key: unicode(val) if '*' not in unicode(val) else unicode(val.replace('*', '%')) for key, val in param.items() if key in self.filterparams.keys()}
param = {key: val.decode('UTF-8') if '*' not in val.decode('UTF-8') else val.replace('*', '%').decode('UTF-8') for key, val in param.items() if key in self.filterparams.keys()}
self.filterparams.update(param)
self._setForms()
def _update_params(self, param):
''' this is now broken, this should update the boolean params in the filter condition '''
''' Update any input parameters that have been bound already. Input is a dictionary of key, value pairs representing
parameter name to update, and the value (number only) to update. This does not allow to change the operand.
Does not update self.params
e.g.
original input parameters {'nsa.z': '< 0.012'}
newparams = {'nsa.z': '0.2'}
update_params(newparams)
new condition will be nsa.z < 0.2
'''
param = {key: unicode(val) if '*' not in unicode(val) else unicode(val.replace('*', '%')) for key, val in param.items() if key in self.filterparams.keys()}
self.query = self.query.params(param)
def _alreadyInFilter(self, names):
''' Checks if the parameter name already added into the filter '''
infilter = None
if names:
if not isinstance(self.query, type(None)):
if not isinstance(self.query.whereclause, type(None)):
wc = str(self.query.whereclause.compile(dialect=postgresql.dialect(), compile_kwargs={'literal_binds': True}))
infilter = any([name in wc for name in names])
return infilter
@makeBaseQuery
@checkCondition
@updateConfig
def run(self, start=None, end=None, raw=None, orm=None, core=None):
''' Runs a Marvin Query
Runs the query and return an instance of Marvin Results class
to deal with results.
Parameters:
start (int):
Starting value of a subset. Default is None
end (int):
Ending value of a subset. Default is None
Returns:
results (object):
An instance of the Marvin Results class containing the
results from the Query.
'''
if self.mode == 'local':
# Check for adding a sort
self._sortQuery()
# Check to add the cache
if self._caching:
from marvin.core.caching_query import FromCache
self.query = self.query.options(FromCache("default")).\
options(*marvindb.cache_bits)
# turn on streaming of results
self.query = self.query.execution_options(stream_results=True)
# get total count, and if more than 150 results, paginate and only return the first 100
starttime = datetime.datetime.now()
# check for query and get count
if marvindb.isdbconnected:
qm = self._check_history(check_only=True)
self.totalcount = qm.count if qm else None
# run count if it doesn't exist
if self.totalcount is None:
self.totalcount = self.query.count()
# get the new count if start and end exist
if start and end:
count = (end - start)
else:
count = self.totalcount
# # run the query
# res = self.query.slice(start, end).all()
# count = len(res)
# self.totalcount = count if not self.totalcount else self.totalcount
# check history
if marvindb.isdbconnected:
query_meta = self._check_history()
if count > self.count_threshold and self.return_all is False:
# res = res[0:self.limit]
start = 0
end = self.limit
count = (end - start)
warnings.warn('Results contain more than {0} entries. '
'Only returning first {1}'.format(self.count_threshold, self.limit), MarvinUserWarning)
elif self.return_all is True:
warnings.warn('Warning: Attempting to return all results. This may take a long time or crash.', MarvinUserWarning)
start = None
end = None
elif start and end:
warnings.warn('Getting subset of data {0} to {1}'.format(start, end), MarvinUserWarning)
# slice the query
query = self.query.slice(start, end)
# run the query
if not any([raw, core, orm]):
raw = True
if raw:
# use the db api cursor
sql = str(self._get_sql(query))
conn = marvindb.db.engine.raw_connection()
cursor = conn.cursor('query_cursor')
cursor.execute(sql)
res = self._fetch_data(cursor)
conn.close()
elif core:
# use the core connection
sql = str(self._get_sql(query))
with marvindb.db.engine.connect() as conn:
results = conn.execution_options(stream_results=True).execute(sql)
res = self._fetch_data(results)
elif orm:
# use the orm query
yield_num = int(10**(np.floor(np.log10(self.totalcount))))
results = string_folding_wrapper(query.yield_per(yield_num), keys=self.params)
res = list(results)
# get the runtime
endtime = datetime.datetime.now()
self.runtime = (endtime - starttime)
# clear the session
self.session.close()
# pass the results into Marvin Results
final = Results(results=res, query=query, count=count, mode=self.mode,
returntype=self.returntype, queryobj=self, totalcount=self.totalcount,
chunk=self.limit, runtime=self.runtime, start=start, end=end)
# get the final time
posttime = datetime.datetime.now()
self.finaltime = (posttime - starttime)
return final
elif self.mode == 'remote':
# Fail if no route map initialized
if not config.urlmap:
raise MarvinError('No URL Map found. Cannot make remote call')
if self.return_all:
warnings.warn('Warning: Attempting to return all results. This may take a long time or crash.')
# Get the query route
url = config.urlmap['api']['querycubes']['url']
params = {'searchfilter': self.searchfilter,
'params': ','.join(self._returnparams) if self._returnparams else None,
'returntype': self.returntype,
'limit': self.limit,
'sort': self.sort, 'order': self.order,
'release': self._release,
'return_all': self.return_all,
'start': start,
'end': end,
'caching': self._caching}
try:
ii = Interaction(route=url, params=params, stream=True)
except Exception as e:
# if a remote query fails for any reason, then try to clean them up
# self._cleanUpQueries()
raise MarvinError('API Query call failed: {0}'.format(e))
else:
res = ii.getData()
self.queryparams_order = ii.results['queryparams_order']
self.params = ii.results['params']
self.query = ii.results['query']
count = ii.results['count']
chunk = int(ii.results['chunk'])
totalcount = ii.results['totalcount']
query_runtime = ii.results['runtime']
resp_runtime = ii.response_time
if self.return_all:
msg = 'Returning all {0} results'.format(totalcount)
else:
msg = 'Only returning the first {0} results.'.format(count)
if not self.quiet:
print('Results contain of a total of {0}. {1}'.format(totalcount, msg))
return Results(results=res, query=self.query, mode=self.mode, queryobj=self, count=count,
returntype=self.returntype, totalcount=totalcount, chunk=chunk,
runtime=query_runtime, response_time=resp_runtime, start=start, end=end)
def _fetch_data(self, obj):
''' Fetch query using fetchall or fetchmany '''
res = []
if not self.return_all:
res = obj.fetchall()
else:
while True:
rows = obj.fetchmany(100000)
if rows:
res.extend(rows)
else:
break
return res
def _check_history(self, check_only=None):
''' Check the query against the query history schema '''
sf = self.marvinform._param_form_lookup.mapToColumn('searchfilter')
stringfilter = self.searchfilter.strip().replace(' ', '')
qm = self.session.query(sf.class_).filter(sf == stringfilter, sf.class_.release == self._release).one_or_none()
if check_only:
return qm
with self.session.begin():
if not qm:
qm = sf.class_(searchfilter=stringfilter, n_run=1, release=self._release, count=self.totalcount)
self.session.add(qm)
else:
qm.n_run += 1
return qm
def _cleanUpQueries(self):
''' Attempt to clean up idle queries on the server
This is a hack to try to kill all idl processes on the server.
Using pg_terminate_backend and pg_stat_activity it terminates all
transactions that are in an idle, or idle in transaction, state
that have running for > 1 minute, and whose application_name is
not psql, and the process is not the one initiating the terminate.
The rank part ranks the processes and originally killed all > 1, to
leave one alive as a warning to the others. I've changed this to 0
to kill everything.
I think this will sometimes also leave a newly orphaned idle
ROLLBACK transaction. Not sure why.
'''
if self.mode == 'local':
sql = ("with inactive as (select p.pid, rank() over (partition by \
p.client_addr order by p.backend_start ASC) as rank from \
pg_stat_activity as p where p.application_name !~ 'psql' \
and p.state ilike '%idle%' and p.pid <> pg_backend_pid() and \
current_timestamp-p.state_change > interval '1 minutes') \
select pg_terminate_backend(pid) from inactive where rank > 0;")
self.session.expire_all()
self.session.expunge_all()
res = self.session.execute(sql)
tmp = res.fetchall()
#self.session.close()
#marvindb.db.engine.dispose()
elif self.mode == 'remote':
# Fail if no route map initialized
if not config.urlmap:
raise MarvinError('No URL Map found. Cannot make remote call')
# Get the query route
url = config.urlmap['api']['cleanupqueries']['url']
params = {'task': 'clean', 'release': self._release}
try:
ii = Interaction(route=url, params=params)
except Exception as e:
raise MarvinError('API Query call failed: {0}'.format(e))
else:
res = ii.getData()
def _getIdleProcesses(self):
''' Get a list of all idle processes on server
This grabs a list of all processes in a state of
idle, or idle in transaction using pg_stat_activity
and returns the process id, the state, and the query
'''
if self.mode == 'local':
sql = ("select p.pid,p.state,p.query from pg_stat_activity as p \
where p.state ilike '%idle%';")
res = self.session.execute(sql)
procs = res.fetchall()
elif self.mode == 'remote':
# Fail if no route map initialized
if not config.urlmap:
raise MarvinError('No URL Map found. Cannot make remote call')
# Get the query route
url = config.urlmap['api']['cleanupqueries']['url']
params = {'task': 'getprocs', 'release': self._release}
try:
ii = Interaction(route=url, params=params)
except Exception as e:
raise MarvinError('API Query call failed: {0}'.format(e))
else:
procs = ii.getData()
return procs
def _sortQuery(self):
''' Sort the query by a given parameter '''
if not isinstance(self.sort, type(None)):
# set the sort variable ModelClass parameter
if '.' in self.sort:
param = self.datamodel.parameters[str(self.sort)].full
else:
param = self.datamodel.parameters.get_full_from_remote(self.sort)
sortparam = self.marvinform._param_form_lookup.mapToColumn(param)
# If order is specified, then do the sort
if self.order:
assert self.order in ['asc', 'desc'], 'Sort order parameter must be either "asc" or "desc"'
# Check if order by already applied
if 'ORDER' in str(self.query.statement):
self.query = self.query.order_by(None)
# Do the sorting
if 'desc' in self.order:
self.query = self.query.order_by(desc(sortparam))
else:
self.query = self.query.order_by(sortparam)
@updateConfig
def show(self, prop=None):
''' Prints into to the console
Displays the query to the console with parameter variables plugged in.
Works only in local mode. Input prop can be one of Can be one of query,
tables, joins, or filter.
Only works in LOCAL mode.
Allowed Values for Prop:
query - displays the entire query (default if nothing specified)
tables - displays the tables that have been joined in the query
joins - same as table
filter - displays only the filter used on the query
Parameters:
prop (str):
The type of info to print.
Example:
TODO add example
'''
assert prop in [None, 'query', 'tables', 'joins', 'filter'], 'Input must be query, tables, joins, or filter'
if self.mode == 'local':
if not prop or 'query' in prop:
sql = self._get_sql(self.query)
elif prop == 'tables':
sql = self.joins
elif prop == 'filter':
'''oddly this does not update when bound parameters change, but the statement above does '''
sql = self.query.whereclause.compile(dialect=postgresql.dialect(), compile_kwargs={'literal_binds': True})
else:
sql = self.__getattribute__(prop)
return str(sql)
elif self.mode == 'remote':
sql = 'Cannot show full SQL query in remote mode, use the Results showQuery'
warnings.warn(sql, MarvinUserWarning)
return sql
def _get_sql(self, query):
''' Get the sql for a given query
Parameters:
query (object):
An SQLAlchemy Query object
Returms:
A raw sql string
'''
return query.statement.compile(dialect=postgresql.dialect(), compile_kwargs={'literal_binds': True})
def reset(self):
''' Resets all query attributes '''
self.__init__()
@updateConfig
def _createBaseQuery(self):
''' Create the base query session object. Passes in a list of parameters defined in
returnparams, filterparams, and defaultparams
'''
labeledqps = [qp.label(self.params[i]) for i, qp in enumerate(self.queryparams)]
self.query = self.session.query(*labeledqps)
def _query_column(self, column_name):
''' query and return a specific column from the current query '''
qp = self.marvinform._param_form_lookup.mapToColumn(column_name)
qp = qp.label(column_name)
return self.query.from_self(qp).all()
def _getPipeInfo(self, pipename):
''' Retrieve the pipeline Info for a given pipeline version name '''
assert pipename.lower() in ['drp', 'dap'], 'Pipeline Name must either be DRP or DAP'
# bindparam values
bindname = 'drpver' if pipename.lower() == 'drp' else 'dapver'
bindvalue = self._drpver if pipename.lower() == 'drp' else self._dapver
# class names
if pipename.lower() == 'drp':
inclasses = self._tableInQuery('cube') or 'cube' in str(self.query.statement.compile())
elif pipename.lower() == 'dap':
inclasses = self._tableInQuery('file') or 'file' in str(self.query.statement.compile())
# set alias
pipealias = self._drp_alias if pipename.lower() == 'drp' else self._dap_alias
# get the pipeinfo
if inclasses:
pipeinfo = marvindb.session.query(pipealias).\
join(marvindb.datadb.PipelineName, marvindb.datadb.PipelineVersion).\
filter(marvindb.datadb.PipelineName.label == pipename.upper(),
marvindb.datadb.PipelineVersion.version == bindparam(bindname, bindvalue)).one()
else:
pipeinfo = None
return pipeinfo
def _addPipeline(self):
''' Adds the DRP and DAP Pipeline Info into the Query '''
self._drp_alias = aliased(marvindb.datadb.PipelineInfo, name='drpalias')
self._dap_alias = aliased(marvindb.datadb.PipelineInfo, name='dapalias')
drppipe = self._getPipeInfo('drp')
dappipe = self._getPipeInfo('dap')
# Add DRP pipeline version
if drppipe:
self.query = self.query.join(self._drp_alias, marvindb.datadb.Cube.pipelineInfo).\
filter(self._drp_alias.pk == drppipe.pk)
# Add DAP pipeline version
if dappipe:
self.query = self.query.join(self._dap_alias, marvindb.dapdb.File.pipelineinfo).\
filter(self._dap_alias.pk == dappipe.pk)
@makeBaseQuery
def _tableInQuery(self, name):
''' Checks if a given SQL table is already in the SQL query '''
# do the check
try:
isin = name in str(self.query._from_obj[0])
except IndexError as e:
isin = False
except AttributeError as e:
if isinstance(self.query, six.string_types):
isin = name in self.query
else:
isin = False
return isin
def _group_by(self, params=None):
''' Group the query by a set of parameters
Parameters:
params (list):
A list of string parameter names to group the query by
Returns:
A new SQLA Query object
'''
if not params:
params = [d for d in self.defaultparams if 'spaxelprop' not in d]
newdefaults = self.marvinform._param_form_lookup.mapToColumn(params)
self.params = params
newq = self.query.from_self(*newdefaults).group_by(*newdefaults)
return newq
# ------------------------------------------------------
# DAP Specific Query Modifiers - subqueries, etc go below here
# -----------------------------------------------------
def _buildDapQuery(self):
''' Builds a DAP zonal query
'''
# get the appropriate Junk (SpaxelProp) ModelClass
self._junkclass = self.marvinform.\
_param_form_lookup['spaxelprop.file'].Meta.model
# get good spaxels
# bingood = self.getGoodSpaxels()
# self.query = self.query.\
# join(bingood, bingood.c.binfile == marvindb.dapdb.Junk.file_pk)
# check for additional modifier criteria
if self._parsed.functions:
# loop over all functions
for fxn in self._parsed.functions:
# look up the function name in the marvinform dictionary
try:
methodname = self.marvinform._param_fxn_lookup[fxn.fxnname]
except KeyError as e:
self.reset()
raise MarvinError('Could not set function: {0}'.format(e))
else:
# run the method
methodcall = self.__getattribute__(methodname)
methodcall(fxn)
def _check_dapall_query(self):
''' Checks if the query is on the DAPall table. '''
isdapall = self._check_query('dapall')
if isdapall:
self.query = self._group_by()
def _getGoodSpaxels(self):
''' Subquery - Counts the number of good spaxels
Counts the number of good spaxels with binid != -1
Uses the junk.bindid_pk != 9999 since this is known and set.
Removes need to join to the binid table
Returns:
bincount (subquery):
An SQLalchemy subquery to be joined into the main query object
'''
spaxelname = self._junkclass.__name__
bincount = self.session.query(self._junkclass.file_pk.label('binfile'),
func.count(self._junkclass.pk).label('goodcount'))
# optionally add the filter if the table is SpaxelProp
if 'CleanSpaxelProp' not in spaxelname:
bincount = bincount.filter(self._junkclass.binid != -1)
# group the results by file_pk
bincount = bincount.group_by(self._junkclass.file_pk).subquery('bingood', with_labels=True)
return bincount
def _getCountOf(self, expression):
''' Subquery - Counts spaxels satisfying an expression
Counts the number of spaxels of a given
parameter above a certain value.
Parameters:
expression (str):
The filter expression to parse
Returns:
valcount (subquery):
An SQLalchemy subquery to be joined into the main query object
Example:
>>> expression = 'junk.emline_gflux_ha_6564 >= 25'
'''
# parse the expression into name, operator, value
param, ops, value = self._parseExpression(expression)
# look up the InstrumentedAttribute, Operator, and convert Value
attribute = self.marvinform._param_form_lookup.mapToColumn(param)
op = opdict[ops]
value = float(value)
# Build the subquery
valcount = self.session.query(self._junkclass.file_pk.label('valfile'),
(func.count(self._junkclass.pk)).label('valcount')).\
filter(op(attribute, value)).\
group_by(self._junkclass.file_pk).subquery('goodhacount', with_labels=True)
return valcount
def getPercent(self, fxn, **kwargs):
''' Query - Computes count comparisons
Retrieves the number of objects that have satisfy a given expression
in x% of good spaxels. Expression is of the form
Parameter Operand Value. This function is mapped to
the "npergood" filter name.
Syntax: fxnname(expression) operator value
Parameters:
fxn (str):
The function condition used in the query filter
Example:
>>> fxn = 'npergood(junk.emline_gflux_ha_6564 > 25) >= 20'
>>> Syntax: npergood() - function name
>>> npergood(expression) operator value
>>>
>>> Select objects that have Ha flux > 25 in more than
>>> 20% of their (good) spaxels.
'''
# parse the function into name, condition, operator, and value
name, condition, ops, value = self._parseFxn(fxn)
percent = float(value) / 100.
op = opdict[ops]
# Retrieve the necessary subqueries
bincount = self._getGoodSpaxels()
valcount = self._getCountOf(condition)
# Join to the main query
self.query = self.query.join(bincount, bincount.c.binfile == self._junkclass.file_pk).\
join(valcount, valcount.c.valfile == self._junkclass.file_pk).\
filter(op(valcount.c.valcount, percent * bincount.c.goodcount))
# Group the results by main defaultdatadb parameters,
# so as not to include all spaxels
newdefs = [d for d in self.defaultparams if 'spaxelprop' not in d]
self.query = self._group_by(params=newdefs)
# newdefaults = self.marvinform._param_form_lookup.mapToColumn(newdefs)
# self.params = newdefs
# self.query = self.query.from_self(*newdefaults).group_by(*newdefaults)
def _parseFxn(self, fxn):
''' Parse a fxn condition '''
return fxn.fxnname, fxn.fxncond, fxn.op, fxn.value
def _parseExpression(self, expr):
''' Parse an expression '''
return expr.fullname, expr.op, expr.value
def _checkParsed(self):
''' Check the boolean parsed object
check for function conditions vs normal. This should be moved
into SQLalchemy Boolean Search
'''
# Triggers for only one filter and it is a function condition
if hasattr(self._parsed, 'fxn'):
self._parsed.functions = [self._parsed]
# Checks for shortcut names and replaces them in params
# now redundant after pre-check on searchfilter
for key, val in self._parsed.params.items():
if key in self.marvinform._param_form_lookup._nameShortcuts.keys():
newkey = self.marvinform._param_form_lookup._nameShortcuts[key]
self._parsed.params.pop(key)
self._parsed.params.update({newkey: val})
| [
"marvin.utils.general.temp_setattr",
"marvin.tools.results.Results",
"marvin.marvindb.db.engine.raw_connection",
"marvin.core.marvin_pickle.restore",
"marvin.core.exceptions.MarvinError",
"marvin.marvindb.db.engine.connect",
"marvin.core.exceptions.MarvinBreadCrumb",
"marvin.api.api.Interaction",
"m... | [((1667, 1685), 'marvin.core.exceptions.MarvinBreadCrumb', 'MarvinBreadCrumb', ([], {}), '()\n', (1683, 1685), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((1711, 1728), 'collections.defaultdict', 'defaultdict', (['tree'], {}), '(tree)\n', (1722, 1728), False, 'from collections import defaultdict, OrderedDict\n'), ((2595, 2603), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (2600, 2603), False, 'from functools import wraps\n'), ((2950, 2958), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (2955, 2958), False, 'from functools import wraps\n'), ((3257, 3265), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (3262, 3265), False, 'from functools import wraps\n'), ((5634, 5678), 'marvin.config.lookUpVersions', 'config.lookUpVersions', ([], {'release': 'self._release'}), '(release=self._release)\n', (5655, 5678), False, 'from marvin import config, marvindb\n'), ((5973, 5989), 'collections.defaultdict', 'defaultdict', (['str'], {}), '(str)\n', (5984, 5989), False, 'from collections import defaultdict, OrderedDict\n'), ((17031, 17053), 'os.path.realpath', 'os.path.realpath', (['path'], {}), '(path)\n', (17047, 17053), False, 'import os\n'), ((17066, 17085), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (17079, 17085), False, 'import os\n'), ((17347, 17368), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (17362, 17368), False, 'import os\n'), ((18351, 18393), 'marvin.core.marvin_pickle.restore', 'marvin_pickle.restore', (['path'], {'delete': 'delete'}), '(path, delete=delete)\n', (18372, 18393), False, 'from marvin.core import marvin_pickle\n'), ((43940, 43994), 'sqlalchemy.orm.aliased', 'aliased', (['marvindb.datadb.PipelineInfo'], {'name': '"""drpalias"""'}), "(marvindb.datadb.PipelineInfo, name='drpalias')\n", (43947, 43994), False, 'from sqlalchemy.orm import aliased\n'), ((44021, 44075), 'sqlalchemy.orm.aliased', 'aliased', (['marvindb.datadb.PipelineInfo'], {'name': '"""dapalias"""'}), "(marvindb.datadb.PipelineInfo, name='dapalias')\n", (44028, 44075), False, 'from sqlalchemy.orm import aliased\n'), ((9061, 9149), 'warnings.warn', 'warnings.warn', (['"""No local database found. Cannot perform queries."""', 'MarvinUserWarning'], {}), "('No local database found. Cannot perform queries.',\n MarvinUserWarning)\n", (9074, 9149), False, 'import warnings\n'), ((9164, 9238), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No local database found. Query cannot be run in local mode"""'], {}), "('No local database found. Query cannot be run in local mode')\n", (9175, 9238), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((9413, 9478), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No URL Map found. Cannot make remote query calls!"""'], {}), "('No URL Map found. Cannot make remote query calls!')\n", (9424, 9478), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((16987, 17014), 'os.path.join', 'os.path.join', (["(path + '.mpf')"], {}), "(path + '.mpf')\n", (16999, 17014), False, 'import os\n'), ((17105, 17170), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""path must be a full route, including the filename."""'], {}), "('path must be a full route, including the filename.')\n", (17116, 17170), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((17183, 17203), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (17197, 17203), False, 'import os\n'), ((17235, 17308), 'warnings.warn', 'warnings.warn', (['"""file already exists. Not overwriting."""', 'MarvinUserWarning'], {}), "('file already exists. Not overwriting.', MarvinUserWarning)\n", (17248, 17308), False, 'import warnings\n'), ((17384, 17407), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (17398, 17407), False, 'import os\n'), ((17421, 17441), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (17432, 17441), False, 'import os\n'), ((28727, 28750), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (28748, 28750), False, 'import datetime\n'), ((31500, 31523), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (31521, 31523), False, 'import datetime\n'), ((31711, 31916), 'marvin.tools.results.Results', 'Results', ([], {'results': 'res', 'query': 'query', 'count': 'count', 'mode': 'self.mode', 'returntype': 'self.returntype', 'queryobj': 'self', 'totalcount': 'self.totalcount', 'chunk': 'self.limit', 'runtime': 'self.runtime', 'start': 'start', 'end': 'end'}), '(results=res, query=query, count=count, mode=self.mode, returntype=\n self.returntype, queryobj=self, totalcount=self.totalcount, chunk=self.\n limit, runtime=self.runtime, start=start, end=end)\n', (31718, 31916), False, 'from marvin.tools.results import Results\n'), ((32020, 32043), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (32041, 32043), False, 'import datetime\n'), ((11957, 11990), 'collections.OrderedDict.fromkeys', 'OrderedDict.fromkeys', (['self.params'], {}), '(self.params)\n', (11977, 11990), False, 'from collections import defaultdict, OrderedDict\n'), ((16941, 16963), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (16957, 16963), False, 'import os\n'), ((17626, 17657), 'marvin.utils.general.temp_setattr', 'temp_setattr', (['self', 'attrs', 'None'], {}), '(self, attrs, None)\n', (17638, 17657), False, 'from marvin.utils.general import temp_setattr\n'), ((17771, 17791), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (17785, 17791), False, 'import os\n'), ((21501, 21567), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""Input parameters must be a natural language string!"""'], {}), "('Input parameters must be a natural language string!')\n", (21512, 21567), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((30671, 30706), 'marvin.marvindb.db.engine.raw_connection', 'marvindb.db.engine.raw_connection', ([], {}), '()\n', (30704, 30706), False, 'from marvin import config, marvindb\n'), ((34224, 34452), 'marvin.tools.results.Results', 'Results', ([], {'results': 'res', 'query': 'self.query', 'mode': 'self.mode', 'queryobj': 'self', 'count': 'count', 'returntype': 'self.returntype', 'totalcount': 'totalcount', 'chunk': 'chunk', 'runtime': 'query_runtime', 'response_time': 'resp_runtime', 'start': 'start', 'end': 'end'}), '(results=res, query=self.query, mode=self.mode, queryobj=self, count\n =count, returntype=self.returntype, totalcount=totalcount, chunk=chunk,\n runtime=query_runtime, response_time=resp_runtime, start=start, end=end)\n', (34231, 34452), False, 'from marvin.tools.results import Results\n'), ((41463, 41500), 'warnings.warn', 'warnings.warn', (['sql', 'MarvinUserWarning'], {}), '(sql, MarvinUserWarning)\n', (41476, 41500), False, 'import warnings\n'), ((41797, 41817), 'sqlalchemy.dialects.postgresql.dialect', 'postgresql.dialect', ([], {}), '()\n', (41815, 41817), False, 'from sqlalchemy.dialects import postgresql\n'), ((7265, 7338), 'warnings.warn', 'warnings.warn', (['"""local mode failed. Trying remote now."""', 'MarvinUserWarning'], {}), "('local mode failed. Trying remote now.', MarvinUserWarning)\n", (7278, 7338), False, 'import warnings\n'), ((17809, 17824), 'os.remove', 'os.remove', (['path'], {}), '(path)\n', (17818, 17824), False, 'import os\n'), ((21269, 21303), 'sqlalchemy_boolean_search.parse_boolean_search', 'parse_boolean_search', (['searchfilter'], {}), '(searchfilter)\n', (21289, 21303), False, 'from sqlalchemy_boolean_search import parse_boolean_search, BooleanSearchException\n'), ((23288, 23305), 'numpy.invert', 'np.invert', (['isgood'], {}), '(isgood)\n', (23297, 23305), True, 'import numpy as np\n'), ((30053, 30177), 'warnings.warn', 'warnings.warn', (['"""Warning: Attempting to return all results. This may take a long time or crash."""', 'MarvinUserWarning'], {}), "(\n 'Warning: Attempting to return all results. This may take a long time or crash.'\n , MarvinUserWarning)\n", (30066, 30177), False, 'import warnings\n'), ((32262, 32319), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No URL Map found. Cannot make remote call"""'], {}), "('No URL Map found. Cannot make remote call')\n", (32273, 32319), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((32369, 32474), 'warnings.warn', 'warnings.warn', (['"""Warning: Attempting to return all results. This may take a long time or crash."""'], {}), "(\n 'Warning: Attempting to return all results. This may take a long time or crash.'\n )\n", (32382, 32474), False, 'import warnings\n'), ((33129, 33179), 'marvin.api.api.Interaction', 'Interaction', ([], {'route': 'url', 'params': 'params', 'stream': '(True)'}), '(route=url, params=params, stream=True)\n', (33140, 33179), False, 'from marvin.api.api import Interaction\n'), ((37228, 37285), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No URL Map found. Cannot make remote call"""'], {}), "('No URL Map found. Cannot make remote call')\n", (37239, 37285), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((37490, 37527), 'marvin.api.api.Interaction', 'Interaction', ([], {'route': 'url', 'params': 'params'}), '(route=url, params=params)\n', (37501, 37527), False, 'from marvin.api.api import Interaction\n'), ((38351, 38408), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No URL Map found. Cannot make remote call"""'], {}), "('No URL Map found. Cannot make remote call')\n", (38362, 38408), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((38616, 38653), 'marvin.api.api.Interaction', 'Interaction', ([], {'route': 'url', 'params': 'params'}), '(route=url, params=params)\n', (38627, 38653), False, 'from marvin.api.api import Interaction\n'), ((47691, 47721), 'sqlalchemy.func.count', 'func.count', (['self._junkclass.pk'], {}), '(self._junkclass.pk)\n', (47701, 47721), False, 'from sqlalchemy import func\n'), ((31006, 31034), 'marvin.marvindb.db.engine.connect', 'marvindb.db.engine.connect', ([], {}), '()\n', (31032, 31034), False, 'from marvin import config, marvindb\n'), ((39794, 39809), 'sqlalchemy.sql.expression.desc', 'desc', (['sortparam'], {}), '(sortparam)\n', (39798, 39809), False, 'from sqlalchemy.sql.expression import desc\n'), ((28409, 28429), 'marvin.core.caching_query.FromCache', 'FromCache', (['"""default"""'], {}), "('default')\n", (28418, 28429), False, 'from marvin.core.caching_query import FromCache\n'), ((43713, 43743), 'sqlalchemy.bindparam', 'bindparam', (['bindname', 'bindvalue'], {}), '(bindname, bindvalue)\n', (43722, 43743), False, 'from sqlalchemy import bindparam\n'), ((27304, 27324), 'sqlalchemy.dialects.postgresql.dialect', 'postgresql.dialect', ([], {}), '()\n', (27322, 27324), False, 'from sqlalchemy.dialects import postgresql\n'), ((41167, 41187), 'sqlalchemy.dialects.postgresql.dialect', 'postgresql.dialect', ([], {}), '()\n', (41185, 41187), False, 'from sqlalchemy.dialects import postgresql\n'), ((31287, 31312), 'numpy.log10', 'np.log10', (['self.totalcount'], {}), '(self.totalcount)\n', (31295, 31312), True, 'import numpy as np\n'), ((43446, 43479), 'marvin.marvindb.session.query', 'marvindb.session.query', (['pipealias'], {}), '(pipealias)\n', (43468, 43479), False, 'from marvin import config, marvindb\n'), ((49071, 49101), 'sqlalchemy.func.count', 'func.count', (['self._junkclass.pk'], {}), '(self._junkclass.pk)\n', (49081, 49101), False, 'from sqlalchemy import func\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Component tests for VPC network functionality - Port Forwarding Rules.
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.integration.lib.base import (stopRouter,
startRouter,
Account,
VpcOffering,
VPC,
ServiceOffering,
NATRule,
NetworkACL,
PublicIPAddress,
NetworkOffering,
Network,
VirtualMachine,
LoadBalancerRule,
StaticNATRule)
from marvin.integration.lib.common import (get_domain,
get_zone,
get_template,
cleanup_resources,
list_routers)
import socket
class Services:
"""Test VPC network services - Port Forwarding Rules Test Data Class.
"""
def __init__(self):
self.services = {
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended for unique
# username
"password": "password",
},
"host1":None,
"host2":None,
"service_offering": {
"name": "Tiny Instance",
"displaytext": "Tiny Instance",
"cpunumber": 1,
"cpuspeed": 100,
"memory": 128,
},
"network_offering": {
"name": 'VPC Network offering',
"displaytext": 'VPC Network off',
"guestiptype": 'Isolated',
"supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL',
"traffictype": 'GUEST',
"availability": 'Optional',
"useVpc": 'on',
"serviceProviderList": {
"Vpn": 'VpcVirtualRouter',
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"Lb": 'VpcVirtualRouter',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
},
},
"network_offering_no_lb": {
"name": 'VPC Network offering',
"displaytext": 'VPC Network off',
"guestiptype": 'Isolated',
"supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,UserData,StaticNat,NetworkACL',
"traffictype": 'GUEST',
"availability": 'Optional',
"useVpc": 'on',
"serviceProviderList": {
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
},
},
"vpc_offering": {
"name": 'VPC off',
"displaytext": 'VPC off',
"supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat',
},
"vpc": {
"name": "TestVPC",
"displaytext": "TestVPC",
"cidr": '10.0.0.1/24'
},
"network": {
"name": "Test Network",
"displaytext": "Test Network",
"netmask": '255.255.255.0'
},
"lbrule": {
"name": "SSH",
"alg": "leastconn",
# Algorithm used for load balancing
"privateport": 22,
"publicport": 2222,
"openfirewall": False,
"startport": 22,
"endport": 2222,
"protocol": "TCP",
"cidrlist": '0.0.0.0/0',
},
"lbrule_http": {
"name": "HTTP",
"alg": "leastconn",
# Algorithm used for load balancing
"privateport": 80,
"publicport": 8888,
"openfirewall": False,
"startport": 80,
"endport": 8888,
"protocol": "TCP",
"cidrlist": '0.0.0.0/0',
},
"ssh_rule": {
"privateport": 22,
"publicport": 22,
"startport": 22,
"endport": 22,
"protocol": "TCP",
"cidrlist": '0.0.0.0/0',
},
"http_rule": {
"privateport": 80,
"publicport": 80,
"startport": 80,
"endport": 80,
"cidrlist": '0.0.0.0/0',
"protocol": "TCP"
},
"virtual_machine": {
"displayname": "Test VM",
"username": "root",
"password": "password",
"ssh_port": 22,
"hypervisor": 'XenServer',
# Hypervisor type should be same as
# hypervisor type of cluster
"privateport": 22,
"publicport": 22,
"protocol": 'TCP',
},
"ostype": 'CentOS 5.3 (64-bit)',
"sleep": 60,
"timeout": 10,
}
class TestVPCNetworkPFRules(cloudstackTestCase):
@classmethod
def setUpClass(cls):
# We want to fail quicker if it's failure
socket.setdefaulttimeout(60)
cls.api_client = super(
TestVPCNetworkPFRules,
cls
).getClsTestClient().getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup = [cls.service_offering]
return
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
print("Warning: Exception during cleanup : %s" % e)
#raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account]
self.debug("Creating a VPC offering..")
self.vpc_off = VpcOffering.create(
self.apiclient,
self.services["vpc_offering"]
)
self.cleanup.append(self.vpc_off)
self.debug("Enabling the VPC offering created")
self.vpc_off.update(self.apiclient, state='Enabled')
self.debug("Creating a VPC network in the account: %s" % self.account.name)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
self.vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=self.vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
return
def tearDown(self):
try:
#Clean up, terminate the created network offerings
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
self.debug("Warning: Exception during cleanup : %s" % e)
#raise Exception("Warning: Exception during cleanup : %s" % e)
return
def get_Router_For_VPC(self):
routers = list_routers(self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
)
self.assertEqual(isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(len(routers),
0,
"Check list router response"
)
router = routers[0]
return router
def stop_VPC_VRouter(self):
router = self.get_Router_For_VPC()
self.debug("Stopping router ID: %s" % router.id)
cmd = stopRouter.stopRouterCmd()
cmd.id = router.id
self.apiclient.stopRouter(cmd)
routers = list_routers(self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
)
self.assertEqual(isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
router = routers[0]
self.assertEqual(router.state,
'Stopped',
"Check list router response for router state"
)
return router
def start_VPC_VRouter(self, router):
# Start the VPC Router
cmd = startRouter.startRouterCmd()
cmd.id = router.id
self.apiclient.startRouter(cmd)
routers = list_routers(self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.assertEqual(isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
router = routers[0]
self.assertEqual(router.state,
'Running',
"Check list router response for router state"
)
def check_ssh_into_vm(self, vm, public_ip, testnegative=False):
self.debug("Checking if we can SSH into VM=%s on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress))
try:
vm.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress)
if not testnegative:
self.debug("SSH into VM=%s on public_ip=%s is successfully" % (vm.name, public_ip.ipaddress.ipaddress))
else:
self.fail("SSH into VM=%s on public_ip=%s is successfully" % (vm.name, public_ip.ipaddress.ipaddress))
except:
if not testnegative:
self.fail("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress))
else:
self.debug("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress))
def check_wget_from_vm(self, vm, public_ip, testnegative=False):
import urllib
self.debug("Checking if we can wget from a VM=%s http server on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress))
try:
urllib.urlretrieve("http://%s/test.html" % public_ip.ipaddress.ipaddress, filename="test.html")
if not testnegative:
self.debug("Successful to wget from VM=%s http server on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress))
else:
self.fail("Successful to wget from VM=%s http server on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress))
except:
if not testnegative:
self.fail("Failed to wget from VM=%s http server on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress))
else:
self.debug("Failed to wget from VM=%s http server on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress))
def create_StaticNatRule_For_VM(self, vm, public_ip, network):
self.debug("Enabling static NAT for IP: %s" %
public_ip.ipaddress.ipaddress)
try:
StaticNATRule.enable(
self.apiclient,
ipaddressid=public_ip.ipaddress.id,
virtualmachineid=vm.id,
networkid=network.id
)
self.debug("Static NAT enabled for IP: %s" %
public_ip.ipaddress.ipaddress)
except Exception as e:
self.fail("Failed to enable static NAT on IP: %s - %s" % (
public_ip.ipaddress.ipaddress, e))
def acquire_Public_IP(self, network):
self.debug("Associating public IP for network: %s" % network.name)
public_ip = PublicIPAddress.create(self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=None, #network.id,
vpcid=self.vpc.id
)
self.debug("Associated %s with network %s" % (public_ip.ipaddress.ipaddress,
network.id
))
return public_ip
def create_VPC(self, cidr='10.1.2.1/16'):
self.debug("Creating a VPC offering..")
self.services["vpc_offering"]["name"] = self.services["vpc_offering"]["name"] + str(cidr)
vpc_off = VpcOffering.create(
self.apiclient,
self.services["vpc_offering"]
)
self.cleanup.append(self.vpc_off)
self.debug("Enabling the VPC offering created")
vpc_off.update(self.apiclient, state='Enabled')
self.debug("Creating a VPC network in the account: %s" % self.account.name)
self.services["vpc"]["cidr"] = cidr
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
return vpc
def create_Network(self, net_offerring, gateway='10.1.1.1',vpc=None):
try:
self.debug('Create NetworkOffering')
net_offerring["name"] = "NET_OFF-" + str(gateway)
nw_off = NetworkOffering.create(self.apiclient,
net_offerring,
conservemode=False
)
# Enable Network offering
nw_off.update(self.apiclient, state='Enabled')
self.cleanup.append(nw_off)
self.debug('Created and Enabled NetworkOffering')
self.services["network"]["name"] = "NETWORK-" + str(gateway)
self.debug('Adding Network=%s' % self.services["network"])
obj_network = Network.create(self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=nw_off.id,
zoneid=self.zone.id,
gateway=gateway,
vpcid=vpc.id if vpc else self.vpc.id
)
self.debug("Created network with ID: %s" % obj_network.id)
return obj_network
except:
self.fail('Unable to create a Network with offering=%s' % net_offerring)
def create_VM_in_Network(self, network, host_id=None):
try:
self.debug('Creating VM in network=%s' % network.name)
vm = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(network.id)],
hostid=host_id
)
self.debug('Created VM=%s in network=%s' % (vm.id, network.name))
return vm
except:
self.fail('Unable to create VM in a Network=%s' % network.name)
def create_LB_Rule(self, public_ip, network, vmarray, services=None):
self.debug("Creating LB rule for IP address: %s" %
public_ip.ipaddress.ipaddress)
objservices = None
if services:
objservices = services
else:
objservices = self.services["lbrule"]
lb_rule = LoadBalancerRule.create(
self.apiclient,
objservices,
ipaddressid=public_ip.ipaddress.id,
accountid=self.account.name,
networkid=network.id,
vpcid=self.vpc.id,
domainid=self.account.domainid
)
self.debug("Adding virtual machines %s and %s to LB rule" % (vmarray))
lb_rule.assign(self.apiclient, vmarray)
return lb_rule
def create_ingress_rule(self, network, services=None):
if not services:
services = self.services["ssh_rule"]
self.debug("Adding NetworkACL rules to make NAT rule accessible")
nwacl_nat = NetworkACL.create(self.apiclient,
services,
networkid=network.id,
traffictype='Ingress'
)
return nwacl_nat
@attr(tags=["advanced", "intervlan"])
def test_01_VPC_StaticNatRuleCreateStoppedState(self):
""" Test case no extra :
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Create a Network offering - NO1 with all supported services
# 3. Add network1(10.1.1.1/24) using N01 to this VPC.
# 4. Deploy vm1 in network1.
# 5. Stop the VPC Virtual Router.
# 6. Use the Create PF rule for vm in network1.
# 7. Start VPC Virtual Router.
# 8. Successfully ssh into the Guest VM using the PF rule
network_1 = self.create_Network(self.services["network_offering"])
self.create_ingress_rule(network_1)
vm_1 = self.create_VM_in_Network(network_1)
public_ip_1 = self.acquire_Public_IP(network_1)
router = self.stop_VPC_VRouter()
self.create_StaticNatRule_For_VM( vm_1, public_ip_1, network_1)
self.start_VPC_VRouter(router)
self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False)
return
@attr(tags=["advanced", "intervlan"])
def test_02_VPC_CreateStaticNatRule(self):
""" Test case no 229 : Create Static NAT Rule for a single virtual network of
a VPC using a new Public IP Address available with the VPC when the Virtual Router is in Running State
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Create a Network offering - NO1 with all supported services
# 3. Add network1(10.1.1.1/24) using N01 to this VPC.
# 4. Deploy vm1 in network1.
# 5. Use the Create Static Nat rule for vm in network1.
# 6. Successfully ssh into the Guest VM using the PF rule
network_1 = self.create_Network(self.services["network_offering"])
self.create_ingress_rule(network_1)
vm_1 = self.create_VM_in_Network(network_1)
public_ip_1 = self.acquire_Public_IP(network_1)
self.create_StaticNatRule_For_VM( vm_1, public_ip_1, network_1)
self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False)
return
@attr(tags=["advanced", "intervlan"])
def test_03_VPC_StopCreateMultipleStaticNatRuleStopppedState(self):
""" Test case no extra : Create Static Nat Rule rules for a two/multiple virtual networks of a VPC using
a new Public IP Address available with the VPC when Virtual Router is in Stopped State
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Create a Network offering - NO1 with all supported services
# 3. Add network1(10.1.1.1/24) using N01 to this VPC.
# 4. Add network2(10.1.2.1/24) using N01 to this VPC.
# 5. Deploy vm1 in network1.
# 6. Deploy vm2 in network2.
# 7. Stop the VPC Virtual Router.
# 8. Use the Create PF rule for vm1 in network1.
# 9. Use the Create PF rule for vm2 in network2.
# 10. Start VPC Virtual Router.
# 11. Successfully ssh into the Guest VM1 and VM2 using the PF rule
network_1 = self.create_Network(self.services["network_offering_no_lb"])
network_2 = self.create_Network(self.services["network_offering_no_lb"], '10.1.2.1')
self.create_ingress_rule(network_1)
self.create_ingress_rule(network_2)
vm_1 = self.create_VM_in_Network(network_1)
vm_2 = self.create_VM_in_Network(network_2)
public_ip_1 = self.acquire_Public_IP(network_1)
public_ip_2 = self.acquire_Public_IP(network_2)
router = self.stop_VPC_VRouter()
self.create_StaticNatRule_For_VM(vm_1, public_ip_1, network_1)
self.create_StaticNatRule_For_VM(vm_2, public_ip_2, network_2)
self.start_VPC_VRouter(router)
self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False)
self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=False)
return
@attr(tags=["advanced", "intervlan"])
def test_04_VPC_CreateMultipleStaticNatRule(self):
""" Test case no 230 : Create Static NAT Rules for a two/multiple virtual networks of
a VPC using a new Public IP Address available with the VPC when the Virtual Router is in Running State
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Create a Network offering - NO1 with all supported services
# 3. Add network1(10.1.1.1/24) using N01 to this VPC.
# 4. Add network2(10.1.2.1/24) using N01 to this VPC.
# 5. Deploy vm1 in network1.
# 6. Deploy vm2 in network2.
# 7. Use the Create PF rule for vm1 in network1.
# 8. Use the Create PF rule for vm2 in network2.
# 9. Start VPC Virtual Router.
# 10. Successfully ssh into the Guest VM1 and VM2 using the PF rule
network_1 = self.create_Network(self.services["network_offering"])
network_2 = self.create_Network(self.services["network_offering_no_lb"], '10.1.2.1')
self.create_ingress_rule(network_1)
self.create_ingress_rule(network_2)
vm_1 = self.create_VM_in_Network(network_1)
vm_2 = self.create_VM_in_Network(network_2)
public_ip_1 = self.acquire_Public_IP(network_1)
public_ip_2 = self.acquire_Public_IP(network_2)
router = self.stop_VPC_VRouter()
self.create_StaticNatRule_For_VM(vm_1, public_ip_1, network_1)
self.create_StaticNatRule_For_VM(vm_2, public_ip_2, network_2)
self.start_VPC_VRouter(router)
self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False)
self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=False)
return
@attr(tags=["advanced", "intervlan"])
def test_05_network_services_VPC_DeleteAllPF(self):
""" Test case no 232: Delete all Static NAT Rules for a single virtual network of
a VPC belonging to a single Public IP Address when the Virtual Router is in Running State
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Create a Network offering - NO1 with all supported services
# 3. Add network1(10.1.1.1/24) using N01 to this VPC.
# 4. Deploy vm1 in network1.
# 5. Use the Create PF rule for vm in network1.
# 6. Successfully ssh into the Guest VM using the PF rule.
# 7. Successfully wget a file on http server of VM1.
# 8. Delete all PF rule
# 9. wget a file present on http server of VM1 should fail
# 10. ssh into Guest VM using the PF rule should fail
network_1 = self.create_Network(self.services["network_offering"])
self.create_ingress_rule(network_1)
self.create_ingress_rule(network_1, self.services["http_rule"])
vm_1 = self.create_VM_in_Network(network_1)
public_ip_1 = self.acquire_Public_IP(network_1)
nat_rule = self.create_StaticNatRule_For_VM(vm_1, public_ip_1, network_1)
http_rule = self.create_StaticNatRule_For_VM(vm_1, public_ip_1, network_1, self.services["http_rule"])
self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False)
self.check_wget_from_vm(vm_1, public_ip_1, testnegative=False)
http_rule.delete(self.apiclient)
nat_rule.delete(self.apiclient)
self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=True)
self.check_wget_from_vm(vm_1, public_ip_1, testnegative=True)
return
@attr(tags=["advanced", "intervlan"])
def test_06_network_services_VPC_DeleteAllMultiplePF(self):
""" Test case no 233: Delete all Static NAT rules for two/multiple virtual networks of a VPC.
Observe the status of the Public IP Addresses of the rules when the Virtual Router is in Running State.
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16.
# 2. Create a Network offering - NO1 with all supported services.
# 3. Add network1(10.1.1.1/24) using N01 to this VPC.
# 4. Add network2(10.1.2.1/24) using N01 to this VPC.
# 5. Deploy vm1 and vm2 in network1.
# 6. Deploy vm3 and vm4 in network2.
# 7. Use the Create PF rule ssh and http for vm1 and vm2 in network1.
# 8. Use the Create PF rule ssh and http for vm3 and vm4 in network2.
# 9. Successfully ssh into the Guest vm1, vm2, vm3 and vm4 using the PF rule.
# 10. Succesfully wget a file from http server present on vm1, vm2, vm3 and vm4.
# 12. Delete all PF rultes for vm1, vm2, vm3 and vm4.
# 13. Fail to ssh and http to vm1, vm2, vm3 and vm4.
network_1 = self.create_Network(self.services["network_offering"])
network_2 = self.create_Network(self.services["network_offering_no_lb"], '10.1.2.1')
self.create_ingress_rule(network_1)
self.create_ingress_rule(network_2)
self.create_ingress_rule(network_1, self.services["http_rule"])
self.create_ingress_rule(network_2, self.services["http_rule"])
vm_1 = self.create_VM_in_Network(network_1)
vm_2 = self.create_VM_in_Network(network_1)
vm_3 = self.create_VM_in_Network(network_2)
vm_4 = self.create_VM_in_Network(network_2)
public_ip_1 = self.acquire_Public_IP(network_1)
public_ip_2 = self.acquire_Public_IP(network_1)
public_ip_3 = self.acquire_Public_IP(network_2)
public_ip_4 = self.acquire_Public_IP(network_2)
nat_rule1 = self.create_StaticNatRule_For_VM(vm_1, public_ip_1, network_1)
nat_rule2 = self.create_StaticNatRule_For_VM(vm_2, public_ip_2, network_1)
nat_rule3 = self.create_StaticNatRule_For_VM(vm_3, public_ip_3, network_2)
nat_rule4 = self.create_StaticNatRule_For_VM(vm_4, public_ip_4, network_2)
self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False)
self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=False)
self.check_ssh_into_vm(vm_3, public_ip_1, testnegative=False)
self.check_ssh_into_vm(vm_4, public_ip_2, testnegative=False)
self.check_wget_from_vm(vm_1, public_ip_1, testnegative=False)
self.check_wget_from_vm(vm_2, public_ip_2, testnegative=False)
self.check_wget_from_vm(vm_3, public_ip_1, testnegative=False)
self.check_wget_from_vm(vm_4, public_ip_2, testnegative=False)
nat_rule1.delete(self.apiclient)
nat_rule2.delete(self.apiclient)
nat_rule3.delete(self.apiclient)
nat_rule4.delete(self.apiclient)
self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=True)
self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=True)
self.check_ssh_into_vm(vm_3, public_ip_1, testnegative=True)
self.check_ssh_into_vm(vm_4, public_ip_2, testnegative=True)
self.check_wget_from_vm(vm_1, public_ip_1, testnegative=True)
self.check_wget_from_vm(vm_2, public_ip_2, testnegative=True)
self.check_wget_from_vm(vm_3, public_ip_1, testnegative=True)
self.check_wget_from_vm(vm_4, public_ip_2, testnegative=True)
return
| [
"marvin.integration.lib.common.get_domain",
"marvin.integration.lib.base.startRouter.startRouterCmd",
"marvin.integration.lib.base.Account.create",
"marvin.integration.lib.base.StaticNATRule.enable",
"marvin.integration.lib.base.PublicIPAddress.create",
"marvin.integration.lib.base.NetworkOffering.create"... | [((25923, 25959), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (25927, 25959), False, 'from nose.plugins.attrib import attr\n'), ((26998, 27034), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (27002, 27034), False, 'from nose.plugins.attrib import attr\n'), ((28074, 28110), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (28078, 28110), False, 'from nose.plugins.attrib import attr\n'), ((29901, 29937), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (29905, 29937), False, 'from nose.plugins.attrib import attr\n'), ((31656, 31692), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (31660, 31692), False, 'from nose.plugins.attrib import attr\n'), ((33432, 33468), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (33436, 33468), False, 'from nose.plugins.attrib import attr\n'), ((11174, 11202), 'socket.setdefaulttimeout', 'socket.setdefaulttimeout', (['(60)'], {}), '(60)\n', (11198, 11202), False, 'import socket\n'), ((11524, 11564), 'marvin.integration.lib.common.get_domain', 'get_domain', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (11534, 11564), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, cleanup_resources, list_routers\n'), ((11584, 11622), 'marvin.integration.lib.common.get_zone', 'get_zone', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (11592, 11622), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, cleanup_resources, list_routers\n'), ((11646, 11711), 'marvin.integration.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (11658, 11711), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, cleanup_resources, list_routers\n'), ((12024, 12096), 'marvin.integration.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (12046, 12096), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((12770, 12867), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (12784, 12867), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((13215, 13280), 'marvin.integration.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (13233, 13280), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((13744, 13913), 'marvin.integration.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=self.account.name, domainid=self.\n account.domainid)\n", (13754, 13913), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((14549, 14641), 'marvin.integration.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (14561, 14641), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, cleanup_resources, list_routers\n'), ((15349, 15375), 'marvin.integration.lib.base.stopRouter.stopRouterCmd', 'stopRouter.stopRouterCmd', ([], {}), '()\n', (15373, 15375), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((15461, 15553), 'marvin.integration.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (15473, 15553), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, cleanup_resources, list_routers\n'), ((16186, 16214), 'marvin.integration.lib.base.startRouter.startRouterCmd', 'startRouter.startRouterCmd', ([], {}), '()\n', (16212, 16214), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((16301, 16414), 'marvin.integration.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, zoneid=self.zone.id)\n', (16313, 16414), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, cleanup_resources, list_routers\n'), ((19869, 20034), 'marvin.integration.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'None', 'vpcid': 'self.vpc.id'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=None, vpcid=\n self.vpc.id)\n', (19891, 20034), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((20718, 20783), 'marvin.integration.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (20736, 20783), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((21228, 21391), 'marvin.integration.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (21238, 21391), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((24694, 24894), 'marvin.integration.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', 'objservices'], {'ipaddressid': 'public_ip.ipaddress.id', 'accountid': 'self.account.name', 'networkid': 'network.id', 'vpcid': 'self.vpc.id', 'domainid': 'self.account.domainid'}), '(self.apiclient, objservices, ipaddressid=public_ip.\n ipaddress.id, accountid=self.account.name, networkid=network.id, vpcid=\n self.vpc.id, domainid=self.account.domainid)\n', (24717, 24894), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((25641, 25733), 'marvin.integration.lib.base.NetworkACL.create', 'NetworkACL.create', (['self.apiclient', 'services'], {'networkid': 'network.id', 'traffictype': '"""Ingress"""'}), "(self.apiclient, services, networkid=network.id,\n traffictype='Ingress')\n", (25658, 25733), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((12435, 12482), 'marvin.integration.lib.common.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (12452, 12482), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, cleanup_resources, list_routers\n'), ((14258, 14305), 'marvin.integration.lib.common.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (14275, 14305), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, cleanup_resources, list_routers\n'), ((18071, 18170), 'urllib.urlretrieve', 'urllib.urlretrieve', (["('http://%s/test.html' % public_ip.ipaddress.ipaddress)"], {'filename': '"""test.html"""'}), "('http://%s/test.html' % public_ip.ipaddress.ipaddress,\n filename='test.html')\n", (18089, 18170), False, 'import urllib\n'), ((19069, 19191), 'marvin.integration.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient'], {'ipaddressid': 'public_ip.ipaddress.id', 'virtualmachineid': 'vm.id', 'networkid': 'network.id'}), '(self.apiclient, ipaddressid=public_ip.ipaddress.id,\n virtualmachineid=vm.id, networkid=network.id)\n', (19089, 19191), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((21860, 21933), 'marvin.integration.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'net_offerring'], {'conservemode': '(False)'}), '(self.apiclient, net_offerring, conservemode=False)\n', (21882, 21933), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n'), ((22501, 22738), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'nw_off.id', 'zoneid': 'self.zone.id', 'gateway': 'gateway', 'vpcid': '(vpc.id if vpc else self.vpc.id)'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=nw_off.\n id, zoneid=self.zone.id, gateway=gateway, vpcid=vpc.id if vpc else self\n .vpc.id)\n", (22515, 22738), False, 'from marvin.integration.lib.base import stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule, StaticNATRule\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for NuageVsp network Plugin
"""
# Import Local Modules
from marvin.lib.base import Account
from nose.plugins.attrib import attr
from nuageTestCase import nuageTestCase
class TestNuageVsp(nuageTestCase):
""" Test NuageVsp network plugin
"""
@classmethod
def setUpClass(cls):
super(TestNuageVsp, cls).setUpClass()
return
def setUp(self):
# Create an account
self.account = Account.create(self.api_client,
self.test_data["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account]
return
@attr(tags=["advanced", "nuagevsp"], required_hardware="false")
def test_nuage_vsp(self):
""" Test NuageVsp network plugin with basic Isolated Network functionality
"""
# 1. Verify that the NuageVsp network service provider is successfully created and enabled.
# 2. Create and enable Nuage Vsp Isolated Network offering, check if it is successfully created and enabled.
# 3. Create an Isolated Network with Nuage Vsp Isolated Network offering, check if it is successfully created
# and is in the "Allocated" state.
# 4. Deploy a VM in the created Isolated network, check if the Isolated network state is changed to
# "Implemented", and both the VM & VR are successfully deployed and are in the "Running" state.
# 5. Deploy one more VM in the created Isolated network, check if the VM is successfully deployed and is in the
# "Running" state.
# 6. Delete the created Isolated Network after destroying its VMs, check if the Isolated network is successfully
# deleted.
self.debug("Validating the NuageVsp network service provider...")
self.validate_NetworkServiceProvider("NuageVsp", state="Enabled")
# Creating a network offering
self.debug("Creating and enabling Nuage Vsp Isolated Network offering...")
network_offering = self.create_NetworkOffering(
self.test_data["nuage_vsp_services"]["isolated_network_offering"])
self.validate_network_offering(network_offering, state="Enabled")
# Creating a network
self.debug("Creating an Isolated Network with Nuage Vsp Isolated Network offering...")
network = self.create_Network(network_offering, gateway='10.1.1.1')
self.validate_network(network, state="Allocated")
# Deploying a VM in the network
vm_1 = self.create_VM_in_Network(network)
self.validate_network(network, state="Implemented")
vr = self.get_network_router(network)
self.check_router_state(vr, state="Running")
self.check_vm_state(vm_1, state="Running")
# VSPK verification
self.verify_vsp_network(self.domain.id, network)
self.verify_vsp_router(vr)
self.verify_vsp_vm(vm_1)
# Deploying one more VM in the network
vm_2 = self.create_VM_in_Network(network)
self.check_vm_state(vm_2, state="Running")
# VSPK verification
self.verify_vsp_vm(vm_2)
# Deleting the network
self.debug("Deleting the Isolated Network with Nuage Vsp Isolated Network offering...")
self.delete_VM(vm_1)
self.delete_VM(vm_2)
self.delete_Network(network)
with self.assertRaises(Exception):
self.validate_network(network)
self.debug("Isolated Network successfully deleted in CloudStack")
# VSPK verification
with self.assertRaises(Exception):
self.verify_vsp_network(self.domain.id, network)
self.debug("Isolated Network successfully deleted in VSD")
| [
"marvin.lib.base.Account.create"
] | [((1534, 1596), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'nuagevsp']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'nuagevsp'], required_hardware='false')\n", (1538, 1596), False, 'from nose.plugins.attrib import attr\n'), ((1226, 1325), 'marvin.lib.base.Account.create', 'Account.create', (['self.api_client', "self.test_data['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.test_data['account'], admin=True,\n domainid=self.domain.id)\n", (1240, 1325), False, 'from marvin.lib.base import Account\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for Multiple IPs per NIC feature
Test Plan: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Multiple+IPs+per+NIC+Test+Plan
Issue Link: https://issues.apache.org/jira/browse/CLOUDSTACK-4840
Design Document: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Multiple+IP+address+per+NIC
"""
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (cleanup_resources,
random_gen,
validateList)
from marvin.lib.base import (Account,
VirtualMachine,
PublicIPAddress,
NATRule,
StaticNATRule,
FireWallRule,
NIC,
Network,
VPC,
ServiceOffering,
VpcOffering,
Domain,
Router)
from marvin.lib.common import (get_domain,
get_template,
get_zone,
setSharedNetworkParams,
get_free_vlan,
createEnabledNetworkOffering)
from nose.plugins.attrib import attr
from marvin.codes import PASS, ISOLATED_NETWORK, VPC_NETWORK, SHARED_NETWORK, FAIL, FAILED
from ddt import ddt, data
import time
def createNetwork(self, networkType):
"""Create a network of given type (isolated/shared/isolated in VPC)"""
network = None
if networkType == ISOLATED_NETWORK:
try:
network = Network.create(
self.apiclient,
self.services["isolated_network"],
networkofferingid=self.isolated_network_offering.id,
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id)
self.cleanup.append(network)
except Exception as e:
self.fail("Isolated network creation failed because: %s" % e)
elif networkType == SHARED_NETWORK:
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
# create network using the shared network offering created
self.services["shared_network"]["acltype"] = "domain"
self.services["shared_network"]["vlan"] = vlan
self.services["shared_network"][
"networkofferingid"] = self.shared_network_offering.id
self.services["shared_network"][
"physicalnetworkid"] = physical_network.id
self.services["shared_network"] = setSharedNetworkParams(
self.services["shared_network"])
try:
network = Network.create(
self.api_client,
self.services["shared_network"],
networkofferingid=self.shared_network_offering.id,
zoneid=self.zone.id)
self.cleanup.append(network)
except Exception as e:
self.fail("Shared Network creation failed because: %s" % e)
elif networkType == VPC_NETWORK:
self.services["vpc"]["cidr"] = "10.1.1.1/16"
self.debug("creating a VPC network in the account: %s" %
self.account.name)
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=self.vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid)
self.cleanup.append(vpc)
vpcs = VPC.list(self.apiclient, id=vpc.id)
self.assertEqual(
validateList(vpcs)[0],
PASS,
"VPC list validation failed, vpc list is %s" %
vpcs)
network = Network.create(
self.api_client,
self.services["isolated_network"],
networkofferingid=self.isolated_network_offering_vpc.id,
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
vpcid=vpc.id,
gateway="10.1.1.1",
netmask="255.255.255.0")
self.cleanup.append(network)
return network
def CreateEnabledNetworkOffering(apiclient, networkServices):
"""Create network offering of given services and enable it"""
result = createEnabledNetworkOffering(apiclient, networkServices)
assert result[
0] == PASS, "Network offering creation/enabling failed due to %s" % result[2]
return result[1]
def createNetworkRules(
self,
virtual_machine,
network,
vmguestip,
networktype,
ruletype):
""" Acquire public ip in the given network, open firewall if required and
create NAT rule for the public ip to the given guest vm ip address"""
try:
public_ip = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if networktype == VPC_NETWORK else None)
self.cleanup.append(public_ip)
if networktype != VPC_NETWORK:
fwr = FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
self.cleanup.append(fwr)
if ruletype == "nat":
nat_rule = NATRule.create(
self.api_client,
virtual_machine,
self.services["natrule"],
ipaddressid=public_ip.ipaddress.id,
networkid=network.id,
vmguestip=vmguestip)
self.cleanup.append(nat_rule)
elif ruletype == "staticnat":
StaticNATRule.enable(
self.apiclient,
public_ip.ipaddress.id,
virtual_machine.id,
network.id,
vmguestip=vmguestip)
except Exception as e:
self.debug("Exception occurred while creating network rules: %s" % e)
return FAIL
return PASS
@ddt
class TestBasicOperations(cloudstackTestCase):
"""Test Basic operations (add/remove/list) IP to/from NIC
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestBasicOperations, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.hypervisor = cls.testClient.getHypervisorInfo().lower()
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services[
"ostype"]
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup = [cls.service_offering]
cls.services["shared_network_offering_all_services"][
"specifyVlan"] = "True"
cls.services["shared_network_offering_all_services"][
"specifyIpRanges"] = "True"
cls.shared_network_offering = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["shared_network_offering_all_services"])
cls._cleanup.append(cls.shared_network_offering)
cls.mode = cls.zone.networktype
cls.isolated_network_offering = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["isolated_network_offering"])
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_network_offering_vpc = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["nw_offering_isolated_vpc"])
cls._cleanup.append(cls.isolated_network_offering_vpc)
cls.vpc_off = VpcOffering.create(
cls.api_client,
cls.services["vpc_offering"])
cls.vpc_off.update(cls.api_client, state='Enabled')
cls._cleanup.append(cls.vpc_off)
return
@classmethod
def tearDownClass(cls):
super(TestBasicOperations, cls).tearDownClass()
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
super(TestBasicOperations, self).tearDown()
def VerifyStaticNatForPublicIp(self, ipaddressid, natrulestatus):
""" List public IP and verify that NAT rule status for the IP is as desired """
publiciplist = PublicIPAddress.list(
self.apiclient,
id=ipaddressid,
listall=True)
self.assertEqual(
validateList(publiciplist)[0],
PASS,
"Public IP list validation failed")
self.assertEqual(
publiciplist[0].isstaticnat,
natrulestatus,
"isstaticnat should be %s, it is %s" %
(natrulestatus,
publiciplist[0].isstaticnat))
return
@data(SHARED_NETWORK)
@attr(tags=["advanced"])
def test_add_ip_to_nic(self, value):
""" Add secondary IP to NIC of a VM"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add secondary IP to the default nic of VM
# 4. Try to add the same IP again
# 5. Try to add secondary IP providing wrong virtual machine id
# 6. Try to add secondary IP with correct virtual machine id but wrong
# IP address
# Validations:
# 1. Step 3 should succeed
# 2. Step 4 should fail
# 3. Step 5 should should fail
# 4. Step 6 should fail
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
self.cleanup.append(virtual_machine)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
try:
NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id,
ipaddress=ipaddress_1.ipaddress)
self.debug(
"Adding already added secondary IP %s to NIC of vm %s succeeded, should have failed" %
(ipaddress_1.ipaddress, virtual_machine.id))
except Exception as e:
self.debug(
"Failed while adding already added secondary IP to NIC of vm %s" %
virtual_machine.id)
try:
NIC.addIp(
self.apiclient, id=(
virtual_machine.nic[0].id + random_gen()))
self.fail(
"Adding secondary IP with wrong NIC id succeded, it shoud have failed")
except Exception as e:
self.debug("Failed while adding secondary IP to wrong NIC")
try:
NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id,
ipaddress="255.255.255.300")
self.fail(
"Adding secondary IP with wrong ipaddress succeded, it should have failed")
except Exception as e:
self.debug(
"Failed while adding wrong secondary IP to NIC of VM %s: %s" %
(virtual_machine.id, e))
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced"])
def test_remove_ip_from_nic(self, value):
""" Remove secondary IP from NIC of a VM"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add secondary IP to the default nic of VM
# 4. Remove the secondary IP
# 5. Try to remove secondary ip by giving incorrect ipaddress id
# Validations:
# 1. Step 4 should succeed
# 2. Step 5 should fail
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
self.cleanup.append(virtual_machine)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
NIC.removeIp(self.apiclient, ipaddressid=ipaddress_1.id)
#Following block is to verify
#1.Removing nic in shared network should mark allocated state to NULL in DB
#2.To make sure that re-add the same ip address to the same nic
#3.Remove the IP from the NIC
#All the above steps should succeed
if value == SHARED_NETWORK:
qresultset = self.dbclient.execute(
"select allocated from user_ip_address where public_ip_address = '%s';"
% str(ipaddress_1.ipaddress)
)
self.assertEqual(
qresultset[0][0],
None,
"Removing IP from nic didn't release the ip address from user_ip_address table"
)
else:
qresultset = self.dbclient.execute(
"select id from nic_secondary_ips where ip4_address = '%s';"
% str(ipaddress_1.ipaddress))
if len(qresultset):
self.fail("Failed to release the secondary ip from the nic")
ipaddress_2 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id,
ipaddress=ipaddress_1.ipaddress
)
NIC.removeIp(self.apiclient, ipaddressid=ipaddress_2.id)
try:
NIC.removeIp(
self.apiclient,
ipaddressid=(
ipaddress_1.id +
random_gen()))
self.fail("Removing invalid IP address, it should have failed")
except Exception as e:
self.debug(
"Removing invalid IP failed as expected with Exception %s" %
e)
return
@attr(tags=["advanced"])
def test_remove_invalid_ip(self):
""" Remove invalid ip"""
# Steps:
# 1. Try to remove secondary ip without passing ip address id
# Validations:
# 1. Step 1 should fail
try:
NIC.removeIp(self.apiclient, ipaddressid="")
self.fail(
"Removing IP address without passing IP succeeded, it should have failed")
except Exception as e:
self.debug(
"Removing IP from NIC without passing ipaddressid failed as expected with Exception %s" %
e)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced"])
def test_list_nics(self, value):
"""Test listing nics associated with the ip address"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add secondary IP to the default nic of VM
# 4. Try to list the secondary ips without passing vm id
# 5. Try to list secondary IPs by passing correct vm id
# 6. Try to list secondary IPs by passing correct vm id and its nic id
# 7. Try to list secondary IPs by passing incorrect vm id and correct nic id
# 8. Try to list secondary IPs by passing correct vm id and incorrect nic id
# 9. Try to list secondary IPs by passing incorrect vm id and incorrect
# nic id
# Validations:
# 1. Step 4 should fail
# 2. Step 5 should succeed
# 3. Step 6 should succeed
# 4. Step 7 should fail
# 5. Step 8 should fail
# 6. Step 9 should fail
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
self.cleanup.append(virtual_machine)
NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
try:
nics = NIC.list(self.apiclient)
self.fail(
"Listing NICs without passign VM id succeeded, it should have failed, list is %s" %
nics)
except Exception as e:
self.debug(
"Listing NICs without passing virtual machine id failed as expected")
try:
NIC.list(self.apiclient, virtualmachineid=virtual_machine.id)
except Exception as e:
self.fail(
"Listing NICs for virtual machine %s failed with Exception %s" %
(virtual_machine.id, e))
NIC.list(
self.apiclient,
virtualmachineid=virtual_machine.id,
nicid=virtual_machine.nic[0].id)
try:
nics = NIC.list(
self.apiclient,
virtualmachineid=(
virtual_machine.id +
random_gen()),
nicid=virtual_machine.nic[0].id)
self.fail(
"Listing NICs with wrong virtual machine id and right nic id succeeded, should have failed")
except Exception as e:
self.debug(
"Listing NICs with wrong virtual machine id and right nic failed as expected with Exception %s" %
e)
try:
nics = NIC.list(
self.apiclient,
virtualmachineid=virtual_machine.id,
nicid=(
virtual_machine.nic[0].id +
random_gen()))
self.fail(
"Listing NICs with correct virtual machine id but wrong nic id succeeded, should have failed")
except Exception as e:
self.debug(
"Listing NICs with correct virtual machine id but wrong nic id failed as expected with Exception %s" %
e)
try:
nics = NIC.list(
self.apiclient,
virtualmachineid=(
virtual_machine.id +
random_gen()),
nicid=(
virtual_machine.nic[0].id +
random_gen()))
self.fail(
"Listing NICs with wrong virtual machine id and wrong nic id succeeded, should have failed")
except Exception as e:
self.debug(
"Listing NICs with wrong virtual machine id and wrong nic id failed as expected with Exception %s" %
e)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced"])
def test_operations_non_root_admin_api_client(self, value):
"""Test basic operations using non root admin apii client"""
# Steps:
# 1. Create Domain and Account in it
# 2. Create network in it (isoalted/ shared/ vpc)
# 3. Create User API client of this account
# 4. Deploy a VM in this network and account
# 5. Add secondary IP to the default nic of VM using non root admin api client
# 6. List secondary IPs using non root admin api client
# 7. Remove secondary IP using non root admin api client
# Validations:
# 1. All the operations should be successful
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
child_domain = Domain.create(
self.apiclient,
services=self.services["domain"],
parentdomainid=self.domain.id)
self.cleanup.append(child_domain)
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=child_domain.id)
self.cleanup.append(self.account)
apiclient = self.testClient.getUserApiClient(
UserName=self.account.name,
DomainName=self.account.domain)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
self.cleanup.append(virtual_machine)
ipaddress_1 = NIC.addIp(apiclient, id=virtual_machine.nic[0].id)
try:
NIC.list(apiclient, virtualmachineid=virtual_machine.id)
except Exception as e:
self.fail(
"Listing NICs for virtual machine %s failed with Exception %s" %
(virtual_machine.id, e))
try:
NIC.list(
apiclient,
virtualmachineid=virtual_machine.id,
nicid=virtual_machine.nic[0].id)
except Exception as e:
self.fail(
"Listing NICs for virtual machine %s and nic id %s failed with Exception %s" %
(virtual_machine.id, virtual_machine.nic[0].id, e))
try:
NIC.removeIp(apiclient, ipaddressid=ipaddress_1.id)
except Exception as e:
self.fail(
"Removing seondary IP %s from NIC failed as expected with Exception %s" %
(ipaddress_1.id, e))
return
@ddt
class TestNetworkRules(cloudstackTestCase):
"""Test PF/NAT/static nat rules with the secondary IPs
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestNetworkRules, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.hypervisor = cls.testClient.getHypervisorInfo().lower()
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services[
"ostype"]
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup = [cls.service_offering]
cls.services["shared_network_offering_all_services"][
"specifyVlan"] = "True"
cls.services["shared_network_offering_all_services"][
"specifyIpRanges"] = "True"
cls.shared_network_offering = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["shared_network_offering_all_services"])
cls._cleanup.append(cls.shared_network_offering)
cls.mode = cls.zone.networktype
cls.isolated_network_offering = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["isolated_network_offering"])
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_network_offering_vpc = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["nw_offering_isolated_vpc"])
cls._cleanup.append(cls.isolated_network_offering_vpc)
cls.vpc_off = VpcOffering.create(
cls.api_client,
cls.services["vpc_offering"])
cls._cleanup.append(cls.vpc_off)
cls.vpc_off.update(cls.api_client, state='Enabled')
return
@classmethod
def tearDownClass(cls):
super(TestNetworkRules, cls).tearDownClass()
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
super(TestNetworkRules, self).tearDown()
def VerifyStaticNatForPublicIp(self, ipaddressid, natrulestatus):
""" List public IP and verify that NAT rule status for the IP is as desired """
publiciplist = PublicIPAddress.list(
self.apiclient,
id=ipaddressid,
listall=True)
self.assertEqual(
validateList(publiciplist)[0],
PASS,
"Public IP list validation failed")
self.assertEqual(
publiciplist[0].isstaticnat,
natrulestatus,
"isstaticnat should be %s, it is %s" %
(natrulestatus,
publiciplist[0].isstaticnat))
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced", "dvs"])
def test_add_PF_rule(self, value):
""" Add secondary IP to NIC of a VM"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add 2 secondary IPs to the default nic of VM
# 4. Acquire public IP, open firewall for it, and
# create NAT rule for this public IP to the 1st secondary IP
# 5. Repeat step 4 for another public IP
# 6. Repeat step 4 for 2nd secondary IP
# 7. Repeat step 4 for invalid secondary IP
# Validations:
# 1. Step 4 should succeed
# 2. Step 5 should succeed
# 3. Step 6 should succeed
# 4. Step 7 should fail
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
self.cleanup.append(virtual_machine)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
ipaddress_2 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
self.assertEqual(
createNetworkRules(
self,
virtual_machine,
network,
ipaddress_1.ipaddress,
value,
ruletype="nat"),
PASS,
"Failure in creating NAT rule")
self.assertEqual(
createNetworkRules(
self,
virtual_machine,
network,
ipaddress_1.ipaddress,
value,
ruletype="nat"),
PASS,
"Failure in creating NAT rule")
self.assertEqual(
createNetworkRules(
self,
virtual_machine,
network,
ipaddress_2.ipaddress,
value,
ruletype="nat"),
PASS,
"Failure in creating NAT rule")
self.assertEqual(
createNetworkRules(
self,
virtual_machine,
network,
"255.255.255.300",
value,
ruletype="nat"),
FAIL,
"Failure in NAT rule creation")
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced", "dvs"])
def test_delete_PF_nat_rule(self, value):
""" Add secondary IP to NIC of a VM"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add secondary IP to the default nic of VM
# 4. Acquire public IP, open firewall for it, and
# create NAT rule for this public IP to the 1st secondary IP
# 5. Try to delete secondary IP when NAT rule exists for it
# 6. Delete firewall rule and NAT rule
# Validations:
# 1. Step 5 should fail
# 2. Step 6 should succeed
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
firewallrule = None
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
self.cleanup.append(virtual_machine)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
public_ip = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
self.cleanup.append(public_ip)
if value != VPC_NETWORK:
firewallrule = FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
self.cleanup.append(firewallrule)
# Create NAT rule
natrule = NATRule.create(
self.api_client,
virtual_machine,
self.services["natrule"],
ipaddressid=public_ip.ipaddress.id,
networkid=network.id,
vmguestip=ipaddress_1.ipaddress)
self.cleanup.append(natrule)
try:
NIC.removeIp(self.apiclient, ipaddressid=ipaddress_1.id)
self.fail(
"Removing secondary IP succeeded while it had active NAT rule on it, should have failed")
except Exception as e:
self.debug(
"Removing secondary IP with active NAT rule failed as expected")
if firewallrule:
try:
firewallrule.delete(self.apiclient)
self.cleanup.remove(firewallrule)
except Exception as e:
self.fail(
"Exception while deleting firewall rule %s: %s" %
(firewallrule.id, e))
natrule.delete(self.apiclient)
self.cleanup.remove(natrule)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced", "dvs"])
def test_disassociate_ip_mapped_to_secondary_ip_through_PF_rule(
self,
value):
""" Add secondary IP to NIC of a VM"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add secondary IP to the default nic of VM
# 4. Acquire public IP, open firewall for it, and
# create NAT rule for this public IP to the 1st secondary IP
# 5. Try to delete the public IP used for NAT rule
# Validations:
# 1. Step 5 should succeed
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
public_ip = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
if value != VPC_NETWORK:
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
# Create NAT rule
NATRule.create(
self.api_client,
virtual_machine,
self.services["natrule"],
ipaddressid=public_ip.ipaddress.id,
networkid=network.id,
vmguestip=ipaddress_1.ipaddress)
public_ip.delete(self.apiclient)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced", "dvs"])
def test_add_static_nat_rule(self, value):
""" Add secondary IP to NIC of a VM"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add 2 secondary IPs to the default nic of VM
# 4. Acquire public IP, open firewall for it, and
# create static NAT rule for this public IP to the 1st secondary IP
# 5. Repeat step 4 for another public IP
# 6. Repeat step 4 for 2nd secondary IP
# 7. Repeat step 4 for invalid secondary IP
# 8. Try to remove 1st secondary IP (with active static nat rule)
# Validations:
# 1. Step 4 should succeed
# 2. Step 5 should succeed
# 3. Step 6 should succeed
# 4. Step 7 should fail
# 5. Step 8 should succeed
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
ipaddress_2 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
self.assertEqual(
createNetworkRules(
self,
virtual_machine,
network,
ipaddress_1.ipaddress,
value,
ruletype="staticnat"),
PASS,
"Failure in creating NAT rule")
self.assertEqual(
createNetworkRules(
self,
virtual_machine,
network,
ipaddress_1.ipaddress,
value,
ruletype="staticnat"),
FAIL,
"Failure in creating NAT rule")
self.assertEqual(
createNetworkRules(
self,
virtual_machine,
network,
ipaddress_2.ipaddress,
value,
ruletype="staticnat"),
PASS,
"Failure in creating NAT rule")
self.assertEqual(
createNetworkRules(
self,
virtual_machine,
network,
"255.255.255.300",
value,
ruletype="staticnat"),
FAIL,
"Failure in NAT rule creation")
try:
NIC.removeIp(self.apiclient, ipaddress_1.id)
self.fail(
"Ip address should not get removed when active static NAT rule is defined for it")
except Exception as e:
self.debug(
"Exception while removing secondary ip address as expected\
because static nat rule is present for it: %s" % e)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced", "dvs"])
def test_disable_static_nat(self, value):
""" Add secondary IP to NIC of a VM"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add 2 secondary IPs to the default nic of VM
# 4. Acquire public IP, open firewall for it, and
# enable static NAT rule for this public IP to the 1st secondary IP
# 5. Disable the static nat rule and enable it again
# Validations:
# 1. Verify step 5 by listing seconday IP and checking the appropriate
# flag
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
public_ip = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
if value != VPC_NETWORK:
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
StaticNATRule.enable(
self.apiclient,
public_ip.ipaddress.id,
virtual_machine.id,
network.id,
vmguestip=ipaddress_1.ipaddress)
self.VerifyStaticNatForPublicIp(public_ip.ipaddress.id, True)
# Disabling static NAT
StaticNATRule.disable(self.apiclient, public_ip.ipaddress.id)
self.VerifyStaticNatForPublicIp(public_ip.ipaddress.id, False)
StaticNATRule.enable(
self.apiclient,
public_ip.ipaddress.id,
virtual_machine.id,
network.id,
vmguestip=ipaddress_1.ipaddress)
self.VerifyStaticNatForPublicIp(public_ip.ipaddress.id, True)
public_ip.delete(self.apiclient)
return
@ddt
class TestVmNetworkOperations(cloudstackTestCase):
"""Test VM and Network operations with network rules created on secondary IP
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestVmNetworkOperations, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.hypervisor = cls.testClient.getHypervisorInfo().lower()
# Fill services from the external config file
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services[
"ostype"]
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup = [cls.service_offering]
cls.services["shared_network_offering_all_services"][
"specifyVlan"] = "True"
cls.services["shared_network_offering_all_services"][
"specifyIpRanges"] = "True"
cls.shared_network_offering = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["shared_network_offering_all_services"])
cls._cleanup.append(cls.shared_network_offering)
cls.mode = cls.zone.networktype
cls.isolated_network_offering = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["isolated_network_offering"])
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_network_offering_vpc = CreateEnabledNetworkOffering(
cls.api_client,
cls.services["nw_offering_isolated_vpc"])
cls._cleanup.append(cls.isolated_network_offering_vpc)
cls.vpc_off = VpcOffering.create(
cls.api_client,
cls.services["vpc_offering"])
cls.vpc_off.update(cls.api_client, state='Enabled')
cls._cleanup.append(cls.vpc_off)
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def VerifyStaticNatForPublicIp(self, ipaddressid, natrulestatus):
""" List public IP and verify that NAT rule status for the IP is as desired """
publiciplist = PublicIPAddress.list(
self.apiclient,
id=ipaddressid,
listall=True)
self.assertEqual(
validateList(publiciplist)[0],
PASS,
"Public IP list validation failed")
self.assertEqual(
publiciplist[0].isstaticnat,
natrulestatus,
"isstaticnat should be %s, it is %s" %
(natrulestatus,
publiciplist[0].isstaticnat))
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced"])
def test_delete_vm(self, value):
""" Test delete VM and verify network rules are cleaned up"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add 2 secondary IPs to the default nic of VM
# 4. Acquire 2 public IPs in the network
# 5. For 1st public IP create nat rule to 1st private IP, for 2nd public IP, create
# static nat rule to 2nd private IP
# 6. Destroy the virtual machine
# 7. Verify that nat rule does not exist and static nat is not enabled for
# secondary IP
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
# Add secondary IPs to default NIC of VM
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
ipaddress_2 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
# Acquire public IP addresses in the network
public_ip_1 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
public_ip_2 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
# Create Firewall and natrule for 1st IP and static nat rule for 2nd IP
if value != VPC_NETWORK:
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip_1.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
natrule = NATRule.create(
self.api_client,
virtual_machine,
self.services["natrule"],
ipaddressid=public_ip_1.ipaddress.id,
networkid=network.id,
vmguestip=ipaddress_1.ipaddress)
StaticNATRule.enable(
self.apiclient,
public_ip_2.ipaddress.id,
virtual_machine.id,
network.id,
vmguestip=ipaddress_2.ipaddress)
# Delete VM
virtual_machine.delete(self.apiclient, expunge=True)
# Make sure the VM is expunged
retriesCount = 20
while True:
vms = VirtualMachine.list(self.apiclient, id=virtual_machine.id)
if vms is None:
break
elif retriesCount == 0:
self.fail("Failed to expunge vm even after 20 minutes")
time.sleep(60)
retriesCount -= 1
# Try to list nat rule
with self.assertRaises(Exception):
NATRule.list(self.apiclient, id=natrule.id, listall=True)
# Verify static nat rule is no longer enabled
self.VerifyStaticNatForPublicIp(public_ip_2.ipaddress.id, False)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced"])
def test_recover_vm(self, value):
""" Test recover VM operation with VM having secondary IPs"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add 2 secondary IPs to the default nic of VM
# 4. Acquire 2 public IPs in the network
# 5. For 1st public IP create nat rule to 1st private IP, for 2nd public IP, create
# static nat rule to 2nd private IP
# 6. Destroy the virtual machine and recover it
# 7. Verify that nat and static nat rules exist
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
ipaddress_2 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
public_ip_1 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
public_ip_2 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
if value != VPC_NETWORK:
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip_1.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
natrule = NATRule.create(
self.api_client,
virtual_machine,
self.services["natrule"],
ipaddressid=public_ip_1.ipaddress.id,
networkid=network.id,
vmguestip=ipaddress_1.ipaddress)
StaticNATRule.enable(
self.apiclient,
public_ip_2.ipaddress.id,
virtual_machine.id,
network.id,
vmguestip=ipaddress_2.ipaddress)
virtual_machine.delete(self.apiclient, expunge=False)
virtual_machine.recover(self.apiclient)
retriesCount = 10
while True:
vms = VirtualMachine.list(self.apiclient, id=virtual_machine.id)
self.assertEqual(
validateList(vms)[0],
PASS,
"vms list validation failed")
if str(vms[0].state).lower() == "stopped":
break
elif retriesCount == 0:
self.fail("Failed to recover vm even after 10 mins")
time.sleep(60)
retriesCount -= 1
natrules = NATRule.list(self.apiclient, id=natrule.id, listall=True)
self.assertEqual(
validateList(natrules)[0],
PASS,
"nat rules validation failed")
self.VerifyStaticNatForPublicIp(public_ip_2.ipaddress.id, True)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced"])
def test_network_restart_cleanup_true(self, value):
"""Test network restart (cleanup True) with VM having secondary IPs and related network rules"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add 2 secondary IPs to the default nic of VM
# 4. Acquire 2 public IPs in the network
# 5. For 1st public IP create nat rule to 1st private IP, for 2nd public IP, create
# static nat rule to 2nd private IP
# 6. Restart the network with cleanup option True
# 7. Verify that nat and static nat rules exist after network restart
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
ipaddress_2 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
public_ip_1 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
public_ip_2 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
if value != VPC_NETWORK:
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip_1.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
natrule = NATRule.create(
self.api_client,
virtual_machine,
self.services["natrule"],
ipaddressid=public_ip_1.ipaddress.id,
networkid=network.id,
vmguestip=ipaddress_1.ipaddress)
StaticNATRule.enable(
self.apiclient,
public_ip_2.ipaddress.id,
virtual_machine.id,
network.id,
vmguestip=ipaddress_2.ipaddress)
network.restart(self.apiclient, cleanup=True)
natrulelist = NATRule.list(self.apiclient, id=natrule.id, listall=True)
self.assertEqual(
validateList(natrulelist)[0],
PASS,
"nat rules list validation failed")
self.VerifyStaticNatForPublicIp(public_ip_2.ipaddress.id, True)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced"])
def test_network_restart_cleanup_false(self, value):
"""Test network restart (cleanup True) with VM having secondary IPs and related network rules"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add 2 secondary IPs to the default nic of VM
# 4. Acquire 2 public IPs in the network
# 5. For 1st public IP create nat rule to 1st private IP, for 2nd public IP, create
# static nat rule to 2nd private IP
# 6. Restart the network with cleanup option False
# 7. Verify that nat and static nat rules exist after network restart
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
ipaddress_2 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
public_ip_1 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
public_ip_2 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
if value != VPC_NETWORK:
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip_1.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
natrule = NATRule.create(
self.api_client,
virtual_machine,
self.services["natrule"],
ipaddressid=public_ip_1.ipaddress.id,
networkid=network.id,
vmguestip=ipaddress_1.ipaddress)
StaticNATRule.enable(
self.apiclient,
public_ip_2.ipaddress.id,
virtual_machine.id,
network.id,
vmguestip=ipaddress_2.ipaddress)
network.restart(self.apiclient, cleanup=False)
natrulelist = NATRule.list(self.apiclient, id=natrule.id, listall=True)
self.assertEqual(
validateList(natrulelist)[0],
PASS,
"nat rules list validation failed")
self.VerifyStaticNatForPublicIp(public_ip_2.ipaddress.id, True)
return
@data(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)
@attr(tags=["advanced"])
def test_reboot_router_VM(self, value):
""" Test reboot router and persistence of network rules"""
# Steps:
# 1. Create Account and create network in it (isoalted/ shared/ vpc)
# 2. Deploy a VM in this network and account
# 3. Add 2 secondary IPs to the default nic of VM
# 4. Acquire 2 public IPs in the network
# 5. For 1st public IP create nat rule to 1st private IP, for 2nd public IP, create
# static nat rule to 2nd private IP
# 6. Reboot router VM
# 7. Verify that nat and static nat rules exist after router restart
if value == VPC_NETWORK and self.hypervisor == 'hyperv':
self.skipTest("VPC is not supported on Hyper-V")
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
network = createNetwork(self, value)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
networkids=[
network.id],
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.account.domainid)
ipaddress_1 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
ipaddress_2 = NIC.addIp(
self.apiclient,
id=virtual_machine.nic[0].id)
public_ip_1 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
public_ip_2 = PublicIPAddress.create(
self.api_client,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id,
vpcid=network.vpcid if value == VPC_NETWORK else None)
if value != VPC_NETWORK:
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip_1.ipaddress.id,
protocol='TCP',
cidrlist=[
self.services["fwrule"]["cidr"]],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"])
natrule = NATRule.create(
self.api_client,
virtual_machine,
self.services["natrule"],
ipaddressid=public_ip_1.ipaddress.id,
networkid=network.id,
vmguestip=ipaddress_1.ipaddress)
StaticNATRule.enable(
self.apiclient,
public_ip_2.ipaddress.id,
virtual_machine.id,
network.id,
vmguestip=ipaddress_2.ipaddress)
routers = Router.list(
self.apiclient,
networkid=network.id,
listall=True)
self.assertEqual(
validateList(routers)[0],
PASS,
"routers list validation failed")
Router.reboot(self.apiclient, id=routers[0].id)
natrulelist = NATRule.list(self.apiclient, id=natrule.id, listall=True)
self.assertEqual(
validateList(natrulelist)[0],
PASS,
"nat rules list validation failed")
self.VerifyStaticNatForPublicIp(public_ip_2.ipaddress.id, True)
return
| [
"marvin.lib.base.Router.reboot",
"marvin.lib.utils.validateList",
"marvin.lib.common.setSharedNetworkParams",
"marvin.lib.base.NATRule.create",
"marvin.lib.common.createEnabledNetworkOffering",
"marvin.lib.utils.random_gen",
"marvin.lib.base.Domain.create",
"marvin.lib.base.NATRule.list",
"marvin.li... | [((5212, 5268), 'marvin.lib.common.createEnabledNetworkOffering', 'createEnabledNetworkOffering', (['apiclient', 'networkServices'], {}), '(apiclient, networkServices)\n', (5240, 5268), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((10618, 10638), 'ddt.data', 'data', (['SHARED_NETWORK'], {}), '(SHARED_NETWORK)\n', (10622, 10638), False, 'from ddt import ddt, data\n'), ((10644, 10667), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (10648, 10667), False, 'from nose.plugins.attrib import attr\n'), ((13382, 13433), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (13386, 13433), False, 'from ddt import ddt, data\n'), ((13439, 13462), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (13443, 13462), False, 'from nose.plugins.attrib import attr\n'), ((16497, 16520), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (16501, 16520), False, 'from nose.plugins.attrib import attr\n'), ((17122, 17173), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (17126, 17173), False, 'from ddt import ddt, data\n'), ((17179, 17202), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (17183, 17202), False, 'from nose.plugins.attrib import attr\n'), ((21494, 21545), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (21498, 21545), False, 'from ddt import ddt, data\n'), ((21551, 21574), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (21555, 21574), False, 'from nose.plugins.attrib import attr\n'), ((27671, 27722), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (27675, 27722), False, 'from ddt import ddt, data\n'), ((27728, 27758), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'dvs']"}), "(tags=['advanced', 'dvs'])\n", (27732, 27758), False, 'from nose.plugins.attrib import attr\n'), ((30619, 30670), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (30623, 30670), False, 'from ddt import ddt, data\n'), ((30676, 30706), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'dvs']"}), "(tags=['advanced', 'dvs'])\n", (30680, 30706), False, 'from nose.plugins.attrib import attr\n'), ((34059, 34110), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (34063, 34110), False, 'from ddt import ddt, data\n'), ((34116, 34146), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'dvs']"}), "(tags=['advanced', 'dvs'])\n", (34120, 34146), False, 'from nose.plugins.attrib import attr\n'), ((36551, 36602), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (36555, 36602), False, 'from ddt import ddt, data\n'), ((36608, 36638), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'dvs']"}), "(tags=['advanced', 'dvs'])\n", (36612, 36638), False, 'from nose.plugins.attrib import attr\n'), ((40002, 40053), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (40006, 40053), False, 'from ddt import ddt, data\n'), ((40059, 40089), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'dvs']"}), "(tags=['advanced', 'dvs'])\n", (40063, 40089), False, 'from nose.plugins.attrib import attr\n'), ((46738, 46789), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (46742, 46789), False, 'from ddt import ddt, data\n'), ((46795, 46818), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (46799, 46818), False, 'from nose.plugins.attrib import attr\n'), ((50728, 50779), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (50732, 50779), False, 'from ddt import ddt, data\n'), ((50785, 50808), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (50789, 50808), False, 'from nose.plugins.attrib import attr\n'), ((54654, 54705), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (54658, 54705), False, 'from ddt import ddt, data\n'), ((54711, 54734), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (54715, 54734), False, 'from nose.plugins.attrib import attr\n'), ((58112, 58163), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (58116, 58163), False, 'from ddt import ddt, data\n'), ((58169, 58192), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (58173, 58192), False, 'from nose.plugins.attrib import attr\n'), ((61573, 61624), 'ddt.data', 'data', (['ISOLATED_NETWORK', 'SHARED_NETWORK', 'VPC_NETWORK'], {}), '(ISOLATED_NETWORK, SHARED_NETWORK, VPC_NETWORK)\n', (61577, 61624), False, 'from ddt import ddt, data\n'), ((61630, 61653), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (61634, 61653), False, 'from nose.plugins.attrib import attr\n'), ((5722, 5935), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if networktype == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if networktype == VPC_NETWORK else None)\n', (5744, 5935), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((7758, 7784), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (7768, 7784), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((7886, 7951), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (7898, 7951), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((8330, 8402), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (8352, 8402), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((9396, 9460), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['cls.api_client', "cls.services['vpc_offering']"], {}), "(cls.api_client, cls.services['vpc_offering'])\n", (9414, 9460), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((10141, 10207), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.apiclient'], {'id': 'ipaddressid', 'listall': '(True)'}), '(self.apiclient, id=ipaddressid, listall=True)\n', (10161, 10207), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((11359, 11445), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (11373, 11445), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((11593, 11802), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (11614, 11802), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((11953, 12008), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (11962, 12008), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((14116, 14202), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (14130, 14202), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((14350, 14559), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (14371, 14559), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((14710, 14765), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (14719, 14765), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((14800, 14856), 'marvin.lib.base.NIC.removeIp', 'NIC.removeIp', (['self.apiclient'], {'ipaddressid': 'ipaddress_1.id'}), '(self.apiclient, ipaddressid=ipaddress_1.id)\n', (14812, 14856), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((15876, 15969), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id', 'ipaddress': 'ipaddress_1.ipaddress'}), '(self.apiclient, id=virtual_machine.nic[0].id, ipaddress=\n ipaddress_1.ipaddress)\n', (15885, 15969), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((16019, 16075), 'marvin.lib.base.NIC.removeIp', 'NIC.removeIp', (['self.apiclient'], {'ipaddressid': 'ipaddress_2.id'}), '(self.apiclient, ipaddressid=ipaddress_2.id)\n', (16031, 16075), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((18354, 18440), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (18368, 18440), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((18588, 18797), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (18609, 18797), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((18934, 18989), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (18943, 18989), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((19607, 19706), 'marvin.lib.base.NIC.list', 'NIC.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine.id', 'nicid': 'virtual_machine.nic[0].id'}), '(self.apiclient, virtualmachineid=virtual_machine.id, nicid=\n virtual_machine.nic[0].id)\n', (19615, 19706), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((22378, 22476), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.apiclient'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.apiclient, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (22391, 22476), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((22576, 22663), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'child_domain.id'}), "(self.apiclient, self.services['account'], domainid=\n child_domain.id)\n", (22590, 22663), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((22950, 23159), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (22971, 23159), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((23310, 23360), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(apiclient, id=virtual_machine.nic[0].id)\n', (23319, 23360), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((24817, 24843), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (24827, 24843), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((24945, 25010), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (24957, 25010), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((25389, 25461), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (25411, 25461), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((26455, 26519), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['cls.api_client', "cls.services['vpc_offering']"], {}), "(cls.api_client, cls.services['vpc_offering'])\n", (26473, 26519), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((27194, 27260), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.apiclient'], {'id': 'ipaddressid', 'listall': '(True)'}), '(self.apiclient, id=ipaddressid, listall=True)\n', (27214, 27260), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((28642, 28728), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (28656, 28728), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((28876, 29085), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (28897, 29085), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((29236, 29291), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (29245, 29291), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((29340, 29395), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (29349, 29395), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((31490, 31576), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (31504, 31576), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((31752, 31961), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (31773, 31961), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((32112, 32167), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (32121, 32167), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((32214, 32421), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (32236, 32421), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((33019, 33193), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'public_ip.ipaddress.id', 'networkid': 'network.id', 'vmguestip': 'ipaddress_1.ipaddress'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=public_ip.ipaddress.id, networkid=network.id, vmguestip=\n ipaddress_1.ipaddress)\n", (33033, 33193), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((34903, 34989), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (34917, 34989), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((35137, 35346), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (35158, 35346), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((35452, 35507), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (35461, 35507), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((35554, 35761), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (35576, 35761), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((36249, 36423), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'public_ip.ipaddress.id', 'networkid': 'network.id', 'vmguestip': 'ipaddress_1.ipaddress'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=public_ip.ipaddress.id, networkid=network.id, vmguestip=\n ipaddress_1.ipaddress)\n", (36263, 36423), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((37646, 37732), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (37660, 37732), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((37880, 38089), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (37901, 38089), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((38195, 38250), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (38204, 38250), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((38299, 38354), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (38308, 38354), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((40856, 40942), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (40870, 40942), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((41090, 41299), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (41111, 41299), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((41405, 41460), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (41414, 41460), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((41507, 41714), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (41529, 41714), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((42176, 42305), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'public_ip.ipaddress.id', 'virtual_machine.id', 'network.id'], {'vmguestip': 'ipaddress_1.ipaddress'}), '(self.apiclient, public_ip.ipaddress.id,\n virtual_machine.id, network.id, vmguestip=ipaddress_1.ipaddress)\n', (42196, 42305), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((42474, 42535), 'marvin.lib.base.StaticNATRule.disable', 'StaticNATRule.disable', (['self.apiclient', 'public_ip.ipaddress.id'], {}), '(self.apiclient, public_ip.ipaddress.id)\n', (42495, 42535), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((42617, 42746), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'public_ip.ipaddress.id', 'virtual_machine.id', 'network.id'], {'vmguestip': 'ipaddress_1.ipaddress'}), '(self.apiclient, public_ip.ipaddress.id,\n virtual_machine.id, network.id, vmguestip=ipaddress_1.ipaddress)\n', (42637, 42746), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((43508, 43534), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (43518, 43534), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((43636, 43701), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (43648, 43701), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((44079, 44151), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (44101, 44151), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((45145, 45209), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['cls.api_client', "cls.services['vpc_offering']"], {}), "(cls.api_client, cls.services['vpc_offering'])\n", (45163, 45209), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((46261, 46327), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.apiclient'], {'id': 'ipaddressid', 'listall': '(True)'}), '(self.apiclient, id=ipaddressid, listall=True)\n', (46281, 46327), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((47621, 47707), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (47635, 47707), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((47855, 48064), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (47876, 48064), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((48219, 48274), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (48228, 48274), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((48322, 48377), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (48331, 48377), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((48479, 48686), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (48501, 48686), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((48774, 48981), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (48796, 48981), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((49535, 49711), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'public_ip_1.ipaddress.id', 'networkid': 'network.id', 'vmguestip': 'ipaddress_1.ipaddress'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=public_ip_1.ipaddress.id, networkid=network.id, vmguestip=\n ipaddress_1.ipaddress)\n", (49549, 49711), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((49785, 49916), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'public_ip_2.ipaddress.id', 'virtual_machine.id', 'network.id'], {'vmguestip': 'ipaddress_2.ipaddress'}), '(self.apiclient, public_ip_2.ipaddress.id,\n virtual_machine.id, network.id, vmguestip=ipaddress_2.ipaddress)\n', (49805, 49916), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((51574, 51660), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (51588, 51660), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((51808, 52017), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (51829, 52017), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((52123, 52178), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (52132, 52178), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((52226, 52281), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (52235, 52281), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((52330, 52537), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (52352, 52537), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((52625, 52832), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (52647, 52832), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((53306, 53482), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'public_ip_1.ipaddress.id', 'networkid': 'network.id', 'vmguestip': 'ipaddress_1.ipaddress'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=public_ip_1.ipaddress.id, networkid=network.id, vmguestip=\n ipaddress_1.ipaddress)\n", (53320, 53482), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((53556, 53687), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'public_ip_2.ipaddress.id', 'virtual_machine.id', 'network.id'], {'vmguestip': 'ipaddress_2.ipaddress'}), '(self.apiclient, public_ip_2.ipaddress.id,\n virtual_machine.id, network.id, vmguestip=ipaddress_2.ipaddress)\n', (53576, 53687), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((54375, 54432), 'marvin.lib.base.NATRule.list', 'NATRule.list', (['self.apiclient'], {'id': 'natrule.id', 'listall': '(True)'}), '(self.apiclient, id=natrule.id, listall=True)\n', (54387, 54432), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((55577, 55663), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (55591, 55663), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((55811, 56020), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (55832, 56020), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((56126, 56181), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (56135, 56181), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((56229, 56284), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (56238, 56284), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((56333, 56540), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (56355, 56540), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((56628, 56835), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (56650, 56835), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((57309, 57485), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'public_ip_1.ipaddress.id', 'networkid': 'network.id', 'vmguestip': 'ipaddress_1.ipaddress'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=public_ip_1.ipaddress.id, networkid=network.id, vmguestip=\n ipaddress_1.ipaddress)\n", (57323, 57485), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((57559, 57690), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'public_ip_2.ipaddress.id', 'virtual_machine.id', 'network.id'], {'vmguestip': 'ipaddress_2.ipaddress'}), '(self.apiclient, public_ip_2.ipaddress.id,\n virtual_machine.id, network.id, vmguestip=ipaddress_2.ipaddress)\n', (57579, 57690), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((57826, 57883), 'marvin.lib.base.NATRule.list', 'NATRule.list', (['self.apiclient'], {'id': 'natrule.id', 'listall': '(True)'}), '(self.apiclient, id=natrule.id, listall=True)\n', (57838, 57883), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((59037, 59123), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (59051, 59123), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((59271, 59480), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (59292, 59480), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((59586, 59641), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (59595, 59641), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((59689, 59744), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (59698, 59744), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((59793, 60000), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (59815, 60000), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((60088, 60295), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (60110, 60295), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((60769, 60945), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'public_ip_1.ipaddress.id', 'networkid': 'network.id', 'vmguestip': 'ipaddress_1.ipaddress'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=public_ip_1.ipaddress.id, networkid=network.id, vmguestip=\n ipaddress_1.ipaddress)\n", (60783, 60945), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((61019, 61150), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'public_ip_2.ipaddress.id', 'virtual_machine.id', 'network.id'], {'vmguestip': 'ipaddress_2.ipaddress'}), '(self.apiclient, public_ip_2.ipaddress.id,\n virtual_machine.id, network.id, vmguestip=ipaddress_2.ipaddress)\n', (61039, 61150), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((61287, 61344), 'marvin.lib.base.NATRule.list', 'NATRule.list', (['self.apiclient'], {'id': 'natrule.id', 'listall': '(True)'}), '(self.apiclient, id=natrule.id, listall=True)\n', (61299, 61344), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((62417, 62503), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (62431, 62503), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((62651, 62860), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'networkids': '[network.id]', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['virtual_machine'],\n networkids=[network.id], serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.account.domainid)\n", (62672, 62860), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((62966, 63021), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (62975, 63021), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((63069, 63124), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id'}), '(self.apiclient, id=virtual_machine.nic[0].id)\n', (63078, 63124), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((63173, 63380), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (63195, 63380), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((63468, 63675), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.api_client'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': '(network.vpcid if value == VPC_NETWORK else None)'}), '(self.api_client, accountid=self.account.name, zoneid\n =self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=network.vpcid if value == VPC_NETWORK else None)\n', (63490, 63675), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((64149, 64325), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'public_ip_1.ipaddress.id', 'networkid': 'network.id', 'vmguestip': 'ipaddress_1.ipaddress'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=public_ip_1.ipaddress.id, networkid=network.id, vmguestip=\n ipaddress_1.ipaddress)\n", (64163, 64325), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((64399, 64530), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'public_ip_2.ipaddress.id', 'virtual_machine.id', 'network.id'], {'vmguestip': 'ipaddress_2.ipaddress'}), '(self.apiclient, public_ip_2.ipaddress.id,\n virtual_machine.id, network.id, vmguestip=ipaddress_2.ipaddress)\n', (64419, 64530), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((64607, 64670), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'network.id', 'listall': '(True)'}), '(self.apiclient, networkid=network.id, listall=True)\n', (64618, 64670), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((64845, 64892), 'marvin.lib.base.Router.reboot', 'Router.reboot', (['self.apiclient'], {'id': 'routers[0].id'}), '(self.apiclient, id=routers[0].id)\n', (64858, 64892), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((64916, 64973), 'marvin.lib.base.NATRule.list', 'NATRule.list', (['self.apiclient'], {'id': 'natrule.id', 'listall': '(True)'}), '(self.apiclient, id=natrule.id, listall=True)\n', (64928, 64973), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((2492, 2701), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_network_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['isolated_network'],\n networkofferingid=self.isolated_network_offering.id, accountid=self.\n account.name, domainid=self.account.domainid, zoneid=self.zone.id)\n", (2506, 2701), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((3010, 3054), 'marvin.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (3023, 3054), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((3487, 3542), 'marvin.lib.common.setSharedNetworkParams', 'setSharedNetworkParams', (["self.services['shared_network']"], {}), "(self.services['shared_network'])\n", (3509, 3542), False, 'from marvin.lib.common import get_domain, get_template, get_zone, setSharedNetworkParams, get_free_vlan, createEnabledNetworkOffering\n'), ((6097, 6334), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (6116, 6334), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((6530, 6692), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.api_client', 'virtual_machine', "self.services['natrule']"], {'ipaddressid': 'public_ip.ipaddress.id', 'networkid': 'network.id', 'vmguestip': 'vmguestip'}), "(self.api_client, virtual_machine, self.services['natrule'],\n ipaddressid=public_ip.ipaddress.id, networkid=network.id, vmguestip=\n vmguestip)\n", (6544, 6692), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((12060, 12153), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id', 'ipaddress': 'ipaddress_1.ipaddress'}), '(self.apiclient, id=virtual_machine.nic[0].id, ipaddress=\n ipaddress_1.ipaddress)\n', (12069, 12153), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((12937, 13026), 'marvin.lib.base.NIC.addIp', 'NIC.addIp', (['self.apiclient'], {'id': 'virtual_machine.nic[0].id', 'ipaddress': '"""255.255.255.300"""'}), "(self.apiclient, id=virtual_machine.nic[0].id, ipaddress=\n '255.255.255.300')\n", (12946, 13026), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((16762, 16806), 'marvin.lib.base.NIC.removeIp', 'NIC.removeIp', (['self.apiclient'], {'ipaddressid': '""""""'}), "(self.apiclient, ipaddressid='')\n", (16774, 16806), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((19023, 19047), 'marvin.lib.base.NIC.list', 'NIC.list', (['self.apiclient'], {}), '(self.apiclient)\n', (19031, 19047), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((19360, 19421), 'marvin.lib.base.NIC.list', 'NIC.list', (['self.apiclient'], {'virtualmachineid': 'virtual_machine.id'}), '(self.apiclient, virtualmachineid=virtual_machine.id)\n', (19368, 19421), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((23387, 23443), 'marvin.lib.base.NIC.list', 'NIC.list', (['apiclient'], {'virtualmachineid': 'virtual_machine.id'}), '(apiclient, virtualmachineid=virtual_machine.id)\n', (23395, 23443), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((23646, 23740), 'marvin.lib.base.NIC.list', 'NIC.list', (['apiclient'], {'virtualmachineid': 'virtual_machine.id', 'nicid': 'virtual_machine.nic[0].id'}), '(apiclient, virtualmachineid=virtual_machine.id, nicid=\n virtual_machine.nic[0].id)\n', (23654, 23740), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((24028, 24079), 'marvin.lib.base.NIC.removeIp', 'NIC.removeIp', (['apiclient'], {'ipaddressid': 'ipaddress_1.id'}), '(apiclient, ipaddressid=ipaddress_1.id)\n', (24040, 24079), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((32586, 32823), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (32605, 32823), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((33320, 33376), 'marvin.lib.base.NIC.removeIp', 'NIC.removeIp', (['self.apiclient'], {'ipaddressid': 'ipaddress_1.id'}), '(self.apiclient, ipaddressid=ipaddress_1.id)\n', (33332, 33376), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((35872, 36109), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (35891, 36109), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((39607, 39651), 'marvin.lib.base.NIC.removeIp', 'NIC.removeIp', (['self.apiclient', 'ipaddress_1.id'], {}), '(self.apiclient, ipaddress_1.id)\n', (39619, 39651), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((41825, 42062), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (41844, 42062), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((45459, 45506), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (45476, 45506), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((45910, 45957), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (45927, 45957), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((49172, 49411), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip_1.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip_1.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (49191, 49411), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((50160, 50218), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine.id'}), '(self.apiclient, id=virtual_machine.id)\n', (50179, 50218), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((50389, 50403), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (50399, 50403), False, 'import time\n'), ((50521, 50578), 'marvin.lib.base.NATRule.list', 'NATRule.list', (['self.apiclient'], {'id': 'natrule.id', 'listall': '(True)'}), '(self.apiclient, id=natrule.id, listall=True)\n', (50533, 50578), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((52943, 53182), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip_1.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip_1.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (52962, 53182), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((53921, 53979), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine.id'}), '(self.apiclient, id=virtual_machine.id)\n', (53940, 53979), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((54310, 54324), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (54320, 54324), False, 'import time\n'), ((56946, 57185), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip_1.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip_1.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (56965, 57185), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((60406, 60645), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip_1.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip_1.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (60425, 60645), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((63786, 64025), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip_1.ipaddress.id', 'protocol': '"""TCP"""', 'cidrlist': "[self.services['fwrule']['cidr']]", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=public_ip_1.ipaddress.id,\n protocol='TCP', cidrlist=[self.services['fwrule']['cidr']], startport=\n self.services['fwrule']['startport'], endport=self.services['fwrule'][\n 'endport'])\n", (63805, 64025), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((3592, 3732), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (3606, 3732), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((4146, 4315), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=self.account.name, domainid=self.\n account.domainid)\n", (4156, 4315), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((4427, 4462), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'vpc.id'}), '(self.apiclient, id=vpc.id)\n', (4435, 4462), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((4638, 4915), 'marvin.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_network_offering_vpc.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id', 'vpcid': 'vpc.id', 'gateway': '"""10.1.1.1"""', 'netmask': '"""255.255.255.0"""'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_network_offering_vpc.id, accountid=self\n .account.name, domainid=self.account.domainid, zoneid=self.zone.id,\n vpcid=vpc.id, gateway='10.1.1.1', netmask='255.255.255.0')\n", (4652, 4915), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((6873, 6990), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'public_ip.ipaddress.id', 'virtual_machine.id', 'network.id'], {'vmguestip': 'vmguestip'}), '(self.apiclient, public_ip.ipaddress.id,\n virtual_machine.id, network.id, vmguestip=vmguestip)\n', (6893, 6990), False, 'from marvin.lib.base import Account, VirtualMachine, PublicIPAddress, NATRule, StaticNATRule, FireWallRule, NIC, Network, VPC, ServiceOffering, VpcOffering, Domain, Router\n'), ((10283, 10309), 'marvin.lib.utils.validateList', 'validateList', (['publiciplist'], {}), '(publiciplist)\n', (10295, 10309), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((27336, 27362), 'marvin.lib.utils.validateList', 'validateList', (['publiciplist'], {}), '(publiciplist)\n', (27348, 27362), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((46403, 46429), 'marvin.lib.utils.validateList', 'validateList', (['publiciplist'], {}), '(publiciplist)\n', (46415, 46429), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((54471, 54493), 'marvin.lib.utils.validateList', 'validateList', (['natrules'], {}), '(natrules)\n', (54483, 54493), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((57922, 57947), 'marvin.lib.utils.validateList', 'validateList', (['natrulelist'], {}), '(natrulelist)\n', (57934, 57947), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((61383, 61408), 'marvin.lib.utils.validateList', 'validateList', (['natrulelist'], {}), '(natrulelist)\n', (61395, 61408), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((64746, 64767), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (64758, 64767), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((65012, 65037), 'marvin.lib.utils.validateList', 'validateList', (['natrulelist'], {}), '(natrulelist)\n', (65024, 65037), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((54026, 54043), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (54038, 54043), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((4501, 4519), 'marvin.lib.utils.validateList', 'validateList', (['vpcs'], {}), '(vpcs)\n', (4513, 4519), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((12682, 12694), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (12692, 12694), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((16234, 16246), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (16244, 16246), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((19910, 19922), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (19920, 19922), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((20514, 20526), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (20524, 20526), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((21027, 21039), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (21037, 21039), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n'), ((21134, 21146), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (21144, 21146), False, 'from marvin.lib.utils import cleanup_resources, random_gen, validateList\n')] |
# mglearn_select_sample.py
#
# Created by <NAME> on 31 Mar 2017.
from __future__ import division, print_function, absolute_import, unicode_literals
import os
import click
from marvin import config
from mglearn import selection
@click.command()
@click.option('--release', default=None)
@click.option('--drpver', default=None)
@click.option('--path-drpall', default=None)
@click.option('--bits', '-b', type=click.INT, multiple=True, help='DAP pixel bitmasks.')
@click.option('--targeting_bit', default='mngtarg1')
@click.option('--main_sample', default=False, is_flag=True)
@click.option('--path_out', default=None)
@click.option('--overwrite', '-o', default=False, is_flag=True)
@click.argument('filename', click.File('w'))
def select_sample(filename, release, drpver, path_drpall, bits, targeting_bit, main_sample,
path_out, overwrite):
"""Select MaNGA sample.
Parameters:
filename (str):
Output file of plate-ifu identifiers.
release (str):
MaNGA MPL release. Default is None.
drpver (str):
MaNGA data reduction pipeline (DRP) version. Default is None.
path_drpall (str):
Path to local drpall file. Default is None.
bits (int):
Bits of ``targeting_bit`` to use for sample selection.
targeting_bit (str):
Targeting bit to use. Default is ``mngtarg1``.
"""
drpver_ = selection.set_drpver(drpver=drpver, release=release)
release_ = config.lookUpRelease(drpver_)
if main_sample:
bits = (10, 11, 12)
desc = 'Main Sample (Primary, Secondary, and Color Enhanced galaxies)'
else:
if not isinstance(bits, tuple):
bits = (bits,) if isinstance(bits, int) else tuple(bits)
desc = '{0} bits {1}'.format(targeting_bit, *bits) if len(bits) > 0 else 'No bits set.'
header = '# {0} {1}\n'.format(release_, desc)
drpall = selection.read_drpall(drpver=drpver_, path_drpall=path_drpall)
sample_obs = selection.apply_bitmasks(drpall[targeting_bit], bits)
plateifus = drpall['plateifu'][sample_obs]
mangaids = drpall['mangaid'][sample_obs]
sn2 = drpall['bluesn2'] + drpall['redsn2']
sample_unique = selection.remove_duplicates(plateifus, mangaids, sn2)
if path_out is None:
path_out = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')),
'data', 'samples', filename.split('.')[0])
if not os.path.isdir(path_out):
os.mkdir(path_out)
path_full = os.path.join(path_out, filename)
if overwrite or (not os.path.isfile(path_full)):
selection.write(sample_unique, path_full, header)
click.echo('\nWrote plate-ifu list to:\n{}\n'.format(path_full))
else:
click.echo('\nFile already exists:\n{}\n\nUse "-o" to overwrite.\n'.format(path_full))
| [
"marvin.config.lookUpRelease"
] | [((233, 248), 'click.command', 'click.command', ([], {}), '()\n', (246, 248), False, 'import click\n'), ((250, 289), 'click.option', 'click.option', (['"""--release"""'], {'default': 'None'}), "('--release', default=None)\n", (262, 289), False, 'import click\n'), ((291, 329), 'click.option', 'click.option', (['"""--drpver"""'], {'default': 'None'}), "('--drpver', default=None)\n", (303, 329), False, 'import click\n'), ((331, 374), 'click.option', 'click.option', (['"""--path-drpall"""'], {'default': 'None'}), "('--path-drpall', default=None)\n", (343, 374), False, 'import click\n'), ((376, 468), 'click.option', 'click.option', (['"""--bits"""', '"""-b"""'], {'type': 'click.INT', 'multiple': '(True)', 'help': '"""DAP pixel bitmasks."""'}), "('--bits', '-b', type=click.INT, multiple=True, help=\n 'DAP pixel bitmasks.')\n", (388, 468), False, 'import click\n'), ((465, 516), 'click.option', 'click.option', (['"""--targeting_bit"""'], {'default': '"""mngtarg1"""'}), "('--targeting_bit', default='mngtarg1')\n", (477, 516), False, 'import click\n'), ((518, 576), 'click.option', 'click.option', (['"""--main_sample"""'], {'default': '(False)', 'is_flag': '(True)'}), "('--main_sample', default=False, is_flag=True)\n", (530, 576), False, 'import click\n'), ((578, 618), 'click.option', 'click.option', (['"""--path_out"""'], {'default': 'None'}), "('--path_out', default=None)\n", (590, 618), False, 'import click\n'), ((620, 682), 'click.option', 'click.option', (['"""--overwrite"""', '"""-o"""'], {'default': '(False)', 'is_flag': '(True)'}), "('--overwrite', '-o', default=False, is_flag=True)\n", (632, 682), False, 'import click\n'), ((1431, 1483), 'mglearn.selection.set_drpver', 'selection.set_drpver', ([], {'drpver': 'drpver', 'release': 'release'}), '(drpver=drpver, release=release)\n', (1451, 1483), False, 'from mglearn import selection\n'), ((1499, 1528), 'marvin.config.lookUpRelease', 'config.lookUpRelease', (['drpver_'], {}), '(drpver_)\n', (1519, 1528), False, 'from marvin import config\n'), ((1938, 2000), 'mglearn.selection.read_drpall', 'selection.read_drpall', ([], {'drpver': 'drpver_', 'path_drpall': 'path_drpall'}), '(drpver=drpver_, path_drpall=path_drpall)\n', (1959, 2000), False, 'from mglearn import selection\n'), ((2018, 2071), 'mglearn.selection.apply_bitmasks', 'selection.apply_bitmasks', (['drpall[targeting_bit]', 'bits'], {}), '(drpall[targeting_bit], bits)\n', (2042, 2071), False, 'from mglearn import selection\n'), ((2232, 2285), 'mglearn.selection.remove_duplicates', 'selection.remove_duplicates', (['plateifus', 'mangaids', 'sn2'], {}), '(plateifus, mangaids, sn2)\n', (2259, 2285), False, 'from mglearn import selection\n'), ((2567, 2599), 'os.path.join', 'os.path.join', (['path_out', 'filename'], {}), '(path_out, filename)\n', (2579, 2599), False, 'import os\n'), ((711, 726), 'click.File', 'click.File', (['"""w"""'], {}), "('w')\n", (721, 726), False, 'import click\n'), ((2498, 2521), 'os.path.isdir', 'os.path.isdir', (['path_out'], {}), '(path_out)\n', (2511, 2521), False, 'import os\n'), ((2531, 2549), 'os.mkdir', 'os.mkdir', (['path_out'], {}), '(path_out)\n', (2539, 2549), False, 'import os\n'), ((2662, 2711), 'mglearn.selection.write', 'selection.write', (['sample_unique', 'path_full', 'header'], {}), '(sample_unique, path_full, header)\n', (2677, 2711), False, 'from mglearn import selection\n'), ((2626, 2651), 'os.path.isfile', 'os.path.isfile', (['path_full'], {}), '(path_full)\n', (2640, 2651), False, 'import os\n'), ((2373, 2398), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2388, 2398), False, 'import os\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" BVT tests for Network Life Cycle
"""
# Import Local Modules
from marvin.codes import (FAILED, STATIC_NAT_RULE, LB_RULE,
NAT_RULE, PASS)
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackException import CloudstackAPIException
from marvin.cloudstackAPI import rebootRouter
from marvin.sshClient import SshClient
from marvin.lib.utils import cleanup_resources, get_process_status
from marvin.lib.base import (Account,
VirtualMachine,
ServiceOffering,
NATRule,
PublicIPAddress,
StaticNATRule,
FireWallRule,
Network,
NetworkOffering,
LoadBalancerRule,
Router)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
list_hosts,
list_publicIP,
list_nat_rules,
list_routers,
list_virtual_machines,
list_lb_rules,
list_configurations,
verifyGuestTrafficPortGroups)
from nose.plugins.attrib import attr
from ddt import ddt, data
# Import System modules
import time
import logging
_multiprocess_shared_ = True
logger = logging.getLogger('TestNetworkOps')
stream_handler = logging.StreamHandler()
logger.setLevel(logging.DEBUG)
logger.addHandler(stream_handler)
class TestPublicIP(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
@classmethod
def setUpClass(cls):
testClient = super(TestPublicIP, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
# Create Accounts & networks
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls.user = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id
)
cls.services["network"]["zoneid"] = cls.zone.id
cls.network_offering = NetworkOffering.create(
cls.apiclient,
cls.services["network_offering"],
)
# Enable Network offering
cls.network_offering.update(cls.apiclient, state='Enabled')
cls.services["network"]["networkoffering"] = cls.network_offering.id
cls.account_network = Network.create(
cls.apiclient,
cls.services["network"],
cls.account.name,
cls.account.domainid
)
cls.user_network = Network.create(
cls.apiclient,
cls.services["network"],
cls.user.name,
cls.user.domainid
)
# Create Source NAT IP addresses
PublicIPAddress.create(
cls.apiclient,
cls.account.name,
cls.zone.id,
cls.account.domainid
)
PublicIPAddress.create(
cls.apiclient,
cls.user.name,
cls.zone.id,
cls.user.domainid
)
cls._cleanup = [
cls.account_network,
cls.user_network,
cls.account,
cls.user,
cls.network_offering
]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "advancedns", "smoke", "dvs"], required_hardware="false")
def test_public_ip_admin_account(self):
"""Test for Associate/Disassociate public IP address for admin account"""
# Validate the following:
# 1. listPubliIpAddresses API returns the list of acquired addresses
# 2. the returned list should contain our acquired IP address
ip_address = PublicIPAddress.create(
self.apiclient,
self.account.name,
self.zone.id,
self.account.domainid
)
list_pub_ip_addr_resp = list_publicIP(
self.apiclient,
id=ip_address.ipaddress.id
)
self.assertEqual(
isinstance(list_pub_ip_addr_resp, list),
True,
"Check list response returns a valid list"
)
# listPublicIpAddresses should return newly created public IP
self.assertNotEqual(
len(list_pub_ip_addr_resp),
0,
"Check if new IP Address is associated"
)
self.assertEqual(
list_pub_ip_addr_resp[0].id,
ip_address.ipaddress.id,
"Check Correct IP Address is returned in the List Cacls"
)
ip_address.delete(self.apiclient)
time.sleep(30)
# Validate the following:
# 1.listPublicIpAddresses should no more return the released address
list_pub_ip_addr_resp = list_publicIP(
self.apiclient,
id=ip_address.ipaddress.id
)
if list_pub_ip_addr_resp is None:
return
if (list_pub_ip_addr_resp) and (
isinstance(
list_pub_ip_addr_resp,
list)) and (
len(list_pub_ip_addr_resp) > 0):
self.fail("list public ip response is not empty")
return
@attr(tags=["advanced", "advancedns", "smoke", "dvs"], required_hardware="false")
def test_public_ip_user_account(self):
"""Test for Associate/Disassociate public IP address for user account"""
# Validate the following:
# 1. listPubliIpAddresses API returns the list of acquired addresses
# 2. the returned list should contain our acquired IP address
ip_address = PublicIPAddress.create(
self.apiclient,
self.user.name,
self.zone.id,
self.user.domainid
)
# listPublicIpAddresses should return newly created public IP
list_pub_ip_addr_resp = list_publicIP(
self.apiclient,
id=ip_address.ipaddress.id
)
self.assertEqual(
isinstance(list_pub_ip_addr_resp, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_pub_ip_addr_resp),
0,
"Check if new IP Address is associated"
)
self.assertEqual(
list_pub_ip_addr_resp[0].id,
ip_address.ipaddress.id,
"Check Correct IP Address is returned in the List Call"
)
ip_address.delete(self.apiclient)
list_pub_ip_addr_resp = list_publicIP(
self.apiclient,
id=ip_address.ipaddress.id
)
self.assertEqual(
list_pub_ip_addr_resp,
None,
"Check if disassociated IP Address is no longer available"
)
return
class TestPortForwarding(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestPortForwarding, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
cls.hypervisor = testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
template = get_template(
cls.apiclient,
cls.zone.id,
cls.services["ostype"]
)
if template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services[
"ostype"]
# Create an account, network, VM and IP addresses
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["tiny"]
)
cls.virtual_machine = VirtualMachine.create(
cls.apiclient,
cls.services["virtual_machine"],
templateid=template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id
)
cls._cleanup = [
cls.virtual_machine,
cls.account,
cls.service_offering
]
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
return
@classmethod
def tearDownClass(cls):
try:
cls.apiclient = super(
TestPortForwarding,
cls).getClsTestClient().getApiClient()
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def tearDown(self):
cleanup_resources(self.apiclient, self.cleanup)
return
@attr(tags=["advanced", "advancedns", "smoke", "dvs"], required_hardware="true")
def test_01_port_fwd_on_src_nat(self):
"""Test for port forwarding on source NAT"""
# Validate the following:
# 1. listPortForwarding rules API should return the added PF rule
# 2. attempt to do an ssh into the user VM through the sourceNAT
src_nat_ip_addrs = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(src_nat_ip_addrs, list),
True,
"Check list response returns a valid list"
)
src_nat_ip_addr = src_nat_ip_addrs[0]
# Check if VM is in Running state before creating NAT rule
vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
isinstance(vm_response, list),
True,
"Check list VM returns a valid list"
)
self.assertNotEqual(
len(vm_response),
0,
"Check Port Forwarding Rule is created"
)
self.assertEqual(
vm_response[0].state,
'Running',
"VM state should be Running before creating a NAT rule."
)
# Open up firewall port for SSH
FireWallRule.create(
self.apiclient,
ipaddressid=src_nat_ip_addr.id,
protocol=self.services["natrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["natrule"]["publicport"],
endport=self.services["natrule"]["publicport"]
)
# Create NAT rule
nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine,
self.services["natrule"],
src_nat_ip_addr.id
)
list_nat_rule_response = list_nat_rules(
self.apiclient,
id=nat_rule.id
)
self.assertEqual(
isinstance(list_nat_rule_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_nat_rule_response),
0,
"Check Port Forwarding Rule is created"
)
self.assertEqual(
list_nat_rule_response[0].id,
nat_rule.id,
"Check Correct Port forwarding Rule is returned"
)
# SSH virtual machine to test port forwarding
try:
logger.debug("SSHing into VM with IP address %s with NAT IP %s" %
(
self.virtual_machine.ipaddress,
src_nat_ip_addr.ipaddress
))
self.virtual_machine.get_ssh_client(src_nat_ip_addr.ipaddress)
vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
if vm_response[0].state != 'Running':
self.fail(
"State of VM : %s is not found to be Running" % str(
self.virtual_machine.ipaddress))
except Exception as e:
self.fail(
"SSH Access failed for %s: %s" %
(self.virtual_machine.ipaddress, e)
)
try:
nat_rule.delete(self.apiclient)
except Exception as e:
self.fail("NAT Rule Deletion Failed: %s" % e)
# NAT rule listing should fail as the nat rule does not exist
with self.assertRaises(Exception):
list_nat_rules(self.apiclient,
id=nat_rule.id)
# Check if the Public SSH port is inaccessible
with self.assertRaises(Exception):
logger.debug(
"SSHing into VM with IP address %s after NAT rule deletion" %
self.virtual_machine.ipaddress)
SshClient(
src_nat_ip_addr.ipaddress,
self.virtual_machine.ssh_port,
self.virtual_machine.username,
self.virtual_machine.password,
retries=2,
delay=0
)
return
@attr(tags=["advanced", "advancedns", "smoke", "dvs"], required_hardware="true")
def test_02_port_fwd_on_non_src_nat(self):
"""Test for port forwarding on non source NAT"""
# Validate the following:
# 1. listPortForwardingRules should not return the deleted rule anymore
# 2. attempt to do ssh should now fail
ip_address = PublicIPAddress.create(
self.apiclient,
self.account.name,
self.zone.id,
self.account.domainid,
self.services["virtual_machine"]
)
self.cleanup.append(ip_address)
# Check if VM is in Running state before creating NAT rule
vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
isinstance(vm_response, list),
True,
"Check list VM returns a valid list"
)
self.assertNotEqual(
len(vm_response),
0,
"Check Port Forwarding Rule is created"
)
self.assertEqual(
vm_response[0].state,
'Running',
"VM state should be Running before creating a NAT rule."
)
# Open up firewall port for SSH
FireWallRule.create(
self.apiclient,
ipaddressid=ip_address.ipaddress.id,
protocol=self.services["natrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["natrule"]["publicport"],
endport=self.services["natrule"]["publicport"]
)
# Create NAT rule
nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine,
self.services["natrule"],
ip_address.ipaddress.id
)
# Validate the following:
# 1. listPortForwardingRules should not return the deleted rule anymore
# 2. attempt to do ssh should now fail
list_nat_rule_response = list_nat_rules(
self.apiclient,
id=nat_rule.id
)
self.assertEqual(
isinstance(list_nat_rule_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_nat_rule_response),
0,
"Check Port Forwarding Rule is created"
)
self.assertEqual(
list_nat_rule_response[0].id,
nat_rule.id,
"Check Correct Port forwarding Rule is returned"
)
try:
logger.debug("SSHing into VM with IP address %s with NAT IP %s" %
(
self.virtual_machine.ipaddress,
ip_address.ipaddress.ipaddress
))
self.virtual_machine.get_ssh_client(ip_address.ipaddress.ipaddress)
except Exception as e:
self.fail(
"SSH Access failed for %s: %s" %
(self.virtual_machine.ipaddress, e)
)
nat_rule.delete(self.apiclient)
try:
list_nat_rule_response = list_nat_rules(
self.apiclient,
id=nat_rule.id
)
except CloudstackAPIException:
logger.debug("Nat Rule is deleted")
# Check if the Public SSH port is inaccessible
with self.assertRaises(Exception):
logger.debug(
"SSHing into VM with IP address %s after NAT rule deletion" %
self.virtual_machine.ipaddress)
SshClient(
ip_address.ipaddress.ipaddress,
self.virtual_machine.ssh_port,
self.virtual_machine.username,
self.virtual_machine.password,
retries=2,
delay=0
)
return
@attr(tags=["dvs"], required_hardware="true")
def test_guest_traffic_port_groups_isolated_network(self):
""" Verify port groups are created for guest traffic
used by isolated network """
if self.hypervisor.lower() == "vmware":
response = verifyGuestTrafficPortGroups(self.apiclient,
self.config,
self.zone)
assert response[0] == PASS, response[1]
class TestRebootRouter(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.services = self.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
self.domain = get_domain(self.apiclient)
self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
template = get_template(
self.apiclient,
self.zone.id,
self.services["ostype"]
)
if template == FAILED:
self.fail(
"get_template() failed to return template with description %s" %
self.services["ostype"])
self.services["virtual_machine"]["zoneid"] = self.zone.id
# Create an account, network, VM and IP addresses
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["tiny"]
)
self.vm_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id
)
# Wait for VM to come up
time.sleep(120)
src_nat_ip_addrs = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
try:
src_nat_ip_addr = src_nat_ip_addrs[0]
except Exception as e:
raise Exception(
"Warning: Exception during fetching source NAT: %s" %
e)
self.public_ip = PublicIPAddress.create(
self.apiclient,
self.vm_1.account,
self.vm_1.zoneid,
self.vm_1.domainid,
self.services["virtual_machine"]
)
# Open up firewall port for SSH
FireWallRule.create(
self.apiclient,
ipaddressid=self.public_ip.ipaddress.id,
protocol=self.services["lbrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["lbrule"]["publicport"],
endport=self.services["lbrule"]["publicport"]
)
lb_rule = LoadBalancerRule.create(
self.apiclient,
self.services["lbrule"],
src_nat_ip_addr.id,
self.account.name
)
lb_rule.assign(self.apiclient, [self.vm_1])
self.nat_rule = NATRule.create(
self.apiclient,
self.vm_1,
self.services["natrule"],
ipaddressid=self.public_ip.ipaddress.id
)
self.cleanup = [self.nat_rule,
lb_rule,
self.vm_1,
self.service_offering,
self.account,
]
return
@attr(tags=["advanced", "advancedns", "smoke", "dvs"], required_hardware="true")
def test_reboot_router(self):
"""Test for reboot router"""
# Validate the Following
# 1. Post restart PF and LB rules should still function
# 2. verify if the ssh into the virtual machine
# still works through the sourceNAT Ip
# Retrieve router for the user account
logger.debug("Public IP: %s" % self.vm_1.ssh_ip)
logger.debug("Public IP: %s" % self.public_ip.ipaddress.ipaddress)
routers = list_routers(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(routers, list),
True,
"Check list routers returns a valid list"
)
router = routers[0]
logger.debug("Rebooting the router (ID: %s)" % router.id)
cmd = rebootRouter.rebootRouterCmd()
cmd.id = router.id
self.apiclient.rebootRouter(cmd)
# Poll listVM to ensure VM is stopped properly
timeout = self.services["timeout"]
while True:
time.sleep(self.services["sleep"])
# Ensure that VM is in stopped state
list_vm_response = list_virtual_machines(
self.apiclient,
id=self.vm_1.id
)
if isinstance(list_vm_response, list):
vm = list_vm_response[0]
if vm.state == 'Running':
logger.debug("VM state: %s" % vm.state)
break
if timeout == 0:
raise Exception(
"Failed to start VM (ID: %s) in change service offering" %
vm.id)
timeout = timeout - 1
# we should be able to SSH after successful reboot
try:
logger.debug("SSH into VM (ID : %s ) after reboot" % self.vm_1.id)
SshClient(
self.public_ip.ipaddress.ipaddress,
self.services["natrule"]["publicport"],
self.vm_1.username,
self.vm_1.password,
retries=5
)
except Exception as e:
self.fail(
"SSH Access failed for %s: %s" %
(self.public_ip.ipaddress.ipaddress, e))
return
def tearDown(self):
cleanup_resources(self.apiclient, self.cleanup)
return
class TestReleaseIP(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.services = self.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
self.domain = get_domain(self.apiclient)
self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
template = get_template(
self.apiclient,
self.zone.id,
self.services["ostype"]
)
self.services["virtual_machine"]["zoneid"] = self.zone.id
# Create an account, network, VM, Port forwarding rule, LB rules
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["tiny"]
)
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id
)
self.ip_address = PublicIPAddress.create(
self.apiclient,
self.account.name,
self.zone.id,
self.account.domainid
)
ip_addrs = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
issourcenat=False
)
try:
self.ip_addr = ip_addrs[0]
except Exception as e:
raise Exception(
"Failed: During acquiring source NAT for account: %s, :%s" %
(self.account.name, e))
self.nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine,
self.services["natrule"],
self.ip_addr.id
)
self.lb_rule = LoadBalancerRule.create(
self.apiclient,
self.services["lbrule"],
self.ip_addr.id,
accountid=self.account.name
)
self.cleanup = [
self.virtual_machine,
self.account
]
return
def tearDown(self):
cleanup_resources(self.apiclient, self.cleanup)
@attr(tags=["advanced", "advancedns", "smoke", "dvs"], required_hardware="false")
def test_releaseIP(self):
"""Test for release public IP address"""
logger.debug("Deleting Public IP : %s" % self.ip_addr.id)
self.ip_address.delete(self.apiclient)
retriesCount = 10
isIpAddressDisassociated = False
while retriesCount > 0:
listResponse = list_publicIP(
self.apiclient,
id=self.ip_addr.id
)
if listResponse is None:
isIpAddressDisassociated = True
break
retriesCount -= 1
time.sleep(60)
# End while
self.assertTrue(
isIpAddressDisassociated,
"Failed to disassociate IP address")
# ListPortForwardingRules should not list
# associated rules with Public IP address
try:
list_nat_rule = list_nat_rules(
self.apiclient,
id=self.nat_rule.id
)
logger.debug("List NAT Rule response" + str(list_nat_rule))
except CloudstackAPIException:
logger.debug("Port Forwarding Rule is deleted")
# listLoadBalancerRules should not list
# associated rules with Public IP address
try:
list_lb_rule = list_lb_rules(
self.apiclient,
id=self.lb_rule.id
)
logger.debug("List LB Rule response" + str(list_lb_rule))
except CloudstackAPIException:
logger.debug("Port Forwarding Rule is deleted")
# SSH Attempt though public IP should fail
with self.assertRaises(Exception):
SshClient(
self.ip_addr.ipaddress,
self.services["natrule"]["publicport"],
self.virtual_machine.username,
self.virtual_machine.password,
retries=2,
delay=0
)
return
class TestDeleteAccount(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.services = self.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
self.domain = get_domain(self.apiclient)
self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
template = get_template(
self.apiclient,
self.zone.id,
self.services["ostype"]
)
self.services["virtual_machine"]["zoneid"] = self.zone.id
# Create an account, network, VM and IP addresses
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["tiny"]
)
self.vm_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id
)
src_nat_ip_addrs = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
try:
src_nat_ip_addr = src_nat_ip_addrs[0]
except Exception as e:
self.fail("SSH failed for VM with IP: %s %s" %
(src_nat_ip_addr.ipaddress, e))
self.lb_rule = LoadBalancerRule.create(
self.apiclient,
self.services["lbrule"],
src_nat_ip_addr.id,
self.account.name
)
self.lb_rule.assign(self.apiclient, [self.vm_1])
self.nat_rule = NATRule.create(
self.apiclient,
self.vm_1,
self.services["natrule"],
src_nat_ip_addr.id
)
self.cleanup = []
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="false")
def test_delete_account(self):
"""Test for delete account"""
# Validate the Following
# 1. after account.cleanup.interval (global setting)
# time all the PF/LB rules should be deleted
# 2. verify that list(LoadBalancer/PortForwarding)Rules
# API does not return any rules for the account
# 3. The domR should have been expunged for this account
self.account.delete(self.apiclient)
interval = list_configurations(
self.apiclient,
name='account.cleanup.interval'
)
self.assertEqual(
isinstance(interval, list),
True,
"Check if account.cleanup.interval config present"
)
# Sleep to ensure that all resources are deleted
time.sleep(int(interval[0].value))
# ListLoadBalancerRules should not list
# associated rules with deleted account
# Unable to find account testuser1 in domain 1 : Exception
try:
list_lb_rules(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
except CloudstackAPIException:
logger.debug("Port Forwarding Rule is deleted")
# ListPortForwardingRules should not
# list associated rules with deleted account
try:
list_nat_rules(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
except CloudstackAPIException:
logger.debug("NATRule is deleted")
# Retrieve router for the user account
try:
routers = list_routers(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
routers,
None,
"Check routers are properly deleted."
)
except CloudstackAPIException:
logger.debug("Router is deleted")
except Exception as e:
raise Exception(
"Encountered %s raised while fetching routers for account: %s" %
(e, self.account.name))
return
def tearDown(self):
cleanup_resources(self.apiclient, self.cleanup)
return
@ddt
class TestRouterRules(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestRouterRules, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.hypervisor = testClient.getHypervisorInfo()
template = get_template(
cls.apiclient,
cls.zone.id,
cls.services["ostype"]
)
if template == FAILED:
assert False, "get_template() failed to return template\
with description %s" % cls.services["ostype"]
# Create an account, network, VM and IP addresses
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["tiny"]
)
cls.virtual_machine = VirtualMachine.create(
cls.apiclient,
cls.services["virtual_machine"],
templateid=template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id
)
cls.defaultNetworkId = cls.virtual_machine.nic[0].networkid
cls._cleanup = [
cls.virtual_machine,
cls.account,
cls.service_offering
]
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def tearDown(self):
cleanup_resources(self.apiclient, self.cleanup)
return
def getCommandResultFromRouter(self, router, command):
"""Run given command on router and return the result"""
if (self.hypervisor.lower() == 'vmware'
or self.hypervisor.lower() == 'hyperv'):
result = get_process_status(
self.apiclient.connection.mgtSvr,
22,
self.apiclient.connection.user,
self.apiclient.connection.passwd,
router.linklocalip,
command,
hypervisor=self.hypervisor
)
else:
hosts = list_hosts(
self.apiclient,
id=router.hostid,
)
self.assertEqual(
isinstance(hosts, list),
True,
"Check for list hosts response return valid data"
)
host = hosts[0]
host.user = self.services["configurableData"]["host"]["username"]
host.passwd = self.services["configurableData"]["host"]["password"]
result = get_process_status(
host.ipaddress,
22,
host.user,
host.passwd,
router.linklocalip,
command
)
return result
def createNetworkRules(self, rule, ipaddressobj, networkid):
""" Create specified rule on acquired public IP and
default network of virtual machine
"""
# Open up firewall port for SSH
self.fw_rule = FireWallRule.create(
self.apiclient,
ipaddressid=ipaddressobj.ipaddress.id,
protocol=self.services["fwrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["fwrule"]["startport"],
endport=self.services["fwrule"]["endport"]
)
if rule == STATIC_NAT_RULE:
StaticNATRule.enable(
self.apiclient,
ipaddressobj.ipaddress.id,
self.virtual_machine.id,
networkid
)
elif rule == LB_RULE:
self.lb_rule = LoadBalancerRule.create(
self.apiclient,
self.services["lbrule"],
ipaddressid=ipaddressobj.ipaddress.id,
accountid=self.account.name,
networkid=self.virtual_machine.nic[0].networkid,
domainid=self.account.domainid)
vmidipmap = [{"vmid": str(self.virtual_machine.id),
"vmip": str(self.virtual_machine.nic[0].ipaddress)}]
self.lb_rule.assign(
self.apiclient,
vmidipmap=vmidipmap
)
else:
self.nat_rule = NATRule.create(
self.apiclient,
self.virtual_machine,
self.services["natrule"],
ipaddressobj.ipaddress.id
)
return
def removeNetworkRules(self, rule):
""" Remove specified rule on acquired public IP and
default network of virtual machine
"""
self.fw_rule.delete(self.apiclient)
if rule == STATIC_NAT_RULE:
StaticNATRule.disable(
self.apiclient,
self.ipaddress.ipaddress.id)
elif rule == LB_RULE:
self.lb_rule.delete(self.apiclient)
else:
self.nat_rule.delete(self.apiclient)
logger.debug("Releasing IP %s from account %s" % (self.ipaddress.ipaddress.ipaddress, self.account.name))
self.ipaddress.delete(self.apiclient)
return
@data(STATIC_NAT_RULE, NAT_RULE, LB_RULE)
@attr(tags=["advanced", "advancedns", "smoke", "dvs"], required_hardware="true")
def test_network_rules_acquired_public_ip(self, value):
"""Test for Router rules for network rules on acquired public IP"""
# Validate the following:
# 1. listPortForwardingRules should not return the deleted rule anymore
# 2. attempt to do ssh should now fail
self.ipaddress = PublicIPAddress.create(
self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=self.defaultNetworkId
)
self.createNetworkRules(rule=value,
ipaddressobj=self.ipaddress,
networkid=self.defaultNetworkId)
router = Router.list(self.apiclient,
networkid=self.virtual_machine.nic[0].networkid,
listall=True)[0]
response = self.getCommandResultFromRouter(router, "ip addr")
logger.debug(response)
stringToMatch = "inet %s" % self.ipaddress.ipaddress.ipaddress
self.assertTrue(stringToMatch in str(response), "IP address is\
not added to the VR!")
try:
logger.debug("SSHing into VM with IP address %s with NAT IP %s" %
(
self.virtual_machine.ipaddress,
self.ipaddress.ipaddress.ipaddress
))
self.virtual_machine.get_ssh_client(
self.ipaddress.ipaddress.ipaddress)
except Exception as e:
self.fail(
"SSH Access failed for %s: %s" %
(self.virtual_machine.ipaddress, e)
)
# Validate the following:
# 1. listIpForwardingRules should not return the deleted rule anymore
# 2. attempt to do ssh should now fail
self.removeNetworkRules(rule=value)
response = self.getCommandResultFromRouter(router, "ip addr")
logger.debug(response)
stringToMatch = "inet %s" % self.ipaddress.ipaddress.ipaddress
self.assertFalse(stringToMatch in str(response), "IP address is\
not removed from VR even after disabling stat in NAT")
# Check if the Public SSH port is inaccessible
with self.assertRaises(Exception):
logger.debug(
"SSHing into VM with IP address %s after NAT rule deletion" %
self.virtual_machine.ipaddress)
SshClient(
self.ipaddress.ipaddress.ipaddress,
self.virtual_machine.ssh_port,
self.virtual_machine.username,
self.virtual_machine.password,
retries=2,
delay=0
)
return
| [
"marvin.lib.common.list_hosts",
"marvin.lib.base.NATRule.create",
"marvin.lib.utils.get_process_status",
"marvin.cloudstackAPI.rebootRouter.rebootRouterCmd",
"marvin.lib.common.list_nat_rules",
"marvin.lib.base.StaticNATRule.enable",
"marvin.lib.base.Router.list",
"marvin.lib.base.VirtualMachine.list"... | [((2367, 2402), 'logging.getLogger', 'logging.getLogger', (['"""TestNetworkOps"""'], {}), "('TestNetworkOps')\n", (2384, 2402), False, 'import logging\n'), ((2420, 2443), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2441, 2443), False, 'import logging\n'), ((4969, 5054), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'dvs']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'smoke', 'dvs'], required_hardware='false'\n )\n", (4973, 5054), False, 'from nose.plugins.attrib import attr\n'), ((6846, 6931), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'dvs']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'smoke', 'dvs'], required_hardware='false'\n )\n", (6850, 6931), False, 'from nose.plugins.attrib import attr\n'), ((10657, 10736), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'dvs']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke', 'dvs'], required_hardware='true')\n", (10661, 10736), False, 'from nose.plugins.attrib import attr\n'), ((14966, 15045), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'dvs']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke', 'dvs'], required_hardware='true')\n", (14970, 15045), False, 'from nose.plugins.attrib import attr\n'), ((18867, 18911), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['dvs']", 'required_hardware': '"""true"""'}), "(tags=['dvs'], required_hardware='true')\n", (18871, 18911), False, 'from nose.plugins.attrib import attr\n'), ((22488, 22567), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'dvs']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke', 'dvs'], required_hardware='true')\n", (22492, 22567), False, 'from nose.plugins.attrib import attr\n'), ((27407, 27492), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'dvs']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'smoke', 'dvs'], required_hardware='false'\n )\n", (27411, 27492), False, 'from nose.plugins.attrib import attr\n'), ((31485, 31558), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='false')\n", (31489, 31558), False, 'from nose.plugins.attrib import attr\n'), ((39740, 39780), 'ddt.data', 'data', (['STATIC_NAT_RULE', 'NAT_RULE', 'LB_RULE'], {}), '(STATIC_NAT_RULE, NAT_RULE, LB_RULE)\n', (39744, 39780), False, 'from ddt import ddt, data\n'), ((39786, 39865), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'dvs']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke', 'dvs'], required_hardware='true')\n", (39790, 39865), False, 'from nose.plugins.attrib import attr\n'), ((2909, 2934), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2919, 2934), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((3119, 3214), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (3133, 3214), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((3288, 3366), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (3302, 3366), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((3501, 3572), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['network_offering']"], {}), "(cls.apiclient, cls.services['network_offering'])\n", (3523, 3572), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((3818, 3916), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network']", 'cls.account.name', 'cls.account.domainid'], {}), "(cls.apiclient, cls.services['network'], cls.account.name,\n cls.account.domainid)\n", (3832, 3916), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((3998, 4091), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network']", 'cls.user.name', 'cls.user.domainid'], {}), "(cls.apiclient, cls.services['network'], cls.user.name, cls.\n user.domainid)\n", (4012, 4091), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((4195, 4290), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['cls.apiclient', 'cls.account.name', 'cls.zone.id', 'cls.account.domainid'], {}), '(cls.apiclient, cls.account.name, cls.zone.id, cls.\n account.domainid)\n', (4217, 4290), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((4352, 4441), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['cls.apiclient', 'cls.user.name', 'cls.zone.id', 'cls.user.domainid'], {}), '(cls.apiclient, cls.user.name, cls.zone.id, cls.user.\n domainid)\n', (4374, 4441), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((5380, 5478), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.account.name', 'self.zone.id', 'self.account.domainid'], {}), '(self.apiclient, self.account.name, self.zone.id,\n self.account.domainid)\n', (5402, 5478), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((5565, 5622), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'id': 'ip_address.ipaddress.id'}), '(self.apiclient, id=ip_address.ipaddress.id)\n', (5578, 5622), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((6269, 6283), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (6279, 6283), False, 'import time\n'), ((6428, 6485), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'id': 'ip_address.ipaddress.id'}), '(self.apiclient, id=ip_address.ipaddress.id)\n', (6441, 6485), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((7255, 7348), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.user.name', 'self.zone.id', 'self.user.domainid'], {}), '(self.apiclient, self.user.name, self.zone.id, self.\n user.domainid)\n', (7277, 7348), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((7505, 7562), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'id': 'ip_address.ipaddress.id'}), '(self.apiclient, id=ip_address.ipaddress.id)\n', (7518, 7562), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((8163, 8220), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'id': 'ip_address.ipaddress.id'}), '(self.apiclient, id=ip_address.ipaddress.id)\n', (8176, 8220), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((8822, 8847), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (8832, 8847), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((8940, 9004), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (8952, 9004), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((9294, 9389), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (9308, 9389), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((9538, 9623), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['tiny']"], {}), "(cls.apiclient, cls.services['service_offerings']['tiny']\n )\n", (9560, 9623), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((9683, 9887), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.apiclient, cls.services['virtual_machine'],\n templateid=template.id, accountid=cls.account.name, domainid=cls.\n account.domainid, serviceofferingid=cls.service_offering.id)\n", (9704, 9887), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((10588, 10635), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (10605, 10635), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((11044, 11137), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (11057, 11137), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((11473, 11536), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (11492, 11536), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((12065, 12314), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'src_nat_ip_addr.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=src_nat_ip_addr.id,\n protocol=self.services['natrule']['protocol'], cidrlist=['0.0.0.0/0'],\n startport=self.services['natrule']['publicport'], endport=self.services\n ['natrule']['publicport'])\n", (12084, 12314), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((12430, 12533), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine', "self.services['natrule']", 'src_nat_ip_addr.id'], {}), "(self.apiclient, self.virtual_machine, self.services[\n 'natrule'], src_nat_ip_addr.id)\n", (12444, 12533), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((12621, 12667), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'id': 'nat_rule.id'}), '(self.apiclient, id=nat_rule.id)\n', (12635, 12667), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((15334, 15466), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.account.name', 'self.zone.id', 'self.account.domainid', "self.services['virtual_machine']"], {}), "(self.apiclient, self.account.name, self.zone.id,\n self.account.domainid, self.services['virtual_machine'])\n", (15356, 15466), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((15663, 15726), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (15682, 15726), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((16255, 16509), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ip_address.ipaddress.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=ip_address.ipaddress.id,\n protocol=self.services['natrule']['protocol'], cidrlist=['0.0.0.0/0'],\n startport=self.services['natrule']['publicport'], endport=self.services\n ['natrule']['publicport'])\n", (16274, 16509), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((16624, 16732), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine', "self.services['natrule']", 'ip_address.ipaddress.id'], {}), "(self.apiclient, self.virtual_machine, self.services[\n 'natrule'], ip_address.ipaddress.id)\n", (16638, 16732), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((16981, 17027), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'id': 'nat_rule.id'}), '(self.apiclient, id=nat_rule.id)\n', (16995, 17027), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((19625, 19651), 'marvin.lib.common.get_domain', 'get_domain', (['self.apiclient'], {}), '(self.apiclient)\n', (19635, 19651), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((19751, 19818), 'marvin.lib.common.get_template', 'get_template', (['self.apiclient', 'self.zone.id', "self.services['ostype']"], {}), "(self.apiclient, self.zone.id, self.services['ostype'])\n", (19763, 19818), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((20189, 20286), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (20203, 20286), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((20373, 20460), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['tiny']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'tiny'])\n", (20395, 20460), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((20510, 20719), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.apiclient, self.services['virtual_machine'],\n templateid=template.id, accountid=self.account.name, domainid=self.\n account.domainid, serviceofferingid=self.service_offering.id)\n", (20531, 20719), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((20835, 20850), 'time.sleep', 'time.sleep', (['(120)'], {}), '(120)\n', (20845, 20850), False, 'import time\n'), ((20879, 20972), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (20892, 20972), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((21252, 21385), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.vm_1.account', 'self.vm_1.zoneid', 'self.vm_1.domainid', "self.services['virtual_machine']"], {}), "(self.apiclient, self.vm_1.account, self.vm_1.zoneid,\n self.vm_1.domainid, self.services['virtual_machine'])\n", (21274, 21385), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((21500, 21755), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'self.public_ip.ipaddress.id', 'protocol': "self.services['lbrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['lbrule']['publicport']", 'endport': "self.services['lbrule']['publicport']"}), "(self.apiclient, ipaddressid=self.public_ip.ipaddress.id,\n protocol=self.services['lbrule']['protocol'], cidrlist=['0.0.0.0/0'],\n startport=self.services['lbrule']['publicport'], endport=self.services[\n 'lbrule']['publicport'])\n", (21519, 21755), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((21844, 21951), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']", 'src_nat_ip_addr.id', 'self.account.name'], {}), "(self.apiclient, self.services['lbrule'],\n src_nat_ip_addr.id, self.account.name)\n", (21867, 21951), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((22082, 22194), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.vm_1', "self.services['natrule']"], {'ipaddressid': 'self.public_ip.ipaddress.id'}), "(self.apiclient, self.vm_1, self.services['natrule'],\n ipaddressid=self.public_ip.ipaddress.id)\n", (22096, 22194), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((23041, 23133), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (23053, 23133), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((23433, 23463), 'marvin.cloudstackAPI.rebootRouter.rebootRouterCmd', 'rebootRouter.rebootRouterCmd', ([], {}), '()\n', (23461, 23463), False, 'from marvin.cloudstackAPI import rebootRouter\n'), ((24911, 24958), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (24928, 24958), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((25225, 25251), 'marvin.lib.common.get_domain', 'get_domain', (['self.apiclient'], {}), '(self.apiclient)\n', (25235, 25251), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((25351, 25418), 'marvin.lib.common.get_template', 'get_template', (['self.apiclient', 'self.zone.id', "self.services['ostype']"], {}), "(self.apiclient, self.zone.id, self.services['ostype'])\n", (25363, 25418), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((25628, 25725), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (25642, 25725), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((25813, 25900), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['tiny']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'tiny'])\n", (25835, 25900), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((25962, 26171), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.apiclient, self.services['virtual_machine'],\n templateid=template.id, accountid=self.account.name, domainid=self.\n account.domainid, serviceofferingid=self.service_offering.id)\n", (25983, 26171), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((26272, 26370), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.account.name', 'self.zone.id', 'self.account.domainid'], {}), '(self.apiclient, self.account.name, self.zone.id,\n self.account.domainid)\n', (26294, 26370), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((26445, 26557), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'issourcenat': '(False)'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, issourcenat=False)\n', (26458, 26557), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((26865, 26965), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine', "self.services['natrule']", 'self.ip_addr.id'], {}), "(self.apiclient, self.virtual_machine, self.services[\n 'natrule'], self.ip_addr.id)\n", (26879, 26965), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((27042, 27157), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']", 'self.ip_addr.id'], {'accountid': 'self.account.name'}), "(self.apiclient, self.services['lbrule'], self.\n ip_addr.id, accountid=self.account.name)\n", (27065, 27157), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((27353, 27400), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (27370, 27400), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((29661, 29687), 'marvin.lib.common.get_domain', 'get_domain', (['self.apiclient'], {}), '(self.apiclient)\n', (29671, 29687), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((29787, 29854), 'marvin.lib.common.get_template', 'get_template', (['self.apiclient', 'self.zone.id', "self.services['ostype']"], {}), "(self.apiclient, self.zone.id, self.services['ostype'])\n", (29799, 29854), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((30049, 30146), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (30063, 30146), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((30233, 30320), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['tiny']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'tiny'])\n", (30255, 30320), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((30370, 30579), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.apiclient, self.services['virtual_machine'],\n templateid=template.id, accountid=self.account.name, domainid=self.\n account.domainid, serviceofferingid=self.service_offering.id)\n", (30391, 30579), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((30681, 30774), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (30694, 30774), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((31048, 31155), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']", 'src_nat_ip_addr.id', 'self.account.name'], {}), "(self.apiclient, self.services['lbrule'],\n src_nat_ip_addr.id, self.account.name)\n", (31071, 31155), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((31292, 31383), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.vm_1', "self.services['natrule']", 'src_nat_ip_addr.id'], {}), "(self.apiclient, self.vm_1, self.services['natrule'],\n src_nat_ip_addr.id)\n", (31306, 31383), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((32035, 32103), 'marvin.lib.common.list_configurations', 'list_configurations', (['self.apiclient'], {'name': '"""account.cleanup.interval"""'}), "(self.apiclient, name='account.cleanup.interval')\n", (32054, 32103), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((33889, 33936), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (33906, 33936), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((34286, 34311), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (34296, 34311), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((34460, 34524), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (34472, 34524), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((34818, 34913), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (34832, 34913), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((35062, 35147), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['tiny']"], {}), "(cls.apiclient, cls.services['service_offerings']['tiny']\n )\n", (35084, 35147), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((35207, 35411), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.apiclient, cls.services['virtual_machine'],\n templateid=template.id, accountid=cls.account.name, domainid=cls.\n account.domainid, serviceofferingid=cls.service_offering.id)\n", (35228, 35411), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((36055, 36102), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (36072, 36102), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((37650, 37899), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ipaddressobj.ipaddress.id', 'protocol': "self.services['fwrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['fwrule']['startport']", 'endport': "self.services['fwrule']['endport']"}), "(self.apiclient, ipaddressid=ipaddressobj.ipaddress.id,\n protocol=self.services['fwrule']['protocol'], cidrlist=['0.0.0.0/0'],\n startport=self.services['fwrule']['startport'], endport=self.services[\n 'fwrule']['endport'])\n", (37669, 37899), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((40190, 40353), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'self.defaultNetworkId'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=self.\n defaultNetworkId)\n', (40212, 40353), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((4796, 4842), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (4813, 4842), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((10403, 10449), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (10420, 10449), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((13587, 13650), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (13606, 13650), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((14347, 14393), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'id': 'nat_rule.id'}), '(self.apiclient, id=nat_rule.id)\n', (14361, 14393), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((14685, 14844), 'marvin.sshClient.SshClient', 'SshClient', (['src_nat_ip_addr.ipaddress', 'self.virtual_machine.ssh_port', 'self.virtual_machine.username', 'self.virtual_machine.password'], {'retries': '(2)', 'delay': '(0)'}), '(src_nat_ip_addr.ipaddress, self.virtual_machine.ssh_port, self.\n virtual_machine.username, self.virtual_machine.password, retries=2, delay=0\n )\n', (14694, 14844), False, 'from marvin.sshClient import SshClient\n'), ((18137, 18183), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'id': 'nat_rule.id'}), '(self.apiclient, id=nat_rule.id)\n', (18151, 18183), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((18581, 18743), 'marvin.sshClient.SshClient', 'SshClient', (['ip_address.ipaddress.ipaddress', 'self.virtual_machine.ssh_port', 'self.virtual_machine.username', 'self.virtual_machine.password'], {'retries': '(2)', 'delay': '(0)'}), '(ip_address.ipaddress.ipaddress, self.virtual_machine.ssh_port,\n self.virtual_machine.username, self.virtual_machine.password, retries=2,\n delay=0)\n', (18590, 18743), False, 'from marvin.sshClient import SshClient\n'), ((19145, 19213), 'marvin.lib.common.verifyGuestTrafficPortGroups', 'verifyGuestTrafficPortGroups', (['self.apiclient', 'self.config', 'self.zone'], {}), '(self.apiclient, self.config, self.zone)\n', (19173, 19213), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((23664, 23698), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (23674, 23698), False, 'import time\n'), ((23780, 23834), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'id': 'self.vm_1.id'}), '(self.apiclient, id=self.vm_1.id)\n', (23801, 23834), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((24472, 24613), 'marvin.sshClient.SshClient', 'SshClient', (['self.public_ip.ipaddress.ipaddress', "self.services['natrule']['publicport']", 'self.vm_1.username', 'self.vm_1.password'], {'retries': '(5)'}), "(self.public_ip.ipaddress.ipaddress, self.services['natrule'][\n 'publicport'], self.vm_1.username, self.vm_1.password, retries=5)\n", (24481, 24613), False, 'from marvin.sshClient import SshClient\n'), ((27809, 27858), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'id': 'self.ip_addr.id'}), '(self.apiclient, id=self.ip_addr.id)\n', (27822, 27858), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((28054, 28068), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (28064, 28068), False, 'import time\n'), ((28344, 28395), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'id': 'self.nat_rule.id'}), '(self.apiclient, id=self.nat_rule.id)\n', (28358, 28395), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((28752, 28801), 'marvin.lib.common.list_lb_rules', 'list_lb_rules', (['self.apiclient'], {'id': 'self.lb_rule.id'}), '(self.apiclient, id=self.lb_rule.id)\n', (28765, 28801), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((29124, 29287), 'marvin.sshClient.SshClient', 'SshClient', (['self.ip_addr.ipaddress', "self.services['natrule']['publicport']", 'self.virtual_machine.username', 'self.virtual_machine.password'], {'retries': '(2)', 'delay': '(0)'}), "(self.ip_addr.ipaddress, self.services['natrule']['publicport'],\n self.virtual_machine.username, self.virtual_machine.password, retries=2,\n delay=0)\n", (29133, 29287), False, 'from marvin.sshClient import SshClient\n'), ((32584, 32677), 'marvin.lib.common.list_lb_rules', 'list_lb_rules', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (32597, 32677), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((32958, 33052), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (32972, 33052), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((33279, 33371), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (33291, 33371), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((35870, 35916), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (35887, 35916), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((36369, 36557), 'marvin.lib.utils.get_process_status', 'get_process_status', (['self.apiclient.connection.mgtSvr', '(22)', 'self.apiclient.connection.user', 'self.apiclient.connection.passwd', 'router.linklocalip', 'command'], {'hypervisor': 'self.hypervisor'}), '(self.apiclient.connection.mgtSvr, 22, self.apiclient.\n connection.user, self.apiclient.connection.passwd, router.linklocalip,\n command, hypervisor=self.hypervisor)\n', (36387, 36557), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((36709, 36753), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'router.hostid'}), '(self.apiclient, id=router.hostid)\n', (36719, 36753), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_publicIP, list_nat_rules, list_routers, list_virtual_machines, list_lb_rules, list_configurations, verifyGuestTrafficPortGroups\n'), ((37182, 37278), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', '(22)', 'host.user', 'host.passwd', 'router.linklocalip', 'command'], {}), '(host.ipaddress, 22, host.user, host.passwd, router.\n linklocalip, command)\n', (37200, 37278), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((38018, 38122), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'ipaddressobj.ipaddress.id', 'self.virtual_machine.id', 'networkid'], {}), '(self.apiclient, ipaddressobj.ipaddress.id, self.\n virtual_machine.id, networkid)\n', (38038, 38122), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((39315, 39381), 'marvin.lib.base.StaticNATRule.disable', 'StaticNATRule.disable', (['self.apiclient', 'self.ipaddress.ipaddress.id'], {}), '(self.apiclient, self.ipaddress.ipaddress.id)\n', (39336, 39381), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((40603, 40697), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'self.virtual_machine.nic[0].networkid', 'listall': '(True)'}), '(self.apiclient, networkid=self.virtual_machine.nic[0].networkid,\n listall=True)\n', (40614, 40697), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((42359, 42525), 'marvin.sshClient.SshClient', 'SshClient', (['self.ipaddress.ipaddress.ipaddress', 'self.virtual_machine.ssh_port', 'self.virtual_machine.username', 'self.virtual_machine.password'], {'retries': '(2)', 'delay': '(0)'}), '(self.ipaddress.ipaddress.ipaddress, self.virtual_machine.ssh_port,\n self.virtual_machine.username, self.virtual_machine.password, retries=2,\n delay=0)\n', (42368, 42525), False, 'from marvin.sshClient import SshClient\n'), ((38254, 38480), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']"], {'ipaddressid': 'ipaddressobj.ipaddress.id', 'accountid': 'self.account.name', 'networkid': 'self.virtual_machine.nic[0].networkid', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['lbrule'],\n ipaddressid=ipaddressobj.ipaddress.id, accountid=self.account.name,\n networkid=self.virtual_machine.nic[0].networkid, domainid=self.account.\n domainid)\n", (38277, 38480), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n'), ((38867, 38977), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine', "self.services['natrule']", 'ipaddressobj.ipaddress.id'], {}), "(self.apiclient, self.virtual_machine, self.services[\n 'natrule'], ipaddressobj.ipaddress.id)\n", (38881, 38977), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, Router\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" BVT tests for Service offerings"""
#Import Local Modules
from marvin.codes import FAILED
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import changeServiceForVirtualMachine,updateServiceOffering
from marvin.lib.utils import (isAlmostEqual,
cleanup_resources,
random_gen)
from marvin.lib.base import (ServiceOffering,
Account,
VirtualMachine)
from marvin.lib.common import (list_service_offering,
list_virtual_machines,
get_domain,
get_zone,
get_template)
from nose.plugins.attrib import attr
_multiprocess_shared_ = True
class TestCreateServiceOffering(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
self.services = self.testClient.getParsedTestDataConfig()
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "advancedns", "smoke", "basic", "eip", "sg"])
def test_01_create_service_offering(self):
"""Test to create service offering"""
# Validate the following:
# 1. createServiceOfferings should return a valid information for newly created offering
# 2. The Cloud Database contains the valid information
service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]
)
self.cleanup.append(service_offering)
self.debug("Created service offering with ID: %s" % service_offering.id)
list_service_response = list_service_offering(
self.apiclient,
id=service_offering.id
)
self.assertEqual(
isinstance(list_service_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_service_response),
0,
"Check Service offering is created"
)
self.assertEqual(
list_service_response[0].cpunumber,
self.services["service_offerings"]["cpunumber"],
"Check server id in createServiceOffering"
)
self.assertEqual(
list_service_response[0].cpuspeed,
self.services["service_offerings"]["cpuspeed"],
"Check cpuspeed in createServiceOffering"
)
self.assertEqual(
list_service_response[0].displaytext,
self.services["service_offerings"]["displaytext"],
"Check server displaytext in createServiceOfferings"
)
self.assertEqual(
list_service_response[0].memory,
self.services["service_offerings"]["memory"],
"Check memory in createServiceOffering"
)
self.assertEqual(
list_service_response[0].name,
self.services["service_offerings"]["name"],
"Check name in createServiceOffering"
)
return
class TestServiceOfferings(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def setUpClass(cls):
testClient = super(TestServiceOfferings, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
#Adding storage type as 'local' otherwise it won't work because default is 'shared'.
cls.services["service_offerings"]["small"]['storagetype'] = 'local'
cls.services["service_offerings"]["medium"]['storagetype'] = 'local'
cls.services['ostype'] = 'CentOS 5.6 (64-bit)'
domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
cls.service_offering_1 = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]
)
cls.service_offering_2 = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]
)
template = get_template(
cls.apiclient,
cls.zone.id,
cls.services["ostype"]
)
if template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]
# Set Zones and disk offerings
cls.services["small"]["zoneid"] = cls.zone.id
cls.services["small"]["template"] = template.id
cls.services["medium"]["zoneid"] = cls.zone.id
cls.services["medium"]["template"] = template.id
# Create VMs, NAT Rules etc
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=domain.id
)
cls.small_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["small"]
)
cls.medium_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["medium"]
)
cls.medium_virtual_machine = VirtualMachine.create(
cls.apiclient,
cls.services["medium"],
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.medium_offering.id,
mode=cls.services["mode"]
)
cls._cleanup = [
cls.small_offering,
cls.medium_offering,
cls.account
]
return
@classmethod
def tearDownClass(cls):
try:
cls.apiclient = super(TestServiceOfferings, cls).getClsTestClient().getApiClient()
#Clean up, terminate the created templates
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "advancedns", "smoke", "basic", "eip", "sg"])
def test_02_edit_service_offering(self):
"""Test to update existing service offering"""
# Validate the following:
# 1. updateServiceOffering should return
# a valid information for newly created offering
#Generate new name & displaytext from random data
random_displaytext = random_gen()
random_name = random_gen()
self.debug("Updating service offering with ID: %s" %
self.service_offering_1.id)
cmd = updateServiceOffering.updateServiceOfferingCmd()
#Add parameters for API call
cmd.id = self.service_offering_1.id
cmd.displaytext = random_displaytext
cmd.name = random_name
self.apiclient.updateServiceOffering(cmd)
list_service_response = list_service_offering(
self.apiclient,
id=self.service_offering_1.id
)
self.assertEqual(
isinstance(list_service_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_service_response),
0,
"Check Service offering is updated"
)
self.assertEqual(
list_service_response[0].displaytext,
random_displaytext,
"Check server displaytext in updateServiceOffering"
)
self.assertEqual(
list_service_response[0].name,
random_name,
"Check server name in updateServiceOffering"
)
return
@attr(tags=["advanced", "advancedns", "smoke", "basic", "eip", "sg"])
def test_03_delete_service_offering(self):
"""Test to delete service offering"""
# Validate the following:
# 1. deleteServiceOffering should return
# a valid information for newly created offering
self.debug("Deleting service offering with ID: %s" %
self.service_offering_2.id)
self.service_offering_2.delete(self.apiclient)
list_service_response = list_service_offering(
self.apiclient,
id=self.service_offering_2.id
)
self.assertEqual(
list_service_response,
None,
"Check if service offering exists in listDiskOfferings"
)
return | [
"marvin.lib.common.get_domain",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.common.list_service_offering",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.utils.random_gen",
"marvin.cloudstackAPI.updateServiceOffering.updateServiceOfferingCmd",
"mar... | [((2253, 2321), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'basic', 'eip', 'sg']"}), "(tags=['advanced', 'advancedns', 'smoke', 'basic', 'eip', 'sg'])\n", (2257, 2321), False, 'from nose.plugins.attrib import attr\n'), ((8160, 8228), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'basic', 'eip', 'sg']"}), "(tags=['advanced', 'advancedns', 'smoke', 'basic', 'eip', 'sg'])\n", (8164, 8228), False, 'from nose.plugins.attrib import attr\n'), ((9796, 9864), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke', 'basic', 'eip', 'sg']"}), "(tags=['advanced', 'advancedns', 'smoke', 'basic', 'eip', 'sg'])\n", (9800, 9864), False, 'from nose.plugins.attrib import attr\n'), ((2638, 2712), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']"], {}), "(self.apiclient, self.services['service_offerings'])\n", (2660, 2712), False, 'from marvin.lib.base import ServiceOffering, Account, VirtualMachine\n'), ((2908, 2969), 'marvin.lib.common.list_service_offering', 'list_service_offering', (['self.apiclient'], {'id': 'service_offering.id'}), '(self.apiclient, id=service_offering.id)\n', (2929, 2969), False, 'from marvin.lib.common import list_service_offering, list_virtual_machines, get_domain, get_zone, get_template\n'), ((5344, 5369), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (5354, 5369), False, 'from marvin.lib.common import list_service_offering, list_virtual_machines, get_domain, get_zone, get_template\n'), ((5529, 5601), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']"], {}), "(cls.apiclient, cls.services['service_offerings'])\n", (5551, 5601), False, 'from marvin.lib.base import ServiceOffering, Account, VirtualMachine\n'), ((5669, 5741), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']"], {}), "(cls.apiclient, cls.services['service_offerings'])\n", (5691, 5741), False, 'from marvin.lib.base import ServiceOffering, Account, VirtualMachine\n'), ((5795, 5859), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (5807, 5859), False, 'from marvin.lib.common import list_service_offering, list_virtual_machines, get_domain, get_zone, get_template\n'), ((6441, 6515), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'domain.id'}), "(cls.apiclient, cls.services['account'], domainid=domain.id)\n", (6455, 6515), False, 'from marvin.lib.base import ServiceOffering, Account, VirtualMachine\n'), ((6660, 6746), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['small']"], {}), "(cls.apiclient, cls.services['service_offerings'][\n 'small'])\n", (6682, 6746), False, 'from marvin.lib.base import ServiceOffering, Account, VirtualMachine\n'), ((6883, 6970), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['medium']"], {}), "(cls.apiclient, cls.services['service_offerings'][\n 'medium'])\n", (6905, 6970), False, 'from marvin.lib.base import ServiceOffering, Account, VirtualMachine\n'), ((7113, 7311), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['medium']"], {'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.medium_offering.id', 'mode': "cls.services['mode']"}), "(cls.apiclient, cls.services['medium'], accountid=cls.\n account.name, domainid=cls.account.domainid, serviceofferingid=cls.\n medium_offering.id, mode=cls.services['mode'])\n", (7134, 7311), False, 'from marvin.lib.base import ServiceOffering, Account, VirtualMachine\n'), ((8561, 8573), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (8571, 8573), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n'), ((8596, 8608), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (8606, 8608), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n'), ((8733, 8781), 'marvin.cloudstackAPI.updateServiceOffering.updateServiceOfferingCmd', 'updateServiceOffering.updateServiceOfferingCmd', ([], {}), '()\n', (8779, 8781), False, 'from marvin.cloudstackAPI import changeServiceForVirtualMachine, updateServiceOffering\n'), ((9022, 9090), 'marvin.lib.common.list_service_offering', 'list_service_offering', (['self.apiclient'], {'id': 'self.service_offering_1.id'}), '(self.apiclient, id=self.service_offering_1.id)\n', (9043, 9090), False, 'from marvin.lib.common import list_service_offering, list_virtual_machines, get_domain, get_zone, get_template\n'), ((10300, 10368), 'marvin.lib.common.list_service_offering', 'list_service_offering', (['self.apiclient'], {'id': 'self.service_offering_2.id'}), '(self.apiclient, id=self.service_offering_2.id)\n', (10321, 10368), False, 'from marvin.lib.common import list_service_offering, list_virtual_machines, get_domain, get_zone, get_template\n'), ((2077, 2124), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (2094, 2124), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n'), ((4628, 4675), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (4645, 4675), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n'), ((7986, 8032), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (8003, 8032), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Test cases for VM/Volume recurring snapshot Test Path
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.lib.utils import (cleanup_resources,
is_snapshot_on_nfs,
validateList
)
from marvin.lib.base import (Account,
ServiceOffering,
DiskOffering,
VirtualMachine,
SnapshotPolicy,
Snapshot,
Configurations
)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
list_volumes,
list_snapshots,
list_snapshot_policy
)
from marvin.codes import PASS
import time
class TestVolumeRecurringSnapshot(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestVolumeRecurringSnapshot, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
cls.hypervisor = cls.testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
cls._cleanup = []
if cls.hypervisor.lower() not in [
"vmware",
"kvm",
"xenserver"]:
raise unittest.SkipTest(
"Storage migration not supported on %s" %
cls.hypervisor)
try:
# Create an account
cls.account = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
# Create user api client of the account
cls.userapiclient = testClient.getUserApiClient(
UserName=cls.account.name,
DomainName=cls.account.domain
)
# Create Service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
)
cls._cleanup.append(cls.service_offering)
# Create Disk offering
cls.disk_offering = DiskOffering.create(
cls.apiclient,
cls.testdata["disk_offering"],
)
cls._cleanup.append(cls.disk_offering)
# Deploy A VM
cls.vm_1 = VirtualMachine.create(
cls.userapiclient,
cls.testdata["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
zoneid=cls.zone.id,
diskofferingid=cls.disk_offering.id,
mode=cls.zone.networktype
)
cls.volume = list_volumes(
cls.apiclient,
virtualmachineid=cls.vm_1.id,
type='ROOT',
listall=True
)
cls.data_volume = list_volumes(
cls.apiclient,
virtualmachineid=cls.vm_1.id,
type='DATADISK',
listall=True
)
except Exception as e:
cls.tearDownClass()
raise e
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "basic"],required_hardware="true")
def test_01_volume_snapshot(self):
""" Test Volume (root) Snapshot
# 1. Create Hourly, Daily,Weekly recurring snapshot policy for ROOT disk and
Verify the presence of the corresponding snapshots on the Secondary Storage
# 2. Delete the snapshot policy and verify the entry as Destroyed in snapshot_schedule
# 3. Verify that maxsnaps should not consider manual snapshots for deletion
# 4. Snapshot policy should reflect the correct timezone
# 5. Verify that listSnapshotPolicies() should return all snapshot policies
that belong to the account (both manual and recurring snapshots)
# 6. Verify that listSnapshotPolicies() should not return snapshot
policies that have been deleted
# 7. Verify that snapshot should not be created for VM in Destroyed state
# 8. Verify that snapshot should get created after resuming the VM
# 9. Verify that All the recurring policies associated with the VM should be
deleted after VM get destroyed.
"""
# Step 1
self.testdata["recurring_snapshot"]["intervaltype"] = 'HOURLY'
recurring_snapshot = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
# ListSnapshotPolicy should return newly created policy
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
timeout = self.testdata["timeout"]
while True:
snapshots = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata[
"recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
if isinstance(snapshots, list):
break
elif timeout == 0:
raise Exception("List snapshots API call failed.")
for snapshot in snapshots:
self.assertEqual(
self.dbclient.execute(
"select type_description from snapshots where name='%s'" %
snapshot.name)[0][0],
"HOURLY"
)
time.sleep(180)
for snapshot in snapshots:
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snapshot.id))
recurring_snapshot.delete(self.apiclient)
self.assertEqual(
self.dbclient.execute(
"select * from snapshot_policy where uuid='%s'" %
recurring_snapshot.id),
[]
)
self.testdata["recurring_snapshot"]["intervaltype"] = 'DAILY'
self.testdata["recurring_snapshot"]["schedule"] = '00:00'
recurring_snapshot_daily = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
list_snapshots_policy_daily = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_daily.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy_daily)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
snap_db_daily = self.dbclient.execute(
"select * from snapshot_policy where uuid='%s'" %
recurring_snapshot_daily.id)
validation_result_1 = validateList(snap_db_daily)
self.assertEqual(
validation_result_1[0],
PASS,
"snapshot_policy list validation failed due to %s" %
validation_result_1[2])
self.assertNotEqual(
len(snap_db_daily),
0,
"Check DB Query result set"
)
recurring_snapshot_daily.delete(self.apiclient)
self.assertEqual(
self.dbclient.execute(
"select * from snapshot_policy where uuid='%s'" %
recurring_snapshot_daily.id),
[]
)
self.testdata["recurring_snapshot"]["intervaltype"] = 'WEEKLY'
self.testdata["recurring_snapshot"]["schedule"] = '00:00:1'
recurring_snapshot_weekly = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
list_snapshots_policy_weekly = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_weekly.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy_weekly)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
snap_sch_2 = self.dbclient.execute(
"select * from snapshot_policy where uuid='%s'" %
recurring_snapshot_weekly.id)
validation_result_2 = validateList(snap_sch_2)
self.assertEqual(
validation_result_2[0],
PASS,
"snapshot_policy list validation failed due to %s" %
validation_result_2[2])
self.assertNotEqual(
len(snap_sch_2),
0,
"Check DB Query result set"
)
recurring_snapshot_weekly.delete(self.apiclient)
self.assertEqual(
self.dbclient.execute(
"select * from snapshot_policy where uuid='%s'" %
recurring_snapshot_weekly.id),
[]
)
self.testdata["recurring_snapshot"]["intervaltype"] = 'MONTHLY'
self.testdata["recurring_snapshot"]["schedule"] = '00:00:1'
recurring_snapshot_monthly = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
list_snapshots_policy_monthly = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_monthly.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy_monthly)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
snap_sch_3 = self.dbclient.execute(
"select * from snapshot_policy where uuid='%s'" %
recurring_snapshot_monthly.id)
validation_result = validateList(snap_sch_3)
self.assertEqual(
validation_result[0],
PASS,
"snapshot_policy list validation failed due to %s" %
validation_result[2])
self.assertNotEqual(
len(snap_sch_3),
0,
"Check DB Query result set"
)
recurring_snapshot_monthly.delete(self.apiclient)
self.assertEqual(
self.dbclient.execute(
"select * from snapshot_policy where uuid='%s'" %
recurring_snapshot_weekly.id),
[]
)
snapshots = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata["recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
# Step 3
self.testdata["recurring_snapshot"]["intervaltype"] = 'HOURLY'
self.testdata["recurring_snapshot"]["schedule"] = 1
recurring_snapshot_1 = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
# ListSnapshotPolicy should return newly created policy
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_1.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
timeout = self.testdata["timeout"]
while True:
snapshots = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata[
"recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
if isinstance(snapshots, list):
break
elif timeout == 0:
raise Exception("List snapshots API call failed.")
snap_to_delete = snapshots[0]
time.sleep(
(self.testdata["recurring_snapshot"]["maxsnaps"]) * 3600
)
snapshots_1 = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata["recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
self.assertTrue(snap_to_delete not in snapshots_1)
time.sleep(360)
self.assertEqual(
self.dbclient.execute(
"select status from snapshots where uuid='%s'" %
snap_to_delete.id)[0][0],
"Destroyed"
)
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snap_to_delete.id))
# Step 4
recurring_snapshot = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
# ListSnapshotPolicy should return newly created policy
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
time.sleep(180)
snap_time_hourly = self.dbclient.execute(
"select scheduled_timestamp from \
snapshot_schedule where uuid='%s'" %
recurring_snapshot.id)
self.debug("Timestamp for hourly snapshot %s" % snap_time_hourly)
recurring_snapshot.delete(self.apiclient)
self.testdata["recurring_snapshot"]["intervaltype"] = 'DAILY'
self.testdata["recurring_snapshot"]["schedule"] = '00:00'
recurring_snapshot_daily = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
list_snapshots_policy_daily = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_daily.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy_daily)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
time.sleep(180)
snap_time_daily = self.dbclient.execute(
"select scheduled_timestamp from \
snapshot_schedule where uuid='%s'" %
recurring_snapshot_daily.id)
self.debug("Timestamp for daily snapshot %s" % snap_time_daily)
recurring_snapshot_daily.delete(self.apiclient)
self.testdata["recurring_snapshot"]["intervaltype"] = 'WEEKLY'
self.testdata["recurring_snapshot"]["schedule"] = '00:00:1'
recurring_snapshot_weekly = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
list_snapshots_policy_weekly = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_weekly.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy_weekly)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
time.sleep(180)
snap_time_weekly = self.dbclient.execute(
"select scheduled_timestamp from \
snapshot_schedule where uuid='%s'" %
recurring_snapshot_weekly.id)
self.debug("Timestamp for monthly snapshot %s" % snap_time_weekly)
recurring_snapshot_weekly.delete(self.apiclient)
self.testdata["recurring_snapshot"]["intervaltype"] = 'MONTHLY'
self.testdata["recurring_snapshot"]["schedule"] = '00:00:1'
recurring_snapshot_monthly = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
list_snapshots_policy_monthly = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_monthly.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy_monthly)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
time.sleep(180)
snap_time_monthly = self.dbclient.execute(
"select scheduled_timestamp from \
snapshot_schedule where uuid='%s'" %
recurring_snapshot_monthly.id)
self.debug("Timestamp for monthly snapshot %s" % snap_time_monthly)
recurring_snapshot_monthly.delete(self.apiclient)
# Step 5
self.testdata["recurring_snapshot"]["intervaltype"] = 'HOURLY'
self.testdata["recurring_snapshot"]["schedule"] = 1
recurring_snapshot_hourly = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
self.testdata["recurring_snapshot"]["intervaltype"] = 'MONTHLY'
self.testdata["recurring_snapshot"]["schedule"] = '00:00:1'
recurring_snapshot_monthly = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
for rec in [recurring_snapshot_hourly, recurring_snapshot_monthly]:
self.assertTrue(
rec.id in any(
policy['id']) for policy in list_snapshots_policy)
recurring_snapshot_hourly.delete(self.apiclient)
recurring_snapshot_monthly.delete(self.apiclient)
# Step 6
self.testdata["recurring_snapshot"]["intervaltype"] = 'HOURLY'
self.testdata["recurring_snapshot"]["schedule"] = 1
recurring_snapshot_hourly = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
self.testdata["recurring_snapshot"]["intervaltype"] = 'MONTHLY'
self.testdata["recurring_snapshot"]["schedule"] = '00:00:1'
recurring_snapshot_monthly = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
recurring_snapshot_monthly.delete(self.apiclient)
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
self.assertTrue(
recurring_snapshot_hourly.id in any(
policy['id']) for policy in list_snapshots_policy)
self.assertTrue(
recurring_snapshot_monthly.id not in any(
policy['id']) for policy in list_snapshots_policy)
# Step 7
self.testdata["recurring_snapshot"]["intervaltype"] = 'HOURLY'
self.testdata["recurring_snapshot"]["schedule"] = 1
recurring_snapshot = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
# ListSnapshotPolicy should return newly created policy
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
timeout = self.testdata["timeout"]
while True:
snapshots = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata[
"recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
if isinstance(snapshots, list):
break
elif timeout == 0:
raise Exception("List snapshots API call failed.")
self.vm_1.delete(self.apiclient, expunge=False)
time.sleep(3600)
snapshot_list = Snapshot.list(
self.apiclient,
volumeid=self.volume[0].id
)
list_validation = validateList(snapshot_list)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
self.assertEqual(len(snapshot_list),
1,
"Verify that snapsot is not created after VM deletion"
)
# Step 8
self.vm_1.recover(self.apiclient)
time.sleep(3600)
snapshot_list = Snapshot.list(
self.apiclient,
volumeid=self.volume[0].id
)
self.assertEqual(len(snapshot_list),
2,
"Verify that snapsot is not created after VM deletion"
)
# Step 9
self.vm_1.delete(self.apiclient)
time.sleep(180)
with self.assertRaises(Exception):
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
volumeid=self.volume[0].id
)
@attr(tags=["advanced", "basic"], required_hardware="true")
def test_02_volume_max_snapshot(self):
""" Test Volume Snapshot
# 1. Create Hourly reccuring snapshot policy with maxsnaps=2
verify that when 3rd snapshot is taken first snapshot gets deleted
"""
if self.hypervisor.lower() not in ["kvm", "vmware"]:
self.skipTest("Skip test for hypervisor other than KVM and VMWare")
# Step 1
self.testdata["recurring_snapshot"]["intervaltype"] = 'HOURLY'
self.testdata["recurring_snapshot"]["schedule"] = 1
recurring_snapshot_1 = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
# ListSnapshotPolicy should return newly created policy
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_1.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
timeout = self.testdata["timeout"]
while True:
snapshots = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata[
"recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
if isinstance(snapshots, list):
break
elif timeout == 0:
raise Exception("List snapshots API call failed.")
snap_to_delete = snapshots[0]
time.sleep(
(self.testdata["recurring_snapshot"]["maxsnaps"]) * 3600
)
snapshots_1 = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata["recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
self.assertTrue(snap_to_delete not in snapshots_1)
time.sleep(360)
self.assertEqual(
self.dbclient.execute(
"select status from snapshots where uuid='%s'" %
snap_to_delete.id)[0][0],
"Destroyed"
)
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snap_to_delete.id))
# DATA DISK
recurring_snapshot_data = SnapshotPolicy.create(
self.apiclient,
self.data_volume[0].id,
self.testdata["recurring_snapshot"]
)
# ListSnapshotPolicy should return newly created policy
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_data.id,
volumeid=self.data_volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
timeout = self.testdata["timeout"]
while True:
snapshots = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata[
"recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
if isinstance(snapshots, list):
break
elif timeout == 0:
raise Exception("List snapshots API call failed.")
data_snap_to_delete = snapshots[0]
time.sleep(
(self.testdata["recurring_snapshot"]["maxsnaps"]) * 3600
)
data_snapshots_1 = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata["recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
self.assertTrue(data_snap_to_delete not in data_snapshots_1)
time.sleep(360)
self.assertEqual(
self.dbclient.execute(
"select status from snapshots where uuid='%s'" %
snap_to_delete.id)[0][0],
"Destroyed"
)
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
data_snap_to_delete.id))
@attr(tags=["advanced", "basic"],required_hardware="true")
def test_03_volume_rec_snapshot(self):
""" Test Volume (root) Snapshot
# 1. For snapshot.delta.max > maxsnaps verify that when number of snapshot exceeds
maxsnaps value previous snapshot should get deleted from database but remain
on secondary storage and when the value exceeds snapshot.delta.max the
snapshot should get deleted from secondary storage
"""
if self.hypervisor.lower() != "xenserver":
self.skipTest("Skip test for hypervisor other than Xenserver")
# Step 1
self.testdata["recurring_snapshot"]["intervaltype"] = 'HOURLY'
self.testdata["recurring_snapshot"]["schedule"] = 1
recurring_snapshot_root = SnapshotPolicy.create(
self.apiclient,
self.volume[0].id,
self.testdata["recurring_snapshot"]
)
Configurations.update(self.apiclient,
name="snapshot.delta.max",
value="3"
)
list_snapshots_policy = list_snapshot_policy(
self.apiclient,
id=recurring_snapshot_root.id,
volumeid=self.volume[0].id
)
list_validation = validateList(list_snapshots_policy)
self.assertEqual(
list_validation[0],
PASS,
"snapshot list validation failed due to %s" %
list_validation[2])
timeout = self.testdata["timeout"]
while True:
snapshots = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata[
"recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
if isinstance(snapshots, list):
break
elif timeout == 0:
raise Exception("List snapshots API call failed.")
time.sleep(3600 * 2)
snapshots_2 = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata["recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
self.assertTrue(snapshots[0] not in snapshots_2)
for snapshot in snapshots_2:
snapshots.append(snapshot)
time.sleep(360)
self.assertEqual(
self.dbclient.execute(
"select status from snapshots where uuid='%s'" %
snapshots[0].id)[0][0],
"Destroyed"
)
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snapshots[0].id))
time.sleep(3600)
snapshots_3 = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata["recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
self.assertTrue(snapshots[1] not in snapshots_3)
snapshots.append(snapshots_3[1])
time.sleep(180)
self.assertEqual(
self.dbclient.execute(
"select status from snapshots where uuid='%s'" %
snapshots[1].id)[0][0],
"Destroyed"
)
for snapshot in [snapshots[0], snapshots[1]]:
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snapshot.id))
time.sleep(3600)
snapshots_4 = list_snapshots(
self.apiclient,
volumeid=self.volume[0].id,
intervaltype=self.testdata["recurring_snapshot"]["intervaltype"],
snapshottype='RECURRING',
listall=True
)
self.assertTrue(snapshots[2] not in snapshots_4)
snapshots.append(snapshots_4[1])
time.sleep(180)
self.assertEqual(
self.dbclient.execute(
"select status from snapshots where uuid='%s'" %
snapshots[2].id)[0][0],
"Destroyed"
)
for snapshot in [snapshots[0], snapshots[1], snapshots[2]]:
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
snapshot.id))
return
| [
"marvin.lib.common.get_domain",
"marvin.lib.common.list_snapshot_policy",
"marvin.lib.utils.validateList",
"marvin.lib.base.Configurations.update",
"marvin.lib.base.Account.create",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.common.list_volumes",
"marvin.lib.utils.cleanup_resources",
"mar... | [((5258, 5316), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (5262, 5316), False, 'from nose.plugins.attrib import attr\n'), ((24980, 25038), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (24984, 25038), False, 'from nose.plugins.attrib import attr\n'), ((29792, 29850), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (29796, 29850), False, 'from nose.plugins.attrib import attr\n'), ((2225, 2250), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2235, 2250), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((2348, 2412), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.testdata['ostype'])\n", (2360, 2412), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((6531, 6629), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (6552, 6629), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((6767, 6862), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot.id, volumeid=\n self.volume[0].id)\n', (6787, 6862), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((6930, 6965), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (6942, 6965), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((7941, 7956), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (7951, 7956), False, 'import time\n'), ((8646, 8744), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (8667, 8744), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((8825, 8925), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_daily.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_daily.id,\n volumeid=self.volume[0].id)\n', (8845, 8925), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((8995, 9036), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy_daily'], {}), '(list_snapshots_policy_daily)\n', (9007, 9036), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((9386, 9413), 'marvin.lib.utils.validateList', 'validateList', (['snap_db_daily'], {}), '(snap_db_daily)\n', (9398, 9413), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((10159, 10257), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (10180, 10257), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((10339, 10440), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_weekly.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_weekly.id,\n volumeid=self.volume[0].id)\n', (10359, 10440), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((10510, 10552), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy_weekly'], {}), '(list_snapshots_policy_weekly)\n', (10522, 10552), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((10900, 10924), 'marvin.lib.utils.validateList', 'validateList', (['snap_sch_2'], {}), '(snap_sch_2)\n', (10912, 10924), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((11667, 11765), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (11688, 11765), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((11848, 11950), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_monthly.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_monthly.id,\n volumeid=self.volume[0].id)\n', (11868, 11950), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((12020, 12063), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy_monthly'], {}), '(list_snapshots_policy_monthly)\n', (12032, 12063), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((12410, 12434), 'marvin.lib.utils.validateList', 'validateList', (['snap_sch_3'], {}), '(snap_sch_3)\n', (12422, 12434), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((13017, 13191), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (13031, 13191), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((13432, 13530), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (13453, 13530), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((13668, 13765), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_1.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_1.id, volumeid=\n self.volume[0].id)\n', (13688, 13765), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((13833, 13868), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (13845, 13868), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((14618, 14684), 'time.sleep', 'time.sleep', (["(self.testdata['recurring_snapshot']['maxsnaps'] * 3600)"], {}), "(self.testdata['recurring_snapshot']['maxsnaps'] * 3600)\n", (14628, 14684), False, 'import time\n'), ((14732, 14906), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (14746, 14906), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((15036, 15051), 'time.sleep', 'time.sleep', (['(360)'], {}), '(360)\n', (15046, 15051), False, 'import time\n'), ((15520, 15618), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (15541, 15618), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((15756, 15851), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot.id, volumeid=\n self.volume[0].id)\n', (15776, 15851), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((15919, 15954), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (15931, 15954), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((16131, 16146), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (16141, 16146), False, 'import time\n'), ((16625, 16723), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (16646, 16723), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((16804, 16904), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_daily.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_daily.id,\n volumeid=self.volume[0].id)\n', (16824, 16904), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((16974, 17015), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy_daily'], {}), '(list_snapshots_policy_daily)\n', (16986, 17015), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((17192, 17207), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (17202, 17207), False, 'import time\n'), ((17707, 17805), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (17728, 17805), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((17887, 17988), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_weekly.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_weekly.id,\n volumeid=self.volume[0].id)\n', (17907, 17988), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((18058, 18100), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy_weekly'], {}), '(list_snapshots_policy_weekly)\n', (18070, 18100), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((18277, 18292), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (18287, 18292), False, 'import time\n'), ((18800, 18898), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (18821, 18898), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((18981, 19083), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_monthly.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_monthly.id,\n volumeid=self.volume[0].id)\n', (19001, 19083), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((19153, 19196), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy_monthly'], {}), '(list_snapshots_policy_monthly)\n', (19165, 19196), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((19373, 19388), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (19383, 19388), False, 'import time\n'), ((19908, 20006), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (19929, 20006), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((20225, 20323), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (20246, 20323), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((20398, 20462), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'volumeid': 'self.volume[0].id'}), '(self.apiclient, volumeid=self.volume[0].id)\n', (20418, 20462), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((20524, 20559), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (20536, 20559), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((21236, 21334), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (21257, 21334), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((21554, 21652), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (21575, 21652), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((21786, 21850), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'volumeid': 'self.volume[0].id'}), '(self.apiclient, volumeid=self.volume[0].id)\n', (21806, 21850), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((21912, 21947), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (21924, 21947), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((22582, 22680), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (22603, 22680), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((22818, 22913), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot.id, volumeid=\n self.volume[0].id)\n', (22838, 22913), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((22981, 23016), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (22993, 23016), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((23784, 23800), 'time.sleep', 'time.sleep', (['(3600)'], {}), '(3600)\n', (23794, 23800), False, 'import time\n'), ((23825, 23882), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.apiclient'], {'volumeid': 'self.volume[0].id'}), '(self.apiclient, volumeid=self.volume[0].id)\n', (23838, 23882), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((23944, 23971), 'marvin.lib.utils.validateList', 'validateList', (['snapshot_list'], {}), '(snapshot_list)\n', (23956, 23971), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((24387, 24403), 'time.sleep', 'time.sleep', (['(3600)'], {}), '(3600)\n', (24397, 24403), False, 'import time\n'), ((24429, 24486), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.apiclient'], {'volumeid': 'self.volume[0].id'}), '(self.apiclient, volumeid=self.volume[0].id)\n', (24442, 24486), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((24768, 24783), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (24778, 24783), False, 'import time\n'), ((25602, 25700), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (25623, 25700), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((25838, 25935), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_1.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_1.id, volumeid=\n self.volume[0].id)\n', (25858, 25935), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((26003, 26038), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (26015, 26038), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((26788, 26854), 'time.sleep', 'time.sleep', (["(self.testdata['recurring_snapshot']['maxsnaps'] * 3600)"], {}), "(self.testdata['recurring_snapshot']['maxsnaps'] * 3600)\n", (26798, 26854), False, 'import time\n'), ((26910, 27084), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (26924, 27084), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((27214, 27229), 'time.sleep', 'time.sleep', (['(360)'], {}), '(360)\n', (27224, 27229), False, 'import time\n'), ((27706, 27809), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.data_volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.data_volume[0].id, self.testdata\n ['recurring_snapshot'])\n", (27727, 27809), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((27947, 28051), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_data.id', 'volumeid': 'self.data_volume[0].id'}), '(self.apiclient, id=recurring_snapshot_data.id,\n volumeid=self.data_volume[0].id)\n', (27967, 28051), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((28121, 28156), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (28133, 28156), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((28911, 28977), 'time.sleep', 'time.sleep', (["(self.testdata['recurring_snapshot']['maxsnaps'] * 3600)"], {}), "(self.testdata['recurring_snapshot']['maxsnaps'] * 3600)\n", (28921, 28977), False, 'import time\n'), ((29030, 29204), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (29044, 29204), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((29344, 29359), 'time.sleep', 'time.sleep', (['(360)'], {}), '(360)\n', (29354, 29359), False, 'import time\n'), ((30596, 30694), 'marvin.lib.base.SnapshotPolicy.create', 'SnapshotPolicy.create', (['self.apiclient', 'self.volume[0].id', "self.testdata['recurring_snapshot']"], {}), "(self.apiclient, self.volume[0].id, self.testdata[\n 'recurring_snapshot'])\n", (30617, 30694), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((30745, 30820), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""snapshot.delta.max"""', 'value': '"""3"""'}), "(self.apiclient, name='snapshot.delta.max', value='3')\n", (30766, 30820), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((30945, 31044), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'id': 'recurring_snapshot_root.id', 'volumeid': 'self.volume[0].id'}), '(self.apiclient, id=recurring_snapshot_root.id,\n volumeid=self.volume[0].id)\n', (30965, 31044), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((31113, 31148), 'marvin.lib.utils.validateList', 'validateList', (['list_snapshots_policy'], {}), '(list_snapshots_policy)\n', (31125, 31148), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((31859, 31879), 'time.sleep', 'time.sleep', (['(3600 * 2)'], {}), '(3600 * 2)\n', (31869, 31879), False, 'import time\n'), ((31903, 32077), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (31917, 32077), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((32282, 32297), 'time.sleep', 'time.sleep', (['(360)'], {}), '(360)\n', (32292, 32297), False, 'import time\n'), ((32722, 32738), 'time.sleep', 'time.sleep', (['(3600)'], {}), '(3600)\n', (32732, 32738), False, 'import time\n'), ((32762, 32936), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (32776, 32936), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((33104, 33119), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (33114, 33119), False, 'import time\n'), ((33623, 33639), 'time.sleep', 'time.sleep', (['(3600)'], {}), '(3600)\n', (33633, 33639), False, 'import time\n'), ((33663, 33837), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (33677, 33837), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((34006, 34021), 'time.sleep', 'time.sleep', (['(180)'], {}), '(180)\n', (34016, 34021), False, 'import time\n'), ((2618, 2693), 'unittest.SkipTest', 'unittest.SkipTest', (["('Storage migration not supported on %s' % cls.hypervisor)"], {}), "('Storage migration not supported on %s' % cls.hypervisor)\n", (2635, 2693), False, 'import unittest\n'), ((2799, 2877), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.testdata['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.testdata['account'], domainid=cls.domain.id)\n", (2813, 2877), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((3274, 3345), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {}), "(cls.apiclient, cls.testdata['service_offering'])\n", (3296, 3345), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((3514, 3579), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['cls.apiclient', "cls.testdata['disk_offering']"], {}), "(cls.apiclient, cls.testdata['disk_offering'])\n", (3533, 3579), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((3727, 4018), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.userapiclient', "cls.testdata['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id', 'zoneid': 'cls.zone.id', 'diskofferingid': 'cls.disk_offering.id', 'mode': 'cls.zone.networktype'}), "(cls.userapiclient, cls.testdata['small'], templateid=\n cls.template.id, accountid=cls.account.name, domainid=cls.account.\n domainid, serviceofferingid=cls.service_offering.id, zoneid=cls.zone.id,\n diskofferingid=cls.disk_offering.id, mode=cls.zone.networktype)\n", (3748, 4018), False, 'from marvin.lib.base import Account, ServiceOffering, DiskOffering, VirtualMachine, SnapshotPolicy, Snapshot, Configurations\n'), ((4189, 4277), 'marvin.lib.common.list_volumes', 'list_volumes', (['cls.apiclient'], {'virtualmachineid': 'cls.vm_1.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(cls.apiclient, virtualmachineid=cls.vm_1.id, type='ROOT',\n listall=True)\n", (4201, 4277), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((4383, 4475), 'marvin.lib.common.list_volumes', 'list_volumes', (['cls.apiclient'], {'virtualmachineid': 'cls.vm_1.id', 'type': '"""DATADISK"""', 'listall': '(True)'}), "(cls.apiclient, virtualmachineid=cls.vm_1.id, type='DATADISK',\n listall=True)\n", (4395, 4475), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((4720, 4766), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (4737, 4766), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((5084, 5131), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (5101, 5131), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((7221, 7395), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (7235, 7395), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((14124, 14298), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (14138, 14298), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((15295, 15394), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snap_to_delete.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snap_to_delete.id)\n', (15313, 15394), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((23272, 23446), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (23286, 23446), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((24863, 24927), 'marvin.lib.common.list_snapshot_policy', 'list_snapshot_policy', (['self.apiclient'], {'volumeid': 'self.volume[0].id'}), '(self.apiclient, volumeid=self.volume[0].id)\n', (24883, 24927), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((26294, 26468), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (26308, 26468), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((27473, 27572), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snap_to_delete.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snap_to_delete.id)\n', (27491, 27572), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((28412, 28586), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (28426, 28586), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((29603, 29707), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'data_snap_to_delete.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n data_snap_to_delete.id)\n', (29621, 29707), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((31404, 31578), 'marvin.lib.common.list_snapshots', 'list_snapshots', (['self.apiclient'], {'volumeid': 'self.volume[0].id', 'intervaltype': "self.testdata['recurring_snapshot']['intervaltype']", 'snapshottype': '"""RECURRING"""', 'listall': '(True)'}), "(self.apiclient, volumeid=self.volume[0].id, intervaltype=\n self.testdata['recurring_snapshot']['intervaltype'], snapshottype=\n 'RECURRING', listall=True)\n", (31418, 31578), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, list_snapshots, list_snapshot_policy\n'), ((32537, 32634), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snapshots[0].id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snapshots[0].id)\n', (32555, 32634), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((8038, 8131), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snapshot.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snapshot.id)\n', (8056, 8131), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((33422, 33515), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snapshot.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snapshot.id)\n', (33440, 33515), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n'), ((34339, 34432), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'snapshot.id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n snapshot.id)\n', (34357, 34432), False, 'from marvin.lib.utils import cleanup_resources, is_snapshot_on_nfs, validateList\n')] |
# Licensed under a 3-clause BSD style license
"""
Marvin is a package intended to simply the access, exploration, and visualization of
the MaNGA dataset for SDSS-IV. It provides a suite of Python tools, a web interface,
and a REST-like API, under tools/, web/, and api/, respectively. Core functionality
of Marvin stems from Marvin's Brain.
"""
import os
import re
import warnings
import sys
import marvin
from collections import OrderedDict
# Set the Marvin version
__version__ = '2.2.6dev'
# try:
# from marvin.version import get_version
# except ImportError as e:
# __version__ = 'dev'
# else:
# __version__ = get_version()
# Does this so that the implicit module definitions in extern can happen.
from marvin import extern
from marvin.core.exceptions import MarvinUserWarning, MarvinError
from brain.utils.general.general import getDbMachine
from brain import bconfig
from brain.core.core import URLMapDict
# Inits the log
from brain.core.logger import initLog
from astropy.wcs import FITSFixedWarning
# Defines log dir.
if 'MARVIN_LOGS_DIR' in os.environ:
logFilePath = os.path.join(os.path.realpath(os.environ['MARVIN_LOGS_DIR']), 'marvin.log')
else:
logFilePath = os.path.realpath(os.path.join(os.environ['HOME'], '.marvin', 'marvin.log'))
log = initLog(logFilePath)
warnings.simplefilter('once')
warnings.filterwarnings('ignore', 'Skipped unsupported reflection of expression-based index')
warnings.filterwarnings('ignore', '(.)+size changed, may indicate binary incompatibility(.)+')
warnings.filterwarnings('ignore', category=FITSFixedWarning)
# Filters for PY3
# TODO: undestand why these warnings are issued and fix the root of the problem (JSG)
warnings.filterwarnings('ignore', 'can\'t resolve package(.)+')
warnings.filterwarnings('ignore', 'unclosed file <_io.TextIOWrapper+')
class MarvinConfig(object):
''' Global Marvin Configuration
The global configuration of Marvin. Use the config object to globally set options for
your Marvin session.
Parameters:
release (str):
The release version of the MaNGA data you want to use. Either MPL or DR.
download (bool):
Set to turn on downloading of objects with sdss_access
use_sentry (bool):
Set to turn on/off the Sentry error logging. Default is True.
add_github_message (bool):
Set to turn on/off the additional Github Issue message in MarvinErrors. Default is True.
drpall (str):
The location to your DRPall file, based on which release you have set.
mode (str):
The current mode of Marvin. Either 'auto', 'remote', or 'local'. Default is 'auto'
sasurl (str):
The url of the Marvin API on the Utah Science Archive Server (SAS)
urlmap (dict):
A dictionary containing the API routing information used by Marvin
xyorig (str):
Globally set the origin point for all your spaxel selections. Either 'center' or 'lower'.
Default is 'center'
'''
def __init__(self):
self._drpall = None
self._inapp = False
self._urlmap = None
self._xyorig = None
self._release = None
self.vermode = None
self.download = False
self.use_sentry = True
self.add_github_message = True
self._plantTree()
self._checkSDSSAccess()
self._check_manga_dirs()
self._setDbConfig()
self._checkConfig()
self._check_netrc()
self.setDefaultDrpAll()
def _checkPaths(self, name):
''' Check for the necessary path existence.
This should only run if someone already has TREE_DIR installed
but somehow does not have a SAS_BASE_DIR, MANGA_SPECTRO_REDUX, or
MANGA_SPECTRO_ANALYSIS directory
'''
name = name.upper()
if name not in os.environ:
if name == 'SAS_BASE_DIR':
path_dir = os.path.expanduser('~/sas')
elif name == 'MANGA_SPECTRO_REDUX':
path_dir = os.path.join(os.path.abspath(os.environ['SAS_BASE_DIR']), 'mangawork/manga/spectro/redux')
elif name == 'MANGA_SPECTRO_ANALYSIS':
path_dir = os.path.join(os.path.abspath(os.environ['SAS_BASE_DIR']), 'mangawork/manga/spectro/analysis')
if not os.path.exists(path_dir):
warnings.warn('no {0}_DIR found. Creating it in {1}'.format(name, path_dir))
os.makedirs(path_dir)
os.environ[name] = path_dir
def _check_netrc(self):
"""Makes sure there is a valid netrc."""
netrc_path = os.path.join(os.environ['HOME'], '.netrc')
if not os.path.exists(netrc_path):
warnings.warn('cannot find a .netrc file in your HOME directory. '
'Remote functionality may not work. Go to '
'https://api.sdss.org/doc/manga/marvin/api.html#marvin-authentication '
'for more information.', MarvinUserWarning)
return
if oct(os.stat(netrc_path).st_mode)[-3:] != '600':
warnings.warn('your .netrc file has not 600 permissions. Please fix it by '
'running chmod 600 ~/.netrc. Authentication will not work with '
'permissions different from 600.')
def _check_manga_dirs(self):
"""Check if $SAS_BASE_DIR and MANGA dirs are defined.
If they are not, creates and defines them.
"""
self._checkPaths('SAS_BASE_DIR')
self._checkPaths('MANGA_SPECTRO_REDUX')
self._checkPaths('MANGA_SPECTRO_ANALYSIS')
def setDefaultDrpAll(self, drpver=None):
"""Tries to set the default location of drpall.
Sets the drpall attribute to the location of your DRPall file, based on the
drpver. If drpver not set, it is extracted from the release attribute. It sets the
location based on the MANGA_SPECTRO_REDUX environment variable
Parameters:
drpver (str):
The DRP version to set. Defaults to the version corresponding to config.release.
"""
if not drpver:
drpver, __ = self.lookUpVersions(self.release)
self.drpall = self._getDrpAllPath(drpver)
def _getDrpAllPath(self, drpver):
"""Returns the default path for drpall, give a certain ``drpver``."""
if 'MANGA_SPECTRO_REDUX' in os.environ and drpver:
return os.path.join(os.environ['MANGA_SPECTRO_REDUX'], str(drpver),
'drpall-{0}.fits'.format(drpver))
else:
raise MarvinError('Must have the MANGA_SPECTRO_REDUX environment variable set')
############ Brain Config overrides ############
# These are configuration parameter defined in Brain.bconfig. We need
# to be able to modify them during run time, so we define properties and
# setters to do that from Marvin.config.
@property
def mode(self):
return bconfig.mode
@mode.setter
def mode(self, value):
bconfig.mode = value
@property
def sasurl(self):
return bconfig.sasurl
@sasurl.setter
def sasurl(self, value):
bconfig.sasurl = value
@property
def release(self):
return self._release
@release.setter
def release(self, value):
value = value.upper()
if value not in self._mpldict:
raise MarvinError('trying to set an invalid release version. Valid releases are: {0}'
.format(', '.join(sorted(list(self._mpldict)))))
self._release = value
drpver = self._mpldict[self.release][0]
self.drpall = self._getDrpAllPath(drpver)
@property
def session_id(self):
return bconfig.session_id
@session_id.setter
def session_id(self, value):
bconfig.session_id = value
@property
def _traceback(self):
return bconfig.traceback
@_traceback.setter
def _traceback(self, value):
bconfig.traceback = value
#################################################
@property
def urlmap(self):
"""Retrieves the URLMap the first time it is needed."""
if self._urlmap is None or (isinstance(self._urlmap, dict) and len(self._urlmap) == 0):
try:
response = Interaction('api/general/getroutemap', request_type='get')
except Exception as e:
warnings.warn('Cannot retrieve URLMap. Remote functionality will not work: {0}'.format(e),
MarvinUserWarning)
self.urlmap = URLMapDict()
else:
self.urlmap = response.getRouteMap()
return self._urlmap
@urlmap.setter
def urlmap(self, value):
"""Manually sets the URLMap."""
self._urlmap = value
arg_validate.urlmap = self._urlmap
@property
def xyorig(self):
if not self._xyorig:
self._xyorig = 'center'
return self._xyorig
@xyorig.setter
def xyorig(self, value):
assert value.lower() in ['center', 'lower'], 'xyorig must be center or lower.'
self._xyorig = value.lower()
@property
def drpall(self):
return self._drpall
@drpall.setter
def drpall(self, value):
if os.path.exists(value):
self._drpall = value
else:
self._drpall = None
warnings.warn('path {0} cannot be found. Setting drpall to None.'
.format(value), MarvinUserWarning)
def _setDbConfig(self):
''' Set the db configuration '''
self.db = getDbMachine()
def _checkConfig(self):
''' Check the config '''
# set and sort the base MPL dictionary
mpldict = {'MPL-6': ('v2_3_1', '2.1.3'),
'MPL-5': ('v2_0_1', '2.0.2'),
'MPL-4': ('v1_5_1', '1.1.1')} # , 'DR13': ('v1_5_4', None), 'DR14': ('v2_1_2', None)}
mplsorted = sorted(mpldict.items(), key=lambda p: p[1][0], reverse=True)
self._mpldict = OrderedDict(mplsorted)
# Check the versioning config
if not self.release:
topkey = list(self._mpldict)[0]
log.info('No release version set. Setting default to {0}'.format(topkey))
self.release = topkey
def setRelease(self, version):
"""Set the release version.
Parameters:
version (str):
The MPL/DR version to set, in form of MPL-X or DRXX.
Example:
>>> config.setRelease('MPL-4')
>>> config.setRelease('DR13')
"""
version = version.upper()
self.release = version
def setMPL(self, mplver):
"""As :func:`setRelease` but check that the version is an MPL."""
self.setRelease(mplver)
def setDR(self, drver):
"""As :func:`setRelease` but check that the version is a DR."""
self.setRelease(drver)
def lookUpVersions(self, release=None):
"""Retrieve the DRP and DAP versions that make up a release version.
Parameters:
release (str or None):
The release version. If ``None``, uses the currently set
``release`` value.
Returns:
drpver, dapver (tuple):
A tuple of strings of the DRP and DAP versions according
to the input MPL version
"""
release = release or self.release
try:
drpver, dapver = self._mpldict[release]
except KeyError:
raise MarvinError('MPL/DR version {0} not found in lookup table. '
'No associated DRP/DAP versions. '
'Should they be added? Check for typos.'.format(release))
return drpver, dapver
def lookUpRelease(self, drpver):
"""Retrieve the release version for a given DRP version
Parameters:
drpver (str):
The DRP version to use
Returns:
release (str):
The release version according to the input DRP version
"""
# Flip the mpldict
verdict = {val[0]: key for key, val in self._mpldict.items()}
try:
release = verdict[drpver]
except KeyError:
raise MarvinError('DRP version {0} not found in lookup table. '
'No associated MPL version. Should one be added? '
'Check for typos.'.format(drpver))
return release
def switchSasUrl(self, sasmode='utah', ngrokid=None, port=5000, test=False):
''' Switches the SAS url config attribute
Easily switch the sasurl configuration variable between
utah and local. utah sets it to the real API. Local switches to
use localhost.
Parameters:
sasmode ({'utah', 'local'}):
the SAS mode to switch to. Default is Utah
ngrokid (str):
The ngrok id to use when using a 'localhost' sas mode.
This assumes localhost server is being broadcast by ngrok
port (int):
The port of your localhost server
test (bool):
If ``True``, sets the Utah sasurl to the test production, test/marvin2
'''
assert sasmode in ['utah', 'local'], 'SAS mode can only be utah or local'
if sasmode == 'local':
if ngrokid:
self.sasurl = 'http://{0}.ngrok.io/marvin2/'.format(ngrokid)
else:
self.sasurl = 'http://localhost:{0}/marvin2/'.format(port)
elif sasmode == 'utah':
marvin_base = 'test/marvin2/' if test else 'marvin2/'
self.sasurl = 'https://api.sdss.org/{0}'.format(marvin_base)
self.urlmap = None
def forceDbOff(self):
''' Force the database to be turned off '''
config.db = None
from marvin import marvindb
marvindb.forceDbOff()
def forceDbOn(self):
''' Force the database to be reconnected '''
self._setDbConfig()
from marvin import marvindb
marvindb.forceDbOn(dbtype=self.db)
def _addExternal(self, name):
''' Adds an external product into the path '''
assert type(name) == str, 'name must be a string'
externdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'extern', name)
extern_envvar = '{0}_DIR'.format(name.upper())
os.environ[extern_envvar] = externdir
pypath = os.path.join(externdir, 'python')
if os.path.isdir(pypath):
sys.path.append(pypath)
else:
warnings.warn('Python path for external product {0} does not exist'.format(name))
def _plantTree(self):
''' Sets up the sdss tree product root '''
if 'TREE_DIR' not in os.environ:
# set up tree using marvin's extern package
self._addExternal('tree')
try:
from tree.tree import Tree
except ImportError:
self._tree = None
else:
self._tree = Tree(key='MANGA')
def _checkSDSSAccess(self):
''' Checks the client sdss_access setup '''
if 'SDSS_ACCESS_DIR' not in os.environ:
# set up sdss_access using marvin's extern package
self._addExternal('sdss_access')
try:
from sdss_access.path import Path
except ImportError:
Path = None
else:
self._sdss_access_isloaded = True
config = MarvinConfig()
# Inits the Database session and ModelClasses
from marvin.db.marvindb import MarvinDB
marvindb = MarvinDB(dbtype=config.db)
# Init MARVIN_DIR
marvindir = os.environ.get('MARVIN_DIR', None)
if not marvindir:
moduledir = os.path.dirname(os.path.abspath(__file__))
marvindir = moduledir.rsplit('/', 2)[0]
os.environ['MARVIN_DIR'] = marvindir
# Inits the URL Route Map
from marvin.api.api import Interaction
config.sasurl = 'https://api.sdss.org/marvin2/'
from marvin.api.base import arg_validate
| [
"marvin.db.marvindb.MarvinDB",
"marvin.marvindb.forceDbOff",
"marvin.api.api.Interaction",
"marvin.core.exceptions.MarvinError",
"marvin.marvindb.forceDbOn"
] | [((1283, 1303), 'brain.core.logger.initLog', 'initLog', (['logFilePath'], {}), '(logFilePath)\n', (1290, 1303), False, 'from brain.core.logger import initLog\n'), ((1305, 1334), 'warnings.simplefilter', 'warnings.simplefilter', (['"""once"""'], {}), "('once')\n", (1326, 1334), False, 'import warnings\n'), ((1335, 1432), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""', '"""Skipped unsupported reflection of expression-based index"""'], {}), "('ignore',\n 'Skipped unsupported reflection of expression-based index')\n", (1358, 1432), False, 'import warnings\n'), ((1429, 1527), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""', '"""(.)+size changed, may indicate binary incompatibility(.)+"""'], {}), "('ignore',\n '(.)+size changed, may indicate binary incompatibility(.)+')\n", (1452, 1527), False, 'import warnings\n'), ((1524, 1584), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'FITSFixedWarning'}), "('ignore', category=FITSFixedWarning)\n", (1547, 1584), False, 'import warnings\n'), ((1690, 1752), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""', '"""can\'t resolve package(.)+"""'], {}), '(\'ignore\', "can\'t resolve package(.)+")\n', (1713, 1752), False, 'import warnings\n'), ((1754, 1824), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""', '"""unclosed file <_io.TextIOWrapper+"""'], {}), "('ignore', 'unclosed file <_io.TextIOWrapper+')\n", (1777, 1824), False, 'import warnings\n'), ((15826, 15852), 'marvin.db.marvindb.MarvinDB', 'MarvinDB', ([], {'dbtype': 'config.db'}), '(dbtype=config.db)\n', (15834, 15852), False, 'from marvin.db.marvindb import MarvinDB\n'), ((15884, 15918), 'os.environ.get', 'os.environ.get', (['"""MARVIN_DIR"""', 'None'], {}), "('MARVIN_DIR', None)\n", (15898, 15918), False, 'import os\n'), ((1113, 1160), 'os.path.realpath', 'os.path.realpath', (["os.environ['MARVIN_LOGS_DIR']"], {}), "(os.environ['MARVIN_LOGS_DIR'])\n", (1129, 1160), False, 'import os\n'), ((1217, 1274), 'os.path.join', 'os.path.join', (["os.environ['HOME']", '""".marvin"""', '"""marvin.log"""'], {}), "(os.environ['HOME'], '.marvin', 'marvin.log')\n", (1229, 1274), False, 'import os\n'), ((4668, 4710), 'os.path.join', 'os.path.join', (["os.environ['HOME']", '""".netrc"""'], {}), "(os.environ['HOME'], '.netrc')\n", (4680, 4710), False, 'import os\n'), ((9385, 9406), 'os.path.exists', 'os.path.exists', (['value'], {}), '(value)\n', (9399, 9406), False, 'import os\n'), ((9714, 9728), 'brain.utils.general.general.getDbMachine', 'getDbMachine', ([], {}), '()\n', (9726, 9728), False, 'from brain.utils.general.general import getDbMachine\n'), ((10147, 10169), 'collections.OrderedDict', 'OrderedDict', (['mplsorted'], {}), '(mplsorted)\n', (10158, 10169), False, 'from collections import OrderedDict\n'), ((14083, 14104), 'marvin.marvindb.forceDbOff', 'marvindb.forceDbOff', ([], {}), '()\n', (14102, 14104), False, 'from marvin import marvindb\n'), ((14256, 14290), 'marvin.marvindb.forceDbOn', 'marvindb.forceDbOn', ([], {'dbtype': 'self.db'}), '(dbtype=self.db)\n', (14274, 14290), False, 'from marvin import marvindb\n'), ((14650, 14683), 'os.path.join', 'os.path.join', (['externdir', '"""python"""'], {}), "(externdir, 'python')\n", (14662, 14683), False, 'import os\n'), ((14695, 14716), 'os.path.isdir', 'os.path.isdir', (['pypath'], {}), '(pypath)\n', (14708, 14716), False, 'import os\n'), ((15969, 15994), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (15984, 15994), False, 'import os\n'), ((4727, 4753), 'os.path.exists', 'os.path.exists', (['netrc_path'], {}), '(netrc_path)\n', (4741, 4753), False, 'import os\n'), ((4767, 4994), 'warnings.warn', 'warnings.warn', (['"""cannot find a .netrc file in your HOME directory. Remote functionality may not work. Go to https://api.sdss.org/doc/manga/marvin/api.html#marvin-authentication for more information."""', 'MarvinUserWarning'], {}), "(\n 'cannot find a .netrc file in your HOME directory. Remote functionality may not work. Go to https://api.sdss.org/doc/manga/marvin/api.html#marvin-authentication for more information.'\n , MarvinUserWarning)\n", (4780, 4994), False, 'import warnings\n'), ((5163, 5342), 'warnings.warn', 'warnings.warn', (['"""your .netrc file has not 600 permissions. Please fix it by running chmod 600 ~/.netrc. Authentication will not work with permissions different from 600."""'], {}), "(\n 'your .netrc file has not 600 permissions. Please fix it by running chmod 600 ~/.netrc. Authentication will not work with permissions different from 600.'\n )\n", (5176, 5342), False, 'import warnings\n'), ((6690, 6763), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""Must have the MANGA_SPECTRO_REDUX environment variable set"""'], {}), "('Must have the MANGA_SPECTRO_REDUX environment variable set')\n", (6701, 6763), False, 'from marvin.core.exceptions import MarvinUserWarning, MarvinError\n'), ((14730, 14753), 'sys.path.append', 'sys.path.append', (['pypath'], {}), '(pypath)\n', (14745, 14753), False, 'import sys\n'), ((3985, 4012), 'os.path.expanduser', 'os.path.expanduser', (['"""~/sas"""'], {}), "('~/sas')\n", (4003, 4012), False, 'import os\n'), ((4371, 4395), 'os.path.exists', 'os.path.exists', (['path_dir'], {}), '(path_dir)\n', (4385, 4395), False, 'import os\n'), ((4506, 4527), 'os.makedirs', 'os.makedirs', (['path_dir'], {}), '(path_dir)\n', (4517, 4527), False, 'import os\n'), ((8400, 8458), 'marvin.api.api.Interaction', 'Interaction', (['"""api/general/getroutemap"""'], {'request_type': '"""get"""'}), "('api/general/getroutemap', request_type='get')\n", (8411, 8458), False, 'from marvin.api.api import Interaction\n'), ((14488, 14513), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (14503, 14513), False, 'import os\n'), ((15248, 15265), 'tree.tree.Tree', 'Tree', ([], {'key': '"""MANGA"""'}), "(key='MANGA')\n", (15252, 15265), False, 'from tree.tree import Tree\n'), ((8680, 8692), 'brain.core.core.URLMapDict', 'URLMapDict', ([], {}), '()\n', (8690, 8692), False, 'from brain.core.core import URLMapDict\n'), ((4101, 4144), 'os.path.abspath', 'os.path.abspath', (["os.environ['SAS_BASE_DIR']"], {}), "(os.environ['SAS_BASE_DIR'])\n", (4116, 4144), False, 'import os\n'), ((5107, 5126), 'os.stat', 'os.stat', (['netrc_path'], {}), '(netrc_path)\n', (5114, 5126), False, 'import os\n'), ((4270, 4313), 'os.path.abspath', 'os.path.abspath', (["os.environ['SAS_BASE_DIR']"], {}), "(os.environ['SAS_BASE_DIR'])\n", (4285, 4313), False, 'import os\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
'''
@Desc: Module for providing logging facilities to marvin
'''
import logging
import sys
import time
import os
from marvin.codes import (SUCCESS,
FAILED
)
from marvin.cloudstackException import GetDetailExceptionInfo
from marvin.lib.utils import random_gen
class MarvinLog:
'''
@Name : MarvinLog
@Desc : provides interface for logging to marvin
@Input : logger_name : name for logger
'''
logFormat = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
_instance = None
def __new__(cls, logger_name):
if not cls._instance:
cls._instance = super(MarvinLog, cls).__new__(cls)
return cls._instance
def __init__(self, logger_name):
'''
@Name: __init__
@Input: logger_name for logger
'''
self.__loggerName = logger_name
'''
Logger for Logging Info
'''
self.__logger = None
'''
Log Folder Directory
'''
self.__logFolderDir = None
self.__setLogger()
def __setLogger(self):
'''
@Name : __setLogger
@Desc : Sets the Logger and Level
'''
self.__logger = logging.getLogger(self.__loggerName)
self.__logger.setLevel(logging.DEBUG)
def __setLogHandler(self, log_file_path,
log_format=None,
log_level=logging.DEBUG):
'''
@Name : __setLogHandler
@Desc: Adds the given Log handler to the current logger
@Input: log_file_path: Log File Path as where to store the logs
log_format : Format of log messages to be dumped
log_level : Determines the level of logging for this logger
@Output: SUCCESS if no issues else FAILED
'''
try:
if log_file_path is not None:
stream = logging.FileHandler(log_file_path)
else:
stream = logging.StreamHandler(stream=sys.stdout)
if log_format is not None:
stream.setFormatter(log_format)
else:
stream.setFormatter(self.__class__.logFormat)
stream.setLevel(log_level)
self.__logger.addHandler(stream)
return SUCCESS
except Exception as e:
print("\nException Occurred Under " \
"__setLogHandler %s" % GetDetailExceptionInfo(e))
return FAILED
def __cleanPreviousLogs(self, logfolder_to_remove):
'''
@Name : __cleanPreviousLogs
@Desc : Removes the Previous Logs
@Return: N\A
@Input: logfolder_to_remove: Path of Log to remove
'''
try:
if os.path.isdir(logfolder_to_remove):
os.rmdir(logfolder_to_remove)
except Exception as e:
print("\n Exception Occurred Under __cleanPreviousLogs :%s" % \
GetDetailExceptionInfo(e))
return FAILED
def getLogger(self):
'''
@Name:getLogger
@Desc : Returns the Logger
'''
return self.__logger
def getLogFolderPath(self):
'''
@Name : getLogFolderPath
@Desc : Returns the final log directory path for marvin run
'''
return self.__logFolderDir
def createLogs(self,
test_module_name=None,
log_cfg=None,
user_provided_logpath=None, use_temp_path=True):
'''
@Name : createLogs
@Desc : Gets the Logger with file paths initialized and created
@Inputs :test_module_name: Test Module Name to use for logs while
creating log folder path
log_cfg: Log Configuration provided inside of
Configuration
user_provided_logpath:LogPath provided by user
If user provided log path
is available, then one in cfg
will not be picked up.
use_temp_path: Boolean value which specifies either logs will
be prepended by random path or not.
@Output : SUCCESS\FAILED
'''
try:
temp_ts = time.strftime("%b_%d_%Y_%H_%M_%S", time.localtime())
if test_module_name is None:
temp_path = temp_ts + "_" + random_gen()
else:
temp_path = str(test_module_name) + "__" + str(temp_ts) + "_" + random_gen()
if user_provided_logpath:
temp_dir = os.path.join(user_provided_logpath, "MarvinLogs")
elif ((log_cfg is not None) and
('LogFolderPath' in list(log_cfg.__dict__.keys())) and
(log_cfg.__dict__.get('LogFolderPath') is not None)):
temp_dir = os.path.join(log_cfg.__dict__.get('LogFolderPath'), "MarvinLogs")
if use_temp_path == True:
self.__logFolderDir = os.path.join(temp_dir, temp_path)
else:
if test_module_name == None:
self.__logFolderDir = temp_dir
else:
self.__logFolderDir = os.path.join(temp_dir, str(test_module_name))
print("\n==== Log Folder Path: %s. All logs will be available here ====" % str(self.__logFolderDir))
os.makedirs(self.__logFolderDir)
'''
Log File Paths
1. FailedExceptionLog
2. RunLog contains the complete Run Information for Test Run
3. ResultFile contains the TC result information for Test Run
'''
tc_failed_exception_log = os.path.join(self.__logFolderDir, "failed_plus_exceptions.txt")
tc_run_log = os.path.join(self.__logFolderDir, "runinfo.txt")
if self.__setLogHandler(tc_run_log,
log_level=logging.DEBUG) != FAILED:
self.__setLogHandler(tc_failed_exception_log,
log_level=logging.FATAL)
return SUCCESS
return FAILED
except Exception as e:
print("\n Exception Occurred Under createLogs :%s" % \
GetDetailExceptionInfo(e))
return FAILED
| [
"marvin.cloudstackException.GetDetailExceptionInfo",
"marvin.lib.utils.random_gen"
] | [((1268, 1330), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(levelname)s - %(message)s')\n", (1285, 1330), False, 'import logging\n'), ((2025, 2061), 'logging.getLogger', 'logging.getLogger', (['self.__loggerName'], {}), '(self.__loggerName)\n', (2042, 2061), False, 'import logging\n'), ((3546, 3580), 'os.path.isdir', 'os.path.isdir', (['logfolder_to_remove'], {}), '(logfolder_to_remove)\n', (3559, 3580), False, 'import os\n'), ((6248, 6280), 'os.makedirs', 'os.makedirs', (['self.__logFolderDir'], {}), '(self.__logFolderDir)\n', (6259, 6280), False, 'import os\n'), ((6561, 6624), 'os.path.join', 'os.path.join', (['self.__logFolderDir', '"""failed_plus_exceptions.txt"""'], {}), "(self.__logFolderDir, 'failed_plus_exceptions.txt')\n", (6573, 6624), False, 'import os\n'), ((6650, 6698), 'os.path.join', 'os.path.join', (['self.__logFolderDir', '"""runinfo.txt"""'], {}), "(self.__logFolderDir, 'runinfo.txt')\n", (6662, 6698), False, 'import os\n'), ((2706, 2740), 'logging.FileHandler', 'logging.FileHandler', (['log_file_path'], {}), '(log_file_path)\n', (2725, 2740), False, 'import logging\n'), ((2784, 2824), 'logging.StreamHandler', 'logging.StreamHandler', ([], {'stream': 'sys.stdout'}), '(stream=sys.stdout)\n', (2805, 2824), False, 'import logging\n'), ((3598, 3627), 'os.rmdir', 'os.rmdir', (['logfolder_to_remove'], {}), '(logfolder_to_remove)\n', (3606, 3627), False, 'import os\n'), ((5157, 5173), 'time.localtime', 'time.localtime', ([], {}), '()\n', (5171, 5173), False, 'import time\n'), ((5451, 5500), 'os.path.join', 'os.path.join', (['user_provided_logpath', '"""MarvinLogs"""'], {}), "(user_provided_logpath, 'MarvinLogs')\n", (5463, 5500), False, 'import os\n'), ((5864, 5897), 'os.path.join', 'os.path.join', (['temp_dir', 'temp_path'], {}), '(temp_dir, temp_path)\n', (5876, 5897), False, 'import os\n'), ((5261, 5273), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (5271, 5273), False, 'from marvin.lib.utils import random_gen\n'), ((5372, 5384), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (5382, 5384), False, 'from marvin.lib.utils import random_gen\n'), ((3226, 3251), 'marvin.cloudstackException.GetDetailExceptionInfo', 'GetDetailExceptionInfo', (['e'], {}), '(e)\n', (3248, 3251), False, 'from marvin.cloudstackException import GetDetailExceptionInfo\n'), ((3753, 3778), 'marvin.cloudstackException.GetDetailExceptionInfo', 'GetDetailExceptionInfo', (['e'], {}), '(e)\n', (3775, 3778), False, 'from marvin.cloudstackException import GetDetailExceptionInfo\n'), ((7117, 7142), 'marvin.cloudstackException.GetDetailExceptionInfo', 'GetDetailExceptionInfo', (['e'], {}), '(e)\n', (7139, 7142), False, 'from marvin.cloudstackException import GetDetailExceptionInfo\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#Test from the Marvin - Testing in Python wiki
import time
#All tests inherit from cloudstackTestCase
from marvin.cloudstackTestCase import cloudstackTestCase
#Import Integration Libraries
#base - contains all resources as entities and defines create, delete, list operations on them
from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock
#utils - utility classes for common cleanup, external library wrappers etc
from marvin.lib.utils import cleanup_resources, validateList
#common - commonly used methods for all tests are listed here
from marvin.lib.common import get_zone, get_domain, get_template
from marvin.codes import PASS
from nose.plugins.attrib import attr
class TestDeployVMHA(cloudstackTestCase):
"""Test VM HA
"""
def setUp(self):
self.testdata = self.testClient.getParsedTestDataConfig()
self.apiclient = self.testClient.getApiClient()
# Get Zone, Domain and Default Built-in template
self.domain = get_domain(self.apiclient)
self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
self.testdata["mode"] = self.zone.networktype
self.template = get_template(self.apiclient, self.zone.id, self.testdata["ostype"])
self.hosts = []
suitablecluster = None
clusters = Cluster.list(self.apiclient)
self.assertTrue(isinstance(clusters, list) and len(clusters) > 0, msg = "No clusters found")
for cluster in clusters:
self.hosts = Host.list(self.apiclient, clusterid=cluster.id, type='Routing')
if isinstance(self.hosts, list) and len(self.hosts) >= 2:
suitablecluster = cluster
break
self.assertEqual(validateList(self.hosts)[0], PASS, "hosts list validation failed")
if len(self.hosts) < 2:
self.skipTest("Atleast 2 hosts required in cluster for VM HA test")
#update host tags
for host in self.hosts:
Host.update(self.apiclient, id=host.id, hosttags=self.testdata["service_offerings"]["hasmall"]["hosttags"])
#create a user account
self.account = Account.create(
self.apiclient,
self.testdata["account"],
domainid=self.domain.id
)
#create a service offering
self.service_offering = ServiceOffering.create(
self.apiclient,
self.testdata["service_offerings"]["hasmall"]
)
#deploy ha vm
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.testdata["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id
)
list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s"\
% self.virtual_machine.id
)
self.assertTrue(isinstance(list_vms, list) and len(list_vms) == 1, msg = "List VM response was empty")
self.virtual_machine = list_vms[0]
self.mock_checkhealth = SimulatorMock.create(
apiclient=self.apiclient,
command="CheckHealthCommand",
zoneid=suitablecluster.zoneid,
podid=suitablecluster.podid,
clusterid=suitablecluster.id,
hostid=self.virtual_machine.hostid,
value="result:fail")
self.mock_ping = SimulatorMock.create(
apiclient=self.apiclient,
command="PingCommand",
zoneid=suitablecluster.zoneid,
podid=suitablecluster.podid,
clusterid=suitablecluster.id,
hostid=self.virtual_machine.hostid,
value="result:fail")
self.mock_checkvirtualmachine = SimulatorMock.create(
apiclient=self.apiclient,
command="CheckVirtualMachineCommand",
zoneid=suitablecluster.zoneid,
podid=suitablecluster.podid,
clusterid=suitablecluster.id,
hostid=self.virtual_machine.hostid,
value="result:fail")
self.mock_pingtest = SimulatorMock.create(
apiclient=self.apiclient,
command="PingTestCommand",
zoneid=suitablecluster.zoneid,
podid=suitablecluster.podid,
value="result:fail")
self.mock_checkonhost_list = []
for host in self.hosts:
if host.id != self.virtual_machine.hostid:
self.mock_checkonhost_list.append(SimulatorMock.create(
apiclient=self.apiclient,
command="CheckOnHostCommand",
zoneid=suitablecluster.zoneid,
podid=suitablecluster.podid,
clusterid=suitablecluster.id,
hostid=host.id,
value="result:fail"))
#build cleanup list
self.cleanup = [
self.service_offering,
self.account,
self.mock_checkhealth,
self.mock_ping,
self.mock_checkvirtualmachine,
self.mock_pingtest
]
self.cleanup = self.cleanup + self.mock_checkonhost_list
@attr(tags = ['advanced'], required_hardware="simulator only")
def test_vm_ha(self):
"""Test VM HA
# Validate the following:
# VM started on other host in cluster
"""
#wait for VM to HA
ping_timeout = Configurations.list(self.apiclient, name="ping.timeout")
ping_interval = Configurations.list(self.apiclient, name="ping.interval")
total_duration = int(float(ping_timeout[0].value) * float(ping_interval[0].value))
time.sleep(total_duration)
duration = 0
vm = None
while duration < total_duration:
list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
self.assertTrue(isinstance(list_vms, list) and len(list_vms) == 1, msg = "List VM response was empty")
vm = list_vms[0]
if vm.hostid != self.virtual_machine.hostid and vm.state == "Running":
break
else:
time.sleep(10)
duration = duration + 10
self.assertEqual(
vm.id,
self.virtual_machine.id,
"VM ids do not match")
self.assertEqual(
vm.name,
self.virtual_machine.name,
"VM names do not match")
self.assertEqual(
vm.state,
"Running",
msg="VM is not in Running state")
self.assertNotEqual(
vm.hostid,
self.virtual_machine.hostid,
msg="VM is not started on another host as part of HA")
def tearDown(self):
try:
for host in self.hosts:
Host.update(self.apiclient, id=host.id, hosttags="")
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
| [
"marvin.lib.common.get_domain",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.utils.validateList",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.Host.list",
"marvin.lib.base.Cluster.list",
"marvin.lib.base.Host.update",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.base.Virtu... | [((6162, 6221), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""simulator only"""'}), "(tags=['advanced'], required_hardware='simulator only')\n", (6166, 6221), False, 'from nose.plugins.attrib import attr\n'), ((1815, 1841), 'marvin.lib.common.get_domain', 'get_domain', (['self.apiclient'], {}), '(self.apiclient)\n', (1825, 1841), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((2001, 2068), 'marvin.lib.common.get_template', 'get_template', (['self.apiclient', 'self.zone.id', "self.testdata['ostype']"], {}), "(self.apiclient, self.zone.id, self.testdata['ostype'])\n", (2013, 2068), False, 'from marvin.lib.common import get_zone, get_domain, get_template\n'), ((2144, 2172), 'marvin.lib.base.Cluster.list', 'Cluster.list', (['self.apiclient'], {}), '(self.apiclient)\n', (2156, 2172), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((2967, 3053), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testdata['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testdata['account'], domainid=self.\n domain.id)\n", (2981, 3053), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((3162, 3252), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.testdata['service_offerings']['hasmall']"], {}), "(self.apiclient, self.testdata['service_offerings'][\n 'hasmall'])\n", (3184, 3252), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((3335, 3575), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.testdata['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering.id, templateid=self.\n template.id)\n", (3356, 3575), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((3675, 3738), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (3694, 3738), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((4069, 4306), 'marvin.lib.base.SimulatorMock.create', 'SimulatorMock.create', ([], {'apiclient': 'self.apiclient', 'command': '"""CheckHealthCommand"""', 'zoneid': 'suitablecluster.zoneid', 'podid': 'suitablecluster.podid', 'clusterid': 'suitablecluster.id', 'hostid': 'self.virtual_machine.hostid', 'value': '"""result:fail"""'}), "(apiclient=self.apiclient, command='CheckHealthCommand',\n zoneid=suitablecluster.zoneid, podid=suitablecluster.podid, clusterid=\n suitablecluster.id, hostid=self.virtual_machine.hostid, value='result:fail'\n )\n", (4089, 4306), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((4403, 4633), 'marvin.lib.base.SimulatorMock.create', 'SimulatorMock.create', ([], {'apiclient': 'self.apiclient', 'command': '"""PingCommand"""', 'zoneid': 'suitablecluster.zoneid', 'podid': 'suitablecluster.podid', 'clusterid': 'suitablecluster.id', 'hostid': 'self.virtual_machine.hostid', 'value': '"""result:fail"""'}), "(apiclient=self.apiclient, command='PingCommand',\n zoneid=suitablecluster.zoneid, podid=suitablecluster.podid, clusterid=\n suitablecluster.id, hostid=self.virtual_machine.hostid, value='result:fail'\n )\n", (4423, 4633), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((4745, 4991), 'marvin.lib.base.SimulatorMock.create', 'SimulatorMock.create', ([], {'apiclient': 'self.apiclient', 'command': '"""CheckVirtualMachineCommand"""', 'zoneid': 'suitablecluster.zoneid', 'podid': 'suitablecluster.podid', 'clusterid': 'suitablecluster.id', 'hostid': 'self.virtual_machine.hostid', 'value': '"""result:fail"""'}), "(apiclient=self.apiclient, command=\n 'CheckVirtualMachineCommand', zoneid=suitablecluster.zoneid, podid=\n suitablecluster.podid, clusterid=suitablecluster.id, hostid=self.\n virtual_machine.hostid, value='result:fail')\n", (4765, 4991), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((5091, 5254), 'marvin.lib.base.SimulatorMock.create', 'SimulatorMock.create', ([], {'apiclient': 'self.apiclient', 'command': '"""PingTestCommand"""', 'zoneid': 'suitablecluster.zoneid', 'podid': 'suitablecluster.podid', 'value': '"""result:fail"""'}), "(apiclient=self.apiclient, command='PingTestCommand',\n zoneid=suitablecluster.zoneid, podid=suitablecluster.podid, value=\n 'result:fail')\n", (5111, 5254), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((6416, 6472), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""ping.timeout"""'}), "(self.apiclient, name='ping.timeout')\n", (6435, 6472), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((6497, 6554), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""ping.interval"""'}), "(self.apiclient, name='ping.interval')\n", (6516, 6554), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((6654, 6680), 'time.sleep', 'time.sleep', (['total_duration'], {}), '(total_duration)\n', (6664, 6680), False, 'import time\n'), ((2332, 2395), 'marvin.lib.base.Host.list', 'Host.list', (['self.apiclient'], {'clusterid': 'cluster.id', 'type': '"""Routing"""'}), "(self.apiclient, clusterid=cluster.id, type='Routing')\n", (2341, 2395), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((2804, 2916), 'marvin.lib.base.Host.update', 'Host.update', (['self.apiclient'], {'id': 'host.id', 'hosttags': "self.testdata['service_offerings']['hasmall']['hosttags']"}), "(self.apiclient, id=host.id, hosttags=self.testdata[\n 'service_offerings']['hasmall']['hosttags'])\n", (2815, 2916), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((6785, 6848), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (6804, 6848), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((7862, 7909), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (7879, 7909), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((2555, 2579), 'marvin.lib.utils.validateList', 'validateList', (['self.hosts'], {}), '(self.hosts)\n', (2567, 2579), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((7132, 7146), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (7142, 7146), False, 'import time\n'), ((7796, 7848), 'marvin.lib.base.Host.update', 'Host.update', (['self.apiclient'], {'id': 'host.id', 'hosttags': '""""""'}), "(self.apiclient, id=host.id, hosttags='')\n", (7807, 7848), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n'), ((5484, 5696), 'marvin.lib.base.SimulatorMock.create', 'SimulatorMock.create', ([], {'apiclient': 'self.apiclient', 'command': '"""CheckOnHostCommand"""', 'zoneid': 'suitablecluster.zoneid', 'podid': 'suitablecluster.podid', 'clusterid': 'suitablecluster.id', 'hostid': 'host.id', 'value': '"""result:fail"""'}), "(apiclient=self.apiclient, command='CheckOnHostCommand',\n zoneid=suitablecluster.zoneid, podid=suitablecluster.podid, clusterid=\n suitablecluster.id, hostid=host.id, value='result:fail')\n", (5504, 5696), False, 'from marvin.lib.base import Account, VirtualMachine, Cluster, Host, ServiceOffering, Configurations, SimulatorMock\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import (createVolume,
createTemplate)
from marvin.lib.base import (Volume,
Iso,
VirtualMachine,
Template,
Snapshot,
SecurityGroup,
Account,
Zone,
Network,
NetworkOffering,
DiskOffering,
ServiceOffering,
VmSnapshot,
SnapshotPolicy,
SSHKeyPair,
Resources,
Configurations,
VpnCustomerGateway,
Hypervisor,
VpcOffering,
VPC,
NetworkACL)
from marvin.lib.common import (get_zone,
get_domain,
get_template,
list_os_types)
from marvin.lib.utils import (validateList,
cleanup_resources,
random_gen)
from marvin.codes import (PASS, FAIL, EMPTY_LIST)
from nose.plugins.attrib import attr
import time
class TestIsos(cloudstackTestCase):
@classmethod
def setUpClass(cls):
try:
cls._cleanup = []
cls.testClient = super(TestIsos, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Domain, Zone, Template
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.services['mode'] = cls.zone.networktype
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
# Getting authentication for user in newly created Account
cls.user = cls.account.user[0]
cls.userapiclient = cls.testClient.getUserApiClient(cls.user.username, cls.domain.name)
cls._cleanup.append(cls.account)
except Exception as e:
cls.tearDownClass()
raise Exception("Warning: Exception in setup : %s" % e)
return
def setUp(self):
self.apiClient = self.testClient.getApiClient()
self.cleanup = []
def tearDown(self):
#Clean up, terminate the created resources
cleanup_resources(self.apiClient, self.cleanup)
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def __verify_values(self, expected_vals, actual_vals):
"""
@Desc: Function to verify expected and actual values
@Steps:
Step1: Initializing return flag to True
Step1: Verifying length of expected and actual dictionaries is matching.
If not matching returning false
Step2: Listing all the keys from expected dictionary
Step3: Looping through each key from step2 and verifying expected and actual dictionaries have same value
If not making return flag to False
Step4: returning the return flag after all the values are verified
"""
return_flag = True
if len(expected_vals) != len(actual_vals):
return False
keys = expected_vals.keys()
for i in range(0, len(expected_vals)):
exp_val = expected_vals[keys[i]]
act_val = actual_vals[keys[i]]
if exp_val == act_val:
return_flag = return_flag and True
else:
return_flag = return_flag and False
self.debug("expected Value: %s, is not matching with actual value: %s" % (
exp_val,
act_val
))
return return_flag
@attr(tags=["advanced", "basic", "provisioning"])
def test_01_list_isos_pagination(self):
"""
@Desc: Test to List ISO's pagination
@steps:
Step1: Listing all the ISO's for a user
Step2: Verifying that no ISO's are listed
Step3: Creating (page size + 1) number of ISO's
Step4: Listing all the ISO's again for a user
Step5: Verifying that list size is (page size + 1)
Step6: Listing all the ISO's in page1
Step7: Verifying that list size is (page size)
Step8: Listing all the ISO's in page2
Step9: Verifying that list size is 1
Step10: Listing the ISO's by Id
Step11: Verifying if the ISO is downloaded and ready.
If yes the continuing
If not waiting and checking for iso to be ready till timeout
Step12: Deleting the ISO present in page 2
Step13: Listing all the ISO's in page2
Step14: Verifying that no ISO's are listed
"""
# Listing all the ISO's for a User
list_iso_before = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"]
)
# Verifying that no ISOs are listed
self.assertIsNone(
list_iso_before,
"ISOs listed for newly created User"
)
self.services["iso"]["zoneid"] = self.zone.id
# Creating pagesize + 1 number of ISO's
for i in range(0, (self.services["pagesize"] + 1)):
iso_created = Iso.create(
self.userapiclient,
self.services["iso"]
)
self.assertIsNotNone(
iso_created,
"ISO creation failed"
)
if(i < self.services["pagesize"]):
self.cleanup.append(iso_created)
# Listing all the ISO's for a User
list_iso_after = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"]
)
status = validateList(list_iso_after)
self.assertEquals(
PASS,
status[0],
"ISO's creation failed"
)
# Verifying that list size is pagesize + 1
self.assertEquals(
self.services["pagesize"] + 1,
len(list_iso_after),
"Failed to create pagesize + 1 number of ISO's"
)
# Listing all the ISO's in page 1
list_iso_page1 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
page=1,
pagesize=self.services["pagesize"]
)
status = validateList(list_iso_page1)
self.assertEquals(
PASS,
status[0],
"Failed to list ISO's in page 1"
)
# Verifying the list size to be equal to pagesize
self.assertEquals(
self.services["pagesize"],
len(list_iso_page1),
"Size of ISO's in page 1 is not matching"
)
# Listing all the Templates in page 2
list_iso_page2 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
page=2,
pagesize=self.services["pagesize"]
)
status = validateList(list_iso_page2)
self.assertEquals(
PASS,
status[0],
"Failed to list ISo's in page 2"
)
# Verifying the list size to be equal to 1
self.assertEquals(
1,
len(list_iso_page2),
"Size of ISO's in page 2 is not matching"
)
# Verifying the state of the ISO to be ready. If not waiting for state to become ready
iso_ready = False
count = 0
while iso_ready is False:
list_iso = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
id=iso_created.id
)
status = validateList(list_iso)
self.assertEquals(
PASS,
status[0],
"Failed to list ISO by Id"
)
if list_iso[0].isready is True:
iso_ready = True
elif (str(list_iso[0].status) == "Error"):
self.fail("Created ISO is in Errored state")
break
elif count > 10:
self.fail("Timed out before ISO came into ready state")
break
else:
time.sleep(self.services["sleep"])
count = count + 1
# Deleting the ISO present in page 2
Iso.delete(
iso_created,
self.userapiclient
)
# Listing all the ISO's in page 2 again
list_iso_page2 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
page=2,
pagesize=self.services["pagesize"]
)
# Verifying that there are no ISO's listed
self.assertIsNone(
list_iso_page2,
"ISO's not deleted from page 2"
)
del self.services["iso"]["zoneid"]
return
@attr(tags=["advanced", "basic", "provisioning"])
def test_02_download_iso(self):
"""
@Desc: Test to Download ISO
@steps:
Step1: Listing all the ISO's for a user
Step2: Verifying that no ISO's are listed
Step3: Creating an ISO
Step4: Listing all the ISO's again for a user
Step5: Verifying that list size is 1
Step6: Verifying if the ISO is in ready state.
If yes the continuing
If not waiting and checking for template to be ready till timeout
Step7: Downloading the ISO (Extract)
Step8: Verifying the details of downloaded ISO
"""
# Listing all the ISO's for a User
list_iso_before = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"]
)
# Verifying that no ISOs are listed
self.assertIsNone(
list_iso_before,
"ISOs listed for newly created User"
)
self.services["iso"]["zoneid"] = self.zone.id
self.services["iso"]["isextractable"] = True
# Creating an ISO's
iso_created = Iso.create(
self.userapiclient,
self.services["iso"]
)
self.assertIsNotNone(
iso_created,
"ISO creation failed"
)
self.cleanup.append(iso_created)
# Listing all the ISO's for a User
list_iso_after = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"]
)
status = validateList(list_iso_after)
self.assertEquals(
PASS,
status[0],
"ISO's creation failed"
)
# Verifying that list size is 1
self.assertEquals(
1,
len(list_iso_after),
"Failed to create an ISO's"
)
# Verifying the state of the ISO to be ready. If not waiting for state to become ready
iso_ready = False
count = 0
while iso_ready is False:
list_iso = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
id=iso_created.id
)
status = validateList(list_iso)
self.assertEquals(
PASS,
status[0],
"Failed to list ISO by Id"
)
if list_iso[0].isready is True:
iso_ready = True
elif (str(list_iso[0].status) == "Error"):
self.fail("Created ISO is in Errored state")
break
elif count > 10:
self.fail("Timed out before ISO came into ready state")
break
else:
time.sleep(self.services["sleep"])
count = count + 1
# Downloading the ISO
download_iso = Iso.extract(
self.userapiclient,
iso_created.id,
mode="HTTP_DOWNLOAD",
zoneid=self.zone.id
)
self.assertIsNotNone(
download_iso,
"Download ISO failed"
)
# Verifying the details of downloaded ISO
self.assertEquals(
"DOWNLOAD_URL_CREATED",
download_iso.state,
"Download URL not created for ISO"
)
self.assertIsNotNone(
download_iso.url,
"Download URL not created for ISO"
)
self.assertEquals(
iso_created.id,
download_iso.id,
"Download ISO details are not same as ISO created"
)
del self.services["iso"]["zoneid"]
del self.services["iso"]["isextractable"]
return
@attr(tags=["advanced", "basic", "provisioning"])
def test_03_edit_iso_details(self):
"""
@Desc: Test to Edit ISO name, displaytext, OSType
@steps:
Step1: Listing all the ISO's for a user
Step2: Verifying that no ISO's are listed
Step3: Creating an ISO
Step4: Listing all the ISO's again for a user
Step5: Verifying that list size is 1
Step6: Verifying if the ISO is in ready state.
If yes the continuing
If not waiting and checking for template to be ready till timeout
Step7: Editing the ISO's name, displaytext
Step8: Verifying that ISO name and displaytext are edited
Step9: Editing the ISO name, displaytext, ostypeid
Step10: Verifying that ISO name, displaytext and ostypeid are edited
"""
# Listing all the ISO's for a User
list_iso_before = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"]
)
# Verifying that no ISOs are listed
self.assertIsNone(
list_iso_before,
"ISOs listed for newly created User"
)
self.services["iso"]["zoneid"] = self.zone.id
# Creating an ISO's
iso_created = Iso.create(
self.userapiclient,
self.services["iso"]
)
self.assertIsNotNone(
iso_created,
"ISO creation failed"
)
self.cleanup.append(iso_created)
# Listing all the ISO's for a User
list_iso_after = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"]
)
status = validateList(list_iso_after)
self.assertEquals(
PASS,
status[0],
"ISO's creation failed"
)
# Verifying that list size is 1
self.assertEquals(
1,
len(list_iso_after),
"Failed to create an ISO's"
)
# Verifying the state of the ISO to be ready. If not waiting for state to become ready
iso_ready = False
count = 0
while iso_ready is False:
list_iso = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
id=iso_created.id
)
status = validateList(list_iso)
self.assertEquals(
PASS,
status[0],
"Failed to list ISO by Id"
)
if list_iso[0].isready is True:
iso_ready = True
elif (str(list_iso[0].status) == "Error"):
self.fail("Created ISO is in Errored state")
break
elif count > 10:
self.fail("Timed out before ISO came into ready state")
break
else:
time.sleep(self.services["sleep"])
count = count + 1
# Editing the ISO name, displaytext
edited_iso = Iso.update(
iso_created,
self.userapiclient,
name="NewISOName",
displaytext="NewISODisplayText"
)
self.assertIsNotNone(
edited_iso,
"Editing ISO failed"
)
# Verifying the details of edited template
expected_dict = {
"id":iso_created.id,
"name":"NewISOName",
"displaytest":"NewISODisplayText",
"account":iso_created.account,
"domainid":iso_created.domainid,
"isfeatured":iso_created.isfeatured,
"ostypeid":iso_created.ostypeid,
"ispublic":iso_created.ispublic,
}
actual_dict = {
"id":edited_iso.id,
"name":edited_iso.name,
"displaytest":edited_iso.displaytext,
"account":edited_iso.account,
"domainid":edited_iso.domainid,
"isfeatured":edited_iso.isfeatured,
"ostypeid":edited_iso.ostypeid,
"ispublic":edited_iso.ispublic,
}
edit_iso_status = self.__verify_values(
expected_dict,
actual_dict
)
self.assertEqual(
True,
edit_iso_status,
"Edited ISO details are not as expected"
)
# Editing the ISO name, displaytext, ostypeid
ostype_list = list_os_types(self.userapiclient)
status = validateList(ostype_list)
self.assertEquals(
PASS,
status[0],
"Failed to list OS Types"
)
for i in range(0, len(ostype_list)):
if ostype_list[i].id != iso_created.ostypeid:
newostypeid = ostype_list[i].id
break
edited_iso = Iso.update(
iso_created,
self.userapiclient,
name=iso_created.name,
displaytext=iso_created.displaytext,
ostypeid=newostypeid
)
self.assertIsNotNone(
edited_iso,
"Editing ISO failed"
)
# Verifying the details of edited template
expected_dict = {
"id":iso_created.id,
"name":iso_created.name,
"displaytest":iso_created.displaytext,
"account":iso_created.account,
"domainid":iso_created.domainid,
"isfeatured":iso_created.isfeatured,
"ostypeid":newostypeid,
"ispublic":iso_created.ispublic,
}
actual_dict = {
"id":edited_iso.id,
"name":edited_iso.name,
"displaytest":edited_iso.displaytext,
"account":edited_iso.account,
"domainid":edited_iso.domainid,
"isfeatured":edited_iso.isfeatured,
"ostypeid":edited_iso.ostypeid,
"ispublic":edited_iso.ispublic,
}
edit_iso_status = self.__verify_values(
expected_dict,
actual_dict
)
self.assertEqual(
True,
edit_iso_status,
"Edited ISO details are not as expected"
)
del self.services["iso"]["zoneid"]
return
@attr(tags=["advanced", "basic", "provisioning"])
def test_04_copy_iso(self):
"""
@Desc: Test to copy ISO from one zone to another
@steps:
Step1: Listing Zones available for a user
Step2: Verifying if the zones listed are greater than 1.
If Yes continuing.
If not halting the test.
Step3: Listing all the ISO's for a user in zone1
Step4: Verifying that no ISO's are listed
Step5: Listing all the ISO's for a user in zone2
Step6: Verifying that no ISO's are listed
Step7: Creating an ISO in zone 1
Step8: Listing all the ISO's again for a user in zone1
Step9: Verifying that list size is 1
Step10: Listing all the ISO's for a user in zone2
Step11: Verifying that no ISO's are listed
Step12: Copying the ISO created in step7 from zone1 to zone2
Step13: Listing all the ISO's for a user in zone2
Step14: Verifying that list size is 1
Step15: Listing all the ISO's for a user in zone1
Step16: Verifying that list size is 1
"""
# Listing Zones available for a user
zones_list = Zone.list(
self.userapiclient,
available=True
)
status = validateList(zones_list)
self.assertEquals(
PASS,
status[0],
"Failed to list Zones"
)
if not len(zones_list) > 1:
self.fail("Enough zones doesnot exists to copy iso")
else:
# Listing all the ISO's for a User in Zone 1
list_isos_zone1 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
zoneid=zones_list[0].id
)
# Verifying that no ISO's are listed
self.assertIsNone(
list_isos_zone1,
"ISO's listed for newly created User in Zone1"
)
# Listing all the ISO's for a User in Zone 2
list_isos_zone2 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
zoneid=zones_list[1].id
)
# Verifying that no ISO's are listed
self.assertIsNone(
list_isos_zone2,
"ISO's listed for newly created User in Zone2"
)
self.services["iso"]["zoneid"] = zones_list[0].id
# Creating an ISO in Zone 1
iso_created = Iso.create(
self.userapiclient,
self.services["iso"]
)
self.assertIsNotNone(
iso_created,
"ISO creation failed"
)
self.cleanup.append(iso_created)
# Listing all the ISO's for a User in Zone 1
list_isos_zone1 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
zoneid=zones_list[0].id
)
status = validateList(list_isos_zone1)
self.assertEquals(
PASS,
status[0],
"ISO creation failed in Zone1"
)
# Verifying that list size is 1
self.assertEquals(
1,
len(list_isos_zone1),
"Failed to create a Template"
)
# Listing all the ISO's for a User in Zone 2
list_isos_zone2 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
zoneid=zones_list[1].id
)
# Verifying that no ISO's are listed
self.assertIsNone(
list_isos_zone2,
"ISO's listed for newly created User in Zone2"
)
# Verifying the state of the ISO to be ready. If not waiting for state to become ready
iso_ready = False
count = 0
while iso_ready is False:
list_iso = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
id=iso_created.id
)
status = validateList(list_iso)
self.assertEquals(
PASS,
status[0],
"Failed to list ISO by Id"
)
if list_iso[0].isready is True:
iso_ready = True
elif (str(list_iso[0].status) == "Error"):
self.fail("Created ISO is in Errored state")
break
elif count > 10:
self.fail("Timed out before ISO came into ready state")
break
else:
time.sleep(self.services["sleep"])
count = count + 1
# Copying the ISO from Zone1 to Zone2
copied_iso = Iso.copy(
self.userapiclient,
iso_created.id,
sourcezoneid=iso_created.zoneid,
destzoneid=zones_list[1].id
)
self.assertIsNotNone(
copied_iso,
"Copying ISO from Zone1 to Zone2 failed"
)
# Listing all the ISO's for a User in Zone 1
list_isos_zone1 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
zoneid=zones_list[0].id
)
status = validateList(list_isos_zone1)
self.assertEquals(
PASS,
status[0],
"ISO creation failed in Zone1"
)
# Verifying that list size is 1
self.assertEquals(
1,
len(list_isos_zone1),
"Failed to create a Template"
)
# Listing all the ISO's for a User in Zone 2
list_isos_zone2 = Iso.list(
self.userapiclient,
listall=self.services["listall"],
isofilter=self.services["templatefilter"],
zoneid=zones_list[1].id
)
status = validateList(list_isos_zone2)
self.assertEquals(
PASS,
status[0],
"ISO failed to copy into Zone2"
)
# Verifying that list size is 1
self.assertEquals(
1,
len(list_isos_zone2),
"ISO failed to copy into Zone2"
)
self.assertNotEquals(
"Connection refused",
list_isos_zone2[0].status,
"Failed to copy ISO"
)
self.assertEquals(
True,
list_isos_zone2[0].isready,
"Failed to copy ISO"
)
del self.services["iso"]["zoneid"]
return | [
"marvin.lib.common.get_domain",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.utils.validateList",
"marvin.lib.base.Iso.update",
"marvin.lib.base.Iso.list",
"marvin.lib.common.list_os_types",
"marvin.lib.base.Account.create",
"marvin.lib.base.Iso.copy",
"marvin.lib.base.Zone.list",
"marvin.lib... | [((5728, 5776), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'provisioning']"}), "(tags=['advanced', 'basic', 'provisioning'])\n", (5732, 5776), False, 'from nose.plugins.attrib import attr\n'), ((12550, 12598), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'provisioning']"}), "(tags=['advanced', 'basic', 'provisioning'])\n", (12554, 12598), False, 'from nose.plugins.attrib import attr\n'), ((17407, 17455), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'provisioning']"}), "(tags=['advanced', 'basic', 'provisioning'])\n", (17411, 17455), False, 'from nose.plugins.attrib import attr\n'), ((25553, 25601), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'provisioning']"}), "(tags=['advanced', 'basic', 'provisioning'])\n", (25557, 25601), False, 'from nose.plugins.attrib import attr\n'), ((3942, 3989), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiClient', 'self.cleanup'], {}), '(self.apiClient, self.cleanup)\n', (3959, 3989), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((6800, 6910), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'])\n", (6808, 6910), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((7942, 8052), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'])\n", (7950, 8052), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((8203, 8231), 'marvin.lib.utils.validateList', 'validateList', (['list_iso_after'], {}), '(list_iso_after)\n', (8215, 8231), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((8757, 8916), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'page': '(1)', 'pagesize': "self.services['pagesize']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], page=1, pagesize=self.services['pagesize']\n )\n", (8765, 8916), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((9130, 9158), 'marvin.lib.utils.validateList', 'validateList', (['list_iso_page1'], {}), '(list_iso_page1)\n', (9142, 9158), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((9694, 9853), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'page': '(2)', 'pagesize': "self.services['pagesize']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], page=2, pagesize=self.services['pagesize']\n )\n", (9702, 9853), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((10067, 10095), 'marvin.lib.utils.validateList', 'validateList', (['list_iso_page2'], {}), '(list_iso_page2)\n', (10079, 10095), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((11748, 11791), 'marvin.lib.base.Iso.delete', 'Iso.delete', (['iso_created', 'self.userapiclient'], {}), '(iso_created, self.userapiclient)\n', (11758, 11791), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((11924, 12083), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'page': '(2)', 'pagesize': "self.services['pagesize']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], page=2, pagesize=self.services['pagesize']\n )\n", (11932, 12083), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((13283, 13393), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'])\n", (13291, 13393), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((13893, 13945), 'marvin.lib.base.Iso.create', 'Iso.create', (['self.userapiclient', "self.services['iso']"], {}), "(self.userapiclient, self.services['iso'])\n", (13903, 13945), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((14310, 14420), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'])\n", (14318, 14420), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((14571, 14599), 'marvin.lib.utils.validateList', 'validateList', (['list_iso_after'], {}), '(list_iso_after)\n', (14583, 14599), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((16218, 16312), 'marvin.lib.base.Iso.extract', 'Iso.extract', (['self.userapiclient', 'iso_created.id'], {'mode': '"""HTTP_DOWNLOAD"""', 'zoneid': 'self.zone.id'}), "(self.userapiclient, iso_created.id, mode='HTTP_DOWNLOAD',\n zoneid=self.zone.id)\n", (16229, 16312), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((18319, 18429), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'])\n", (18327, 18429), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((18876, 18928), 'marvin.lib.base.Iso.create', 'Iso.create', (['self.userapiclient', "self.services['iso']"], {}), "(self.userapiclient, self.services['iso'])\n", (18886, 18928), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((19293, 19403), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']"}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'])\n", (19301, 19403), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((19554, 19582), 'marvin.lib.utils.validateList', 'validateList', (['list_iso_after'], {}), '(list_iso_after)\n', (19566, 19582), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((21213, 21313), 'marvin.lib.base.Iso.update', 'Iso.update', (['iso_created', 'self.userapiclient'], {'name': '"""NewISOName"""', 'displaytext': '"""NewISODisplayText"""'}), "(iso_created, self.userapiclient, name='NewISOName', displaytext=\n 'NewISODisplayText')\n", (21223, 21313), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((23135, 23168), 'marvin.lib.common.list_os_types', 'list_os_types', (['self.userapiclient'], {}), '(self.userapiclient)\n', (23148, 23168), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_os_types\n'), ((23186, 23211), 'marvin.lib.utils.validateList', 'validateList', (['ostype_list'], {}), '(ostype_list)\n', (23198, 23211), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((23583, 23712), 'marvin.lib.base.Iso.update', 'Iso.update', (['iso_created', 'self.userapiclient'], {'name': 'iso_created.name', 'displaytext': 'iso_created.displaytext', 'ostypeid': 'newostypeid'}), '(iso_created, self.userapiclient, name=iso_created.name,\n displaytext=iso_created.displaytext, ostypeid=newostypeid)\n', (23593, 23712), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((26735, 26780), 'marvin.lib.base.Zone.list', 'Zone.list', (['self.userapiclient'], {'available': '(True)'}), '(self.userapiclient, available=True)\n', (26744, 26780), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((26893, 26917), 'marvin.lib.utils.validateList', 'validateList', (['zones_list'], {}), '(zones_list)\n', (26905, 26917), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((2660, 2686), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2670, 2686), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_os_types\n'), ((2796, 2861), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (2808, 2861), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_os_types\n'), ((3138, 3217), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], domainid=cls.domain.id)\n", (3152, 3217), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((4076, 4123), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (4093, 4123), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((7441, 7493), 'marvin.lib.base.Iso.create', 'Iso.create', (['self.userapiclient', "self.services['iso']"], {}), "(self.userapiclient, self.services['iso'])\n", (7451, 7493), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((10725, 10854), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'id': 'iso_created.id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], id=iso_created.id)\n", (10733, 10854), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((11033, 11055), 'marvin.lib.utils.validateList', 'validateList', (['list_iso'], {}), '(list_iso)\n', (11045, 11055), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((15195, 15324), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'id': 'iso_created.id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], id=iso_created.id)\n", (15203, 15324), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((15503, 15525), 'marvin.lib.utils.validateList', 'validateList', (['list_iso'], {}), '(list_iso)\n', (15515, 15525), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((20178, 20307), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'id': 'iso_created.id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], id=iso_created.id)\n", (20186, 20307), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((20486, 20508), 'marvin.lib.utils.validateList', 'validateList', (['list_iso'], {}), '(list_iso)\n', (20498, 20508), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((27293, 27428), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'zoneid': 'zones_list[0].id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], zoneid=zones_list[0].id)\n", (27301, 27428), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((27944, 28079), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'zoneid': 'zones_list[1].id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], zoneid=zones_list[1].id)\n", (27952, 28079), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((28636, 28688), 'marvin.lib.base.Iso.create', 'Iso.create', (['self.userapiclient', "self.services['iso']"], {}), "(self.userapiclient, self.services['iso'])\n", (28646, 28688), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((29104, 29239), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'zoneid': 'zones_list[0].id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], zoneid=zones_list[0].id)\n", (29112, 29239), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((29453, 29482), 'marvin.lib.utils.validateList', 'validateList', (['list_isos_zone1'], {}), '(list_isos_zone1)\n', (29465, 29482), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((30023, 30158), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'zoneid': 'zones_list[1].id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], zoneid=zones_list[1].id)\n", (30031, 30158), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((31936, 32047), 'marvin.lib.base.Iso.copy', 'Iso.copy', (['self.userapiclient', 'iso_created.id'], {'sourcezoneid': 'iso_created.zoneid', 'destzoneid': 'zones_list[1].id'}), '(self.userapiclient, iso_created.id, sourcezoneid=iso_created.\n zoneid, destzoneid=zones_list[1].id)\n', (31944, 32047), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((32490, 32625), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'zoneid': 'zones_list[0].id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], zoneid=zones_list[0].id)\n", (32498, 32625), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((32839, 32868), 'marvin.lib.utils.validateList', 'validateList', (['list_isos_zone1'], {}), '(list_isos_zone1)\n', (32851, 32868), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((33409, 33544), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'zoneid': 'zones_list[1].id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], zoneid=zones_list[1].id)\n", (33417, 33544), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((33758, 33787), 'marvin.lib.utils.validateList', 'validateList', (['list_isos_zone2'], {}), '(list_isos_zone2)\n', (33770, 33787), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((30803, 30932), 'marvin.lib.base.Iso.list', 'Iso.list', (['self.userapiclient'], {'listall': "self.services['listall']", 'isofilter': "self.services['templatefilter']", 'id': 'iso_created.id'}), "(self.userapiclient, listall=self.services['listall'], isofilter=\n self.services['templatefilter'], id=iso_created.id)\n", (30811, 30932), False, 'from marvin.lib.base import Volume, Iso, VirtualMachine, Template, Snapshot, SecurityGroup, Account, Zone, Network, NetworkOffering, DiskOffering, ServiceOffering, VmSnapshot, SnapshotPolicy, SSHKeyPair, Resources, Configurations, VpnCustomerGateway, Hypervisor, VpcOffering, VPC, NetworkACL\n'), ((31135, 31157), 'marvin.lib.utils.validateList', 'validateList', (['list_iso'], {}), '(list_iso)\n', (31147, 31157), False, 'from marvin.lib.utils import validateList, cleanup_resources, random_gen\n'), ((11625, 11659), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (11635, 11659), False, 'import time\n'), ((16095, 16129), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (16105, 16129), False, 'import time\n'), ((21078, 21112), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (21088, 21112), False, 'import time\n'), ((31787, 31821), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (31797, 31821), False, 'import time\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Component tests for VPC network functionality - with and without Netscaler (Netscaler tests will be skipped if Netscaler configuration fails)
"""
#Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.cloudstackAPI import startVirtualMachine, stopVirtualMachine
from marvin.lib.utils import cleanup_resources, validateList
from marvin.lib.base import (VirtualMachine,
ServiceOffering,
Account,
NATRule,
NetworkOffering,
Network,
VPC,
VpcOffering,
LoadBalancerRule,
Router,
StaticNATRule,
NetworkACL,
PublicIPAddress)
from marvin.lib.common import (get_zone,
get_domain,
get_template,
wait_for_cleanup,
add_netscaler,
list_networks)
# For more info on ddt refer to http://ddt.readthedocs.org/en/latest/api.html#module-ddt
from ddt import ddt, data
import time
from marvin.codes import PASS
class Services:
"""Test VPC network services
"""
def __init__(self):
self.services = {
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended for unique
# username
"password": "password",
},
"service_offering": {
"name": "Tiny Instance",
"displaytext": "Tiny Instance",
"cpunumber": 1,
"cpuspeed": 100,
"memory": 128,
},
"network_offering": {
"name": 'VPC Network offering',
"displaytext": 'VPC Network off',
"guestiptype": 'Isolated',
"supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL',
"traffictype": 'GUEST',
"availability": 'Optional',
"useVpc": 'on',
"serviceProviderList": {
"Vpn": 'VpcVirtualRouter',
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"Lb": 'VpcVirtualRouter',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
},
"serviceCapabilityList": {
"SourceNat": {"SupportedSourceNatTypes": "peraccount"},
},
},
# Offering that uses Netscaler as provider for LB inside VPC, dedicated = false
"network_off_netscaler": {
"name": 'Network offering-netscaler',
"displaytext": 'Network offering-netscaler',
"guestiptype": 'Isolated',
"supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat',
"traffictype": 'GUEST',
"availability": 'Optional',
"useVpc": 'on',
"serviceProviderList": {
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"Vpn": 'VpcVirtualRouter',
"Lb": 'Netscaler',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
},
"serviceCapabilityList": {
"SourceNat": {"SupportedSourceNatTypes": "peraccount"},
},
},
# Offering that uses Netscaler as provider for LB in VPC, dedicated = True
# This offering is required for the tests that use Netscaler as external LB provider in VPC
"network_offering_vpcns": {
"name": 'VPC Network offering',
"displaytext": 'VPC Network off',
"guestiptype": 'Isolated',
"supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL',
"traffictype": 'GUEST',
"availability": 'Optional',
"useVpc": 'on',
"serviceProviderList": {
"Vpn": 'VpcVirtualRouter',
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"Lb": 'Netscaler',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
},
"serviceCapabilityList": {
"SourceNat": {
"SupportedSourceNatTypes": "peraccount"
},
"lb": {
"SupportedLbIsolation": "dedicated"
},
},
},
"network_off_shared": {
"name": 'Shared Network offering',
"displaytext": 'Shared Network offering',
"guestiptype": 'Shared',
"traffictype": 'GUEST',
"availability": 'Optional',
"useVpc": 'on',
"specifyIpRanges": True,
"specifyVlan": True
},
"vpc_offering": {
"name": 'VPC off',
"displaytext": 'VPC off',
"supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat',
},
"vpc": {
"name": "TestVPC",
"displaytext": "TestVPC",
"cidr": '10.0.0.1/24'
},
# Netscaler should be added as a dedicated device for it to work as external LB provider in VPC
"netscaler": {
"ipaddress": '10.102.192.50',
"username": 'nsroot',
"password": '<PASSWORD>',
"networkdevicetype": 'NetscalerVPXLoadBalancer',
"publicinterface": '1/3',
"privateinterface": '1/4',
"numretries": 2,
"lbdevicededicated": True,
"lbdevicecapacity": 50,
"port": 22,
},
"network": {
"name": "Test Network",
"displaytext": "Test Network",
"netmask": '255.255.255.0'
},
"lbrule": {
"name": "SSH",
"alg": "leastconn",
# Algorithm used for load balancing
"privateport": 22,
"publicport": 2222,
"openfirewall": False,
"startport": 22,
"endport": 2222,
"protocol": "TCP",
"cidrlist": '0.0.0.0/0',
},
"natrule": {
"privateport": 22,
"publicport": 22,
"startport": 22,
"endport": 22,
"protocol": "TCP",
"cidrlist": '0.0.0.0/0',
},
"fw_rule": {
"startport": 1,
"endport": 6000,
"cidr": '0.0.0.0/0',
# Any network (For creating FW rule)
"protocol": "TCP"
},
"icmp_rule": {
"icmptype": -1,
"icmpcode": -1,
"cidrlist": '0.0.0.0/0',
"protocol": "ICMP"
},
"virtual_machine": {
"displayname": "Test VM",
"username": "root",
"password": "password",
"ssh_port": 22,
"hypervisor": 'XenServer',
# Hypervisor type should be same as
# hypervisor type of cluster
"privateport": 22,
"publicport": 22,
"protocol": 'TCP',
},
"ostype": 'CentOS 5.3 (64-bit)',
# Cent OS 5.3 (64 bit)
"sleep": 60,
"timeout": 10,
}
@ddt
class TestVPCNetwork(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestVPCNetwork, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Added an attribute to track if Netscaler addition was successful.
# Value is checked in tests and if not configured, Netscaler tests will be skipped
cls.ns_configured = False
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup.append(cls.service_offering)
# Configure Netscaler device
# If configuration succeeds, set ns_configured to True so that Netscaler tests are executed
try:
cls.netscaler = add_netscaler(cls.api_client, cls.zone.id, cls.services["netscaler"])
cls._cleanup.append(cls.netscaler)
cls.debug("Netscaler configured")
cls.ns_configured = True
except Exception as e:
cls.debug("Warning: Couldn't configure Netscaler: %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.services = Services().services
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account, ]
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
self.debug("Warning: Exception during cleanup : %s" % e)
#raise Exception("Warning: Exception during cleanup : %s" % e)
return
def validate_vpc_offering(self, vpc_offering):
"""Validates the VPC offering"""
self.debug("Check if the VPC offering is created successfully?")
vpc_offs = VpcOffering.list(
self.apiclient,
id=vpc_offering.id
)
self.assertEqual(
isinstance(vpc_offs, list),
True,
"List VPC offerings should return a valid list"
)
self.assertEqual(
vpc_offering.name,
vpc_offs[0].name,
"Name of the VPC offering should match with listVPCOff data"
)
self.debug(
"VPC offering is created successfully - %s" %
vpc_offering.name)
return
def validate_vpc_network(self, network, state=None):
"""Validates the VPC network"""
self.debug("Check if the VPC network is created successfully?")
vpc_networks = VPC.list(
self.apiclient,
id=network.id
)
self.assertEqual(
isinstance(vpc_networks, list),
True,
"List VPC network should return a valid list"
)
self.assertEqual(
network.name,
vpc_networks[0].name,
"Name of the VPC network should match with listVPC data"
)
if state:
self.assertEqual(
vpc_networks[0].state,
state,
"VPC state should be '%s'" % state
)
self.debug("VPC network validated - %s" % network.name)
return
@data("network_offering", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_01_create_network(self, value):
""" Test create network in VPC
"""
# Validate the following
# 1. Create a VPC using Default Offering
# 2. Create a network offering with guest type=Isolated" that has
# all of supported Services(Vpn,dhcpdns,UserData, SourceNat,Static
# NAT,LB and PF,LB,NetworkAcl ) provided by VPCVR and conserve
# mode is ON
# 3. Create a network tier using the network offering created in step2 as
# part of this VPC.
# 4. Validate Network is created
# 5. Repeat test for offering which has Netscaler as external LB provider
if (value == "network_offering_vpcns" and self.ns_configured == False):
self.skipTest('Netscaler not configured: skipping test')
if (value == "network_offering"):
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
else:
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering with Netscaler',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services[value],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" %
self.network_offering.id)
network = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Created network with ID: %s" % network.id)
self.debug(
"Verifying list network response to check if network created?")
networks = Network.list(
self.apiclient,
id=network.id,
listall=True
)
self.assertEqual(
isinstance(networks, list),
True,
"List networks should return a valid response"
)
nw = networks[0]
self.assertEqual(
nw.networkofferingid,
self.network_offering.id,
"Network should be created from network offering - %s" %
self.network_offering.id
)
self.assertEqual(
nw.vpcid,
vpc.id,
"Network should be created in VPC: %s" % vpc.name
)
return
@data("network_offering", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_02_create_network_fail(self, value):
""" Test create network in VPC mismatched services (Should fail)
"""
# Validate the following
# 1. Create a VPC using Default VPC Offering
# 2. Create a network offering with guest type=Isolated" that has
# one of supported Services(Vpn,dhcpdns,UserData, Static
# NAT,LB and PF,LB,NetworkAcl ) provided by VPCVR, SourceNat by VR
# and conserve mode is ON
# 3. Create a network using the network offering created in step2 as
# part of this VPC.
# 4. Network creation should fail since SourceNat offered by VR instead of VPCVR
# 5. Repeat test for offering which has Netscaler as external LB provider
if (value == "network_offering_vpcns" and self.ns_configured == False):
self.skipTest('Netscaler not configured: skipping test')
if (value == "network_offering"):
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
else:
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering with Netscaler',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.services[value]["serviceProviderList"] = {
"SourceNat": 'VirtualRouter', }
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services[value],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" %
self.network_offering.id)
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
return
@data("network_offering", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_04_create_multiple_networks_with_lb(self, value):
""" Test create multiple networks with LB service (Should fail)
"""
# Validate the following
# 1. Create a VPC using Default Offering
# 2. Create a network offering with guest type=Isolated that has LB
# services Enabled and conserve mode is "ON".
# 3. Create a network using the network offering created in step2 as
# part of this VPC.
# 4. Create another network using the network offering created in
# step3 as part of this VPC
# 5. Create Network should fail
# 6. Repeat test for offering which has Netscaler as external LB provider
if (value == "network_offering_vpcns" and self.ns_configured == False):
self.skipTest('Netscaler not configured: skipping test')
if (value == "network_offering"):
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
else:
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering with Netscaler',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services[value],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" %
self.network_offering.id)
network = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Created network with ID: %s" % network.id)
self.debug(
"Verifying list network response to check if network created?")
networks = Network.list(
self.apiclient,
id=network.id,
listall=True
)
self.assertEqual(
isinstance(networks, list),
True,
"List networks should return a valid response"
)
nw = networks[0]
self.assertEqual(
nw.networkofferingid,
self.network_offering.id,
"Network should be created from network offering - %s" %
self.network_offering.id
)
self.assertEqual(
nw.vpcid,
vpc.id,
"Network should be created in VPC: %s" % vpc.name
)
self.debug("Creating another network in VPC: %s" % vpc.name)
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.2.1',
vpcid=vpc.id
)
self.debug(
"Network creation failed as network with LB service already exists")
return
@attr(tags=["intervlan"])
def test_05_create_network_ext_LB(self):
""" Test create network with external LB devices
"""
# Validate the following
# 1.Create a VPC using Default Offering (Without Netscaler)
# 2. Create a network offering with guest type=Isolated that has LB
# service provided by netscaler and conserve mode is "ON".
# 3. Create a network using this network offering as part of this VPC.
# 4. Create Network should fail since it doesn't match the VPC offering
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services["network_offering_vpcns"],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" %
self.network_offering.id)
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Network creation failed")
return
@unittest.skip("skipped - RvR didn't support VPC currently ")
@attr(tags=["advanced", "intervlan", "NA"])
def test_06_create_network_with_rvr(self):
""" Test create network with redundant router capability
"""
# Validate the following
# 1. Create VPC Offering by specifying all supported Services
# (Vpn,dhcpdns,UserData, SourceNat,Static NAT and PF,LB,NetworkAcl)
# 2. Create a VPC using the above VPC offering
# 3. Create a network offering with guest type=Isolated that has all
# services provided by VPC VR,conserver mode ""OFF"" and Redundant
# Router capability enabled.
# 4. Create a VPC using the above VPC offering.
# 5. Create a network using the network offering created in step2 as
# part of this VPC
self.debug("Creating a VPC offering..")
vpc_off = VpcOffering.create(
self.apiclient,
self.services["vpc_offering"]
)
self.cleanup.append(vpc_off)
self.validate_vpc_offering(vpc_off)
self.debug("Enabling the VPC offering created")
vpc_off.update(self.apiclient, state='Enabled')
self.debug("creating a VPC network in the account: %s" %
self.account.name)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
# Enable redundant router capability for the network offering
self.services["network"]["serviceCapabilityList"] = {
"SourceNat": {
"RedundantRouter": "true",
},
}
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" %
self.network_offering.id)
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.2.1',
vpcid=vpc.id
)
self.debug("Network creation failed")
return
@attr(tags=["advanced", "intervlan", "selfservice"])
def test_07_create_network_unsupported_services(self):
""" Test create network services not supported by VPC (Should fail)
"""
# Validate the following
# 1. Create VPC Offering without LB service
# 2. Create a VPC using the above VPC offering
# 3. Create a network offering with guest type=Isolated that has all
# supported Services(Vpn,dhcpdns,UserData, SourceNat,Static NAT,LB
# and PF,LB,NetworkAcl ) provided by VPCVR and conserve mode is OFF
# 4. Create Network with the above offering
# 5. Create network fails since VPC offering doesn't support LB
self.debug("Creating a VPC offering without LB service")
self.services["vpc_offering"]["supportedservices"] = 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,UserData,StaticNat'
vpc_off = VpcOffering.create(
self.apiclient,
self.services["vpc_offering"]
)
self.cleanup.append(vpc_off)
self.validate_vpc_offering(vpc_off)
self.debug("Enabling the VPC offering created")
vpc_off.update(self.apiclient, state='Enabled')
self.debug("creating a VPC network in the account: %s" %
self.account.name)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" %
self.network_offering.id)
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.2.1',
vpcid=vpc.id
)
self.debug("Network creation failed as VPC doesn't have LB service")
return
@attr(tags=["advanced", "intervlan", "selfservice"])
def test_08_create_network_without_sourceNAT(self):
""" Test create network without sourceNAT service in VPC (should fail)
"""
# Validate the following
# 1. Create VPC Offering by specifying supported Services-
# Vpn,dhcpdns,UserData, SourceNat,Static NAT and PF,LB,NetworkAcl)
# with out including LB services.
# 2. Create a VPC using the above VPC offering
# 3. Create a network offering with guest type=Isolated that does not
# have SourceNAT services enabled
# 4. Create a VPC using the above VPC offering
# 5. Create a network using the network offering created in step2 as
# part of this VPC
self.debug("Creating a VPC offering without LB service")
self.services["vpc_offering"]["supportedservices"] = 'Dhcp,Dns,SourceNat,PortForwarding,UserData,StaticNat'
vpc_off = VpcOffering.create(
self.apiclient,
self.services["vpc_offering"]
)
self.cleanup.append(vpc_off)
self.validate_vpc_offering(vpc_off)
self.debug("Enabling the VPC offering created")
vpc_off.update(self.apiclient, state='Enabled')
self.debug("creating a VPC network in the account: %s" %
self.account.name)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.debug("Creating network offering without SourceNAT service")
self.services["network_offering"]["supportedservices"] = 'Dhcp,Dns,PortForwarding,Lb,UserData,StaticNat,NetworkACL'
self.services["network_offering"]["serviceProviderList"] = {
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"Lb": 'VpcVirtualRouter',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
}
self.debug("Creating network offering without SourceNAT")
with self.assertRaises(Exception):
NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
self.debug("Network creation failed as VPC doesn't have LB service")
return
@data("network_off_shared", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_09_create_network_shared_nwoff(self, value):
""" Test create network with shared network offering
"""
# Validate the following
# 1. Create VPC Offering using Default Offering
# 2. Create a VPC using the above VPC offering
# 3. Create a network offering with guest type=shared
# 4. Create a network using the network offering created in step3 as part of this VPC
# 5. Create network fails since it using shared offering
# 6. Repeat test for offering which has Netscaler as external LB provider
if (value == "network_offering_vpcns" and self.ns_configured == False):
self.skipTest('Netscaler not configured: skipping test')
if (value == "network_off_shared"):
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
else:
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering with Netscaler',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.debug("Creating network offering with guesttype=shared")
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services["network_off_shared"],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug(
"Creating network with network offering without SourceNAT: %s" %
self.network_offering.id)
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Network creation failed")
return
@data("network_offering", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_10_create_network_with_conserve_mode(self, value):
""" Test create network with conserve mode ON
"""
# Validate the following
# 1. Create a network offering with guest type=Isolated that has all
# supported Services(Vpn,dhcpdns,UserData, SourceNat,Static NAT,LB
# and PF,LB,NetworkAcl ) provided by VPCVR and conserve mode is ON
# 2. Create offering fails since Conserve mode ON isn't allowed within VPC
# 3. Repeat test for offering which has Netscaler as external LB provider
self.debug("Creating network offering with conserve mode = ON")
with self.assertRaises(Exception):
NetworkOffering.create(
self.apiclient,
self.services[value],
conservemode=True
)
self.debug(
"Network creation failed as VPC support nw with conserve mode OFF")
return
@ddt
class TestVPCNetworkRanges(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestVPCNetworkRanges, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Added an attribute to track if Netscaler addition was successful.
# Value is checked in tests and if not configured, Netscaler tests will be skipped
cls.ns_configured = False
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup.append(cls.service_offering)
# Configure Netscaler device
# If configuration succeeds, set ns_configured to True so that Netscaler tests are executed
try:
cls.netscaler = add_netscaler(cls.api_client, cls.zone.id, cls.services["netscaler"])
cls._cleanup.append(cls.netscaler)
cls.ns_configured = True
except Exception as e:
cls.debug("Warning: Couldn't configure Netscaler: %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account, ]
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
self.debug("Warning: Exception during cleanup : %s" % e)
return
def validate_vpc_offering(self, vpc_offering):
"""Validates the VPC offering"""
self.debug("Check if the VPC offering is created successfully?")
vpc_offs = VpcOffering.list(
self.apiclient,
id=vpc_offering.id
)
self.assertEqual(
isinstance(vpc_offs, list),
True,
"List VPC offerings should return a valid list"
)
self.assertEqual(
vpc_offering.name,
vpc_offs[0].name,
"Name of the VPC offering should match with listVPCOff data"
)
self.debug(
"VPC offering is created successfully - %s" %
vpc_offering.name)
return
def validate_vpc_network(self, network, state=None):
"""Validates the VPC network"""
self.debug("Check if the VPC network is created successfully?")
vpc_networks = VPC.list(
self.apiclient,
id=network.id
)
self.assertEqual(
isinstance(vpc_networks, list),
True,
"List VPC network should return a valid list"
)
self.assertEqual(
network.name,
vpc_networks[0].name,
"Name of the VPC network should match with listVPC data"
)
if state:
self.assertEqual(
vpc_networks[0].state,
state,
"VPC state should be '%s'" % state
)
self.debug("VPC network validated - %s" % network.name)
return
@data("network_offering", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_01_create_network_outside_range(self, value):
""" Test create network outside cidr range of VPC
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Add network1 with cidr - 10.2.1.1/24 to this VPC
# 3. Network creation should fail.
# 4. Repeat test for offering which has Netscaler as external LB provider
if (value == "network_offering_vpcns" and self.ns_configured == False):
self.skipTest('Netscaler not configured: skipping test')
if (value == "network_offering"):
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
else:
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering with Netscaler',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.debug("Creating network offering")
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services[value],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network outside of the VPC's network")
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.2.1.1',
vpcid=vpc.id
)
self.debug(
"Network creation failed as network cidr range is outside of vpc")
return
@attr(tags=["advanced", "intervlan", "selfservice"])
def test_02_create_network_outside_range(self):
""" Test create network outside cidr range of VPC
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Add network1 with cidr - 10.2.1.1/24 to this VPC
# 3. Network creation should fail.
# 4. Repeat test for offering which has Netscaler as external LB provider
self.debug("Creating a VPC offering")
vpc_off = VpcOffering.create(
self.apiclient,
self.services["vpc_offering"]
)
self.cleanup.append(vpc_off)
self.validate_vpc_offering(vpc_off)
self.debug("Enabling the VPC offering created")
vpc_off.update(self.apiclient, state='Enabled')
self.debug("creating a VPC network with cidr: 10.1.1.1/16")
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.debug("Creating network offering")
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network outside of the VPC's network")
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.2.1.1',
vpcid=vpc.id
)
self.debug(
"Network creation failed as network cidr range is outside of vpc")
return
@data("network_offering", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_03_create_network_inside_range(self, value):
""" Test create network inside cidr range of VPC
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Add network1 with cidr - 10.1.1.1/8 to this VPC
# 3. Network creation should fail.
# 4. Repeat test for offering which has Netscaler as external LB provider
if (value == "network_offering_vpcns" and self.ns_configured == False):
self.skipTest('Netscaler not configured: skipping test')
if (value == "network_offering"):
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
else:
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering with Netscaler',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.debug("creating a VPC network with cidr: 10.1.1.1/16")
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.debug("Creating network offering")
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services[value],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network inside of the VPC's network")
with self.assertRaises(Exception):
# cidr = 10.1.1.1/8 -> netmask = 255.0.0.0, gateway = 10.1.1.1
self.services["network"]["netmask"] = '255.0.0.0'
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug(
"Network creation failed as network cidr range is inside of vpc")
return
@data("network_offering", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_04_create_network_overlapping_range(self, value):
""" Test create network overlapping cidr range of VPC
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Add network1 with cidr - 10.1.1.1/24 to this VPC
# 3. Add network2 with cidr - 10.1.1.1/24 to this VPC
# 4. Add network3 with cidr - 10.1.1.1/26 to this VPC
# 5. Network creation in step 3 & 4 should fail.
# 6. Repeat test for offering which has Netscaler as external LB provider
self.services = Services().services
if (value == "network_offering_vpcns" and self.ns_configured == False):
self.skipTest('Netscaler not configured: skipping test')
if (value == "network_offering"):
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
else:
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering with Netscaler',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.debug("creating a VPC network with cidr: 10.1.1.1/16")
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.debug("Creating network offering")
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services[value],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" %
self.network_offering.id)
network = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Created network with ID: %s" % network.id)
self.debug(
"Verifying list network response to check if network created?")
networks = Network.list(
self.apiclient,
id=network.id,
listall=True
)
self.assertEqual(
isinstance(networks, list),
True,
"List networks should return a valid response"
)
nw = networks[0]
self.assertEqual(
nw.networkofferingid,
self.network_offering.id,
"Network should be created from network offering - %s" %
self.network_offering.id
)
self.assertEqual(
nw.vpcid,
vpc.id,
"Network should be created in VPC: %s" % vpc.name
)
# Creating network using the network offering created
self.debug(
"Creating network with same network range as of previous network")
with self.assertRaises(Exception):
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Network creation as network range 10.1.1.1/24 is same" + \
"as that of existing network")
self.debug("Creating network having overlapping network ranges")
with self.assertRaises(Exception):
# cidr = 10.1.1.1/8 -> netmask=255.255.255.192, gateway=10.1.1.1
self.services["network"]["netmask"] = '255.255.255.192'
Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug(
"Network creation failed as network range overlaps each other")
return
@data("network_offering", "network_offering_vpcns")
@attr(tags=["advanced", "intervlan"])
def test_05_create_network_diff_account(self, value):
""" Test create network from different account in VPC
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Add network1 with cidr - 10.1.1.1/24 to this VPC
# 3. Create another account
# 4. Create network using this account - Network creation should fail
# 5. Repeat test for offering which has Netscaler as external LB provider
if (value == "network_offering_vpcns" and self.ns_configured == False):
self.skipTest('Netscaler not configured: skipping test')
if (value == "network_offering"):
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
else:
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering with Netscaler',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.debug("creating a VPC network with cidr: 10.1.1.1/16")
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
self.debug("Creating network offering")
self.network_offering = NetworkOffering.create(
self.apiclient,
self.services[value],
conservemode=False
)
# Enable Network offering
self.network_offering.update(self.apiclient, state='Enabled')
self.cleanup.append(self.network_offering)
self.debug(
"Creating the new account to create new network in VPC: %s" %
vpc.name)
account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup.append(account)
# Creating network using the network offering created
self.debug("Creating network from diff account than VPC")
with self.assertRaises(Exception):
# cidr = 10.1.1.1/8 -> netmask = 255.0.0.0, gateway = 10.1.1.1
self.services["network"]["netmask"] = '255.0.0.0'
Network.create(
self.apiclient,
self.services["network"],
accountid=account.name,
domainid=account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug(
"Network creation failed as VPC belongs to different account")
return
class TestVPCNetworkUpgrade(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestVPCNetworkUpgrade, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup.append(cls.service_offering)
return
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = [self.account, ]
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
self.debug("Warning: Exception during cleanup : %s" % e)
return
def validate_vpc_offering(self, vpc_offering):
"""Validates the VPC offering"""
self.debug("Check if the VPC offering is created successfully?")
vpc_offs = VpcOffering.list(
self.apiclient,
id=vpc_offering.id
)
self.assertEqual(
isinstance(vpc_offs, list),
True,
"List VPC offerings should return a valid list"
)
self.assertEqual(
vpc_offering.name,
vpc_offs[0].name,
"Name of the VPC offering should match with listVPCOff data"
)
self.debug(
"VPC offering is created successfully - %s" %
vpc_offering.name)
return
def validate_vpc_network(self, network, state=None):
"""Validates the VPC network"""
self.debug("Check if the VPC network is created successfully?")
vpc_networks = VPC.list(
self.apiclient,
id=network.id
)
self.assertEqual(
isinstance(vpc_networks, list),
True,
"List VPC network should return a valid list"
)
self.assertEqual(
network.name,
vpc_networks[0].name,
"Name of the VPC network should match with listVPC data"
)
if state:
self.assertEqual(
vpc_networks[0].state,
state,
"VPC state should be '%s'" % state
)
self.debug("VPC network validated - %s" % network.name)
return
@attr(tags=["advanced", "intervlan", "provisioning"])
def test_01_network_services_upgrade(self):
""" Test update Network that is part of a VPC to a network offering that has more services
"""
# Validate the following
# 1. Create a VPC with cidr - 10.1.1.1/16
# 2. Create a Network offering - NO1 with all supported services
# except PF services provided by VRVPC provider, conserve mode=OFF
# 3.Create a Network offering - NO2 with all supported services
# including Pf services provided by VRVPC provider,conserve mode=OFF
# 4. Add network1(10.1.1.1/24) using N01 to this VPC.
# 5. Deploy vm1 and vm2 in network1.
# 6. Create a Static Nat and LB rules for vms in network1.
# 7. Make sure you are not allowed to create a PF rule for any Vm in
# network1 and the Static Nat and LB rules for vms work as expected
# 8. Update network1 to NO2.
self.debug("Creating a VPC offering..")
vpc_off_list=VpcOffering.list(
self.apiclient,
name='Default VPC offering',
listall=True
)
vpc_off=vpc_off_list[0]
self.debug("Creating a VPC with offering: %s" % vpc_off.id)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
nw_off = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
# Enable Network offering
nw_off.update(self.apiclient, state='Enabled')
self.cleanup.append(nw_off)
self.services["network_offering"]["supportedservices"] = 'Vpn,Dhcp,Dns,SourceNat,UserData,Lb,StaticNat,NetworkACL'
self.services["network_offering"]["serviceProviderList"] = {
"Vpn": 'VpcVirtualRouter',
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"Lb": 'VpcVirtualRouter',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
}
nw_off_no_pf = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
# Enable Network offering
nw_off_no_pf.update(self.apiclient, state='Enabled')
self.cleanup.append(nw_off_no_pf)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" %
nw_off_no_pf.id)
network_1 = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=nw_off_no_pf.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Created network with ID: %s" % network_1.id)
self.debug("deploying VMs in network: %s" % network_1.name)
# Spawn an instance in that network
vm_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(network_1.id)]
)
self.debug("Deployed VM in network: %s" % network_1.id)
vm_2 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(network_1.id)]
)
self.debug("Deployed another VM in network: %s" % network_1.id)
self.debug("Associating public IP for network: %s" % network_1.name)
public_ip_1 = PublicIPAddress.create(
self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network_1.id,
vpcid=vpc.id
)
self.debug("Associated %s with network %s" % (
public_ip_1.ipaddress.ipaddress,
network_1.id
))
self.debug("Creating LB rule for IP address: %s" %
public_ip_1.ipaddress.ipaddress)
lb_rule = LoadBalancerRule.create(
self.apiclient,
self.services["lbrule"],
ipaddressid=public_ip_1.ipaddress.id,
accountid=self.account.name,
networkid=network_1.id,
vpcid=vpc.id,
domainid=self.account.domainid
)
self.debug("Adding virtual machines %s to LB rule" % vm_1.name)
lb_rule.assign(self.apiclient, [vm_1])
self.debug("Associating public IP for network: %s" % network_1.name)
public_ip_2 = PublicIPAddress.create(
self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network_1.id,
vpcid=vpc.id
)
self.debug("Associated %s with network %s" % (
public_ip_2.ipaddress.ipaddress,
network_1.id
))
self.debug("Enabling static NAT for IP: %s" %
public_ip_2.ipaddress.ipaddress)
try:
StaticNATRule.enable(
self.apiclient,
ipaddressid=public_ip_2.ipaddress.id,
virtualmachineid=vm_2.id,
networkid=network_1.id
)
self.debug("Static NAT enabled for IP: %s" %
public_ip_2.ipaddress.ipaddress)
except Exception as e:
self.fail("Failed to enable static NAT on IP: %s - %s" % (
public_ip_2.ipaddress.ipaddress, e))
public_ips = PublicIPAddress.list(
self.apiclient,
networkid=network_1.id,
listall=True,
isstaticnat=True,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(public_ips, list),
True,
"List public Ip for network should list the Ip addr"
)
self.assertEqual(
public_ips[0].ipaddress,
public_ip_2.ipaddress.ipaddress,
"List public Ip for network should list the Ip addr"
)
self.debug("Adding NetwrokACl rules to make PF and LB accessible")
NetworkACL.create(
self.apiclient,
networkid=network_1.id,
services=self.services["lbrule"],
traffictype='Ingress'
)
self.debug(
"Adding Egress rules to network %s to access internet" %
(network_1.name))
NetworkACL.create(
self.apiclient,
networkid=network_1.id,
services=self.services["icmp_rule"],
traffictype='Egress'
)
self.debug("Checking if we can SSH into VM_1? - IP: %s" %
public_ip_1.ipaddress.ipaddress)
try:
ssh_1 = vm_1.get_ssh_client(
ipaddress=public_ip_1.ipaddress.ipaddress,
reconnect=True,
port=self.services["lbrule"]["publicport"]
)
self.debug("SSH into VM is successfully")
self.debug("Verifying if we can ping to outside world from VM?")
# Ping to outsite world
res = ssh_1.execute("ping -c 1 www.google.com")
# res = 64 bytes from maa03s17-in-f20.1e100.net (192.168.127.122):
# icmp_req=1 ttl=57 time=25.9 ms
# --- www.l.google.com ping statistics ---
# 1 packets transmitted, 1 received, 0% packet loss, time 0ms
# rtt min/avg/max/mdev = 25.970/25.970/25.970/0.000 ms
except Exception as e:
self.fail("Failed to SSH into VM - %s, %s" %
(public_ip_1.ipaddress.ipaddress, e))
result = str(res)
self.debug("Result: %s" % result)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
self.debug("Checking if we can SSH into VM_2?")
try:
ssh_2 = vm_2.get_ssh_client(
ipaddress=public_ip_2.ipaddress.ipaddress,
reconnect=True,
port=self.services["natrule"]["publicport"]
)
self.debug("SSH into VM is successfully")
self.debug("Verifying if we can ping to outside world from VM?")
res = ssh_2.execute("ping -c 1 www.google.com")
except Exception as e:
self.fail("Failed to SSH into VM - %s, %s" %
(public_ip_2.ipaddress.ipaddress, e))
result = str(res)
self.debug("Result: %s" % result)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
self.debug("Associating public IP for network: %s" % vpc.name)
public_ip_3 = PublicIPAddress.create(
self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network_1.id,
vpcid=vpc.id
)
self.debug("Associated %s with network %s" % (
public_ip_3.ipaddress.ipaddress,
network_1.id
))
self.debug("Creatinng NAT rule in network shall through exception?")
with self.assertRaises(Exception):
NATRule.create(
self.apiclient,
vm_1,
self.services["natrule"],
ipaddressid=public_ip_3.ipaddress.id,
openfirewall=False,
networkid=network_1.id,
vpcid=vpc.id
)
self.debug("Create NAT rule failed!")
self.debug(
"Stopping all the virtual machines in network before upgrade")
try:
vm_1.stop(self.apiclient)
vm_2.stop(self.apiclient)
except Exception as e:
self.fail("Failed to stop VMs, %s" % e)
# When all Vms ain network are stopped, network state changes from Implemented --> Shutdown --> Allocated
# We can't update the network when it is in Shutodown state, hence we should wait for the state to change to
# Allocated and then update the network
retriesCount = 10
while True:
networks = list_networks(self.apiclient, id=network_1.id)
self.assertEqual(validateList(networks)[0], PASS, "networks list validation failed, list id %s" % networks)
self.debug("network state is %s" % networks[0].state)
if networks[0].state == "Allocated":
break
if retriesCount == 0:
self.fail("Network state should change to Allocated, it is %s" % networks[0].state)
retriesCount -= 1
time.sleep(6)
self.debug("Upgrading network offering to support PF services")
try:
network_1.update(
self.apiclient,
networkofferingid=nw_off.id
)
except Exception as e:
self.fail("failed to upgrade the network offering- %s" % e)
self.debug(
"Starting all the virtual machines in network after upgrade")
try:
vm_1.start(self.apiclient)
vm_2.start(self.apiclient)
except Exception as e:
self.fail("Failed to start VMs, %s" % e)
NATRule.create(
self.apiclient,
vm_1,
self.services["natrule"],
ipaddressid=public_ip_3.ipaddress.id,
openfirewall=False,
networkid=network_1.id,
vpcid=vpc.id
)
self.debug("Adding NetwrokACl rules to make NAT rule accessible")
NetworkACL.create(
self.apiclient,
networkid=network_1.id,
services=self.services["natrule"],
traffictype='Ingress'
)
self.debug("Checking if we can SSH into VM using NAT rule?")
try:
ssh_3 = vm_1.get_ssh_client(
ipaddress=public_ip_3.ipaddress.ipaddress,
reconnect=True,
port=self.services["natrule"]["publicport"]
)
self.debug("SSH into VM is successfully")
self.debug("Verifying if we can ping to outside world from VM?")
res = ssh_3.execute("ping -c 1 www.google.com")
except Exception as e:
self.fail("Failed to SSH into VM - %s, %s" %
(public_ip_3.ipaddress.ipaddress, e))
result = str(res)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
return
@attr(tags=["advanced", "intervlan", "provisioning"])
def test_02_network_vpcvr2vr_upgrade(self):
""" Test update Network that is NOT part of a VPC to a nw offering that has services that are provided by VPCVR and vice versa
"""
# Validate the following
# 1. Create a Network offering - NO1 with all supported services
# except PF services provided by VRVPC provider, conserve mode=OFF
# 2.Create a Network offering - NO2 with all supported services
# including Pf services provided by VR provider, conserve mode=OFF
# 3. Deploy a Vm using a network, network1 created from NO2
# 4. Update network1 to NO1.
self.debug("Creating a VPC offering..")
vpc_off = VpcOffering.create(
self.apiclient,
self.services["vpc_offering"]
)
self.cleanup.append(vpc_off)
self.validate_vpc_offering(vpc_off)
self.debug("Enabling the VPC offering created")
vpc_off.update(self.apiclient, state='Enabled')
self.debug("creating a VPC network in the account: %s" %
self.account.name)
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.validate_vpc_network(vpc)
nw_off = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
# Enable Network offering
nw_off.update(self.apiclient, state='Enabled')
self.cleanup.append(nw_off)
self.services["network_offering"]["supportedservices"] = 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,UserData,Lb,StaticNat'
self.services["network_offering"]["serviceProviderList"] = {
"Vpn": 'VirtualRouter',
"Dhcp": 'VirtualRouter',
"Dns": 'VirtualRouter',
"SourceNat": 'VirtualRouter',
"PortForwarding": 'VirtualRouter',
"Lb": 'VirtualRouter',
"UserData": 'VirtualRouter',
"StaticNat": 'VirtualRouter',
}
nw_off_vr = NetworkOffering.create(
self.apiclient,
self.services["network_offering"],
conservemode=False
)
# Enable Network offering
nw_off_vr.update(self.apiclient, state='Enabled')
self.cleanup.append(nw_off_vr)
# Creating network using the network offering created
self.debug("Creating network with network offering: %s" % nw_off.id)
network_1 = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=nw_off.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id
)
self.debug("Created network with ID: %s" % network_1.id)
self.debug("deploying VMs in network: %s" % network_1.name)
# Spawn an instance in that network
vm_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(network_1.id)]
)
self.debug("Deployed VM in network: %s" % network_1.id)
self.debug(
"Stopping all the virtual machines in network before upgrade")
try:
vm_1.stop(self.apiclient)
except Exception as e:
self.fail("Failed to stop VMs, %s" % e)
self.debug("Upgrading network offering to support PF services")
with self.assertRaises(Exception):
network_1.update(
self.apiclient,
networkofferingid=nw_off_vr.id,
changecidr=True
)
return
class TestVPCNetworkGc(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestVPCNetworkGc, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.vpc_off = VpcOffering.create(
cls.api_client,
cls.services["vpc_offering"]
)
cls.vpc_off.update(cls.api_client, state='Enabled')
cls.account = Account.create(
cls.api_client,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
cls.services["vpc"]["cidr"] = '10.1.1.1/16'
cls.vpc = VPC.create(
cls.api_client,
cls.services["vpc"],
vpcofferingid=cls.vpc_off.id,
zoneid=cls.zone.id,
account=cls.account.name,
domainid=cls.account.domainid
)
cls.nw_off = NetworkOffering.create(
cls.api_client,
cls.services["network_offering"],
conservemode=False
)
# Enable Network offering
cls.nw_off.update(cls.api_client, state='Enabled')
cls.network_1 = Network.create(
cls.api_client,
cls.services["network"],
accountid=cls.account.name,
domainid=cls.account.domainid,
networkofferingid=cls.nw_off.id,
zoneid=cls.zone.id,
gateway='10.1.1.1',
vpcid=cls.vpc.id
)
# Spawn an instance in that network
cls.vm_1 = VirtualMachine.create(
cls.api_client,
cls.services["virtual_machine"],
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
networkids=[str(cls.network_1.id)]
)
cls.vm_2 = VirtualMachine.create(
cls.api_client,
cls.services["virtual_machine"],
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
networkids=[str(cls.network_1.id)]
)
cls.public_ip_1 = PublicIPAddress.create(
cls.api_client,
accountid=cls.account.name,
zoneid=cls.zone.id,
domainid=cls.account.domainid,
networkid=cls.network_1.id,
vpcid=cls.vpc.id
)
cls.lb_rule = LoadBalancerRule.create(
cls.api_client,
cls.services["lbrule"],
ipaddressid=cls.public_ip_1.ipaddress.id,
accountid=cls.account.name,
networkid=cls.network_1.id,
vpcid=cls.vpc.id,
domainid=cls.account.domainid
)
cls.lb_rule.assign(cls.api_client, [cls.vm_1, cls.vm_2])
cls.public_ip_2 = PublicIPAddress.create(
cls.api_client,
accountid=cls.account.name,
zoneid=cls.zone.id,
domainid=cls.account.domainid,
networkid=cls.network_1.id,
vpcid=cls.vpc.id
)
StaticNATRule.enable(
cls.api_client,
ipaddressid=cls.public_ip_2.ipaddress.id,
virtualmachineid=cls.vm_1.id,
networkid=cls.network_1.id
)
cls.nwacl_lb = NetworkACL.create(
cls.api_client,
networkid=cls.network_1.id,
services=cls.services["lbrule"],
traffictype='Ingress'
)
cls.nwacl_internet_1 = NetworkACL.create(
cls.api_client,
networkid=cls.network_1.id,
services=cls.services["icmp_rule"],
traffictype='Egress'
)
return
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
# Stop all the VMs as part of test
vms = VirtualMachine.list(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
listall=True
)
for vm in vms:
if vm.state == "Running":
cmd = stopVirtualMachine.stopVirtualMachineCmd()
cmd.id = vm.id
self.apiclient.stopVirtualMachine(cmd)
return
def tearDown(self):
# Start all the VMs after test execution
vms = VirtualMachine.list(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
listall=True
)
for vm in vms:
if vm.state == "Stopped":
cmd = startVirtualMachine.startVirtualMachineCmd()
cmd.id = vm.id
self.apiclient.startVirtualMachine(cmd)
return
def validate_vpc_offering(self, vpc_offering):
"""Validates the VPC offering"""
self.debug("Check if the VPC offering is created successfully?")
vpc_offs = VpcOffering.list(
self.apiclient,
id=vpc_offering.id
)
self.assertEqual(
isinstance(vpc_offs, list),
True,
"List VPC offerings should return a valid list"
)
self.assertEqual(
vpc_offering.name,
vpc_offs[0].name,
"Name of the VPC offering should match with listVPCOff data"
)
self.debug(
"VPC offering is created successfully - %s" %
vpc_offering.name)
return
def validate_vpc_network(self, network, state=None):
"""Validates the VPC network"""
self.debug("Check if the VPC network is created successfully?")
vpc_networks = VPC.list(
self.apiclient,
id=network.id
)
self.assertEqual(
isinstance(vpc_networks, list),
True,
"List VPC network should return a valid list"
)
self.assertEqual(
network.name,
vpc_networks[0].name,
"Name of the VPC network should match with listVPC data"
)
if state:
self.assertEqual(
vpc_networks[0].state,
state,
"VPC state should be '%s'" % state
)
self.debug("VPC network validated - %s" % network.name)
return
@attr(tags=["advanced", "intervlan", "provisioning"])
def test_01_wait_network_gc(self):
""" Test network gc after shutdown of vms in the network
"""
# Validate the following
# 1. Stop vm1 and vm2
# 2. Wait for network GC
# 3. When the network GC thread is run, NIC relating to this guest
# network will get hot unplugged.
# 4. All the PF/Static NAT/LB rules for this network should be cleaned
# from VPCVR.
# 5. All network Acl should be cleaned from VPCVR.
# 6. All the network rules pertaining to the network in "Implemented"
# state should continue to work.
self.debug("Waiting for network garbage collection thread to run")
# Wait for the network garbage collection thread to run
wait_for_cleanup(self.apiclient,
["network.gc.interval", "network.gc.wait"])
lbrules = LoadBalancerRule.list(self.apiclient, networkid=self.network_1.id)
self.debug("List of LB Rules %s" % lbrules)
self.assertEqual(lbrules, None, "LBrules were not cleared after network GC thread is run")
return
@attr(tags=["advanced", "intervlan", "provisioning"])
def test_02_start_vm_network_gc(self):
""" Test network rules after starting a VpcVr that was shutdown after network.gc
"""
# Validate the following
# 1. Stop vm1 and vm2
# 2. Wait for network GC. Start 1st VM
# 3. All the network rules created shall continue to work.
self.debug("Waiting for network garbage collection thread to run")
# Wait for the network garbage collection thread to run
wait_for_cleanup(self.apiclient,
["network.gc.interval", "network.gc.wait"])
self.debug("Starting one of the virtual machine")
try:
self.vm_1.start(self.apiclient)
except Exception as e:
self.fail("Failed to start virtual machine: %s, %s" %
(self.vm_1.name, e))
try:
ssh_1 = self.vm_1.get_ssh_client(
ipaddress=self.public_ip_1.ipaddress.ipaddress,
reconnect=True,
port=self.services["lbrule"]["publicport"]
)
self.debug("SSH into VM is successfully")
self.debug("Verifying if we can ping to outside world from VM?")
# Ping to outsite world
res = ssh_1.execute("ping -c 1 www.google.com")
# res = 64 bytes from maa03s17-in-f20.1e100.net (172.16.17.32):
# icmp_req=1 ttl=57 time=25.9 ms
# --- www.l.google.com ping statistics ---
# 1 packets transmitted, 1 received, 0% packet loss, time 0ms
# rtt min/avg/max/mdev = 25.970/25.970/25.970/0.000 ms
except Exception as e:
self.fail("Failed to SSH into VM - %s, %s" %
(self.public_ip_1.ipaddress.ipaddress, e))
result = str(res)
self.debug("Result: %s" % result)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
self.debug("Checking if we can SSH into VM_2?")
try:
ssh_2 = self.vm_1.get_ssh_client(
ipaddress=self.public_ip_2.ipaddress.ipaddress,
reconnect=True,
port=self.services["natrule"]["publicport"]
)
self.debug("SSH into VM is successfully")
self.debug("Verifying if we can ping to outside world from VM?")
res = ssh_2.execute("ping -c 1 www.google.com")
except Exception as e:
self.fail("Failed to SSH into VM - %s, %s" %
(self.public_ip_2.ipaddress.ipaddress, e))
result = str(res)
self.debug("Result: %s" % result)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
return
@attr(tags=["advanced", "intervlan", "provisioning"])
def test_03_restart_vpcvr(self):
""" Test Stop all the Vms that are part of the a Network
(Wait for network GC).Restart VPCVR.
"""
# Validate the following
# 1. Stop vm3 and vm4
# 2. Wait for network GC. Restart VPC VR
# 3. All the network rules created shall continue to work.
self.debug("Starting instances 1 and 2")
try:
self.vm_1.start(self.apiclient)
self.vm_2.start(self.apiclient)
except Exception as e:
self.fail("Failed to start Virtual machines")
self.debug("Waiting for network garbage collection thread to run")
# Wait for the network garbage collection thread to run
wait_for_cleanup(self.apiclient,
["network.gc.interval", "network.gc.wait"])
self.debug("Finding the VPC virtual router for account: %s" %
self.account.name)
routers = Router.list(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
listall=True
)
self.assertEqual(
isinstance(routers, list),
True,
"List routers shall return a valid list"
)
vpcvr = routers[0]
self.debug("restarting the VPC virtual router")
try:
Router.reboot(
self.apiclient,
id=vpcvr.id
)
except Exception as e:
self.fail("Failed to reboot the virtual router: %s, %s" %
(vpcvr.id, e))
try:
ssh_1 = self.vm_1.get_ssh_client(
ipaddress=self.public_ip_1.ipaddress.ipaddress,
reconnect=True,
port=self.services["lbrule"]["publicport"]
)
self.debug("SSH into VM is successfully")
self.debug("Verifying if we can ping to outside world from VM?")
# Ping to outsite world
res = ssh_1.execute("ping -c 1 www.google.com")
# res = 64 bytes from maa03s17-in-f20.1e100.net (172.16.17.32):
# icmp_req=1 ttl=57 time=25.9 ms
# --- www.l.google.com ping statistics ---
# 1 packets transmitted, 1 received, 0% packet loss, time 0ms
# rtt min/avg/max/mdev = 25.970/25.970/25.970/0.000 ms
except Exception as e:
self.fail("Failed to SSH into VM - %s, %s" %
(self.public_ip_1.ipaddress.ipaddress, e))
result = str(res)
self.debug("Result: %s" % result)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
self.debug("Checking if we can SSH into VM_2?")
try:
ssh_2 = self.vm_1.get_ssh_client(
ipaddress=self.public_ip_2.ipaddress.ipaddress,
reconnect=True,
port=self.services["natrule"]["publicport"]
)
self.debug("SSH into VM is successfully")
self.debug("Verifying if we can ping to outside world from VM?")
res = ssh_2.execute("ping -c 1 www.google.com")
except Exception as e:
self.fail("Failed to SSH into VM - %s, %s" %
(self.public_ip_2.ipaddress.ipaddress, e))
result = str(res)
self.debug("Result: %s" % result)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
return
| [
"marvin.lib.base.Router.reboot",
"marvin.lib.base.Network.list",
"marvin.lib.utils.validateList",
"marvin.lib.base.NATRule.create",
"marvin.lib.common.wait_for_cleanup",
"marvin.lib.common.list_networks",
"marvin.cloudstackTestCase.unittest.skip",
"marvin.lib.base.VpcOffering.list",
"marvin.lib.base... | [((15250, 15300), 'ddt.data', 'data', (['"""network_offering"""', '"""network_offering_vpcns"""'], {}), "('network_offering', 'network_offering_vpcns')\n", (15254, 15300), False, 'from ddt import ddt, data\n'), ((15306, 15342), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (15310, 15342), False, 'from nose.plugins.attrib import attr\n'), ((19501, 19551), 'ddt.data', 'data', (['"""network_offering"""', '"""network_offering_vpcns"""'], {}), "('network_offering', 'network_offering_vpcns')\n", (19505, 19551), False, 'from ddt import ddt, data\n'), ((19557, 19593), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (19561, 19593), False, 'from nose.plugins.attrib import attr\n'), ((22956, 23006), 'ddt.data', 'data', (['"""network_offering"""', '"""network_offering_vpcns"""'], {}), "('network_offering', 'network_offering_vpcns')\n", (22960, 23006), False, 'from ddt import ddt, data\n'), ((23012, 23048), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (23016, 23048), False, 'from nose.plugins.attrib import attr\n'), ((27976, 28000), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['intervlan']"}), "(tags=['intervlan'])\n", (27980, 28000), False, 'from nose.plugins.attrib import attr\n'), ((30543, 30603), 'marvin.cloudstackTestCase.unittest.skip', 'unittest.skip', (['"""skipped - RvR didn\'t support VPC currently """'], {}), '("skipped - RvR didn\'t support VPC currently ")\n', (30556, 30603), False, 'from marvin.cloudstackTestCase import cloudstackTestCase, unittest\n'), ((30609, 30651), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'NA']"}), "(tags=['advanced', 'intervlan', 'NA'])\n", (30613, 30651), False, 'from nose.plugins.attrib import attr\n'), ((34064, 34115), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'selfservice']"}), "(tags=['advanced', 'intervlan', 'selfservice'])\n", (34068, 34115), False, 'from nose.plugins.attrib import attr\n'), ((37243, 37294), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'selfservice']"}), "(tags=['advanced', 'intervlan', 'selfservice'])\n", (37247, 37294), False, 'from nose.plugins.attrib import attr\n'), ((40422, 40474), 'ddt.data', 'data', (['"""network_off_shared"""', '"""network_offering_vpcns"""'], {}), "('network_off_shared', 'network_offering_vpcns')\n", (40426, 40474), False, 'from ddt import ddt, data\n'), ((40480, 40516), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (40484, 40516), False, 'from nose.plugins.attrib import attr\n'), ((43719, 43769), 'ddt.data', 'data', (['"""network_offering"""', '"""network_offering_vpcns"""'], {}), "('network_offering', 'network_offering_vpcns')\n", (43723, 43769), False, 'from ddt import ddt, data\n'), ((43775, 43811), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (43779, 43811), False, 'from nose.plugins.attrib import attr\n'), ((49481, 49531), 'ddt.data', 'data', (['"""network_offering"""', '"""network_offering_vpcns"""'], {}), "('network_offering', 'network_offering_vpcns')\n", (49485, 49531), False, 'from ddt import ddt, data\n'), ((49537, 49573), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (49541, 49573), False, 'from nose.plugins.attrib import attr\n'), ((52505, 52556), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'selfservice']"}), "(tags=['advanced', 'intervlan', 'selfservice'])\n", (52509, 52556), False, 'from nose.plugins.attrib import attr\n'), ((55203, 55253), 'ddt.data', 'data', (['"""network_offering"""', '"""network_offering_vpcns"""'], {}), "('network_offering', 'network_offering_vpcns')\n", (55207, 55253), False, 'from ddt import ddt, data\n'), ((55259, 55295), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (55263, 55295), False, 'from nose.plugins.attrib import attr\n'), ((58428, 58478), 'ddt.data', 'data', (['"""network_offering"""', '"""network_offering_vpcns"""'], {}), "('network_offering', 'network_offering_vpcns')\n", (58432, 58478), False, 'from ddt import ddt, data\n'), ((58484, 58520), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (58488, 58520), False, 'from nose.plugins.attrib import attr\n'), ((64438, 64488), 'ddt.data', 'data', (['"""network_offering"""', '"""network_offering_vpcns"""'], {}), "('network_offering', 'network_offering_vpcns')\n", (64442, 64488), False, 'from ddt import ddt, data\n'), ((64494, 64530), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']"}), "(tags=['advanced', 'intervlan'])\n", (64498, 64530), False, 'from nose.plugins.attrib import attr\n'), ((72235, 72287), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'provisioning']"}), "(tags=['advanced', 'intervlan', 'provisioning'])\n", (72239, 72287), False, 'from nose.plugins.attrib import attr\n'), ((89231, 89283), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'provisioning']"}), "(tags=['advanced', 'intervlan', 'provisioning'])\n", (89235, 89283), False, 'from nose.plugins.attrib import attr\n'), ((104213, 104265), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'provisioning']"}), "(tags=['advanced', 'intervlan', 'provisioning'])\n", (104217, 104265), False, 'from nose.plugins.attrib import attr\n'), ((105392, 105444), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'provisioning']"}), "(tags=['advanced', 'intervlan', 'provisioning'])\n", (105396, 105444), False, 'from nose.plugins.attrib import attr\n'), ((108596, 108648), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan', 'provisioning']"}), "(tags=['advanced', 'intervlan', 'provisioning'])\n", (108600, 108648), False, 'from nose.plugins.attrib import attr\n'), ((10979, 11005), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (10989, 11005), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((11107, 11172), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (11119, 11172), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((11479, 11551), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (11501, 11551), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((12704, 12801), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (12718, 12801), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((13514, 13566), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'id': 'vpc_offering.id'}), '(self.apiclient, id=vpc_offering.id)\n', (13530, 13566), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((14445, 14484), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'network.id'}), '(self.apiclient, id=network.id)\n', (14453, 14484), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((16874, 17037), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (16884, 17037), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((17278, 17363), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'self.services[value]'], {'conservemode': '(False)'}), '(self.apiclient, self.services[value], conservemode=False\n )\n', (17300, 17363), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((17917, 18143), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (17931, 18143), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((18602, 18659), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'network.id', 'listall': '(True)'}), '(self.apiclient, id=network.id, listall=True)\n', (18614, 18659), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((21219, 21382), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (21229, 21382), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((21752, 21837), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'self.services[value]'], {'conservemode': '(False)'}), '(self.apiclient, self.services[value], conservemode=False\n )\n', (21774, 21837), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((24621, 24784), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (24631, 24784), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((25025, 25110), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'self.services[value]'], {'conservemode': '(False)'}), '(self.apiclient, self.services[value], conservemode=False\n )\n', (25047, 25110), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((25664, 25890), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (25678, 25890), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((26349, 26406), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'network.id', 'listall': '(True)'}), '(self.apiclient, id=network.id, listall=True)\n', (26361, 26406), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((28544, 28619), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (28560, 28619), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((28926, 29089), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (28936, 29089), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((29330, 29434), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering_vpcns']"], {'conservemode': '(False)'}), "(self.apiclient, self.services[\n 'network_offering_vpcns'], conservemode=False)\n", (29352, 29434), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((31439, 31504), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (31457, 31504), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((32017, 32180), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (32027, 32180), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((32801, 32898), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (32823, 32898), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((34967, 35032), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (34985, 35032), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((35545, 35708), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (35555, 35708), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((35949, 36046), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (35971, 36046), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((38207, 38272), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (38225, 38272), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((38785, 38948), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (38795, 38948), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((41964, 42127), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (41974, 42127), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((42439, 42538), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_off_shared']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_off_shared'],\n conservemode=False)\n", (42461, 42538), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((45374, 45400), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (45384, 45400), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((45502, 45567), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (45514, 45567), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((45874, 45946), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (45896, 45946), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((47010, 47107), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (47024, 47107), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((47745, 47797), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'id': 'vpc_offering.id'}), '(self.apiclient, id=vpc_offering.id)\n', (47761, 47797), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((48676, 48715), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'network.id'}), '(self.apiclient, id=network.id)\n', (48684, 48715), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((50841, 51004), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (50851, 51004), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((51294, 51379), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'self.services[value]'], {'conservemode': '(False)'}), '(self.apiclient, self.services[value], conservemode=False\n )\n', (51316, 51379), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((53016, 53081), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (53034, 53081), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((53526, 53689), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (53536, 53689), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((53979, 54076), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (54001, 54076), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((56628, 56791), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (56638, 56791), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((57081, 57166), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'self.services[value]'], {'conservemode': '(False)'}), '(self.apiclient, self.services[value], conservemode=False\n )\n', (57103, 57166), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((60047, 60210), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (60057, 60210), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((60500, 60585), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'self.services[value]'], {'conservemode': '(False)'}), '(self.apiclient, self.services[value], conservemode=False\n )\n', (60522, 60585), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((61123, 61349), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (61137, 61349), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((61808, 61865), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'network.id', 'listall': '(True)'}), '(self.apiclient, id=network.id, listall=True)\n', (61820, 61865), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((65940, 66103), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (65950, 66103), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((66393, 66478), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'self.services[value]'], {'conservemode': '(False)'}), '(self.apiclient, self.services[value], conservemode=False\n )\n', (66415, 66478), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((66982, 67079), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (66996, 67079), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((68557, 68583), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (68567, 68583), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((68685, 68750), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (68697, 68750), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((69057, 69129), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (69079, 69129), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((69764, 69861), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (69778, 69861), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((70499, 70551), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'id': 'vpc_offering.id'}), '(self.apiclient, id=vpc_offering.id)\n', (70515, 70551), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((71430, 71469), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'network.id'}), '(self.apiclient, id=network.id)\n', (71438, 71469), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((73272, 73347), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (73288, 73347), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((73654, 73817), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (73664, 73817), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((74043, 74140), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (74065, 74140), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((75290, 75387), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (75312, 75387), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((75893, 76110), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'nw_off_no_pf.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=\n nw_off_no_pf.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (75907, 76110), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((77733, 77900), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network_1.id', 'vpcid': 'vpc.id'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=network_1.id,\n vpcid=vpc.id)\n', (77755, 77900), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((78494, 78703), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['self.apiclient', "self.services['lbrule']"], {'ipaddressid': 'public_ip_1.ipaddress.id', 'accountid': 'self.account.name', 'networkid': 'network_1.id', 'vpcid': 'vpc.id', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['lbrule'],\n ipaddressid=public_ip_1.ipaddress.id, accountid=self.account.name,\n networkid=network_1.id, vpcid=vpc.id, domainid=self.account.domainid)\n", (78517, 78703), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((79202, 79369), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network_1.id', 'vpcid': 'vpc.id'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=network_1.id,\n vpcid=vpc.id)\n', (79224, 79369), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((80579, 80739), 'marvin.lib.base.PublicIPAddress.list', 'PublicIPAddress.list', (['self.apiclient'], {'networkid': 'network_1.id', 'listall': '(True)', 'isstaticnat': '(True)', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, networkid=network_1.id, listall=True,\n isstaticnat=True, account=self.account.name, domainid=self.account.domainid\n )\n', (80599, 80739), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((81523, 81642), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', (['self.apiclient'], {'networkid': 'network_1.id', 'services': "self.services['lbrule']", 'traffictype': '"""Ingress"""'}), "(self.apiclient, networkid=network_1.id, services=self.\n services['lbrule'], traffictype='Ingress')\n", (81540, 81642), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((81942, 82063), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', (['self.apiclient'], {'networkid': 'network_1.id', 'services': "self.services['icmp_rule']", 'traffictype': '"""Egress"""'}), "(self.apiclient, networkid=network_1.id, services=self.\n services['icmp_rule'], traffictype='Egress')\n", (81959, 82063), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((84693, 84860), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network_1.id', 'vpcid': 'vpc.id'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=network_1.id,\n vpcid=vpc.id)\n', (84715, 84860), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((87597, 87764), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'vm_1', "self.services['natrule']"], {'ipaddressid': 'public_ip_3.ipaddress.id', 'openfirewall': '(False)', 'networkid': 'network_1.id', 'vpcid': 'vpc.id'}), "(self.apiclient, vm_1, self.services['natrule'], ipaddressid=\n public_ip_3.ipaddress.id, openfirewall=False, networkid=network_1.id,\n vpcid=vpc.id)\n", (87611, 87764), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((88025, 88145), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', (['self.apiclient'], {'networkid': 'network_1.id', 'services': "self.services['natrule']", 'traffictype': '"""Ingress"""'}), "(self.apiclient, networkid=network_1.id, services=self.\n services['natrule'], traffictype='Ingress')\n", (88042, 88145), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((89986, 90051), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (90004, 90051), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((90564, 90727), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id, account=self.account.name, domainid=self.account.\n domainid)\n", (90574, 90727), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((90953, 91050), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (90975, 91050), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((92150, 92247), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (92172, 92247), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((92681, 92892), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'nw_off.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=nw_off.\n id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (92695, 92892), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((94771, 94797), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (94781, 94797), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((94899, 94964), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (94911, 94964), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((95271, 95343), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (95293, 95343), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((95500, 95564), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['cls.api_client', "cls.services['vpc_offering']"], {}), "(cls.api_client, cls.services['vpc_offering'])\n", (95518, 95564), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((95761, 95856), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], admin=True,\n domainid=cls.domain.id)\n", (95775, 95856), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((96152, 96316), 'marvin.lib.base.VPC.create', 'VPC.create', (['cls.api_client', "cls.services['vpc']"], {'vpcofferingid': 'cls.vpc_off.id', 'zoneid': 'cls.zone.id', 'account': 'cls.account.name', 'domainid': 'cls.account.domainid'}), "(cls.api_client, cls.services['vpc'], vpcofferingid=cls.vpc_off.\n id, zoneid=cls.zone.id, account=cls.account.name, domainid=cls.account.\n domainid)\n", (96162, 96316), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((96506, 96602), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['network_offering']"], {'conservemode': '(False)'}), "(cls.api_client, cls.services['network_offering'],\n conservemode=False)\n", (96528, 96602), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((96895, 97110), 'marvin.lib.base.Network.create', 'Network.create', (['cls.api_client', "cls.services['network']"], {'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'networkofferingid': 'cls.nw_off.id', 'zoneid': 'cls.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'cls.vpc.id'}), "(cls.api_client, cls.services['network'], accountid=cls.\n account.name, domainid=cls.account.domainid, networkofferingid=cls.\n nw_off.id, zoneid=cls.zone.id, gateway='10.1.1.1', vpcid=cls.vpc.id)\n", (96909, 97110), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((98397, 98569), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['cls.api_client'], {'accountid': 'cls.account.name', 'zoneid': 'cls.zone.id', 'domainid': 'cls.account.domainid', 'networkid': 'cls.network_1.id', 'vpcid': 'cls.vpc.id'}), '(cls.api_client, accountid=cls.account.name, zoneid=\n cls.zone.id, domainid=cls.account.domainid, networkid=cls.network_1.id,\n vpcid=cls.vpc.id)\n', (98419, 98569), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((98809, 99029), 'marvin.lib.base.LoadBalancerRule.create', 'LoadBalancerRule.create', (['cls.api_client', "cls.services['lbrule']"], {'ipaddressid': 'cls.public_ip_1.ipaddress.id', 'accountid': 'cls.account.name', 'networkid': 'cls.network_1.id', 'vpcid': 'cls.vpc.id', 'domainid': 'cls.account.domainid'}), "(cls.api_client, cls.services['lbrule'], ipaddressid\n =cls.public_ip_1.ipaddress.id, accountid=cls.account.name, networkid=\n cls.network_1.id, vpcid=cls.vpc.id, domainid=cls.account.domainid)\n", (98832, 99029), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((99398, 99570), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['cls.api_client'], {'accountid': 'cls.account.name', 'zoneid': 'cls.zone.id', 'domainid': 'cls.account.domainid', 'networkid': 'cls.network_1.id', 'vpcid': 'cls.vpc.id'}), '(cls.api_client, accountid=cls.account.name, zoneid=\n cls.zone.id, domainid=cls.account.domainid, networkid=cls.network_1.id,\n vpcid=cls.vpc.id)\n', (99420, 99570), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((99796, 99937), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['cls.api_client'], {'ipaddressid': 'cls.public_ip_2.ipaddress.id', 'virtualmachineid': 'cls.vm_1.id', 'networkid': 'cls.network_1.id'}), '(cls.api_client, ipaddressid=cls.public_ip_2.ipaddress.\n id, virtualmachineid=cls.vm_1.id, networkid=cls.network_1.id)\n', (99816, 99937), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((100108, 100230), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', (['cls.api_client'], {'networkid': 'cls.network_1.id', 'services': "cls.services['lbrule']", 'traffictype': '"""Ingress"""'}), "(cls.api_client, networkid=cls.network_1.id, services=cls.\n services['lbrule'], traffictype='Ingress')\n", (100125, 100230), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((100419, 100543), 'marvin.lib.base.NetworkACL.create', 'NetworkACL.create', (['cls.api_client'], {'networkid': 'cls.network_1.id', 'services': "cls.services['icmp_rule']", 'traffictype': '"""Egress"""'}), "(cls.api_client, networkid=cls.network_1.id, services=cls.\n services['icmp_rule'], traffictype='Egress')\n", (100436, 100543), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((101184, 101297), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'listall': '(True)'}), '(self.apiclient, account=self.account.name, domainid=\n self.account.domainid, listall=True)\n', (101203, 101297), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((101780, 101893), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'listall': '(True)'}), '(self.apiclient, account=self.account.name, domainid=\n self.account.domainid, listall=True)\n', (101799, 101893), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((102477, 102529), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'id': 'vpc_offering.id'}), '(self.apiclient, id=vpc_offering.id)\n', (102493, 102529), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((103408, 103447), 'marvin.lib.base.VPC.list', 'VPC.list', (['self.apiclient'], {'id': 'network.id'}), '(self.apiclient, id=network.id)\n', (103416, 103447), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((105032, 105108), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.apiclient', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.apiclient, ['network.gc.interval', 'network.gc.wait'])\n", (105048, 105108), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((105153, 105219), 'marvin.lib.base.LoadBalancerRule.list', 'LoadBalancerRule.list', (['self.apiclient'], {'networkid': 'self.network_1.id'}), '(self.apiclient, networkid=self.network_1.id)\n', (105174, 105219), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((105915, 105991), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.apiclient', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.apiclient, ['network.gc.interval', 'network.gc.wait'])\n", (105931, 105991), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((109380, 109456), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.apiclient', "['network.gc.interval', 'network.gc.wait']"], {}), "(self.apiclient, ['network.gc.interval', 'network.gc.wait'])\n", (109396, 109456), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((109634, 109739), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'listall': '(True)'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, listall=True)\n', (109645, 109739), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((11913, 11982), 'marvin.lib.common.add_netscaler', 'add_netscaler', (['cls.api_client', 'cls.zone.id', "cls.services['netscaler']"], {}), "(cls.api_client, cls.zone.id, cls.services['netscaler'])\n", (11926, 11982), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((12333, 12380), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (12350, 12380), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((13090, 13137), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (13107, 13137), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((16224, 16299), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (16240, 16299), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((16476, 16572), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering with Netscaler"""', 'listall': '(True)'}), "(self.apiclient, name=\n 'Default VPC offering with Netscaler', listall=True)\n", (16492, 16572), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((20569, 20644), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (20585, 20644), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((20821, 20917), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering with Netscaler"""', 'listall': '(True)'}), "(self.apiclient, name=\n 'Default VPC offering with Netscaler', listall=True)\n", (20837, 20917), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((22428, 22654), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (22442, 22654), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((23971, 24046), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (23987, 24046), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((24223, 24319), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering with Netscaler"""', 'listall': '(True)'}), "(self.apiclient, name=\n 'Default VPC offering with Netscaler', listall=True)\n", (24239, 24319), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((27351, 27577), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.2.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.2.1', vpcid=vpc.id)\n", (27365, 27577), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((30060, 30286), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (30074, 30286), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((33490, 33716), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.2.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.2.1', vpcid=vpc.id)\n", (33504, 33716), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((36638, 36864), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.2.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.2.1', vpcid=vpc.id)\n", (36652, 36864), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((40085, 40182), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.services['network_offering']"], {'conservemode': '(False)'}), "(self.apiclient, self.services['network_offering'],\n conservemode=False)\n", (40107, 40182), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((41314, 41389), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (41330, 41389), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((41566, 41662), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering with Netscaler"""', 'listall': '(True)'}), "(self.apiclient, name=\n 'Default VPC offering with Netscaler', listall=True)\n", (41582, 41662), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((43145, 43371), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (43159, 43371), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((44503, 44582), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'self.services[value]'], {'conservemode': '(True)'}), '(self.apiclient, self.services[value], conservemode=True)\n', (44525, 44582), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((46308, 46377), 'marvin.lib.common.add_netscaler', 'add_netscaler', (['cls.api_client', 'cls.zone.id', "cls.services['netscaler']"], {}), "(cls.api_client, cls.zone.id, cls.services['netscaler'])\n", (46321, 46377), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((46683, 46730), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (46700, 46730), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((47396, 47443), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (47413, 47443), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((50191, 50266), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (50207, 50266), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((50443, 50539), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering with Netscaler"""', 'listall': '(True)'}), "(self.apiclient, name=\n 'Default VPC offering with Netscaler', listall=True)\n", (50459, 50539), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((51878, 52104), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.2.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.2.1.1', vpcid=vpc.id)\n", (51892, 52104), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((54576, 54802), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.2.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.2.1.1', vpcid=vpc.id)\n", (54590, 54802), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((55910, 55985), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (55926, 55985), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((56162, 56258), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering with Netscaler"""', 'listall': '(True)'}), "(self.apiclient, name=\n 'Default VPC offering with Netscaler', listall=True)\n", (56178, 56258), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((57802, 58028), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (57816, 58028), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((59330, 59405), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (59346, 59405), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((59582, 59678), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering with Netscaler"""', 'listall': '(True)'}), "(self.apiclient, name=\n 'Default VPC offering with Netscaler', listall=True)\n", (59598, 59678), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((62903, 63129), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (62917, 63129), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((63814, 64040), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (63828, 64040), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((65222, 65297), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering"""', 'listall': '(True)'}), "(self.apiclient, name='Default VPC offering', listall=True)\n", (65238, 65297), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((65474, 65570), 'marvin.lib.base.VpcOffering.list', 'VpcOffering.list', (['self.apiclient'], {'name': '"""Default VPC offering with Netscaler"""', 'listall': '(True)'}), "(self.apiclient, name=\n 'Default VPC offering with Netscaler', listall=True)\n", (65490, 65570), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((67617, 67833), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'account.name', 'domainid': 'account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': 'vpc.id'}), "(self.apiclient, self.services['network'], accountid=account.\n name, domainid=account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=vpc.id)\n", (67631, 67833), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((69437, 69484), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (69454, 69484), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((70150, 70197), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (70167, 70197), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((79967, 80095), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient'], {'ipaddressid': 'public_ip_2.ipaddress.id', 'virtualmachineid': 'vm_2.id', 'networkid': 'network_1.id'}), '(self.apiclient, ipaddressid=public_ip_2.ipaddress.id,\n virtualmachineid=vm_2.id, networkid=network_1.id)\n', (79987, 80095), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((85435, 85602), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'vm_1', "self.services['natrule']"], {'ipaddressid': 'public_ip_3.ipaddress.id', 'openfirewall': '(False)', 'networkid': 'network_1.id', 'vpcid': 'vpc.id'}), "(self.apiclient, vm_1, self.services['natrule'], ipaddressid=\n public_ip_3.ipaddress.id, openfirewall=False, networkid=network_1.id,\n vpcid=vpc.id)\n", (85449, 85602), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((86475, 86521), 'marvin.lib.common.list_networks', 'list_networks', (['self.apiclient'], {'id': 'network_1.id'}), '(self.apiclient, id=network_1.id)\n', (86488, 86521), False, 'from marvin.lib.common import get_zone, get_domain, get_template, wait_for_cleanup, add_netscaler, list_networks\n'), ((86955, 86968), 'time.sleep', 'time.sleep', (['(6)'], {}), '(6)\n', (86965, 86968), False, 'import time\n'), ((100823, 100870), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (100840, 100870), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((110197, 110239), 'marvin.lib.base.Router.reboot', 'Router.reboot', (['self.apiclient'], {'id': 'vpcvr.id'}), '(self.apiclient, id=vpcvr.id)\n', (110210, 110239), False, 'from marvin.lib.base import VirtualMachine, ServiceOffering, Account, NATRule, NetworkOffering, Network, VPC, VpcOffering, LoadBalancerRule, Router, StaticNATRule, NetworkACL, PublicIPAddress\n'), ((101548, 101590), 'marvin.cloudstackAPI.stopVirtualMachine.stopVirtualMachineCmd', 'stopVirtualMachine.stopVirtualMachineCmd', ([], {}), '()\n', (101588, 101590), False, 'from marvin.cloudstackAPI import startVirtualMachine, stopVirtualMachine\n'), ((102144, 102188), 'marvin.cloudstackAPI.startVirtualMachine.startVirtualMachineCmd', 'startVirtualMachine.startVirtualMachineCmd', ([], {}), '()\n', (102186, 102188), False, 'from marvin.cloudstackAPI import startVirtualMachine, stopVirtualMachine\n'), ((86551, 86573), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (86563, 86573), False, 'from marvin.lib.utils import cleanup_resources, validateList\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster
from marvin.integration.lib.common import get_zone, get_domain, get_template
from marvin.integration.lib.utils import cleanup_resources
from nose.plugins.attrib import attr
class Services:
def __init__(self):
self.services = {
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended for unique
# username
"password": "password",
},
"service_offering": {
"name": "Planner Service Offering",
"displaytext": "Planner Service Offering",
"cpunumber": 1,
"cpuspeed": 100,
# in MHz
"memory": 128,
# In MBs
},
"ostype": 'CentOS 5.3 (64-bit)',
"virtual_machine": {
"hypervisor": "XenServer",
}
}
class TestDeployVmWithVariedPlanners(cloudstackTestCase):
""" Test to create services offerings for deployment planners
- firstfit, userdispersing
"""
@classmethod
def setUpClass(cls):
cls.apiclient = super(TestDeployVmWithVariedPlanners, cls).getClsTestClient().getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient, cls.services)
cls.zone = get_zone(cls.apiclient, cls.services)
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["template"] = cls.template.id
cls.services["zoneid"] = cls.zone.id
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id
)
cls.services["account"] = cls.account.name
cls.hosts = Host.list(cls.apiclient, type='Routing')
cls.clusters = Cluster.list(cls.apiclient)
cls.cleanup = [
cls.account
]
@attr(tags=["simulator", "advanced", "basic", "sg"])
def test_deployvm_firstfit(self):
"""Test to deploy vm with a first fit offering
"""
#FIXME: How do we know that first fit actually happened?
self.service_offering_firstfit = ServiceOffering.create(
self.apiclient,
self.services["service_offering"],
deploymentplanner='FirstFitPlanner'
)
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_firstfit.id,
templateid=self.template.id
)
list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
self.debug(
"Verify listVirtualMachines response for virtual machine: %s"\
% self.virtual_machine.id
)
self.assertEqual(
isinstance(list_vms, list),
True,
"List VM response was not a valid list"
)
self.assertNotEqual(
len(list_vms),
0,
"List VM response was empty"
)
vm = list_vms[0]
self.assertEqual(
vm.state,
"Running",
msg="VM is not in Running state"
)
@attr(tags=["simulator", "advanced", "basic", "sg"])
def test_deployvm_userdispersing(self):
"""Test deploy VMs using user dispersion planner
"""
self.service_offering_userdispersing = ServiceOffering.create(
self.apiclient,
self.services["service_offering"],
deploymentplanner='UserDispersingPlanner'
)
self.virtual_machine_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_userdispersing.id,
templateid=self.template.id
)
self.virtual_machine_2 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_userdispersing.id,
templateid=self.template.id
)
list_vm_1 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_1.id)
list_vm_2 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_2.id)
self.assertEqual(
isinstance(list_vm_1, list),
True,
"List VM response was not a valid list"
)
self.assertEqual(
isinstance(list_vm_2, list),
True,
"List VM response was not a valid list"
)
vm1 = list_vm_1[0]
vm2 = list_vm_2[0]
self.assertEqual(
vm1.state,
"Running",
msg="VM is not in Running state"
)
self.assertEqual(
vm2.state,
"Running",
msg="VM is not in Running state"
)
vm1clusterid = filter(lambda c: c.id == vm1.hostid, self.hosts)[0].clusterid
vm2clusterid = filter(lambda c: c.id == vm2.hostid, self.hosts)[0].clusterid
if vm1clusterid == vm2clusterid:
self.debug("VMs (%s, %s) meant to be dispersed are deployed in the same cluster %s" % (
vm1.id, vm2.id, vm1clusterid))
@attr(tags=["simulator", "advanced", "basic", "sg"])
def test_deployvm_userconcentrated(self):
"""Test deploy VMs using user concentrated planner
"""
self.service_offering_userconcentrated = ServiceOffering.create(
self.apiclient,
self.services["service_offering"],
deploymentplanner='UserConcentratedPodPlanner'
)
self.virtual_machine_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_userconcentrated.id,
templateid=self.template.id
)
self.virtual_machine_2 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
serviceofferingid=self.service_offering_userconcentrated.id,
templateid=self.template.id
)
list_vm_1 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_1.id)
list_vm_2 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_2.id)
self.assertEqual(
isinstance(list_vm_1, list),
True,
"List VM response was not a valid list"
)
self.assertEqual(
isinstance(list_vm_2, list),
True,
"List VM response was not a valid list"
)
vm1 = list_vm_1[0]
vm2 = list_vm_2[0]
self.assertEqual(
vm1.state,
"Running",
msg="VM is not in Running state"
)
self.assertEqual(
vm2.state,
"Running",
msg="VM is not in Running state"
)
vm1clusterid = filter(lambda c: c.id == vm1.hostid, self.hosts)[0].clusterid
vm2clusterid = filter(lambda c: c.id == vm2.hostid, self.hosts)[0].clusterid
vm1podid = filter(lambda p: p.id == vm1clusterid, self.clusters)[0].podid
vm2podid = filter(lambda p: p.id == vm2clusterid, self.clusters)[0].podid
self.assertEqual(
vm1podid,
vm2podid,
msg="VMs (%s, %s) meant to be pod concentrated are deployed on different pods (%s, %s)" % (vm1.id, vm2.id, vm1clusterid, vm2clusterid)
)
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
| [
"marvin.integration.lib.common.get_domain",
"marvin.integration.lib.base.Host.list",
"marvin.integration.lib.base.ServiceOffering.create",
"marvin.integration.lib.base.VirtualMachine.list",
"marvin.integration.lib.base.Account.create",
"marvin.integration.lib.utils.cleanup_resources",
"marvin.integratio... | [((3119, 3170), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['simulator', 'advanced', 'basic', 'sg']"}), "(tags=['simulator', 'advanced', 'basic', 'sg'])\n", (3123, 3170), False, 'from nose.plugins.attrib import attr\n'), ((4554, 4605), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['simulator', 'advanced', 'basic', 'sg']"}), "(tags=['simulator', 'advanced', 'basic', 'sg'])\n", (4558, 4605), False, 'from nose.plugins.attrib import attr\n'), ((6803, 6854), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['simulator', 'advanced', 'basic', 'sg']"}), "(tags=['simulator', 'advanced', 'basic', 'sg'])\n", (6807, 6854), False, 'from nose.plugins.attrib import attr\n'), ((2353, 2392), 'marvin.integration.lib.common.get_domain', 'get_domain', (['cls.apiclient', 'cls.services'], {}), '(cls.apiclient, cls.services)\n', (2363, 2392), False, 'from marvin.integration.lib.common import get_zone, get_domain, get_template\n'), ((2412, 2449), 'marvin.integration.lib.common.get_zone', 'get_zone', (['cls.apiclient', 'cls.services'], {}), '(cls.apiclient, cls.services)\n', (2420, 2449), False, 'from marvin.integration.lib.common import get_zone, get_domain, get_template\n'), ((2473, 2537), 'marvin.integration.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (2485, 2537), False, 'from marvin.integration.lib.common import get_zone, get_domain, get_template\n'), ((2767, 2845), 'marvin.integration.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (2781, 2845), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((2963, 3003), 'marvin.integration.lib.base.Host.list', 'Host.list', (['cls.apiclient'], {'type': '"""Routing"""'}), "(cls.apiclient, type='Routing')\n", (2972, 3003), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((3027, 3054), 'marvin.integration.lib.base.Cluster.list', 'Cluster.list', (['cls.apiclient'], {}), '(cls.apiclient)\n', (3039, 3054), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((3382, 3496), 'marvin.integration.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {'deploymentplanner': '"""FirstFitPlanner"""'}), "(self.apiclient, self.services['service_offering'],\n deploymentplanner='FirstFitPlanner')\n", (3404, 3496), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((3571, 3819), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_firstfit.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_firstfit.id,\n templateid=self.template.id)\n", (3592, 3819), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((3921, 3984), 'marvin.integration.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (3940, 3984), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((4766, 4886), 'marvin.integration.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {'deploymentplanner': '"""UserDispersingPlanner"""'}), "(self.apiclient, self.services['service_offering'],\n deploymentplanner='UserDispersingPlanner')\n", (4788, 4886), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((4963, 5217), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_userdispersing.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_userdispersing.id,\n templateid=self.template.id)\n", (4984, 5217), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((5332, 5586), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_userdispersing.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_userdispersing.id,\n templateid=self.template.id)\n", (5353, 5586), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((5689, 5754), 'marvin.integration.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine_1.id'}), '(self.apiclient, id=self.virtual_machine_1.id)\n', (5708, 5754), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((5775, 5840), 'marvin.integration.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine_2.id'}), '(self.apiclient, id=self.virtual_machine_2.id)\n', (5794, 5840), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((7021, 7146), 'marvin.integration.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {'deploymentplanner': '"""UserConcentratedPodPlanner"""'}), "(self.apiclient, self.services['service_offering'],\n deploymentplanner='UserConcentratedPodPlanner')\n", (7043, 7146), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((7223, 7479), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_userconcentrated.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_userconcentrated.id,\n templateid=self.template.id)\n", (7244, 7479), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((7594, 7850), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering_userconcentrated.id', 'templateid': 'self.template.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, zoneid=self.zone.id, domainid=self.account\n .domainid, serviceofferingid=self.service_offering_userconcentrated.id,\n templateid=self.template.id)\n", (7615, 7850), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((7953, 8018), 'marvin.integration.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine_1.id'}), '(self.apiclient, id=self.virtual_machine_1.id)\n', (7972, 8018), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((8039, 8104), 'marvin.integration.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine_2.id'}), '(self.apiclient, id=self.virtual_machine_2.id)\n', (8058, 8104), False, 'from marvin.integration.lib.base import Account, VirtualMachine, ServiceOffering, Host, Cluster\n'), ((9340, 9385), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls.cleanup'], {}), '(cls.apiclient, cls.cleanup)\n', (9357, 9385), False, 'from marvin.integration.lib.utils import cleanup_resources\n')] |
# !usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2017-05-07 16:40:21
# @Last modified by: <NAME>
# @Last Modified time: 2017-09-28 17:17:58
from __future__ import print_function, division, absolute_import
from marvin.tests.api.conftest import ApiPage
from marvin.tools.query import Query
from marvin.utils.datamodel.query.base import bestparams
from brain.utils.general import get_yaml_loader
import pytest
import yaml
import os
# @pytest.fixture()
# def page(client, request, init_api):
# blue, endpoint = request.param
# page = ApiPage(client, 'api', endpoint)
# yield page
query_data = yaml.load(open(os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/query_test_data.dat'))), Loader=get_yaml_loader())
@pytest.fixture()
def params(release):
return {'release': release}
@pytest.fixture()
def data(release):
return query_data[release]
def get_query_params(release, paramdisplay):
q = Query(mode='local', release=release)
if paramdisplay == 'best':
qparams = bestparams
else:
qparams = q.get_available_params('all')
return qparams
@pytest.mark.parametrize('page', [('api', 'QueryView:index')], ids=['query'], indirect=True)
class TestQueryView(object):
def test_get_query_success(self, page, params):
page.load_page('get', page.url, params=params)
data = 'this is a query'
page.assert_success(data)
@pytest.mark.parametrize('page', [('api', 'querycubes')], ids=['querycubes'], indirect=True)
class TestQueryCubes(object):
@pytest.mark.xfail(reason='something wrong with the teardown of this test')
@pytest.mark.parametrize('reqtype', [('get'), ('post')])
@pytest.mark.parametrize('searchfilter', [('nsa.z < 0.1')])
def test_query_success(self, page, params, reqtype, searchfilter, data):
params.update({'searchfilter': searchfilter})
expdata = data['queries'][searchfilter]['top5']
page.load_page(reqtype, page.url, params=params)
page.assert_success(expdata, issubset=True)
@pytest.mark.parametrize('reqtype', [('get'), ('post')])
@pytest.mark.parametrize('name, missing, errmsg', [(None, 'release', 'Missing data for required field.'),
(None, 'searchfilter', 'Missing data for required field.')],
ids=['norelease', 'nosearchfilter'])
def test_query_failure(self, page, reqtype, params, name, missing, errmsg):
page.route_no_valid_params(page.url, missing, reqtype=reqtype, errmsg=errmsg)
@pytest.mark.parametrize('page', [('api', 'getparams')], ids=['getparams'], indirect=True)
class TestQueryGetParams(object):
@pytest.mark.parametrize('reqtype', [('get'), ('post')])
@pytest.mark.parametrize('paramdisplay', [('all'), ('best')])
def test_getparams_success(self, release, page, params, reqtype, paramdisplay):
params.update({'paramdisplay': paramdisplay})
expdata = get_query_params(release, paramdisplay)
page.load_page(reqtype, page.url, params=params)
page.assert_success(expdata, keys=True)
@pytest.mark.parametrize('reqtype', [('get'), ('post')])
@pytest.mark.parametrize('name, missing, errmsg', [(None, 'release', 'Missing data for required field.'),
(None, 'paramdisplay', 'Missing data for required field.')],
ids=['norelease', 'noparamdisplay'])
def test_plateifu_failure(self, page, reqtype, params, name, missing, errmsg):
page.route_no_valid_params(page.url, missing, reqtype=reqtype, errmsg=errmsg)
| [
"marvin.tools.query.Query"
] | [((812, 828), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (826, 828), False, 'import pytest\n'), ((885, 901), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (899, 901), False, 'import pytest\n'), ((1184, 1279), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""page"""', "[('api', 'QueryView:index')]"], {'ids': "['query']", 'indirect': '(True)'}), "('page', [('api', 'QueryView:index')], ids=['query'],\n indirect=True)\n", (1207, 1279), False, 'import pytest\n'), ((1483, 1578), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""page"""', "[('api', 'querycubes')]"], {'ids': "['querycubes']", 'indirect': '(True)'}), "('page', [('api', 'querycubes')], ids=['querycubes'],\n indirect=True)\n", (1506, 1578), False, 'import pytest\n'), ((2630, 2723), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""page"""', "[('api', 'getparams')]"], {'ids': "['getparams']", 'indirect': '(True)'}), "('page', [('api', 'getparams')], ids=['getparams'],\n indirect=True)\n", (2653, 2723), False, 'import pytest\n'), ((1007, 1043), 'marvin.tools.query.Query', 'Query', ([], {'mode': '"""local"""', 'release': 'release'}), "(mode='local', release=release)\n", (1012, 1043), False, 'from marvin.tools.query import Query\n'), ((1611, 1685), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""something wrong with the teardown of this test"""'}), "(reason='something wrong with the teardown of this test')\n", (1628, 1685), False, 'import pytest\n'), ((1691, 1742), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""reqtype"""', "['get', 'post']"], {}), "('reqtype', ['get', 'post'])\n", (1714, 1742), False, 'import pytest\n'), ((1752, 1808), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""searchfilter"""', "['nsa.z < 0.1']"], {}), "('searchfilter', ['nsa.z < 0.1'])\n", (1775, 1808), False, 'import pytest\n'), ((2113, 2164), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""reqtype"""', "['get', 'post']"], {}), "('reqtype', ['get', 'post'])\n", (2136, 2164), False, 'import pytest\n'), ((2174, 2384), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""name, missing, errmsg"""', "[(None, 'release', 'Missing data for required field.'), (None,\n 'searchfilter', 'Missing data for required field.')]"], {'ids': "['norelease', 'nosearchfilter']"}), "('name, missing, errmsg', [(None, 'release',\n 'Missing data for required field.'), (None, 'searchfilter',\n 'Missing data for required field.')], ids=['norelease', 'nosearchfilter'])\n", (2197, 2384), False, 'import pytest\n'), ((2760, 2811), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""reqtype"""', "['get', 'post']"], {}), "('reqtype', ['get', 'post'])\n", (2783, 2811), False, 'import pytest\n'), ((2821, 2877), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""paramdisplay"""', "['all', 'best']"], {}), "('paramdisplay', ['all', 'best'])\n", (2844, 2877), False, 'import pytest\n'), ((3189, 3240), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""reqtype"""', "['get', 'post']"], {}), "('reqtype', ['get', 'post'])\n", (3212, 3240), False, 'import pytest\n'), ((3250, 3460), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""name, missing, errmsg"""', "[(None, 'release', 'Missing data for required field.'), (None,\n 'paramdisplay', 'Missing data for required field.')]"], {'ids': "['norelease', 'noparamdisplay']"}), "('name, missing, errmsg', [(None, 'release',\n 'Missing data for required field.'), (None, 'paramdisplay',\n 'Missing data for required field.')], ids=['norelease', 'noparamdisplay'])\n", (3273, 3460), False, 'import pytest\n'), ((790, 807), 'brain.utils.general.get_yaml_loader', 'get_yaml_loader', ([], {}), '()\n', (805, 807), False, 'from brain.utils.general import get_yaml_loader\n'), ((722, 747), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (737, 747), False, 'import os\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Test cases for Delta Snapshots Test Path
"""
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (cleanup_resources,
validateList,
is_snapshot_on_nfs)
from marvin.lib.base import (Account,
ServiceOffering,
Template,
VirtualMachine,
Volume,
Configurations,
Snapshot
)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
list_volumes,
createChecksum,
compareChecksum
)
from marvin.sshClient import SshClient
from marvin.codes import (PASS, FAIL, BACKED_UP, ROOT, DATA)
import time
def checkIntegrityOfSnapshot(
self, snapshotsToRestore, checksumToCompare, disk_type=ROOT):
"""
Check integrity of snapshot created of ROOT or DATA Disk:
If ROOT Disk: Deploy a Vm from a template created from the snapshot
and checking the contents of the ROOT disk.
If DATA Disk: Users can create a volume from the snapshot.
The volume can then be mounted to a VM and files
recovered as needed.
Inputs:
1. snapshotsToRestore: Snapshots whose integrity is
to be checked.
2. checksumToCompare: The contents of ROOT Disk to be compared.
3. disk_type: The type of disk - ROOT or DATA Disk
of which snapshot was created.
"""
if disk_type == ROOT:
# Create template from snapshot
template_from_snapshot = Template.create_from_snapshot(
self.apiclient,
snapshotsToRestore,
self.testdata["template_2"])
self.assertNotEqual(
template_from_snapshot,
None,
"Check if result exists in list item call"
)
# Deploy VM
vm_from_temp = VirtualMachine.create(
self.apiclient,
self.testdata["small"],
templateid=template_from_snapshot.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
self.assertNotEqual(
vm_from_temp,
None,
"Check if result exists in list item call"
)
# Verify contents of ROOT disk match with snapshot
compareChecksum(
self.apiclient,
service=self.testdata,
original_checksum=checksumToCompare,
disk_type="rootdiskdevice",
virt_machine=vm_from_temp
)
vm_from_temp.delete(self.apiclient)
template_from_snapshot.delete(self.apiclient)
else:
volumeFormSnap = Volume.create_from_snapshot(
self.apiclient,
snapshotsToRestore.id,
self.testdata["volume"],
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
temp_vm = VirtualMachine.create(
self.apiclient,
self.testdata["small"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
temp_vm.attach_volume(
self.apiclient,
volumeFormSnap
)
temp_vm.reboot(self.apiclient)
compareChecksum(
self.apiclient,
self.testdata,
checksumToCompare,
"datadiskdevice_1",
temp_vm
)
temp_vm.delete(self.apiclient)
volumeFormSnap.delete(self.apiclient)
return
class TestDeltaSnapshots(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestDeltaSnapshots, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.testdata = testClient.getParsedTestDataConfig()
cls.hypervisor = cls.testClient.getHypervisorInfo()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.template = get_template(
cls.apiclient,
cls.zone.id,
cls.testdata["ostype"])
cls.snapshots_created = []
cls._cleanup = []
cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
cls.skiptest = False
if cls.hypervisor.lower() not in ["xenserver"]:
cls.skiptest = True
try:
# Create an account
cls.account = Account.create(
cls.apiclient,
cls.testdata["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
# Create user api client of the account
cls.userapiclient = testClient.getUserApiClient(
UserName=cls.account.name,
DomainName=cls.account.domain
)
# Create Service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.testdata["service_offering"],
)
cls._cleanup.append(cls.service_offering)
if cls.testdata["configurableData"][
"restartManagementServerThroughTestCase"]:
# Set snapshot delta max value
Configurations.update(cls.apiclient,
name="snapshot.delta.max",
value="3"
)
# Restart management server
cls.RestartServer()
time.sleep(120)
configs = Configurations.list(
cls.apiclient,
name="snapshot.delta.max")
cls.delta_max = configs[0].value
cls.vm = VirtualMachine.create(
cls.apiclient,
cls.testdata["small"],
templateid=cls.template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
zoneid=cls.zone.id,
mode=cls.zone.networktype
)
except Exception as e:
cls.tearDownClass()
raise e
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def setUp(self):
if self.skiptest:
self.skipTest(
"Delta snapshot not supported on %s" %
self.hypervisor)
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
for snapshot in self.snapshots_created:
snapshot.delete(self.apiclient)
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def RestartServer(cls):
"""Restart management server"""
sshClient = SshClient(
cls.mgtSvrDetails["mgtSvrIp"],
22,
cls.mgtSvrDetails["user"],
cls.mgtSvrDetails["passwd"]
)
command = "service cloudstack-management restart"
sshClient.execute(command)
return
@attr(tags=["advanced", "basic"], required_hardware="true")
def test_01_delta_snapshots(self):
""" Delta Snapshots
1. Create file on ROOT disk of deployed VM.
2. Create Snapshot of ROOT disk.
3. Verify secondary storage count.
4. Check integrity of Full Snapshot.
5. Delete delta snaphshot and check integrity of\
remaining snapshots.
6. Delete full snapshot and verify it is deleted from\
secondary storage.
"""
checksum_created = []
full_snapshot_count = 0
delta_snapshot_count = 0
# Mulitply delta max value by 2 to set loop counter
# to create 2 Snapshot chains
snapshot_loop_count = int(self.delta_max) * 2
# Get ROOT Volume
root_volumes_list = list_volumes(
self.apiclient,
virtualmachineid=self.vm.id,
type=ROOT,
listall=True
)
status = validateList(root_volumes_list)
self.assertEqual(
status[0],
PASS,
"Check listVolumes response for ROOT Disk")
root_volume = root_volumes_list[0]
# Get Secondary Storage Value from Database
qryresult_before_snapshot = self.dbclient.execute(
" select id, account_name, secondaryStorageTotal\
from account_view where account_name = '%s';" %
self.account.name)
self.assertNotEqual(
len(qryresult_before_snapshot),
0,
"Check sql query to return SecondaryStorageTotal of account")
storage_qry_result_old = qryresult_before_snapshot[0]
secondary_storage_old = storage_qry_result_old[2]
# Create Snapshots
for i in range(snapshot_loop_count):
# Step 1
checksum_root = createChecksum(
self.testdata,
self.vm,
root_volume,
"rootdiskdevice")
time.sleep(30)
checksum_created.append(checksum_root)
# Step 2
root_vol_snapshot = Snapshot.create(
self.apiclient,
root_volume.id)
self.snapshots_created.append(root_vol_snapshot)
snapshots_list = Snapshot.list(self.apiclient,
id=root_vol_snapshot.id)
status = validateList(snapshots_list)
self.assertEqual(status[0], PASS, "Check listSnapshots response")
# Verify Snapshot state
self.assertEqual(
snapshots_list[0].state.lower() in [
BACKED_UP,
],
True,
"Snapshot state is not as expected. It is %s" %
snapshots_list[0].state
)
self.assertEqual(
snapshots_list[0].volumeid,
root_volume.id,
"Snapshot volume id is not matching with the vm's volume id")
# Step 3
qryresult_after_snapshot = self.dbclient.execute(
" select id, account_name, secondaryStorageTotal\
from account_view where account_name = '%s';" %
self.account.name)
self.assertNotEqual(
len(qryresult_after_snapshot),
0,
"Check sql query to return SecondaryStorageTotal of account")
storage_qry_result_from_database = qryresult_after_snapshot[0]
secondary_storage_from_database = storage_qry_result_from_database[
2]
snapshot_size = snapshots_list[0].physicalsize
secondary_storage_after_snapshot = secondary_storage_old + \
snapshot_size
# Reset full_snapshot_count to 0 before start of new snapshot chain
if delta_snapshot_count == (int(self.delta_max) - 1):
full_snapshot_count = 0
delta_snapshot_count = 0
# Full Snapshot of each Snapshot chain
if full_snapshot_count == 0:
full_snapshot_count += 1
full_snapshot_size = snapshot_size
# Check secondary storage count for Full Snapshots
self.assertEqual(
secondary_storage_from_database,
secondary_storage_after_snapshot,
"Secondary storage count after full snapshot\
should be incremented by size of snapshot.")
# Step 4
checkIntegrityOfSnapshot(
self,
snapshots_list[0],
checksum_root,
disk_type=DATA)
else:
# Delta Snapshot of each Snapshot chain
delta_snapshot_count += 1
delta_snapshot_size = snapshot_size
# Check secondary storage count for Delta Snapshots
self.assertTrue(delta_snapshot_size < full_snapshot_size,
"Delta Snapshot size should be less than\
Full Snapshot.")
self.assertEqual(
secondary_storage_from_database,
secondary_storage_after_snapshot,
"Secondary storage count after delta snapshot\
should be incremented by size of snapshot.")
secondary_storage_old = secondary_storage_from_database
# Step 5
# Check in Secondary Storage- Snapshots: S1, S2, S3 are present
for i in range(int(self.delta_max)):
self.assertTrue(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
self.snapshots_created[i].id),
"Check: Snapshot is not on Secondary Storage.")
# Delete S2
Snapshot.delete(self.snapshots_created[1], self.apiclient)
snapshots_list = Snapshot.list(self.apiclient,
id=self.snapshots_created[1].id)
status = validateList(snapshots_list)
self.assertEqual(status[0], FAIL, "Snapshots Not Deleted.")
# Check integrity of Snapshots for S1 and S3
checkIntegrityOfSnapshot(
self,
self.snapshots_created[0],
checksum_created[0],
disk_type=DATA)
checkIntegrityOfSnapshot(
self,
self.snapshots_created[2],
checksum_created[2],
disk_type=DATA)
# Delete S3
Snapshot.delete(self.snapshots_created[2], self.apiclient)
snapshots_list = Snapshot.list(self.apiclient,
id=self.snapshots_created[2].id)
status = validateList(snapshots_list)
self.assertEqual(status[0], FAIL, "Snapshots Not Deleted.")
# Check in Secondary Storage - Snapshots: S2, S3 are deleted
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
self.snapshots_created[2].id),
"Check: Snapshot 2 is still on Secondary Storage. Not Deleted.")
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
self.snapshots_created[1].id),
"Check: Snapshot 3 is still on Secondary Storage. Not Deleted.")
# Restore Snapshots for S1
checkIntegrityOfSnapshot(
self,
self.snapshots_created[0],
checksum_created[0],
disk_type=DATA)
# Step 6
# Delete S1
Snapshot.delete(self.snapshots_created[0], self.apiclient)
snapshots_list = Snapshot.list(self.apiclient,
id=self.snapshots_created[0].id)
status = validateList(snapshots_list)
self.assertEqual(status[0], FAIL, "Snapshots Not Deleted.")
# Check in Secondary Storage - Snapshots: All - S1, S2, S3 are deleted
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
self.snapshots_created[2].id),
"Check: Snapshot 3 is still on Secondary Storage. Not Deleted.")
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
self.snapshots_created[1].id),
"Check: Snapshot 2 is still on Secondary Storage. Not Deleted.")
self.assertFalse(
is_snapshot_on_nfs(
self.apiclient,
self.dbclient,
self.config,
self.zone.id,
self.snapshots_created[0].id),
"Check: Snapshot 1 is still on Secondary Storage. Not Deleted.")
return
| [
"marvin.lib.common.createChecksum",
"marvin.lib.utils.validateList",
"marvin.lib.common.compareChecksum",
"marvin.lib.base.Volume.create_from_snapshot",
"marvin.lib.base.Snapshot.create",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.base.Configurations.update",
"marvin.lib.base.ServiceOffering.cr... | [((8929, 8987), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'basic'], required_hardware='true')\n", (8933, 8987), False, 'from nose.plugins.attrib import attr\n'), ((2692, 2791), 'marvin.lib.base.Template.create_from_snapshot', 'Template.create_from_snapshot', (['self.apiclient', 'snapshotsToRestore', "self.testdata['template_2']"], {}), "(self.apiclient, snapshotsToRestore, self.\n testdata['template_2'])\n", (2721, 2791), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((3017, 3285), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['small']"], {'templateid': 'template_from_snapshot.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.testdata['small'], templateid=\n template_from_snapshot.id, accountid=self.account.name, domainid=self.\n account.domainid, serviceofferingid=self.service_offering.id, zoneid=\n self.zone.id, mode=self.zone.networktype)\n", (3038, 3285), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((3585, 3736), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient'], {'service': 'self.testdata', 'original_checksum': 'checksumToCompare', 'disk_type': '"""rootdiskdevice"""', 'virt_machine': 'vm_from_temp'}), "(self.apiclient, service=self.testdata, original_checksum=\n checksumToCompare, disk_type='rootdiskdevice', virt_machine=vm_from_temp)\n", (3600, 3736), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, createChecksum, compareChecksum\n'), ((3936, 4117), 'marvin.lib.base.Volume.create_from_snapshot', 'Volume.create_from_snapshot', (['self.apiclient', 'snapshotsToRestore.id', "self.testdata['volume']"], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), "(self.apiclient, snapshotsToRestore.id, self.\n testdata['volume'], account=self.account.name, domainid=self.account.\n domainid, zoneid=self.zone.id)\n", (3963, 4117), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((4209, 4468), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testdata['small']"], {'templateid': 'self.template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.testdata['small'], templateid=\n self.template.id, accountid=self.account.name, domainid=self.account.\n domainid, serviceofferingid=self.service_offering.id, zoneid=self.zone.\n id, mode=self.zone.networktype)\n", (4230, 4468), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((4705, 4803), 'marvin.lib.common.compareChecksum', 'compareChecksum', (['self.apiclient', 'self.testdata', 'checksumToCompare', '"""datadiskdevice_1"""', 'temp_vm'], {}), "(self.apiclient, self.testdata, checksumToCompare,\n 'datadiskdevice_1', temp_vm)\n", (4720, 4803), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, createChecksum, compareChecksum\n'), ((5363, 5388), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (5373, 5388), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, createChecksum, compareChecksum\n'), ((5486, 5550), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.testdata['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.testdata['ostype'])\n", (5498, 5550), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, createChecksum, compareChecksum\n'), ((8655, 8760), 'marvin.sshClient.SshClient', 'SshClient', (["cls.mgtSvrDetails['mgtSvrIp']", '(22)', "cls.mgtSvrDetails['user']", "cls.mgtSvrDetails['passwd']"], {}), "(cls.mgtSvrDetails['mgtSvrIp'], 22, cls.mgtSvrDetails['user'], cls\n .mgtSvrDetails['passwd'])\n", (8664, 8760), False, 'from marvin.sshClient import SshClient\n'), ((9766, 9852), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm.id', 'type': 'ROOT', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=self.vm.id, type=ROOT,\n listall=True)\n', (9778, 9852), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, createChecksum, compareChecksum\n'), ((9925, 9956), 'marvin.lib.utils.validateList', 'validateList', (['root_volumes_list'], {}), '(root_volumes_list)\n', (9937, 9956), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((14985, 15043), 'marvin.lib.base.Snapshot.delete', 'Snapshot.delete', (['self.snapshots_created[1]', 'self.apiclient'], {}), '(self.snapshots_created[1], self.apiclient)\n', (15000, 15043), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((15070, 15132), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.apiclient'], {'id': 'self.snapshots_created[1].id'}), '(self.apiclient, id=self.snapshots_created[1].id)\n', (15083, 15132), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((15190, 15218), 'marvin.lib.utils.validateList', 'validateList', (['snapshots_list'], {}), '(snapshots_list)\n', (15202, 15218), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((15676, 15734), 'marvin.lib.base.Snapshot.delete', 'Snapshot.delete', (['self.snapshots_created[2]', 'self.apiclient'], {}), '(self.snapshots_created[2], self.apiclient)\n', (15691, 15734), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((15761, 15823), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.apiclient'], {'id': 'self.snapshots_created[2].id'}), '(self.apiclient, id=self.snapshots_created[2].id)\n', (15774, 15823), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((15881, 15909), 'marvin.lib.utils.validateList', 'validateList', (['snapshots_list'], {}), '(snapshots_list)\n', (15893, 15909), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((16892, 16950), 'marvin.lib.base.Snapshot.delete', 'Snapshot.delete', (['self.snapshots_created[0]', 'self.apiclient'], {}), '(self.snapshots_created[0], self.apiclient)\n', (16907, 16950), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((16977, 17039), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.apiclient'], {'id': 'self.snapshots_created[0].id'}), '(self.apiclient, id=self.snapshots_created[0].id)\n', (16990, 17039), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((17097, 17125), 'marvin.lib.utils.validateList', 'validateList', (['snapshots_list'], {}), '(snapshots_list)\n', (17109, 17125), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((5912, 5990), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.testdata['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.testdata['account'], domainid=cls.domain.id)\n", (5926, 5990), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((6389, 6460), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.testdata['service_offering']"], {}), "(cls.apiclient, cls.testdata['service_offering'])\n", (6411, 6460), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((7064, 7125), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['cls.apiclient'], {'name': '"""snapshot.delta.max"""'}), "(cls.apiclient, name='snapshot.delta.max')\n", (7083, 7125), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((7226, 7476), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.testdata['small']"], {'templateid': 'cls.template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id', 'zoneid': 'cls.zone.id', 'mode': 'cls.zone.networktype'}), "(cls.apiclient, cls.testdata['small'], templateid=cls.\n template.id, accountid=cls.account.name, domainid=cls.account.domainid,\n serviceofferingid=cls.service_offering.id, zoneid=cls.zone.id, mode=cls\n .zone.networktype)\n", (7247, 7476), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((7775, 7821), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (7792, 7821), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((8380, 8427), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (8397, 8427), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((10805, 10874), 'marvin.lib.common.createChecksum', 'createChecksum', (['self.testdata', 'self.vm', 'root_volume', '"""rootdiskdevice"""'], {}), "(self.testdata, self.vm, root_volume, 'rootdiskdevice')\n", (10819, 10874), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_volumes, createChecksum, compareChecksum\n'), ((10953, 10967), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (10963, 10967), False, 'import time\n'), ((11073, 11120), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'root_volume.id'], {}), '(self.apiclient, root_volume.id)\n', (11088, 11120), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((11246, 11300), 'marvin.lib.base.Snapshot.list', 'Snapshot.list', (['self.apiclient'], {'id': 'root_vol_snapshot.id'}), '(self.apiclient, id=root_vol_snapshot.id)\n', (11259, 11300), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((11366, 11394), 'marvin.lib.utils.validateList', 'validateList', (['snapshots_list'], {}), '(snapshots_list)\n', (11378, 11394), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((16086, 16196), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'self.snapshots_created[2].id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n self.snapshots_created[2].id)\n', (16104, 16196), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((16391, 16501), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'self.snapshots_created[1].id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n self.snapshots_created[1].id)\n', (16409, 16501), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((17313, 17423), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'self.snapshots_created[2].id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n self.snapshots_created[2].id)\n', (17331, 17423), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((17618, 17728), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'self.snapshots_created[1].id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n self.snapshots_created[1].id)\n', (17636, 17728), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((17923, 18033), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'self.snapshots_created[0].id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n self.snapshots_created[0].id)\n', (17941, 18033), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n'), ((6738, 6812), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient'], {'name': '"""snapshot.delta.max"""', 'value': '"""3"""'}), "(cls.apiclient, name='snapshot.delta.max', value='3')\n", (6759, 6812), False, 'from marvin.lib.base import Account, ServiceOffering, Template, VirtualMachine, Volume, Configurations, Snapshot\n'), ((7025, 7040), 'time.sleep', 'time.sleep', (['(120)'], {}), '(120)\n', (7035, 7040), False, 'import time\n'), ((14682, 14792), 'marvin.lib.utils.is_snapshot_on_nfs', 'is_snapshot_on_nfs', (['self.apiclient', 'self.dbclient', 'self.config', 'self.zone.id', 'self.snapshots_created[i].id'], {}), '(self.apiclient, self.dbclient, self.config, self.zone.id,\n self.snapshots_created[i].id)\n', (14700, 14792), False, 'from marvin.lib.utils import cleanup_resources, validateList, is_snapshot_on_nfs\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for VPN service
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackException import CloudstackAPIException
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import (
Account,
ServiceOffering,
VirtualMachine,
PublicIPAddress,
Vpn,
VpnUser,
Configurations,
NATRule
)
from marvin.lib.common import (get_domain,
get_zone,
get_template
)
from marvin.lib.utils import cleanup_resources
import subprocess
class Services:
"""Test VPN Service
"""
def __init__(self):
self.services = {
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended for unique
# username
"password": "password",
},
"service_offering": {
"name": "Tiny Instance",
"displaytext": "Tiny Instance",
"cpunumber": 1,
"cpuspeed": 100, # in MHz
"memory": 128, # In MBs
},
"disk_offering": {
"displaytext": "Small Disk Offering",
"name": "Small Disk Offering",
"disksize": 1
},
"virtual_machine": {
"displayname": "TestVM",
"username": "root",
"password": "password",
"ssh_port": 22,
"hypervisor": 'KVM',
"privateport": 22,
"publicport": 22,
"protocol": 'TCP',
},
"vpn_user": {
"username": "test",
"password": "<PASSWORD>",
},
"natrule": {
"privateport": 1701,
"publicport": 1701,
"protocol": "UDP"
},
"ostype": 'CentOS 5.5 (64-bit)',
"sleep": 60,
"timeout": 10,
# Networking mode: Advanced, Basic
}
class TestVPNService(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestVPNService, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.services["mode"] = cls.zone.networktype
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls._cleanup = [cls.service_offering, ]
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
try:
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain.id
)
self.cleanup = [
self.account,
]
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id
)
self.public_ip = PublicIPAddress.create(
self.apiclient,
accountid=self.virtual_machine.account,
zoneid=self.virtual_machine.zoneid,
domainid=self.virtual_machine.domainid,
services=self.services["virtual_machine"]
)
return
except CloudstackAPIException as e:
self.tearDown()
raise e
def tearDown(self):
try:
# Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def create_VPN(self, public_ip):
"""Creates VPN for the network"""
self.debug("Creating VPN with public IP: %s" % public_ip.ipaddress.id)
try:
# Assign VPN to Public IP
vpn = Vpn.create(self.apiclient,
self.public_ip.ipaddress.id,
account=self.account.name,
domainid=self.account.domainid)
self.debug("Verifying the remote VPN access")
vpns = Vpn.list(self.apiclient,
publicipid=public_ip.ipaddress.id,
listall=True)
self.assertEqual(
isinstance(vpns, list),
True,
"List VPNs shall return a valid response"
)
return vpn
except Exception as e:
self.fail("Failed to create remote VPN access: %s" % e)
@attr(tags=["advanced", "advancedns"])
def test_01_VPN_service(self):
"""Tests if VPN service is running"""
# Validate if IPSEC is running on the public
# IP by using ike-scan
self.create_VPN(self.public_ip)
cmd = ['ike-scan', self.public_ip, '-s', '4534'] # Random port
stdout = subprocess.check_output(cmd)
if "1 returned handshake" not in stdout:
self.fail("Unable to connect to VPN service")
return
| [
"marvin.lib.common.get_domain",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.Vpn.list",
"marvin.lib.base.Vpn.create",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.common.get_template",
"marvin.lib.base.PublicIPAddress.create",
"marvin.lib.b... | [((8157, 8194), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns']"}), "(tags=['advanced', 'advancedns'])\n", (8161, 8194), False, 'from nose.plugins.attrib import attr\n'), ((4450, 4476), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (4460, 4476), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((4632, 4697), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (4644, 4697), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((4840, 4912), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (4862, 4912), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, PublicIPAddress, Vpn, VpnUser, Configurations, NATRule\n'), ((8492, 8520), 'subprocess.check_output', 'subprocess.check_output', (['cmd'], {}), '(cmd)\n', (8515, 8520), False, 'import subprocess\n'), ((5119, 5166), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (5136, 5166), False, 'from marvin.lib.utils import cleanup_resources\n'), ((5471, 5557), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain.id)\n", (5485, 5557), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, PublicIPAddress, Vpn, VpnUser, Configurations, NATRule\n'), ((5819, 6033), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.apiclient, self.services['virtual_machine'],\n templateid=self.template.id, accountid=self.account.name, domainid=self\n .account.domainid, serviceofferingid=self.service_offering.id)\n", (5840, 6033), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, PublicIPAddress, Vpn, VpnUser, Configurations, NATRule\n'), ((6308, 6515), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.virtual_machine.account', 'zoneid': 'self.virtual_machine.zoneid', 'domainid': 'self.virtual_machine.domainid', 'services': "self.services['virtual_machine']"}), "(self.apiclient, accountid=self.virtual_machine.\n account, zoneid=self.virtual_machine.zoneid, domainid=self.\n virtual_machine.domainid, services=self.services['virtual_machine'])\n", (6330, 6515), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, PublicIPAddress, Vpn, VpnUser, Configurations, NATRule\n'), ((7037, 7084), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (7054, 7084), False, 'from marvin.lib.utils import cleanup_resources\n'), ((7434, 7553), 'marvin.lib.base.Vpn.create', 'Vpn.create', (['self.apiclient', 'self.public_ip.ipaddress.id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, self.public_ip.ipaddress.id, account=self.\n account.name, domainid=self.account.domainid)\n', (7444, 7553), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, PublicIPAddress, Vpn, VpnUser, Configurations, NATRule\n'), ((7702, 7775), 'marvin.lib.base.Vpn.list', 'Vpn.list', (['self.apiclient'], {'publicipid': 'public_ip.ipaddress.id', 'listall': '(True)'}), '(self.apiclient, publicipid=public_ip.ipaddress.id, listall=True)\n', (7710, 7775), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, PublicIPAddress, Vpn, VpnUser, Configurations, NATRule\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import cloudstackConnection
import asyncJobMgr
import dbConnection
from cloudstackAPI import *
import random
import string
import hashlib
from configGenerator import ConfigManager
from marvin.integration.lib.utils import random_gen
'''
@Desc : CloudStackTestClient is encapsulated class for getting various \
clients viz., apiclient,dbconnection etc
@Input : mgmtDetails : Management Server Details
dbSvrDetails: Database Server details of Management \
Server. Retrieved from configuration file.
asyncTimeout :
defaultWorkerThreads :
logger : provides logging facilities for this library
'''
class cloudstackTestClient(object):
def __init__(self, mgmtDetails,
dbSvrDetails, asyncTimeout=3600,
defaultWorkerThreads=10,
logger=None):
self.mgmtDetails = mgmtDetails
self.connection = \
cloudstackConnection.cloudConnection(self.mgmtDetails,
asyncTimeout,
logger)
self.apiClient =\
cloudstackAPIClient.CloudStackAPIClient(self.connection)
self.dbConnection = None
if dbSvrDetails is not None:
self.createDbConnection(dbSvrDetails.dbSvr, dbSvrDetails.port,
dbSvrDetails.user,
dbSvrDetails.passwd, dbSvrDetails.db)
'''
Provides the Configuration Object to users through getConfigParser
The purpose of this object is to parse the config
and provide dictionary of the config so users can
use that configuration.Users can later call getConfig
on this object and it will return the default parsed
config dictionary from default configuration file,
they can overwrite it with providing their own
configuration file as well.
'''
self.configObj = ConfigManager()
self.asyncJobMgr = None
self.id = None
self.defaultWorkerThreads = defaultWorkerThreads
@property
def identifier(self):
return self.id
@identifier.setter
def identifier(self, id):
self.id = id
def createDbConnection(self, host="localhost", port=3306, user='cloud',
passwd='<PASSWORD>', db='cloud'):
self.dbConnection = dbConnection.dbConnection(host, port, user,
passwd, db)
def isAdminContext(self):
"""
A user is a regular user if he fails to listDomains;
if he is a domain-admin, he can list only domains that are non-ROOT;
if he is an admin, he can list the ROOT domain successfully
"""
try:
listdom = listDomains.listDomainsCmd()
listdom.name = 'ROOT'
listdomres = self.apiClient.listDomains(listdom)
rootdom = listdomres[0].name
if rootdom == 'ROOT':
return 1 # admin
else:
return 2 # domain-admin
except:
return 0 # user
def createUserApiClient(self, UserName, DomainName, acctType=0):
if not self.isAdminContext():
return self.apiClient
listDomain = listDomains.listDomainsCmd()
listDomain.listall = True
listDomain.name = DomainName
try:
domains = self.apiClient.listDomains(listDomain)
domId = domains[0].id
except:
cdomain = createDomain.createDomainCmd()
cdomain.name = DomainName
domain = self.apiClient.createDomain(cdomain)
domId = domain.id
cmd = listAccounts.listAccountsCmd()
cmd.name = UserName
cmd.domainid = domId
try:
accounts = self.apiClient.listAccounts(cmd)
acctId = accounts[0].id
except:
createAcctCmd = createAccount.createAccountCmd()
createAcctCmd.accounttype = acctType
createAcctCmd.domainid = domId
createAcctCmd.email = "test-" + random_gen()\
+ "@cloudstack.org"
createAcctCmd.firstname = UserName
createAcctCmd.lastname = UserName
createAcctCmd.password = 'password'
createAcctCmd.username = UserName
acct = self.apiClient.createAccount(createAcctCmd)
acctId = acct.id
listuser = listUsers.listUsersCmd()
listuser.username = UserName
listuserRes = self.apiClient.listUsers(listuser)
userId = listuserRes[0].id
apiKey = listuserRes[0].apikey
securityKey = listuserRes[0].secretkey
if apiKey is None:
registerUser = registerUserKeys.registerUserKeysCmd()
registerUser.id = userId
registerUserRes = self.apiClient.registerUserKeys(registerUser)
apiKey = registerUserRes.apikey
securityKey = registerUserRes.secretkey
mgtDetails = self.mgmtDetails
mgtDetails.apiKey = apiKey
mgtDetails.securityKey = securityKey
newUserConnection =\
cloudstackConnection.cloudConnection(mgtDetails,
self.connection.asyncTimeout,
self.connection.logger)
self.userApiClient =\
cloudstackAPIClient.CloudStackAPIClient(newUserConnection)
self.userApiClient.connection = newUserConnection
self.userApiClient.hypervisor = self.apiClient.hypervisor
return self.userApiClient
def close(self):
if self.connection is not None:
self.connection.close()
def getDbConnection(self):
return self.dbConnection
def getConfigParser(self):
return self.configObj
def getApiClient(self):
self.apiClient.id = self.identifier
return self.apiClient
def getUserApiClient(self, account, domain, type=0):
"""
0 - user
1 - admin
2 - domain admin
"""
self.createUserApiClient(account, domain, type)
if hasattr(self, "userApiClient"):
return self.userApiClient
return None
def submitCmdsAndWait(self, cmds, workers=1):
'''FixME, httplib has issue if more than one thread submitted'''
if self.asyncJobMgr is None:
self.asyncJobMgr = asyncJobMgr.asyncJobMgr(self.apiClient,
self.dbConnection)
return self.asyncJobMgr.submitCmdsAndWait(cmds, workers)
def submitJob(self, job, ntimes=1, nums_threads=10, interval=1):
'''
submit one job and execute the same job ntimes, with nums_threads
of threads
'''
if self.asyncJobMgr is None:
self.asyncJobMgr = asyncJobMgr.asyncJobMgr(self.apiClient,
self.dbConnection)
self.asyncJobMgr.submitJobExecuteNtimes(job, ntimes, nums_threads,
interval)
def submitJobs(self, jobs, nums_threads=10, interval=1):
'''submit n jobs, execute them with nums_threads of threads'''
if self.asyncJobMgr is None:
self.asyncJobMgr = asyncJobMgr.asyncJobMgr(self.apiClient,
self.dbConnection)
self.asyncJobMgr.submitJobs(jobs, nums_threads, interval)
| [
"marvin.integration.lib.utils.random_gen"
] | [((1725, 1801), 'cloudstackConnection.cloudConnection', 'cloudstackConnection.cloudConnection', (['self.mgmtDetails', 'asyncTimeout', 'logger'], {}), '(self.mgmtDetails, asyncTimeout, logger)\n', (1761, 1801), False, 'import cloudstackConnection\n'), ((2794, 2809), 'configGenerator.ConfigManager', 'ConfigManager', ([], {}), '()\n', (2807, 2809), False, 'from configGenerator import ConfigManager\n'), ((3227, 3282), 'dbConnection.dbConnection', 'dbConnection.dbConnection', (['host', 'port', 'user', 'passwd', 'db'], {}), '(host, port, user, passwd, db)\n', (3252, 3282), False, 'import dbConnection\n'), ((6012, 6119), 'cloudstackConnection.cloudConnection', 'cloudstackConnection.cloudConnection', (['mgtDetails', 'self.connection.asyncTimeout', 'self.connection.logger'], {}), '(mgtDetails, self.connection.\n asyncTimeout, self.connection.logger)\n', (6048, 6119), False, 'import cloudstackConnection\n'), ((7291, 7349), 'asyncJobMgr.asyncJobMgr', 'asyncJobMgr.asyncJobMgr', (['self.apiClient', 'self.dbConnection'], {}), '(self.apiClient, self.dbConnection)\n', (7314, 7349), False, 'import asyncJobMgr\n'), ((7725, 7783), 'asyncJobMgr.asyncJobMgr', 'asyncJobMgr.asyncJobMgr', (['self.apiClient', 'self.dbConnection'], {}), '(self.apiClient, self.dbConnection)\n', (7748, 7783), False, 'import asyncJobMgr\n'), ((8173, 8231), 'asyncJobMgr.asyncJobMgr', 'asyncJobMgr.asyncJobMgr', (['self.apiClient', 'self.dbConnection'], {}), '(self.apiClient, self.dbConnection)\n', (8196, 8231), False, 'import asyncJobMgr\n'), ((4958, 4970), 'marvin.integration.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (4968, 4970), False, 'from marvin.integration.lib.utils import random_gen\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" BVT tests for Vpc offerings"""
#Import Local Modules
from marvin.codes import FAILED
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import (createVPCOffering,
listVPCOfferings,
updateVPCOffering)
from marvin.lib.utils import (isAlmostEqual,
cleanup_resources,
random_gen)
from marvin.lib.base import (Domain,
VpcOffering,
Account,
VPC)
from marvin.lib.common import (get_domain,
get_zone)
from nose.plugins.attrib import attr
import time
from marvin.sshClient import SshClient
from marvin.cloudstackException import CloudstackAPIException
from marvin.lib.decoratorGenerators import skipTestIf
_multiprocess_shared_ = True
class Services:
"""Test VPC network services - Port Forwarding Rules Test Data Class.
"""
def __init__(self):
self.services = {
"vpc_offering": {
"name": 'Redundant VPC off',
"displaytext": 'Redundant VPC off',
"supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat',
"serviceProviderList": {
"Vpn": 'VpcVirtualRouter',
"Dhcp": 'VpcVirtualRouter',
"Dns": 'VpcVirtualRouter',
"SourceNat": 'VpcVirtualRouter',
"PortForwarding": 'VpcVirtualRouter',
"Lb": 'VpcVirtualRouter',
"UserData": 'VpcVirtualRouter',
"StaticNat": 'VpcVirtualRouter',
"NetworkACL": 'VpcVirtualRouter'
},
},
"vpc": {
"name": "TestVPC",
"displaytext": "TestVPC",
"cidr": '10.0.0.0/16'
}
}
class TestCreateDomainsVpcOffering(cloudstackTestCase):
def setUp(self):
self.services = self.testClient.getParsedTestDataConfig()
self.localservices = Services().services
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def setUpClass(cls):
testClient = super(TestCreateDomainsVpcOffering, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
# Create domains
cls.domain_1 = Domain.create(
cls.apiclient,
cls.services["acl"]["domain1"]
)
cls.domain_11 = Domain.create(
cls.apiclient,
cls.services["acl"]["domain11"],
parentdomainid=cls.domain_1.id
)
cls.domain_2 = Domain.create(
cls.apiclient,
cls.services["acl"]["domain2"]
)
cls._cleanup = [
cls.domain_11,
cls.domain_1,
cls.domain_2
]
return
@classmethod
def tearDownClass(cls):
try:
cls.apiclient = super(
TestCreateDomainsVpcOffering,
cls).getClsTestClient().getApiClient()
# Clean up, terminate the created templates
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise
@attr(
tags=[
"advanced",
"basic",
"eip",
"sg",
"advancedns",
"smoke"],
required_hardware="false")
def test_01_create_vpc_offering(self):
"""Test to create vpc offering
# Validate the following:
# 1. createVPCOfferings should return valid info for new offering
# 2. The Cloud Database contains the valid information
"""
offering_data_domainid = "{0},{1}".format(self.domain_11.id, self.domain_2.id)
offering_data = self.localservices["vpc_offering"]
cmd = createVPCOffering.createVPCOfferingCmd()
cmd.name = "-".join([offering_data["name"], random_gen()])
cmd.displaytext = offering_data["displaytext"]
cmd.supportedServices = offering_data["supportedservices"]
cmd.domainid = offering_data_domainid
if "serviceProviderList" in offering_data:
for service, provider in offering_data["serviceProviderList"].items():
providers = provider
if isinstance(provider, str):
providers = [provider]
for provider_item in providers:
cmd.serviceproviderlist.append({
'service': service,
'provider': provider_item
})
vpc_offering = VpcOffering(self.apiclient.createVPCOffering(cmd).__dict__)
self.cleanup.append(vpc_offering)
self.debug("Created Vpc offering with ID: %s" % vpc_offering.id)
cmd = listVPCOfferings.listVPCOfferingsCmd()
cmd.id = vpc_offering.id
list_vpc_response = self.apiclient.listVPCOfferings(cmd)
self.assertEqual(
isinstance(list_vpc_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_vpc_response),
0,
"Check Vpc offering is created"
)
vpc_response = list_vpc_response[0]
self.assertEqual(
vpc_response.id,
vpc_offering.id,
"Check server id in createVPCOffering"
)
self.assertEqual(
vpc_response.displaytext,
self.localservices["vpc_offering"]["displaytext"],
"Check server displaytext in createVPCOffering"
)
self.assertItemsEqual(
vpc_response.domainid.split(","),
offering_data_domainid.split(","),
"Check domainid in createVPCOffering"
)
return
class TestDomainsVpcOfferings(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def setUpClass(cls):
testClient = super(TestDomainsVpcOfferings, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls.localservices = Services().services
cls.services = testClient.getParsedTestDataConfig()
# Create domains
cls.domain_1 = Domain.create(
cls.apiclient,
cls.services["acl"]["domain1"]
)
cls.domain_11 = Domain.create(
cls.apiclient,
cls.services["acl"]["domain11"],
parentdomainid=cls.domain_1.id
)
cls.domain_2 = Domain.create(
cls.apiclient,
cls.services["acl"]["domain2"]
)
cls.domain_3 = Domain.create(
cls.apiclient,
cls.services["acl"]["domain12"]
)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
cls.vpc_offering = VpcOffering.create(
cls.apiclient,
cls.services["vpc_offering"]
)
# Enable Vpc offering
cls.vpc_offering.update(cls.apiclient, state='Enabled')
cls._cleanup = [
cls.vpc_offering,
cls.domain_11,
cls.domain_1,
cls.domain_2,
cls.domain_3
]
return
@classmethod
def tearDownClass(cls):
try:
cls.apiclient = super(TestDomainsVpcOfferings, cls).getClsTestClient().getApiClient()
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "basic", "eip", "sg", "advancedns", "smoke"], required_hardware="false")
def test_02_edit_vpc_offering(self):
"""Test to update existing vpc offering"""
# 1. updateVPCOffering should return a valid information for the updated offering
# 2. updateVPCOffering should fail while tring to add child domain but parent domain
# is already present
# 3. updateVPCOffering should be able to add new domain to the offering
self.debug("Updating vpc offering with ID: %s" %
self.vpc_offering.id)
cmd = updateVPCOffering.updateVPCOfferingCmd()
cmd.id = self.vpc_offering.id
input_domainid ="{0},{1},{2}".format(self.domain_1.id, self.domain_11.id, self.domain_2.id)
result_domainid = "{0},{1}".format(self.domain_1.id, self.domain_2.id)
cmd.domainid = input_domainid
self.apiclient.updateVPCOffering(cmd)
cmd = listVPCOfferings.listVPCOfferingsCmd()
cmd.id = self.vpc_offering.id
list_vpc_response = self.apiclient.listVPCOfferings(cmd)
self.assertEqual(
isinstance(list_vpc_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
len(list_vpc_response),
0,
"Check Vpc offering is updated"
)
try:
self.assertItemsEqual(
list_vpc_response[0].domainid.split(","),
input_domainid.split(","),
"Check child domainid in updateServiceOffering, should fail"
)
self.fail("Child domain added to offering when parent domain already exist. Must be an error.")
except AssertionError:
self.debug("Child domain check successful")
self.assertItemsEqual(
list_vpc_response[0].domainid.split(","),
result_domainid.split(","),
"Check domainid in createVPCOffering"
)
@attr(
tags=[
"advanced",
"basic",
"eip",
"sg",
"advancedns",
"smoke"],
required_hardware="false")
def test_03_create_vpc_domain_vpc_offering(self):
"""Test to creating vpc for an existing domain specified vpc offering"""
# Validate the following:
# 1. Vpc creation should fail for the user from a different domain
# 2. Vpc creation should work for users from domains for which offering is specified
self.debug("Deploying VM using vpc offering with ID: %s" %
self.vpc_offering.id)
self.invalid_account = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain_3.id
)
self.cleanup.append(self.invalid_account)
try:
VPC.create(
apiclient=self.apiclient,
services=self.services["vpc"],
account=self.invalid_account.name,
domainid=self.invalid_account.domainid,
zoneid=self.zone.id,
vpcofferingid=self.vpc_offering.id
)
self.fail("Vpc created for a user from domain which has not been specified for service offering. Must be an error.")
except CloudstackAPIException:
self.debug("Vpc creation for invalid user check")
self.valid_account_1 = Account.create(
self.apiclient,
self.services["account"],
domainid=self.domain_1.id
)
self.cleanup.append(self.valid_account_1)
VPC.create(
apiclient=self.apiclient,
services=self.services["vpc"],
account=self.valid_account_1.name,
domainid=self.valid_account_1.domainid,
zoneid=self.zone.id,
vpcofferingid=self.vpc_offering.id
)
self.debug("Vpc created for first subdomain %s" % self.valid_account_1.domainid)
self.valid_account_2 = Account.create(
self.apiclient,
self.services["account2"],
domainid=self.domain_2.id
)
self.cleanup.append(self.valid_account_2)
VPC.create(
apiclient=self.apiclient,
services=self.services["vpc"],
account=self.valid_account_2.name,
domainid=self.valid_account_2.domainid,
zoneid=self.zone.id,
vpcofferingid=self.vpc_offering.id
)
self.debug("Vpc created for second subdomain %s" % self.valid_account_2.domainid)
self.valid_account_3 = Account.create(
self.apiclient,
self.services["user"],
domainid=self.domain_11.id
)
self.cleanup.append(self.valid_account_3)
VPC.create(
apiclient=self.apiclient,
services=self.services["vpc"],
account=self.valid_account_3.name,
domainid=self.valid_account_3.domainid,
zoneid=self.zone.id,
vpcofferingid=self.vpc_offering.id
)
self.debug("Vpc created for first child subdomain %s" % self.valid_account_3.domainid)
return
| [
"marvin.lib.base.VpcOffering.create",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.base.VPC.create",
"marvin.lib.utils.random_gen",
"marvin.lib.base.Domain.create",
"marvin.cloudstackAPI.createVPCOffering.createVPCOfferingCmd",
"marvin.cloudstackAPI.listVPCOfferings.listVPCOfferingsCmd",
"marvin.... | [((4542, 4641), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke'],\n required_hardware='false')\n", (4546, 4641), False, 'from nose.plugins.attrib import attr\n'), ((9341, 9440), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke'],\n required_hardware='false')\n", (9345, 9440), False, 'from nose.plugins.attrib import attr\n'), ((11359, 11458), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'basic', 'eip', 'sg', 'advancedns', 'smoke'],\n required_hardware='false')\n", (11363, 11458), False, 'from nose.plugins.attrib import attr\n'), ((3671, 3731), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain1']"], {}), "(cls.apiclient, cls.services['acl']['domain1'])\n", (3684, 3731), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((3790, 3887), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain11']"], {'parentdomainid': 'cls.domain_1.id'}), "(cls.apiclient, cls.services['acl']['domain11'],\n parentdomainid=cls.domain_1.id)\n", (3803, 3887), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((3953, 4013), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain2']"], {}), "(cls.apiclient, cls.services['acl']['domain2'])\n", (3966, 4013), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((5154, 5194), 'marvin.cloudstackAPI.createVPCOffering.createVPCOfferingCmd', 'createVPCOffering.createVPCOfferingCmd', ([], {}), '()\n', (5192, 5194), False, 'from marvin.cloudstackAPI import createVPCOffering, listVPCOfferings, updateVPCOffering\n'), ((6124, 6162), 'marvin.cloudstackAPI.listVPCOfferings.listVPCOfferingsCmd', 'listVPCOfferings.listVPCOfferingsCmd', ([], {}), '()\n', (6160, 6162), False, 'from marvin.cloudstackAPI import createVPCOffering, listVPCOfferings, updateVPCOffering\n'), ((7953, 8013), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain1']"], {}), "(cls.apiclient, cls.services['acl']['domain1'])\n", (7966, 8013), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((8072, 8169), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain11']"], {'parentdomainid': 'cls.domain_1.id'}), "(cls.apiclient, cls.services['acl']['domain11'],\n parentdomainid=cls.domain_1.id)\n", (8085, 8169), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((8235, 8295), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain2']"], {}), "(cls.apiclient, cls.services['acl']['domain2'])\n", (8248, 8295), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((8353, 8414), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain12']"], {}), "(cls.apiclient, cls.services['acl']['domain12'])\n", (8366, 8414), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((8551, 8614), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['cls.apiclient', "cls.services['vpc_offering']"], {}), "(cls.apiclient, cls.services['vpc_offering'])\n", (8569, 8614), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((9939, 9979), 'marvin.cloudstackAPI.updateVPCOffering.updateVPCOfferingCmd', 'updateVPCOffering.updateVPCOfferingCmd', ([], {}), '()\n', (9977, 9979), False, 'from marvin.cloudstackAPI import createVPCOffering, listVPCOfferings, updateVPCOffering\n'), ((10296, 10334), 'marvin.cloudstackAPI.listVPCOfferings.listVPCOfferingsCmd', 'listVPCOfferings.listVPCOfferingsCmd', ([], {}), '()\n', (10332, 10334), False, 'from marvin.cloudstackAPI import createVPCOffering, listVPCOfferings, updateVPCOffering\n'), ((12023, 12111), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain_3.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain_3.id)\n", (12037, 12111), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((12801, 12889), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'domainid': 'self.domain_1.id'}), "(self.apiclient, self.services['account'], domainid=self.\n domain_1.id)\n", (12815, 12889), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((12989, 13197), 'marvin.lib.base.VPC.create', 'VPC.create', ([], {'apiclient': 'self.apiclient', 'services': "self.services['vpc']", 'account': 'self.valid_account_1.name', 'domainid': 'self.valid_account_1.domainid', 'zoneid': 'self.zone.id', 'vpcofferingid': 'self.vpc_offering.id'}), "(apiclient=self.apiclient, services=self.services['vpc'], account\n =self.valid_account_1.name, domainid=self.valid_account_1.domainid,\n zoneid=self.zone.id, vpcofferingid=self.vpc_offering.id)\n", (12999, 13197), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((13392, 13481), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account2']"], {'domainid': 'self.domain_2.id'}), "(self.apiclient, self.services['account2'], domainid=self.\n domain_2.id)\n", (13406, 13481), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((13581, 13789), 'marvin.lib.base.VPC.create', 'VPC.create', ([], {'apiclient': 'self.apiclient', 'services': "self.services['vpc']", 'account': 'self.valid_account_2.name', 'domainid': 'self.valid_account_2.domainid', 'zoneid': 'self.zone.id', 'vpcofferingid': 'self.vpc_offering.id'}), "(apiclient=self.apiclient, services=self.services['vpc'], account\n =self.valid_account_2.name, domainid=self.valid_account_2.domainid,\n zoneid=self.zone.id, vpcofferingid=self.vpc_offering.id)\n", (13591, 13789), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((13985, 14071), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['user']"], {'domainid': 'self.domain_11.id'}), "(self.apiclient, self.services['user'], domainid=self.\n domain_11.id)\n", (13999, 14071), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((14171, 14379), 'marvin.lib.base.VPC.create', 'VPC.create', ([], {'apiclient': 'self.apiclient', 'services': "self.services['vpc']", 'account': 'self.valid_account_3.name', 'domainid': 'self.valid_account_3.domainid', 'zoneid': 'self.zone.id', 'vpcofferingid': 'self.vpc_offering.id'}), "(apiclient=self.apiclient, services=self.services['vpc'], account\n =self.valid_account_3.name, domainid=self.valid_account_3.domainid,\n zoneid=self.zone.id, vpcofferingid=self.vpc_offering.id)\n", (14181, 14379), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((3220, 3267), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (3237, 3267), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n'), ((4439, 4485), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (4456, 4485), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n'), ((7459, 7506), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (7476, 7506), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n'), ((9168, 9214), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (9185, 9214), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n'), ((12229, 12437), 'marvin.lib.base.VPC.create', 'VPC.create', ([], {'apiclient': 'self.apiclient', 'services': "self.services['vpc']", 'account': 'self.invalid_account.name', 'domainid': 'self.invalid_account.domainid', 'zoneid': 'self.zone.id', 'vpcofferingid': 'self.vpc_offering.id'}), "(apiclient=self.apiclient, services=self.services['vpc'], account\n =self.invalid_account.name, domainid=self.invalid_account.domainid,\n zoneid=self.zone.id, vpcofferingid=self.vpc_offering.id)\n", (12239, 12437), False, 'from marvin.lib.base import Domain, VpcOffering, Account, VPC\n'), ((5247, 5259), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (5257, 5259), False, 'from marvin.lib.utils import isAlmostEqual, cleanup_resources, random_gen\n')] |
#!/usr/bin/env python
# encoding: utf-8
# Licensed under a 3-clause BSD license.
#
from __future__ import print_function
from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb
from marvin.tools.cube import Cube
from marvin.tools.maps import Maps
from marvin.tools.rss import RSS
from marvin.tools.modelcube import ModelCube
from marvin.tools.spaxel import Spaxel
from marvin.utils.datamodel.query import datamodel
from marvin.utils.datamodel.query.base import ParameterGroup
from marvin import config, log
from marvin.utils.general import getImagesByList, downloadList, map_bins_to_column
from marvin.utils.general import temp_setattr, turn_off_ion
from marvin.api.api import Interaction
from marvin.core import marvin_pickle
import marvin.utils.plot.scatter
from operator import add
import warnings
import json
import os
import datetime
import numpy as np
import six
import copy
from fuzzywuzzy import process
from functools import wraps
from astropy.table import Table, vstack, hstack
from collections import namedtuple
try:
import cPickle as pickle
except:
import pickle
try:
import pandas as pd
except ImportError:
warnings.warn('Could not import pandas.', MarvinUserWarning)
__all__ = ['Results', 'ResultSet']
breadcrumb = MarvinBreadCrumb()
def local_mode_only(fxn):
'''Decorator that bypasses function if in remote mode.'''
@wraps(fxn)
def wrapper(self, *args, **kwargs):
if self.mode == 'remote':
raise MarvinError('{0} not available in remote mode'.format(fxn.__name__))
else:
return fxn(self, *args, **kwargs)
return wrapper
def remote_mode_only(fxn):
'''Decorator that bypasses function if in local mode.'''
@wraps(fxn)
def wrapper(self, *args, **kwargs):
if self.mode == 'local':
raise MarvinError('{0} not available in local mode'.format(fxn.__name__))
else:
return fxn(self, *args, **kwargs)
return wrapper
class ColumnGroup(ParameterGroup):
''' Subclass of Parameter Group '''
def __repr__(self):
''' New repr for the Results Column Parameter Group '''
old = list.__repr__(self)
old = old.replace('>,', '>,\n')
return ('<ParameterGroup name={0.name}, n_parameters={1}>\n '
'{2}'.format(self, len(self), old))
def __str__(self):
''' New string repr for prints '''
return self.__repr__()
def marvintuple(name, params=None, **kwargs):
''' Custom namedtuple class factory for Marvin Results rows
A class factory designed to create a new Marvin ResultRow class object. marvintuple
creates a new class definition which can be instantiated. Parameters can be pushed into
an instance as individual arguments, or as key-value pairs. See the
`namedtuple <https://docs.python.org/2/library/collections.html#collections.namedtuple>`_
for details on the Python container.
Parameters:
name (str):
The name of the Class. Required.
params (str|list):
The list of parameters to add as fields to the namedtuple. Can be a list of names
or a comma-separated string of names.
Returns:
a new namedtuple class
Example:
>>> # create new class with two fields
>>> mt = marvintuple('Row', ['mangaid', 'plateifu'])
>>>
>>> # create a new instance of the class, with values
>>> row = mt('1-209232', '8485-1901')
>>> # or
>>> row = mt(mangaid='1-209232', plateifu='8485-1901')
'''
# check the params input
if params and isinstance(params, six.string_types):
params = params.split(',') if ',' in params else [params]
params = [p.strip() for p in params]
# pop any extra keywords
results = kwargs.pop('results', None)
# create default namedtuple and find new columns
default = namedtuple(name, 'mangaid, plate, plateifu, ifu_name')
newcols = [col for col in params if col not in default._fields] if params else None
finalfields = default._fields + tuple(newcols) if newcols else default._fields
nt = namedtuple(name, finalfields, **kwargs)
def new_add(self, other):
''' Overloaded add to combine tuples without duplicates '''
if self._release:
assert self._release == other._release, 'Cannot add result rows from different releases'
if self._searchfilter:
assert self._searchfilter == other._searchfilter, ('Cannot add result rows generated '
'using different search filters')
assert self.plateifu == other.plateifu, 'The plateifus must be the same to add these rows'
self_dict = self._asdict()
other_dict = other._asdict()
self_dict.update(other_dict)
new_fields = tuple(self_dict.keys())
marvin_row = marvintuple(self.__class__.__name__, new_fields, results=self._results)
return marvin_row(**self_dict)
# append new properties and overloaded methods
nt.__add__ = new_add
nt._results = results
nt._release = results._release if results else None
nt._searchfilter = results.searchfilter if results else None
return nt
class ResultSet(list):
''' A Set of Results
A list object representing a set of query results. Each row of the list is a
ResultRow object, which is a custom Marvin namedtuple object. ResultSets can be
extended column-wise or row-wise by adding them together.
Parameters:
_objects (list):
A list of objects. Required.
count (int):
The count of objects in the current list
totalcount (int):
The total count of objects in the full results
index (int):
The index of the current set within the total set.
columns (list):
A list of columns accompanying this set
results (Results):
The Marvin Results object this set is a part of
'''
def __init__(self, _objects, **kwargs):
list.__init__(self, _objects)
self._results = kwargs.get('results', None)
self.columns = kwargs.get('columns', None)
self.count = kwargs.get('count', None)
self.total = kwargs.get('total', None)
self._populate_from_results()
self.pages = int(np.ceil(self.total / float(self.count))) if self.count else 0
self.index = kwargs.get('index') if kwargs.get('index') else 0
self.end_index = self.index + self.count
self.current_page = (int(self.index) + self.count) / self.count
def __repr__(self):
old = list.__repr__(self)
return ('<ResultSet(set={0.current_page}/{0.pages}, index={0.index}:{0.end_index}, '
'count_in_set={0.count}, total={0.total})>\n{1}'.format(self, old.replace('),', '),\n')))
def __getitem__(self, value):
if isinstance(value, six.string_types):
value = str(value)
if value in self.columns:
colname = self.columns[value].remote
rows = [row.__getattribute__(colname) for row in self]
else:
rows = [row for row in self if value in row]
if rows:
return rows[0] if len(rows) == 1 else rows
else:
raise ValueError('{0} not found in the list'.format(value))
elif isinstance(value, int):
return list.__getitem__(self, value)
elif isinstance(value, slice):
newset = list.__getitem__(self, value)
return ResultSet(newset, index=int(value.start), count=len(newset), total=self.total, columns=self.columns, results=self._results)
elif isinstance(value, np.ndarray):
return np.array(self)[value]
def __getslice__(self, start, stop):
newset = list.__getslice__(self, start, stop)
return ResultSet(newset, index=start, count=len(newset), total=self.total, columns=self.columns, results=self._results)
def __add__(self, other):
newresults = self._results
if not isinstance(other, ResultSet):
raise MarvinUserWarning('Can only add ResultSets together')
# add elements
if self.index == other.index:
# column-wise add
newcols = self.columns.full + [col.full for col in other.columns if col.full not in self.columns.full]
parent = self._results.datamodel if self._results else None
newcols = ColumnGroup('Columns', newcols, parent=parent)
newresults.columns = newcols
new_set = map(add, self, other)
else:
# row-wise add
# warn if the subsets are not consecutive
if abs(self.index - other.index) > self.count:
warnings.warn('You are combining non-consectuive sets! '
'The indexing and ordering will be messed up')
# copy the sets
new_set = copy.copy(self) if self.index < other.index else copy.copy(other)
set_b = copy.copy(other) if self.index < other.index else copy.copy(self)
# filter out any rows that already exist in the set
rows = [row for row in set_b if row not in new_set]
# extend the set
new_set.extend(rows)
newcols = self.columns
self.count = len(new_set)
self.index = min(self.index, other.index)
return ResultSet(new_set, count=self.count, total=self.total, index=self.index,
columns=newcols, results=newresults)
def __radd__(self, other):
return self.__add__(other)
def _populate_from_results(self):
''' Populate some parameters from the results '''
if self._results:
self.columns = self._results.columns if not self.columns else self.columns
self.choices = self.columns.list_params('remote')
self.count = self._results.count if not self.count else self.count
self.total = self._results.totalcount if not self.total else self.total
else:
self.count = self.count if self.count else len(self)
self.total = self.total if self.total else len(self)
def to_dict(self, name=None, format_type='listdict'):
''' Convert the ResultSet into a dictionary
Converts the set of results into a list of dictionaries. Optionally
accepts a column name keyword to extract only that column.
Parameters:
name (str):
Name of the column you wish to extract. Default is None.
format_type (str):
The format of the output dictionary. Can either be a list of dictionaries
or a dictionary of lists.
Returns:
The output converted into dictionary format.
'''
keys = self.columns.list_params('remote')
if format_type == 'listdict':
if name:
output = [{k: res.__getattribute__(k) for k in [name]} for res in self]
else:
output = [{k: res.__getattribute__(k) for k in keys} for res in self]
elif format_type == 'dictlist':
if name:
output = {k: [res._asdict()[k] for res in self] for k in [name]}
else:
output = {k: [res._asdict()[k] for res in self] for k in keys}
else:
raise MarvinError('Cannot output dictionaries. Check your input format_type.')
return output
def to_list(self):
''' Converts to a standard Python list object '''
return list(self)
def sort(self, name=None, reverse=False):
''' Sort the results
In-place sorting of the result set. This is the standard list sorting mechanism.
When no name is specified, does standard list sorting with no key.
Parameters:
name (str):
Column name to sort on. Default is None.
reverse (bool):
If True, sorts in reverse (descending) order.
Returns:
A sorted list
'''
if name:
colname = self.columns[name].remote
return list.sort(self, key=lambda row: row.__getattribute__(colname), reverse=reverse)
else:
return list.sort(self)
class Results(object):
''' A class to handle results from queries on the MaNGA dataset
Parameters:
results (list):
List of results satisfying the input Query
query (object / str):
The query used to produce these results. In local mode, the query is an
SQLalchemy object that can be used to redo the query, or extract subsets
of results from the query. In remote more, the query is a literal string
representation of the SQL query.
returntype (str):
The MarvinTools object to convert the results into. If initially set, the results
are automaticaly converted into the specified Marvin Tool Object on initialization
objects (list):
The list of Marvin Tools objects created by returntype
count (int):
The number of objects in the returned query results
totalcount (int):
The total number of objects in the full query results
mode ({'auto', 'local', 'remote'}):
The load mode to use. See :doc:`Mode secision tree</mode_decision>`.
chunk (int):
For paginated results, the number of results to return. Defaults to 10.
start (int):
For paginated results, the starting index value of the results. Defaults to 0.
end (int):
For paginated results, the ending index value of the resutls. Defaults to start+chunk.
Attributes:
count (int): The count of objects in your current page of results
totalcount (int): The total number of results in the query
query_time (datetime): A datetime TimeDelta representation of the query runtime
Returns:
results: An object representing the Results entity
Example:
>>> f = 'nsa.z < 0.012 and ifu.name = 19*'
>>> q = Query(searchfilter=f)
>>> r = q.run()
>>> print(r)
>>> Results(results=[(u'4-3602', u'1902', -9999.0), (u'4-3862', u'1902', -9999.0), (u'4-3293', u'1901', -9999.0), (u'4-3988', u'1901', -9999.0), (u'4-4602', u'1901', -9999.0)],
>>> query=<sqlalchemy.orm.query.Query object at 0x115217090>,
>>> count=64,
>>> mode=local)
'''
def __init__(self, *args, **kwargs):
self.results = kwargs.get('results', None)
self._queryobj = kwargs.get('queryobj', None)
self._updateQueryObj(**kwargs)
self.count = kwargs.get('count', None)
self.totalcount = kwargs.get('totalcount', self.count)
self._runtime = kwargs.get('runtime', None)
self.query_time = self._getRunTime() if self._runtime is not None else None
self.response_time = kwargs.get('response_time', None)
self.mode = config.mode if not kwargs.get('mode', None) else kwargs.get('mode', None)
self.chunk = kwargs.get('chunk', None)
self.start = kwargs.get('start', None)
self.end = kwargs.get('end', None)
self.datamodel = datamodel[self._release]
self.objects = None
self.sortcol = None
self.order = None
# drop breadcrumb
breadcrumb.drop(message='Initializing MarvinResults {0}'.format(self.__class__),
category=self.__class__)
# Convert results to MarvinTuple
if self.count > 0 and self.results:
self._set_page()
self._create_result_set(index=self.start)
# Auto convert to Marvin Object
if self.returntype:
self.convertToTool(self.returntype)
def __add__(self, other):
assert isinstance(other, Results) is True, 'Can only add Marvin Results together'
assert self._release == other._release, 'Cannot add Marvin Results from different releases'
assert self.searchfilter == other.searchfilter, 'Cannot add Marvin Results with different search filters'
results = self.results + other.results
returnparams = self.returnparams + [p for p in other.returnparams if p not in self.returnparams]
params = self._params + [p for p in other._params if p not in self._params]
return Results(results=results, params=params, returnparams=returnparams, limit=self.limit,
searchfilter=self.searchfilter, count=len(results), totalcount=self.totalcount,
release=self._release, mode=self.mode)
def __radd__(self, other):
return self.__add__(other)
def _updateQueryObj(self, **kwargs):
''' update parameters using the _queryobj '''
self.query = self._queryobj.query if self._queryobj else kwargs.get('query', None)
self.returntype = self._queryobj.returntype if self._queryobj else kwargs.get('returntype', None)
self.searchfilter = self._queryobj.searchfilter if self._queryobj else kwargs.get('searchfilter', None)
self.returnparams = self._queryobj._returnparams if self._queryobj else kwargs.get('returnparams', [])
self.limit = self._queryobj.limit if self._queryobj else kwargs.get('limit', None)
self._params = self._queryobj.params if self._queryobj else kwargs.get('params', None)
self._release = self._queryobj._release if self._queryobj else kwargs.get('release', None)
def __repr__(self):
return ('Marvin Results(query={0}, totalcount={1}, count={2}, mode={3})'.format(self.searchfilter, self.totalcount, self.count, self.mode))
def showQuery(self):
''' Displays the literal SQL query used to generate the Results objects
Returns:
querystring (str):
A string representation of the SQL query
'''
# check unicode or str
isstr = isinstance(self.query, six.string_types)
# return the string query or compile the real query
if isstr:
return self.query
else:
return str(self.query.statement.compile(compile_kwargs={'literal_binds': True}))
def _getRunTime(self):
''' Sets the query runtime as a datetime timedelta object '''
if isinstance(self._runtime, dict):
return datetime.timedelta(**self._runtime)
else:
return self._runtime
def download(self, images=False, limit=None):
''' Download results via sdss_access
Uses sdss_access to download the query results via rsync.
Downloads them to the local sas. The data type downloaded
is indicated by the returntype parameter
i.e. $SAS_BASE_DIR/mangawork/manga/spectro/redux/...
Parameters:
images (bool):
Set to only download the images of the query results
limit (int):
A limit of the number of results to download
Returns:
NA: na
Example:
>>> r = q.run()
>>> r.returntype = 'cube'
>>> r.download()
'''
plateifu = self.getListOf('plateifu')
if images:
tmp = getImagesByList(plateifu, mode='remote', as_url=True, download=True)
else:
downloadList(plateifu, dltype=self.returntype, limit=limit)
def sort(self, name, order='asc'):
''' Sort the set of results by column name
Sorts the results (in place) by a given parameter / column name. Sets
the results to the new sorted results.
Parameters:
name (str):
The column name to sort on
order ({'asc', 'desc'}):
To sort in ascending or descending order. Default is asc.
Example:
>>> r = q.run()
>>> r.getColumns()
>>> [u'mangaid', u'name', u'nsa.z']
>>> r.results
>>> [(u'4-3988', u'1901', -9999.0),
>>> (u'4-3862', u'1902', -9999.0),
>>> (u'4-3293', u'1901', -9999.0),
>>> (u'4-3602', u'1902', -9999.0),
>>> (u'4-4602', u'1901', -9999.0)]
>>> # Sort the results by mangaid
>>> r.sort('mangaid')
>>> [(u'4-3293', u'1901', -9999.0),
>>> (u'4-3602', u'1902', -9999.0),
>>> (u'4-3862', u'1902', -9999.0),
>>> (u'4-3988', u'1901', -9999.0),
>>> (u'4-4602', u'1901', -9999.0)]
>>> # Sort the results by IFU name in descending order
>>> r.sort('ifu.name', order='desc')
>>> [(u'4-3602', u'1902', -9999.0),
>>> (u'4-3862', u'1902', -9999.0),
>>> (u'4-3293', u'1901', -9999.0),
>>> (u'4-3988', u'1901', -9999.0),
>>> (u'4-4602', u'1901', -9999.0)]
'''
remotename = self._check_column(name, 'remote')
self.sortcol = remotename
self.order = order
if self.mode == 'local':
reverse = True if order == 'desc' else False
self.getAll()
self.results.sort(remotename, reverse=reverse)
self.results = self.results[0:self.limit]
elif self.mode == 'remote':
# Fail if no route map initialized
if not config.urlmap:
raise MarvinError('No URL Map found. Cannot make remote call')
# Get the query route
url = config.urlmap['api']['querycubes']['url']
params = {'searchfilter': self.searchfilter, 'params': self.returnparams,
'sort': remotename, 'order': order, 'limit': self.limit}
self._interaction(url, params, create_set=True, calltype='Sort')
return self.results
def toTable(self):
''' Output the results as an Astropy Table
Uses the Python Astropy package
Parameters:
None
Returns:
tableres:
Astropy Table
Example:
>>> r = q.run()
>>> r.toTable()
>>> <Table length=5>
>>> mangaid name nsa.z
>>> unicode6 unicode4 float64
>>> -------- -------- ------------
>>> 4-3602 1902 -9999.0
>>> 4-3862 1902 -9999.0
>>> 4-3293 1901 -9999.0
>>> 4-3988 1901 -9999.0
>>> 4-4602 1901 -9999.0
'''
try:
tabres = Table(rows=self.results, names=self.columns.full)
except ValueError as e:
raise MarvinError('Could not make astropy Table from results: {0}'.format(e))
return tabres
def merge_tables(self, tables, direction='vert', **kwargs):
''' Merges a list of Astropy tables of results together
Combines two Astropy tables using either the Astropy
vstack or hstack method. vstack refers to vertical stacking of table rows.
hstack refers to horizonal stacking of table columns. hstack assumes the rows in each
table refer to the same object. Buyer beware: stacking tables without proper understanding
of your rows and columns may results in deleterious results.
merge_tables also accepts all keyword arguments that Astropy vstack and hstack method do.
See `vstack <http://docs.astropy.org/en/stable/table/operations.html#stack-vertically>`_
See `hstack <http://docs.astropy.org/en/stable/table/operations.html#stack-horizontally>`_
Parameters:
tables (list):
A list of Astropy Table objects. Required.
direction (str):
The direction of the table stacking, either vertical ('vert') or horizontal ('hor').
Default is 'vert'. Direction string can be fuzzy.
Returns:
A new Astropy table that is the stacked combination of all input tables
Example:
>>> # query 1
>>> q, r = doQuery(searchfilter='nsa.z < 0.1', returnparams=['g_r', 'cube.ra', 'cube.dec'])
>>> # query 2
>>> q2, r2 = doQuery(searchfilter='nsa.z < 0.1')
>>>
>>> # convert to tables
>>> table_1 = r.toTable()
>>> table_2 = r2.toTable()
>>> tables = [table_1, table_2]
>>>
>>> # vertical (row) stacking
>>> r.merge_tables(tables, direction='vert')
>>> # horizontal (column) stacking
>>> r.merge_tables(tables, direction='hor')
'''
choices = ['vertical', 'horizontal']
stackdir, score = process.extractOne(direction, choices)
if stackdir == 'vertical':
return vstack(tables, **kwargs)
elif stackdir == 'horizontal':
return hstack(tables, **kwargs)
def toFits(self, filename='myresults.fits', overwrite=False):
''' Output the results as a FITS file
Writes a new FITS file from search results using
the astropy Table.write()
Parameters:
filename (str):
Name of FITS file to output
overwrite (bool):
Set to True to overwrite an existing file
'''
myext = os.path.splitext(filename)[1]
if not myext:
filename = filename + '.fits'
table = self.toTable()
table.write(filename, format='fits', overwrite=overwrite)
print('Writing new FITS file {0}'.format(filename))
def toCSV(self, filename='myresults.csv', overwrite=False):
''' Output the results as a CSV file
Writes a new CSV file from search results using
the astropy Table.write()
Parameters:
filename (str):
Name of CSV file to output
overwrite (bool):
Set to True to overwrite an existing file
'''
myext = os.path.splitext(filename)[1]
if not myext:
filename = filename + '.csv'
table = self.toTable()
table.write(filename, format='csv', overwrite=overwrite)
print('Writing new CSV file {0}'.format(filename))
def toDF(self):
'''Call toDataFrame().
'''
return self.toDataFrame()
def toDataFrame(self):
'''Output the results as an pandas dataframe.
Uses the pandas package.
Parameters:
None
Returns:
dfres:
pandas dataframe
Example:
>>> r = q.run()
>>> r.toDataFrame()
mangaid plate name nsa_mstar z
0 1-22286 7992 12704 1.702470e+11 0.099954
1 1-22301 7992 6101 9.369260e+10 0.105153
2 1-22414 7992 6103 7.489660e+10 0.092272
3 1-22942 7992 12705 8.470360e+10 0.104958
4 1-22948 7992 9102 1.023530e+11 0.119399
'''
try:
dfres = pd.DataFrame(self.results.to_list())
except (ValueError, NameError) as e:
raise MarvinError('Could not make pandas dataframe from results: {0}'.format(e))
return dfres
def _create_result_set(self, index=None, rows=None):
''' Creates a Marvin ResultSet
Parameters:
index (int):
The starting index of the result subset
rows (list|ResultSet):
A list of rows containing the value data to input into the ResultSet
Returns:
creates a marvin ResultSet and sets it as the results attribute
'''
# grab the columns from the results
self.columns = self.getColumns()
ntnames = self.columns.list_params('remote')
# dynamically create a new ResultRow Class
rows = rows if rows else self.results
row_is_dict = isinstance(rows[0], dict)
if not isinstance(rows, ResultSet):
nt = marvintuple('ResultRow', ntnames, results=self)
if row_is_dict:
results = [nt(**r) for r in rows]
else:
results = [nt(*r) for r in rows]
else:
results = rows
self.count = len(results)
# Build the ResultSet
self.results = ResultSet(results, count=self.count, total=self.totalcount, index=index, results=self)
def _set_page(self):
''' Set the page of the data '''
if self.start and self.end:
self.chunk = (self.end - self.start)
else:
self.chunk = self.chunk if self.chunk else self.limit if self.limit else 100
self.start = 0
self.end = self.start + self.chunk
self.pages = int(np.ceil(self.totalcount / float(self.count))) if self.count else 0
self.index = self.start
self.current_page = (int(self.index) + self.count) / self.count
def save(self, path=None, overwrite=False):
''' Save the results as a pickle object
Parameters:
path (str):
Filepath and name of the pickled object
overwrite (bool):
Set this to overwrite an existing pickled file
Returns:
path (str):
The filepath and name of the pickled object
'''
# set the filename and path
sf = self.searchfilter.replace(' ', '') if self.searchfilter else 'anon'
# set the path
if not path:
path = os.path.expanduser('~/marvin_results_{0}.mpf'.format(sf))
# check for file extension
if not os.path.splitext(path)[1]:
path = os.path.join(path + '.mpf')
path = os.path.realpath(path)
if os.path.isdir(path):
raise MarvinError('path must be a full route, including the filename.')
if os.path.exists(path) and not overwrite:
warnings.warn('file already exists. Not overwriting.', MarvinUserWarning)
return
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
# convert results into a dict
dict_results = self.results.to_dict()
# set bad pickled attributes to None
attrs = ['results', 'datamodel', 'columns', '_queryobj']
vals = [dict_results, None, None, None]
isnotstr = not isinstance(self.query, six.string_types)
if isnotstr:
attrs += ['query']
vals += [None]
# pickle the results
try:
with temp_setattr(self, attrs, vals):
pickle.dump(self, open(path, 'wb'), protocol=-1)
except Exception as ee:
if os.path.exists(path):
os.remove(path)
raise MarvinError('Error found while pickling: {0}'.format(str(ee)))
return path
@classmethod
def restore(cls, path, delete=False):
''' Restore a pickled Results object
Parameters:
path (str):
The filename and path to the pickled object
delete (bool):
Turn this on to delete the pickled fil upon restore
Returns:
Results (instance):
The instantiated Marvin Results class
'''
obj = marvin_pickle.restore(path, delete=delete)
obj._create_result_set()
obj.getColumns()
obj.datamodel = datamodel[obj._release]
return obj
def toJson(self):
''' Output the results as a JSON object
Uses Python json package to convert the results to JSON representation
Parameters:
None
Returns:
jsonres:
JSONed results
Example:
>>> r = q.run()
>>> r.toJson()
>>> '[["4-3602", "1902", -9999.0], ["4-3862", "1902", -9999.0], ["4-3293", "1901", -9999.0],
>>> ["4-3988", "1901", -9999.0], ["4-4602", "1901", -9999.0]]'
'''
try:
jsonres = json.dumps(self.results)
except TypeError as e:
raise MarvinError('Results not JSON-ifiable. Check the format of results: {0}'.format(e))
return jsonres
def getColumns(self):
''' Get the columns of the returned reults
Returns a ParameterGroup containing the columns from the
returned results. Each row of the ParameterGroup is a
QueryParameter.
Returns:
columns (list):
A list of column names from the results
Example:
>>> r = q.run()
>>> cols = r.getColumns()
>>> print(cols)
>>> [u'mangaid', u'name', u'nsa.z']
'''
try:
self.columns = ColumnGroup('Columns', self._params, parent=self.datamodel)
except Exception as e:
raise MarvinError('Could not create query columns: {0}'.format(e))
return self.columns
def _interaction(self, url, params, calltype='', create_set=None, **kwargs):
''' Perform a remote Interaction call
Parameters:
url (str):
The url of the request
params (dict):
A dictionary of parameters (get or post) to send with the request
calltype (str):
The method call sending the request
create_set (bool):
If True, sets the response output as the new results and creates a
new named tuple set
Returns:
output:
The output data from the request
Raises:
MarvinError: Raises on any HTTP Request error
'''
# check if the returnparams parameter is in the proper format
if 'params' in params:
return_params = params.get('params', None)
if return_params and isinstance(return_params, list):
params['params'] = ','.join(return_params)
# send the request
try:
ii = Interaction(route=url, params=params, stream=True)
except MarvinError as e:
raise MarvinError('API Query {0} call failed: {1}'.format(calltype, e))
else:
output = ii.getData()
self.response_time = ii.response_time
self._runtime = ii.results['runtime']
self.query_time = self._getRunTime()
index = kwargs.get('index', None)
if create_set:
self._create_result_set(index=index, rows=output)
else:
return output
def _check_column(self, name, name_type):
''' Check if a name exists as a column '''
try:
name_in_col = name in self.columns
except KeyError as e:
raise MarvinError('Column {0} not found in results: {1}'.format(name, e))
else:
assert name_type in ['full', 'remote', 'name', 'short', 'display'], \
'name_type must be one of "full, remote, name, short, display"'
return self.columns[str(name)].__getattribute__(name_type)
def getListOf(self, name=None, to_json=False, to_ndarray=False, return_all=None):
''' Extract a list of a single parameter from results
Parameters:
name (str):
Name of the parameter name to return. If not specified,
it returns all parameters.
to_json (bool):
True/False boolean to convert the output into a JSON format
to_ndarray (bool):
True/False boolean to convert the output into a Numpy array
return_all (bool):
if True, returns the entire result set for that column
Returns:
output (list):
A list of results for one parameter
Example:
>>> r = q.run()
>>> r.getListOf('mangaid')
>>> [u'4-3988', u'4-3862', u'4-3293', u'4-3602', u'4-4602']
Raises:
AssertionError:
Raised when no name is specified.
'''
assert name, 'Must specify a column name'
# check column name and get full name
fullname = self._check_column(name, 'full')
# deal with the output
if return_all:
# # grab all of that column
url = config.urlmap['api']['getcolumn']['url'].format(colname=fullname)
params = {'searchfilter': self.searchfilter, 'format_type': 'list',
'return_all': True, 'params': self.returnparams}
output = self._interaction(url, params, calltype='getList')
else:
# only deal with current page
output = self.results[name] if self.results.count > 1 else [self.results[name]]
if to_json:
output = json.dumps(output) if output else None
if to_ndarray:
output = np.array(output) if output else None
return output
def getDictOf(self, name=None, format_type='listdict', to_json=False, return_all=None):
''' Get a dictionary of specified parameters
Parameters:
name (str):
Name of the parameter name to return. If not specified,
it returns all parameters.
format_type ({'listdict', 'dictlist'}):
The format of the results. Listdict is a list of dictionaries.
Dictlist is a dictionary of lists. Default is listdict.
to_json (bool):
True/False boolean to convert the output into a JSON format
return_all (bool):
if True, returns the entire result set for that column
Returns:
output (list, dict):
Can be either a list of dictionaries, or a dictionary of lists
Example:
>>> # get some results
>>> r = q.run()
>>> # Get a list of dictionaries
>>> r.getDictOf(format_type='listdict')
>>> [{'cube.mangaid': u'4-3988', 'ifu.name': u'1901', 'nsa.z': -9999.0},
>>> {'cube.mangaid': u'4-3862', 'ifu.name': u'1902', 'nsa.z': -9999.0},
>>> {'cube.mangaid': u'4-3293', 'ifu.name': u'1901', 'nsa.z': -9999.0},
>>> {'cube.mangaid': u'4-3602', 'ifu.name': u'1902', 'nsa.z': -9999.0},
>>> {'cube.mangaid': u'4-4602', 'ifu.name': u'1901', 'nsa.z': -9999.0}]
>>> # Get a dictionary of lists
>>> r.getDictOf(format_type='dictlist')
>>> {'cube.mangaid': [u'4-3988', u'4-3862', u'4-3293', u'4-3602', u'4-4602'],
>>> 'ifu.name': [u'1901', u'1902', u'1901', u'1902', u'1901'],
>>> 'nsa.z': [-9999.0, -9999.0, -9999.0, -9999.0, -9999.0]}
>>> # Get a dictionary of only one parameter
>>> r.getDictOf('mangaid')
>>> [{'cube.mangaid': u'4-3988'},
>>> {'cube.mangaid': u'4-3862'},
>>> {'cube.mangaid': u'4-3293'},
>>> {'cube.mangaid': u'4-3602'},
>>> {'cube.mangaid': u'4-4602'}]
'''
# get the remote and full name
remotename = self._check_column(name, 'remote') if name else None
fullname = self._check_column(name, 'full') if name else None
# create the dictionary
output = self.results.to_dict(name=remotename, format_type=format_type)
# deal with the output
if return_all:
# grab all or of a specific column
params = {'searchfilter': self.searchfilter, 'return_all': True,
'format_type': format_type, 'params': self.returnparams}
url = config.urlmap['api']['getcolumn']['url'].format(colname=fullname)
output = self._interaction(url, params, calltype='getDict')
else:
# only deal with current page
output = self.results.to_dict(name=remotename, format_type=format_type)
if to_json:
output = json.dumps(output) if output else None
return output
def loop(self, chunk=None):
''' Loop over the full set of results
Starts a loop to collect all the results (in chunks)
until the current count reaches the total number
of results. Uses extendSet.
Parameters:
chunk (int):
The number of objects to return
Example:
>>> # get some results from a query
>>> r = q.run()
>>> # start a loop, grabbing in chunks of 400
>>> r.loop(chunk=400)
'''
while self.count < self.totalcount:
self.extendSet(chunk=chunk)
def extendSet(self, chunk=None, start=None):
''' Extend the Result set with the next page
Extends the current ResultSet with the next page of results
or a specified page. Calls either getNext or getSubset.
Parameters:
chunk (int):
The number of objects to return
start (int):
The starting index of your subset extraction
Returns:
A new results set
Example:
>>> # run a query
>>> r = q.run()
>>> # extend the current result set with the next page
>>> r.extendSet()
>>>
See Also:
getNext, getSubset
'''
oldset = copy.copy(self.results)
if start is not None:
nextset = self.getSubset(start, limit=chunk)
else:
nextset = self.getNext(chunk=chunk)
newset = oldset + nextset
self.count = len(newset)
self.results = newset
def getNext(self, chunk=None):
''' Retrieve the next chunk of results
Returns the next chunk of results from the query.
from start to end in units of chunk. Used with getPrevious
to paginate through a long list of results
Parameters:
chunk (int):
The number of objects to return
Returns:
results (list):
A list of query results
Example:
>>> r = q.run()
>>> r.getNext(5)
>>> Retrieving next 5, from 35 to 40
>>> [(u'4-4231', u'1902', -9999.0),
>>> (u'4-14340', u'1901', -9999.0),
>>> (u'4-14510', u'1902', -9999.0),
>>> (u'4-13634', u'1901', -9999.0),
>>> (u'4-13538', u'1902', -9999.0)]
See Also:
getAll, getPrevious, getSubset
'''
if chunk and chunk < 0:
warnings.warn('Chunk cannot be negative. Setting to {0}'.format(self.chunk), MarvinUserWarning)
chunk = self.chunk
newstart = self.end
self.chunk = chunk if chunk else self.chunk
newend = newstart + self.chunk
# This handles cases when the number of results is < total
if self.totalcount == self.count:
warnings.warn('You have all the results. Cannot go forward', MarvinUserWarning)
return self.results
# This handles the end edge case
if newend > self.totalcount:
warnings.warn('You have reached the end.', MarvinUserWarning)
newend = self.totalcount
newstart = self.end
# This grabs the next chunk
log.info('Retrieving next {0}, from {1} to {2}'.format(self.chunk, newstart, newend))
if self.mode == 'local':
self.results = self.query.slice(newstart, newend).all()
if self.results:
self._create_result_set(index=newstart)
elif self.mode == 'remote':
# Fail if no route map initialized
if not config.urlmap:
raise MarvinError('No URL Map found. Cannot make remote call')
# Get the query route
url = config.urlmap['api']['getsubset']['url']
params = {'searchfilter': self.searchfilter, 'params': self.returnparams,
'start': newstart, 'end': newend, 'limit': chunk,
'sort': self.sortcol, 'order': self.order}
self._interaction(url, params, calltype='getNext', create_set=True,
index=newstart)
self.start = newstart
self.end = newend
self.count = len(self.results)
if self.returntype:
self.convertToTool(self.returntype)
return self.results
def getPrevious(self, chunk=None):
''' Retrieve the previous chunk of results.
Returns a previous chunk of results from the query.
from start to end in units of chunk. Used with getNext
to paginate through a long list of results
Parameters:
chunk (int):
The number of objects to return
Returns:
results (list):
A list of query results
Example:
>>> r = q.run()
>>> r.getPrevious(5)
>>> Retrieving previous 5, from 30 to 35
>>> [(u'4-3988', u'1901', -9999.0),
>>> (u'4-3862', u'1902', -9999.0),
>>> (u'4-3293', u'1901', -9999.0),
>>> (u'4-3602', u'1902', -9999.0),
>>> (u'4-4602', u'1901', -9999.0)]
See Also:
getNext, getAll, getSubset
'''
if chunk and chunk < 0:
warnings.warn('Chunk cannot be negative. Setting to {0}'.format(self.chunk), MarvinUserWarning)
chunk = self.chunk
newend = self.start
self.chunk = chunk if chunk else self.chunk
newstart = newend - self.chunk
# This handles cases when the number of results is < total
if self.totalcount == self.count:
warnings.warn('You have all the results. Cannot go back', MarvinUserWarning)
return self.results
# This handles the start edge case
if newstart < 0:
warnings.warn('You have reached the beginning.', MarvinUserWarning)
newstart = 0
newend = self.start
# This grabs the previous chunk
log.info('Retrieving previous {0}, from {1} to {2}'.format(self.chunk, newstart, newend))
if self.mode == 'local':
self.results = self.query.slice(newstart, newend).all()
if self.results:
self._create_result_set(index=newstart)
elif self.mode == 'remote':
# Fail if no route map initialized
if not config.urlmap:
raise MarvinError('No URL Map found. Cannot make remote call')
# Get the query route
url = config.urlmap['api']['getsubset']['url']
params = {'searchfilter': self.searchfilter, 'params': self.returnparams,
'start': newstart, 'end': newend, 'limit': chunk,
'sort': self.sortcol, 'order': self.order}
self._interaction(url, params, calltype='getPrevious', create_set=True,
index=newstart)
self.start = newstart
self.end = newend
self.count = len(self.results)
if self.returntype:
self.convertToTool(self.returntype)
return self.results
def getSubset(self, start, limit=None):
''' Extracts a subset of results
Parameters:
start (int):
The starting index of your subset extraction
limit (int):
The limiting number of results to return.
Returns:
results (list):
A list of query results
Example:
>>> r = q.run()
>>> r.getSubset(0, 10)
>>> [(u'14-12', u'1901', -9999.0),
>>> (u'14-13', u'1902', -9999.0),
>>> (u'27-134', u'1901', -9999.0),
>>> (u'27-100', u'1902', -9999.0),
>>> (u'27-762', u'1901', -9999.0),
>>> (u'27-759', u'1902', -9999.0),
>>> (u'27-827', u'1901', -9999.0),
>>> (u'27-828', u'1902', -9999.0),
>>> (u'27-1170', u'1901', -9999.0),
>>> (u'27-1167', u'1902', -9999.0)]
See Also:
getNext, getPrevious, getAll
'''
if not limit:
limit = self.chunk
if limit < 0:
warnings.warn('Limit cannot be negative. Setting to {0}'.format(self.chunk), MarvinUserWarning)
limit = self.chunk
start = 0 if int(start) < 0 else int(start)
end = start + int(limit)
self.start = start
self.end = end
self.chunk = limit
if self.mode == 'local':
self.results = self.query.slice(start, end).all()
if self.results:
self._create_result_set(index=start)
elif self.mode == 'remote':
# Fail if no route map initialized
if not config.urlmap:
raise MarvinError('No URL Map found. Cannot make remote call')
# Get the query route
url = config.urlmap['api']['getsubset']['url']
params = {'searchfilter': self.searchfilter, 'params': self.returnparams,
'start': start, 'end': end, 'limit': limit,
'sort': self.sortcol, 'order': self.order}
self._interaction(url, params, calltype='getSubset', create_set=True, index=start)
self.count = len(self.results)
if self.returntype:
self.convertToTool(self.returntype)
return self.results
def getAll(self, force=False):
''' Retrieve all of the results of a query
Attempts to return all the results of a query. The efficiency of this
method depends heavily on how many rows and columns you wish to return.
A cutoff limit is applied for results with more than 500,000 rows or
results with more than 25 columns.
Parameters
force (bool):
If True, force attempt to download everything
Returns:
The full list of query results.
See Also:
getNext, getPrevious, getSubset, loop
'''
if (self.totalcount > 500000 or len(self.columns) > 25) and not force:
raise MarvinUserWarning("Cannot retrieve all results. The total number of requested "
"rows or columns is too high. Please use the getNext, getPrevious, "
"getSubset, or loop methods to retrieve pages.")
if self.mode == 'local':
self.results = self.query.from_self().all()
self._create_result_set()
elif self.mode == 'remote':
# Get the query route
url = config.urlmap['api']['querycubes']['url']
params = {'searchfilter': self.searchfilter, 'return_all': True,
'params': self.returnparams, 'limit': self.limit,
'sort': self.sortcol, 'order': self.order}
self._interaction(url, params, calltype='getAll', create_set=True)
self.count = self.totalcount
print('Returned all {0} results'.format(self.totalcount))
def convertToTool(self, tooltype, **kwargs):
''' Converts the list of results into Marvin Tool objects
Creates a list of Marvin Tool objects from a set of query results.
The new list is stored in the Results.objects property.
If the Query.returntype parameter is specified, then the Results object
will automatically convert the results to the desired Tool on initialization.
Parameters:
tooltype (str):
The requested Marvin Tool object that the results are converted into.
Overrides the returntype parameter. If not set, defaults
to the returntype parameter.
limit (int):
Limit the number of results you convert to Marvin tools. Useful
for extremely large result sets. Default is None.
mode (str):
The mode to use when attempting to convert to Tool. Default mode
is to use the mode internal to Results. (most often remote mode)
Example:
>>> # Get the results from some query
>>> r = q.run()
>>> r.results
>>> [NamedTuple(mangaid=u'14-12', name=u'1901', nsa.z=-9999.0),
>>> NamedTuple(mangaid=u'14-13', name=u'1902', nsa.z=-9999.0),
>>> NamedTuple(mangaid=u'27-134', name=u'1901', nsa.z=-9999.0),
>>> NamedTuple(mangaid=u'27-100', name=u'1902', nsa.z=-9999.0),
>>> NamedTuple(mangaid=u'27-762', name=u'1901', nsa.z=-9999.0)]
>>> # convert results to Marvin Cube tools
>>> r.convertToTool('cube')
>>> r.objects
>>> [<Marvin Cube (plateifu='7444-1901', mode='remote', data_origin='api')>,
>>> <Marvin Cube (plateifu='7444-1902', mode='remote', data_origin='api')>,
>>> <Marvin Cube (plateifu='7995-1901', mode='remote', data_origin='api')>,
>>> <Marvin Cube (plateifu='7995-1902', mode='remote', data_origin='api')>,
>>> <Marvin Cube (plateifu='8000-1901', mode='remote', data_origin='api')>]
'''
# set the desired tool type
mode = kwargs.get('mode', self.mode)
limit = kwargs.get('limit', None)
toollist = ['cube', 'spaxel', 'maps', 'rss', 'modelcube']
tooltype = tooltype if tooltype else self.returntype
assert tooltype in toollist, 'Returned tool type must be one of {0}'.format(toollist)
# get the parameter list to check against
paramlist = self.columns.full
print('Converting results to Marvin {0} objects'.format(tooltype.title()))
if tooltype == 'cube':
self.objects = [Cube(plateifu=res.plateifu, mode=mode) for res in self.results[0:limit]]
elif tooltype == 'maps':
isbin = 'bintype.name' in paramlist
istemp = 'template.name' in paramlist
self.objects = []
for res in self.results[0:limit]:
mapkwargs = {'mode': mode, 'plateifu': res.plateifu}
if isbin:
binval = res.bintype_name
mapkwargs['bintype'] = binval
if istemp:
tempval = res.template_name
mapkwargs['template_kin'] = tempval
self.objects.append(Maps(**mapkwargs))
elif tooltype == 'spaxel':
assert 'spaxelprop.x' in paramlist and 'spaxelprop.y' in paramlist, \
'Parameters must include spaxelprop.x and y in order to convert to Marvin Spaxel.'
self.objects = []
load = kwargs.get('load', True)
maps = kwargs.get('maps', True)
modelcube = kwargs.get('modelcube', True)
tab = self.toTable()
uniq_plateifus = list(set(self.getListOf('plateifu')))
for plateifu in uniq_plateifus:
c = Cube(plateifu=plateifu, mode=mode)
univals = tab['cube.plateifu'] == plateifu
x = tab[univals]['spaxelprop.x'].tolist()
y = tab[univals]['spaxelprop.y'].tolist()
spaxels = c[y, x]
self.objects.extend(spaxels)
elif tooltype == 'rss':
self.objects = [RSS(plateifu=res.plateifu, mode=mode) for res in self.results[0:limit]]
elif tooltype == 'modelcube':
isbin = 'bintype.name' in paramlist
istemp = 'template.name' in paramlist
self.objects = []
for res in self.results[0:limit]:
mapkwargs = {'mode': mode, 'plateifu': res.plateifu}
if isbin:
binval = res.bintype_name
mapkwargs['bintype'] = binval
if istemp:
tempval = res.template_name
mapkwargs['template_kin'] = tempval
self.objects.append(ModelCube(**mapkwargs))
def plot(self, x_name, y_name, **kwargs):
''' Make a scatter plot from two columns of results
Creates a Matplotlib scatter plot from Results columns.
Accepts as input two string column names. Will extract the total
entire column (if not already available) and plot them. Creates
a scatter plot with (optionally) adjoining 1-d histograms for each column.
See :meth:`marvin.utils.plot.scatter.plot` and
:meth:`marvin.utils.plot.scatter.hist` for details.
Parameters:
x_name (str):
The name of the x-column of data. Required
y_name (str):
The name of the y-column of data. Required
return_plateifus (bool):
If True, includes the plateifus in each histogram bin in the
histogram output. Default is True.
return_figure (bool):
Set to False to not return the Figure and Axis object. Defaults to True.
show_plot (bool):
Set to False to not show the interactive plot
**kwargs (dict):
Any other keyword argument that will be passed to Marvin's
scatter and hist plotting methods
Returns:
The figure, axes, and histogram data from the plotting function
Example:
>>> # do a query and get the results
>>> q = Query(searchfilter='nsa.z < 0.1', returnparams=['nsa.elpetro_ba', 'g_r'])
>>> r = q.run()
>>> # plot the total columns of Redshift vs g-r magnitude
>>> fig, axes, hist_data = r.plot('nsa.z', 'g_r')
'''
assert all([x_name, y_name]), 'Must provide both an x and y column'
return_plateifus = kwargs.pop('return_plateifus', True)
with_hist = kwargs.get('with_hist', True)
show_plot = kwargs.pop('show_plot', True)
return_figure = kwargs.get('return_figure', True)
# get the named column
x_col = self.columns[x_name]
y_col = self.columns[y_name]
# get the values of the two columns
if self.count != self.totalcount:
x_data = self.getListOf(x_name, return_all=True)
y_data = self.getListOf(y_name, return_all=True)
else:
x_data = self.results[x_name]
y_data = self.results[y_name]
with turn_off_ion(show_plot=show_plot):
output = marvin.utils.plot.scatter.plot(x_data, y_data, xlabel=x_col, ylabel=y_col, **kwargs)
# computes a list of plateifus in each bin
if return_plateifus and with_hist:
plateifus = self.getListOf('plateifu', return_all=True)
hdata = output[2] if return_figure else output
if 'xhist' in hdata:
hdata['xhist']['bins_plateifu'] = map_bins_to_column(plateifus, hdata['xhist']['indices'])
if 'yhist' in hdata:
hdata['yhist']['bins_plateifu'] = map_bins_to_column(plateifus, hdata['yhist']['indices'])
output = output[0:2] + (hdata,) if return_figure else hdata
return output
def hist(self, name, **kwargs):
''' Make a histogram for a given column of the results
Creates a Matplotlib histogram from a Results Column.
Accepts as input a string column name. Will extract the total
entire column (if not already available) and plot it.
See :meth:`marvin.utils.plot.scatter.hist` for details.
Parameters:
name (str):
The name of the column of data. Required
return_plateifus (bool):
If True, includes the plateifus in each histogram bin in the
histogram output. Default is True.
return_figure (bool):
Set to False to not return the Figure and Axis object. Defaults to True.
show_plot (bool):
Set to False to not show the interactive plot
**kwargs (dict):
Any other keyword argument that will be passed to Marvin's
hist plotting methods
Returns:
The histogram data, figure, and axes from the plotting function
Example:
>>> # do a query and get the results
>>> q = Query(searchfilter='nsa.z < 0.1', returnparams=['nsa.elpetro_ba', 'g_r'])
>>> r = q.run()
>>> # plot a histogram of the redshift column
>>> hist_data, fig, axes = r.hist('nsa.z')
'''
return_plateifus = kwargs.pop('return_plateifus', True)
show_plot = kwargs.pop('show_plot', True)
return_figure = kwargs.get('return_figure', True)
# get the named column
col = self.columns[name]
# get the values of the two columns
if self.count != self.totalcount:
data = self.getListOf(name, return_all=True)
else:
data = self.results[name]
# xhist, fig, ax_hist_x = output
with turn_off_ion(show_plot=show_plot):
output = marvin.utils.plot.scatter.hist(data, **kwargs)
if return_plateifus:
plateifus = self.getListOf('plateifu', return_all=True)
hdata = output[0] if return_figure else output
hdata['bins_plateifu'] = map_bins_to_column(plateifus, hdata['indices'])
output = (hdata,) + output[1:] if return_figure else hdata
return output
| [
"marvin.tools.maps.Maps",
"marvin.utils.general.downloadList",
"marvin.utils.general.map_bins_to_column",
"marvin.core.marvin_pickle.restore",
"marvin.tools.rss.RSS",
"marvin.core.exceptions.MarvinUserWarning",
"marvin.tools.modelcube.ModelCube",
"marvin.api.api.Interaction",
"marvin.core.exceptions... | [((1279, 1297), 'marvin.core.exceptions.MarvinBreadCrumb', 'MarvinBreadCrumb', ([], {}), '()\n', (1295, 1297), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((1394, 1404), 'functools.wraps', 'wraps', (['fxn'], {}), '(fxn)\n', (1399, 1404), False, 'from functools import wraps\n'), ((1741, 1751), 'functools.wraps', 'wraps', (['fxn'], {}), '(fxn)\n', (1746, 1751), False, 'from functools import wraps\n'), ((3920, 3974), 'collections.namedtuple', 'namedtuple', (['name', '"""mangaid, plate, plateifu, ifu_name"""'], {}), "(name, 'mangaid, plate, plateifu, ifu_name')\n", (3930, 3974), False, 'from collections import namedtuple\n'), ((4155, 4194), 'collections.namedtuple', 'namedtuple', (['name', 'finalfields'], {}), '(name, finalfields, **kwargs)\n', (4165, 4194), False, 'from collections import namedtuple\n'), ((1168, 1228), 'warnings.warn', 'warnings.warn', (['"""Could not import pandas."""', 'MarvinUserWarning'], {}), "('Could not import pandas.', MarvinUserWarning)\n", (1181, 1228), False, 'import warnings\n'), ((24881, 24919), 'fuzzywuzzy.process.extractOne', 'process.extractOne', (['direction', 'choices'], {}), '(direction, choices)\n', (24899, 24919), False, 'from fuzzywuzzy import process\n'), ((29901, 29923), 'os.path.realpath', 'os.path.realpath', (['path'], {}), '(path)\n', (29917, 29923), False, 'import os\n'), ((29936, 29955), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (29949, 29955), False, 'import os\n'), ((30217, 30238), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (30232, 30238), False, 'import os\n'), ((31496, 31538), 'marvin.core.marvin_pickle.restore', 'marvin_pickle.restore', (['path'], {'delete': 'delete'}), '(path, delete=delete)\n', (31517, 31538), False, 'from marvin.core import marvin_pickle\n'), ((41586, 41609), 'copy.copy', 'copy.copy', (['self.results'], {}), '(self.results)\n', (41595, 41609), False, 'import copy\n'), ((8194, 8247), 'marvin.core.exceptions.MarvinUserWarning', 'MarvinUserWarning', (['"""Can only add ResultSets together"""'], {}), "('Can only add ResultSets together')\n", (8211, 8247), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((18556, 18591), 'datetime.timedelta', 'datetime.timedelta', ([], {}), '(**self._runtime)\n', (18574, 18591), False, 'import datetime\n'), ((19428, 19496), 'marvin.utils.general.getImagesByList', 'getImagesByList', (['plateifu'], {'mode': '"""remote"""', 'as_url': '(True)', 'download': '(True)'}), "(plateifu, mode='remote', as_url=True, download=True)\n", (19443, 19496), False, 'from marvin.utils.general import getImagesByList, downloadList, map_bins_to_column\n'), ((19523, 19582), 'marvin.utils.general.downloadList', 'downloadList', (['plateifu'], {'dltype': 'self.returntype', 'limit': 'limit'}), '(plateifu, dltype=self.returntype, limit=limit)\n', (19535, 19582), False, 'from marvin.utils.general import getImagesByList, downloadList, map_bins_to_column\n'), ((22736, 22785), 'astropy.table.Table', 'Table', ([], {'rows': 'self.results', 'names': 'self.columns.full'}), '(rows=self.results, names=self.columns.full)\n', (22741, 22785), False, 'from astropy.table import Table, vstack, hstack\n'), ((24974, 24998), 'astropy.table.vstack', 'vstack', (['tables'], {}), '(tables, **kwargs)\n', (24980, 24998), False, 'from astropy.table import Table, vstack, hstack\n'), ((25497, 25523), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (25513, 25523), False, 'import os\n'), ((26158, 26184), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (26174, 26184), False, 'import os\n'), ((29857, 29884), 'os.path.join', 'os.path.join', (["(path + '.mpf')"], {}), "(path + '.mpf')\n", (29869, 29884), False, 'import os\n'), ((29975, 30040), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""path must be a full route, including the filename."""'], {}), "('path must be a full route, including the filename.')\n", (29986, 30040), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((30053, 30073), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (30067, 30073), False, 'import os\n'), ((30105, 30178), 'warnings.warn', 'warnings.warn', (['"""file already exists. Not overwriting."""', 'MarvinUserWarning'], {}), "('file already exists. Not overwriting.', MarvinUserWarning)\n", (30118, 30178), False, 'import warnings\n'), ((30254, 30277), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (30268, 30277), False, 'import os\n'), ((30291, 30311), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (30302, 30311), False, 'import os\n'), ((32225, 32249), 'json.dumps', 'json.dumps', (['self.results'], {}), '(self.results)\n', (32235, 32249), False, 'import json\n'), ((34215, 34265), 'marvin.api.api.Interaction', 'Interaction', ([], {'route': 'url', 'params': 'params', 'stream': '(True)'}), '(route=url, params=params, stream=True)\n', (34226, 34265), False, 'from marvin.api.api import Interaction\n'), ((43154, 43239), 'warnings.warn', 'warnings.warn', (['"""You have all the results. Cannot go forward"""', 'MarvinUserWarning'], {}), "('You have all the results. Cannot go forward', MarvinUserWarning\n )\n", (43167, 43239), False, 'import warnings\n'), ((43358, 43419), 'warnings.warn', 'warnings.warn', (['"""You have reached the end."""', 'MarvinUserWarning'], {}), "('You have reached the end.', MarvinUserWarning)\n", (43371, 43419), False, 'import warnings\n'), ((45954, 46031), 'warnings.warn', 'warnings.warn', (['"""You have all the results. Cannot go back"""', 'MarvinUserWarning'], {}), "('You have all the results. Cannot go back', MarvinUserWarning)\n", (45967, 46031), False, 'import warnings\n'), ((46145, 46212), 'warnings.warn', 'warnings.warn', (['"""You have reached the beginning."""', 'MarvinUserWarning'], {}), "('You have reached the beginning.', MarvinUserWarning)\n", (46158, 46212), False, 'import warnings\n'), ((50452, 50653), 'marvin.core.exceptions.MarvinUserWarning', 'MarvinUserWarning', (['"""Cannot retrieve all results. The total number of requested rows or columns is too high. Please use the getNext, getPrevious, getSubset, or loop methods to retrieve pages."""'], {}), "(\n 'Cannot retrieve all results. The total number of requested rows or columns is too high. Please use the getNext, getPrevious, getSubset, or loop methods to retrieve pages.'\n )\n", (50469, 50653), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((58722, 58755), 'marvin.utils.general.turn_off_ion', 'turn_off_ion', ([], {'show_plot': 'show_plot'}), '(show_plot=show_plot)\n', (58734, 58755), False, 'from marvin.utils.general import temp_setattr, turn_off_ion\n'), ((61344, 61377), 'marvin.utils.general.turn_off_ion', 'turn_off_ion', ([], {'show_plot': 'show_plot'}), '(show_plot=show_plot)\n', (61356, 61377), False, 'from marvin.utils.general import temp_setattr, turn_off_ion\n'), ((61641, 61688), 'marvin.utils.general.map_bins_to_column', 'map_bins_to_column', (['plateifus', "hdata['indices']"], {}), "(plateifus, hdata['indices'])\n", (61659, 61688), False, 'from marvin.utils.general import getImagesByList, downloadList, map_bins_to_column\n'), ((8852, 8962), 'warnings.warn', 'warnings.warn', (['"""You are combining non-consectuive sets! The indexing and ordering will be messed up"""'], {}), "(\n 'You are combining non-consectuive sets! The indexing and ordering will be messed up'\n )\n", (8865, 8962), False, 'import warnings\n'), ((9037, 9052), 'copy.copy', 'copy.copy', (['self'], {}), '(self)\n', (9046, 9052), False, 'import copy\n'), ((9086, 9102), 'copy.copy', 'copy.copy', (['other'], {}), '(other)\n', (9095, 9102), False, 'import copy\n'), ((9123, 9139), 'copy.copy', 'copy.copy', (['other'], {}), '(other)\n', (9132, 9139), False, 'import copy\n'), ((9173, 9188), 'copy.copy', 'copy.copy', (['self'], {}), '(self)\n', (9182, 9188), False, 'import copy\n'), ((11503, 11576), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""Cannot output dictionaries. Check your input format_type."""'], {}), "('Cannot output dictionaries. Check your input format_type.')\n", (11514, 11576), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((25057, 25081), 'astropy.table.hstack', 'hstack', (['tables'], {}), '(tables, **kwargs)\n', (25063, 25081), False, 'from astropy.table import Table, vstack, hstack\n'), ((29811, 29833), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (29827, 29833), False, 'import os\n'), ((30759, 30790), 'marvin.utils.general.temp_setattr', 'temp_setattr', (['self', 'attrs', 'vals'], {}), '(self, attrs, vals)\n', (30771, 30790), False, 'from marvin.utils.general import temp_setattr, turn_off_ion\n'), ((30904, 30924), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (30918, 30924), False, 'import os\n'), ((37014, 37032), 'json.dumps', 'json.dumps', (['output'], {}), '(output)\n', (37024, 37032), False, 'import json\n'), ((37098, 37114), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (37106, 37114), True, 'import numpy as np\n'), ((40176, 40194), 'json.dumps', 'json.dumps', (['output'], {}), '(output)\n', (40186, 40194), False, 'import json\n'), ((54082, 54120), 'marvin.tools.cube.Cube', 'Cube', ([], {'plateifu': 'res.plateifu', 'mode': 'mode'}), '(plateifu=res.plateifu, mode=mode)\n', (54086, 54120), False, 'from marvin.tools.cube import Cube\n'), ((59168, 59224), 'marvin.utils.general.map_bins_to_column', 'map_bins_to_column', (['plateifus', "hdata['xhist']['indices']"], {}), "(plateifus, hdata['xhist']['indices'])\n", (59186, 59224), False, 'from marvin.utils.general import getImagesByList, downloadList, map_bins_to_column\n'), ((59308, 59364), 'marvin.utils.general.map_bins_to_column', 'map_bins_to_column', (['plateifus', "hdata['yhist']['indices']"], {}), "(plateifus, hdata['yhist']['indices'])\n", (59326, 59364), False, 'from marvin.utils.general import getImagesByList, downloadList, map_bins_to_column\n'), ((21568, 21625), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No URL Map found. Cannot make remote call"""'], {}), "('No URL Map found. Cannot make remote call')\n", (21579, 21625), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((30942, 30957), 'os.remove', 'os.remove', (['path'], {}), '(path)\n', (30951, 30957), False, 'import os\n'), ((43945, 44002), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No URL Map found. Cannot make remote call"""'], {}), "('No URL Map found. Cannot make remote call')\n", (43956, 44002), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((46734, 46791), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No URL Map found. Cannot make remote call"""'], {}), "('No URL Map found. Cannot make remote call')\n", (46745, 46791), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((49124, 49181), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No URL Map found. Cannot make remote call"""'], {}), "('No URL Map found. Cannot make remote call')\n", (49135, 49181), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning, MarvinBreadCrumb\n'), ((54725, 54742), 'marvin.tools.maps.Maps', 'Maps', ([], {}), '(**mapkwargs)\n', (54729, 54742), False, 'from marvin.tools.maps import Maps\n'), ((55304, 55338), 'marvin.tools.cube.Cube', 'Cube', ([], {'plateifu': 'plateifu', 'mode': 'mode'}), '(plateifu=plateifu, mode=mode)\n', (55308, 55338), False, 'from marvin.tools.cube import Cube\n'), ((7818, 7832), 'numpy.array', 'np.array', (['self'], {}), '(self)\n', (7826, 7832), True, 'import numpy as np\n'), ((55653, 55690), 'marvin.tools.rss.RSS', 'RSS', ([], {'plateifu': 'res.plateifu', 'mode': 'mode'}), '(plateifu=res.plateifu, mode=mode)\n', (55656, 55690), False, 'from marvin.tools.rss import RSS\n'), ((56300, 56322), 'marvin.tools.modelcube.ModelCube', 'ModelCube', ([], {}), '(**mapkwargs)\n', (56309, 56322), False, 'from marvin.tools.modelcube import ModelCube\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Tests of user-shared networks
"""
import logging
import time
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import cleanup_resources, random_gen
from marvin.lib.base import (Account,
Domain,
Project,
Configurations,
ServiceOffering,
Zone,
Network,
NetworkOffering,
VPC,
VpcOffering)
from marvin.lib.common import (get_domain,
get_zone,
get_template)
NETWORK_STATE_ALLOCATED = "Allocated"
NETWORK_STATE_IMPLEMENTED = "Implemented"
NETWORK_STATE_SETUP = "Setup"
NETWORK_STATE_REMOVED = "Removed"
class TestUserSharedNetworks(cloudstackTestCase):
"""
Test user-shared networks
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(
TestUserSharedNetworks,
cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.zone = Zone(zone.__dict__)
cls.template = get_template(cls.apiclient, cls.zone.id)
cls._cleanup = []
cls.logger = logging.getLogger("TestUserSharedNetworks")
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
cls.domain = get_domain(cls.apiclient)
# Create small service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["small"]
)
cls._cleanup.append(cls.service_offering)
# Create network offering for user-shared networks (specifyVlan=true)
cls.network_offering_withvlan = NetworkOffering.create(
cls.apiclient,
cls.services["network_offering_shared"]
)
cls.network_offering_withvlan.update(cls.apiclient, state='Enabled')
cls._cleanup.append(cls.network_offering_withvlan)
# Create network offering for user-shared networks (specifyVlan=false)
cls.services["network_offering_shared"]["specifyVlan"] = "False"
cls.network_offering_novlan = NetworkOffering.create(
cls.apiclient,
cls.services["network_offering_shared"]
)
cls.network_offering_novlan.update(cls.apiclient, state='Enabled')
cls._cleanup.append(cls.network_offering_novlan)
# Create network offering for isolated networks
cls.network_offering_isolated = NetworkOffering.create(
cls.apiclient,
cls.services["network_offering"]
)
cls.network_offering_isolated.update(cls.apiclient, state='Enabled')
cls._cleanup.append(cls.network_offering_isolated)
# Create vpc offering
cls.vpc_offering = VpcOffering.create(
cls.apiclient,
cls.services["vpc_offering_multi_lb"])
cls.vpc_offering.update(cls.apiclient, state='Enabled')
cls._cleanup.append(cls.vpc_offering)
# Create network offering for vpc tiers
cls.network_offering_vpc = NetworkOffering.create(
cls.apiclient,
cls.services["nw_offering_isolated_vpc"],
conservemode=False
)
cls.network_offering_vpc.update(cls.apiclient, state='Enabled')
cls._cleanup.append(cls.network_offering_vpc)
# Create sub-domain
cls.sub_domain = Domain.create(
cls.apiclient,
cls.services["acl"]["domain1"]
)
cls._cleanup.append(cls.sub_domain)
# Create domain admin and normal user
cls.domain_admin = Account.create(
cls.apiclient,
cls.services["acl"]["accountD1A"],
admin=True,
domainid=cls.sub_domain.id
)
cls._cleanup.append(cls.domain_admin)
cls.normal_user = Account.create(
cls.apiclient,
cls.services["acl"]["accountD1B"],
domainid=cls.sub_domain.id
)
cls._cleanup.append(cls.normal_user)
# Create project
cls.project = Project.create(
cls.apiclient,
cls.services["project"],
account=cls.domain_admin.name,
domainid=cls.domain_admin.domainid
)
cls._cleanup.append(cls.project)
# Create api clients for domain admin and normal user
cls.domainadmin_user = cls.domain_admin.user[0]
cls.domainapiclient = cls.testClient.getUserApiClient(
cls.domainadmin_user.username, cls.sub_domain.name
)
cls.normaluser_user = cls.normal_user.user[0]
cls.normaluser_apiclient = cls.testClient.getUserApiClient(
cls.normaluser_user.username, cls.sub_domain.name
)
@classmethod
def tearDownClass(cls):
super(TestUserSharedNetworks, cls).tearDownClass()
def setUp(self):
self.cleanup = []
def tearDown(self):
super(TestUserSharedNetworks, self).tearDown()
def create_shared_network_for_account(self, apiclient, domain, account, expected=True):
return self.create_shared_network_with_associated_network(apiclient, domain, account, None, None, expected)
def create_shared_network_with_associated_network_for_domain(self, apiclient, domain, associated_network, expected=True):
return self.create_shared_network_with_associated_network(apiclient, domain, None, None, associated_network, expected)
def create_shared_network_with_associated_network_for_caller(self, apiclient, project, associated_network, expected=True):
return self.create_shared_network_with_associated_network(apiclient, None, None, project, associated_network, expected)
def create_shared_network_with_associated_network(self, apiclient, domain, account, project, associated_network, expected=True):
self.services["network2"]["acltype"] = "Account"
self.services["network2"]["name"] = "Test Network Shared - " + random_gen()
domain_id = None
account_name = None
project_id = None
if domain:
self.services["network2"]["acltype"] = "Domain"
domain_id = domain.id
if account:
self.services["network2"]["acltype"] = "Account"
account_name = account.name
if project:
self.services["network2"]["acltype"] = "Account"
project_id = project.id
associated_network_id = None
if associated_network:
associated_network_id = associated_network.id
try:
network = Network.create(
apiclient,
self.services["network2"],
domainid=domain_id,
accountid=account_name,
projectid=project_id,
associatednetworkid=associated_network_id,
zoneid=self.zone.id
)
except Exception as ex:
network = None
if expected:
self.fail(f"Failed to create Shared network, but expected to succeed : {ex}")
if network and not expected:
self.fail("Shared network is created successfully, but expected to fail")
return network
def delete_network(self, network, apiclient, expected=True):
result = True
try:
Network.delete(
network,
apiclient,
)
except Exception as ex:
result = False
if expected:
self.fail(f"Failed to remove Shared network, but expected to succeed : {ex}")
if result and not expected:
self.fail("network is removed successfully, but expected to fail")
def create_isolated_network_for_account(self, apiclient, domain, account, project, expected=True):
self.services["network"]["name"] = "Test Network Isolated - " + random_gen()
domain_id = None
account_name = None
project_id = None
if domain:
domain_id = domain.id
if account:
account_name = account.name
if project:
project_id = project.id
try:
network = Network.create(
apiclient,
self.services["network"],
domainid=domain_id,
accountid=account_name,
projectid=project_id,
networkofferingid=self.network_offering_isolated.id,
zoneid=self.zone.id
)
except Exception as ex:
network = None
if expected:
self.fail(f"Failed to create Isolated network, but expected to succeed : {ex}")
if network and not expected:
self.fail("Isolated network is created successfully, but expected to fail")
return network
def check_network_state(self, apiclient, network, project, expected_state):
project_id = None
if project:
project_id = project.id
networks = Network.list(
apiclient,
listall=True,
projectid=project_id,
id=network.id
)
if isinstance(networks, list) and len(networks) > 0:
if expected_state == NETWORK_STATE_REMOVED:
self.fail("Found the network, but expected to fail")
if networks[0].state != expected_state:
self.fail(f"Expect network state is {expected_state}, but actual state is {networks[0].state}")
elif expected_state != NETWORK_STATE_REMOVED:
self.fail("Failed to find the network, but expected to succeed")
def create_vpc_for_account(self, apiclient, domain, account, project):
self.services["vpc"]["name"] = "Test VPC - " + random_gen()
self.services["vpc"]["displaytext"] = self.services["vpc"]["name"]
self.services["vpc"]["cidr"] = "10.1.0.0/20"
domain_id = None
account_name = None
if domain:
domain_id = domain.id
if account:
account_name = account.name
project_id = None
if project:
project_id = project.id
vpc = VPC.create(
apiclient,
self.services["vpc"],
domainid=domain_id,
accountid=account_name,
projectid=project_id,
vpcofferingid=self.vpc_offering.id,
zoneid=self.zone.id,
start=False
)
return vpc
def create_vpc_tier_for_account(self, apiclient, vpc, project=None, gateway = '10.1.1.1'):
self.services["network"]["name"] = "Test VPC tier - " + random_gen()
project_id = None
if project:
project_id = project.id
vpc_tier = Network.create(
apiclient,
self.services["network"],
networkofferingid=self.network_offering_vpc.id,
zoneid=self.zone.id,
projectid=project_id,
gateway=gateway,
netmask="255.255.255.0",
vpcid=vpc.id
)
return vpc_tier
def delete_vpc(self, apiclient, vpc, expected=True):
result = True
try:
vpc.delete(apiclient)
except Exception as ex:
result = False
if expected:
self.fail(f"Failed to remove VPC, but expected to succeed : {ex}")
if result and not expected:
self.fail("VPC is removed successfully, but expected to fail")
@attr(tags=["advanced"], required_hardware="false")
def test_01_create_user_shared_network_without_vlan(self):
""" Create user-shared networks without vlan """
self.services["network2"]["networkoffering"] = self.network_offering_novlan.id
self.services["network2"]["vlan"] = None
network1 = self.create_shared_network_for_account(self.apiclient, None, None)
network2 = self.create_shared_network_for_account(self.domainapiclient, None, None)
network3 = self.create_shared_network_for_account(self.normaluser_apiclient, None, None)
self.delete_network(network1, self.apiclient)
self.delete_network(network2, self.domainapiclient)
self.delete_network(network3, self.normaluser_apiclient)
network4 = self.create_shared_network_for_account(self.domainapiclient, self.sub_domain, self.normal_user, True)
self.delete_network(network4, self.normaluser_apiclient)
network5 = self.create_shared_network_for_account(self.apiclient, self.sub_domain, None, True)
self.delete_network(network5, self.apiclient)
network6 = self.create_shared_network_for_account(self.domainapiclient, self.sub_domain, None, True)
self.delete_network(network6, self.apiclient)
self.create_shared_network_for_account(self.normaluser_apiclient, self.sub_domain, None, False)
@attr(tags=["advanced"], required_hardware="false")
def test_02_create_shared_network_with_vlan(self):
""" Create shared networks with vlan
Only be created/deleted by root admin, Cannot create networks with same vlan
"""
self.services["network2"]["networkoffering"] = self.network_offering_withvlan.id
self.services["network2"]["vlan"] = 4000
self.create_shared_network_for_account(self.domainapiclient, self.sub_domain, None, False)
self.create_shared_network_for_account(self.normaluser_apiclient, self.sub_domain, None, False)
network1 = self.create_shared_network_for_account(self.apiclient, self.sub_domain, None, True)
self.create_shared_network_for_account(self.apiclient, self.sub_domain, self.normal_user, False)
self.delete_network(network1, self.domainapiclient, False)
self.delete_network(network1, self.apiclient, True)
self.create_shared_network_for_account(self.domainapiclient, self.sub_domain, self.normal_user, False)
self.create_shared_network_for_account(self.normaluser_apiclient, self.sub_domain, self.normal_user, False)
network2 = self.create_shared_network_for_account(self.apiclient, self.sub_domain, self.normal_user, True)
self.delete_network(network2, self.domainapiclient, False)
self.delete_network(network2, self.normaluser_apiclient, False)
self.delete_network(network2, self.apiclient, True)
@attr(tags=["advanced"], required_hardware="false")
def test_03_create_domain_shared_network_with_associated_network(self):
""" Create domain-level shared networks with associated network """
self.services["network2"]["networkoffering"] = self.network_offering_novlan.id
self.services["network2"]["vlan"] = None
# Create isolated networks
isolated_network1 = self.create_isolated_network_for_account(self.apiclient, None, None, None, True)
isolated_network2 = self.create_isolated_network_for_account(self.apiclient, self.sub_domain, self.domain_admin, None, True)
isolated_network3 = self.create_isolated_network_for_account(self.apiclient, self.sub_domain, self.normal_user, None, True)
isolated_network4 = self.create_isolated_network_for_account(self.apiclient, self.sub_domain, None, self.project, True)
# Create domain-level shared network with associated_network (caller must be root admin/domain admin, must be in same domain)
self.create_shared_network_with_associated_network_for_domain(self.apiclient, self.sub_domain, isolated_network1, False)
self.create_shared_network_with_associated_network_for_domain(self.domainapiclient, self.sub_domain, isolated_network1, False)
self.create_shared_network_with_associated_network_for_domain(self.normaluser_apiclient, self.sub_domain, isolated_network1, False)
self.create_shared_network_with_associated_network_for_domain(self.normaluser_apiclient, self.sub_domain, isolated_network2, False)
self.create_shared_network_with_associated_network_for_domain(self.normaluser_apiclient, self.sub_domain, isolated_network3, False)
self.create_shared_network_with_associated_network_for_domain(self.normaluser_apiclient, self.sub_domain, isolated_network4, False)
shared_network1 = self.create_shared_network_with_associated_network_for_domain(self.apiclient, self.domain, isolated_network1, True)
shared_network2 = self.create_shared_network_with_associated_network_for_domain(self.domainapiclient, self.sub_domain, isolated_network2, True)
shared_network3 = self.create_shared_network_with_associated_network_for_domain(self.domainapiclient, self.sub_domain, isolated_network3, True)
shared_network4 = self.create_shared_network_with_associated_network_for_domain(self.domainapiclient, self.sub_domain, isolated_network4, True)
# Check state of isolated networks (should be Implemented)
self.check_network_state(self.apiclient, isolated_network1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, isolated_network2, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.normaluser_apiclient, isolated_network3, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, isolated_network4, self.project, NETWORK_STATE_IMPLEMENTED)
# Delete isolated networks (should fail)
self.delete_network(isolated_network1, self.apiclient, False)
self.delete_network(isolated_network2, self.apiclient, False)
self.delete_network(isolated_network3, self.apiclient, False)
self.delete_network(isolated_network4, self.apiclient, False)
# Create VPC
vpc1 = self.create_vpc_for_account(self.apiclient, None, None, None)
vpc2 = self.create_vpc_for_account(self.domainapiclient, None, None, None)
vpc3 = self.create_vpc_for_account(self.normaluser_apiclient, None, None, None)
vpc4 = self.create_vpc_for_account(self.domainapiclient, None, None, self.project)
# Create VPC tier
vpc1_tier1 = self.create_vpc_tier_for_account(self.apiclient, vpc1)
vpc2_tier1 = self.create_vpc_tier_for_account(self.domainapiclient, vpc2)
vpc3_tier1 = self.create_vpc_tier_for_account(self.normaluser_apiclient, vpc3)
vpc4_tier1 = self.create_vpc_tier_for_account(self.domainapiclient, vpc4, self.project)
# Create domain-level shared network with associated vpc tier (caller must be root admin/domain admin, must be in same domain)
self.create_shared_network_with_associated_network_for_domain(self.apiclient, self.sub_domain, vpc1_tier1, False)
self.create_shared_network_with_associated_network_for_domain(self.domainapiclient, self.sub_domain, vpc1_tier1, False)
self.create_shared_network_with_associated_network_for_domain(self.normaluser_apiclient, self.sub_domain, vpc1_tier1, False)
self.create_shared_network_with_associated_network_for_domain(self.normaluser_apiclient, self.sub_domain, vpc2_tier1, False)
self.create_shared_network_with_associated_network_for_domain(self.normaluser_apiclient, self.sub_domain, vpc3_tier1, False)
self.create_shared_network_with_associated_network_for_domain(self.normaluser_apiclient, self.sub_domain, vpc4_tier1, False)
shared_network_vpctier1 = self.create_shared_network_with_associated_network_for_domain(self.apiclient, self.domain, vpc1_tier1, True)
shared_network_vpctier2 = self.create_shared_network_with_associated_network_for_domain(self.domainapiclient, self.sub_domain, vpc2_tier1, True)
shared_network_vpctier3 = self.create_shared_network_with_associated_network_for_domain(self.domainapiclient, self.sub_domain, vpc3_tier1, True)
shared_network_vpctier4 = self.create_shared_network_with_associated_network_for_domain(self.domainapiclient, self.sub_domain, vpc4_tier1, True)
# Check state of vpc tiers (should be Implemented)
self.check_network_state(self.apiclient, vpc1_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, vpc2_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.normaluser_apiclient, vpc3_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, vpc4_tier1, self.project, NETWORK_STATE_IMPLEMENTED)
# Delete vpc tiers(should fail)
self.delete_network(vpc1_tier1, self.apiclient, False)
self.delete_network(vpc2_tier1, self.apiclient, False)
self.delete_network(vpc3_tier1, self.apiclient, False)
self.delete_network(vpc4_tier1, self.apiclient, False)
# Delete shared networks associated to domain admin's isolated network or vpc tier(should succeed)
self.delete_network(shared_network2, self.domainapiclient, True)
self.delete_network(shared_network_vpctier2, self.domainapiclient, True)
# Wait for network GC to shut down the isolated networks
gc_wait = Configurations.list(self.apiclient, name="network.gc.wait")
gc_interval = Configurations.list(self.apiclient, name="network.gc.interval")
total_sleep = 360
if gc_wait and gc_interval:
self.logger.debug("network.gc.wait is ==> %s", gc_wait[0].value)
self.logger.debug("network.gc.interval is ==> %s", gc_interval[0].value)
total_sleep = max(int(gc_wait[0].value), int(gc_interval[0].value)) * 2 + 60
else:
self.logger.debug("Could not retrieve the keys 'network.gc.interval' and 'network.gc.wait'. Sleeping for 6 minutes.")
time.sleep(total_sleep)
# Check state of isolated networks (1 should be Allocated, 3 should still be Implemented)
self.check_network_state(self.apiclient, isolated_network1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, isolated_network2, None, NETWORK_STATE_ALLOCATED)
self.check_network_state(self.normaluser_apiclient, isolated_network3, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, isolated_network4, self.project, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.apiclient, vpc1_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, vpc2_tier1, None, NETWORK_STATE_ALLOCATED)
self.check_network_state(self.normaluser_apiclient, vpc3_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, vpc4_tier1, self.project, NETWORK_STATE_IMPLEMENTED)
# Check state of shared network (should be Setup)
self.check_network_state(self.apiclient, shared_network1, None, NETWORK_STATE_SETUP)
self.check_network_state(self.normaluser_apiclient, shared_network3, None, NETWORK_STATE_SETUP)
self.check_network_state(self.domainapiclient, shared_network4, None, NETWORK_STATE_SETUP)
self.check_network_state(self.apiclient, shared_network_vpctier1, None, NETWORK_STATE_SETUP)
self.check_network_state(self.normaluser_apiclient, shared_network_vpctier3, None, NETWORK_STATE_SETUP)
self.check_network_state(self.domainapiclient, shared_network_vpctier4, None, NETWORK_STATE_SETUP)
# Delete admin's shared networks (should succeed)
self.delete_network(shared_network1, self.apiclient, True)
self.delete_network(shared_network3, self.domainapiclient, True)
self.delete_network(shared_network4, self.domainapiclient, True)
self.delete_network(shared_network_vpctier1, self.apiclient, True)
self.delete_network(shared_network_vpctier3, self.domainapiclient, True)
self.delete_network(shared_network_vpctier4, self.domainapiclient, True)
# Delete admin's and domain admin's isolated network, but keep the normal user's network
# normal user's shared network and isolated network should be removed in tearDown successfully
self.delete_network(isolated_network1, self.apiclient, True)
self.delete_network(isolated_network2, self.domainapiclient, True)
self.delete_network(vpc1_tier1, self.apiclient, True)
self.delete_vpc(self.apiclient, vpc1)
@attr(tags=["advanced"], required_hardware="false")
def test_04_create_account_shared_network_with_associated_network(self):
""" Create account-level shared networks with associated network """
self.services["network2"]["networkoffering"] = self.network_offering_novlan.id
self.services["network2"]["vlan"] = None
# Create isolated networks
isolated_network1 = self.create_isolated_network_for_account(self.apiclient, None, None, None, True)
isolated_network2 = self.create_isolated_network_for_account(self.apiclient, self.sub_domain, self.domain_admin, None, True)
isolated_network3 = self.create_isolated_network_for_account(self.apiclient, self.sub_domain, self.normal_user, None, True)
isolated_network4 = self.create_isolated_network_for_account(self.apiclient, self.sub_domain, None, self.project, True)
# Check state of isolated networks (should be Allocated)
self.check_network_state(self.apiclient, isolated_network1, None, NETWORK_STATE_ALLOCATED)
self.check_network_state(self.domainapiclient, isolated_network2, None, NETWORK_STATE_ALLOCATED)
self.check_network_state(self.normaluser_apiclient, isolated_network3, None, NETWORK_STATE_ALLOCATED)
self.check_network_state(self.domainapiclient, isolated_network4, self.project, NETWORK_STATE_ALLOCATED)
# Create shared networks with associated network (must be same owner)
self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, None, isolated_network1, False)
self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, None, isolated_network3, False)
self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, None, isolated_network4, False)
self.create_shared_network_with_associated_network_for_caller(self.normaluser_apiclient, None, isolated_network1, False)
self.create_shared_network_with_associated_network_for_caller(self.normaluser_apiclient, None, isolated_network2, False)
self.create_shared_network_with_associated_network_for_caller(self.normaluser_apiclient, None, isolated_network4, False)
shared_network1 = self.create_shared_network_with_associated_network_for_caller(self.apiclient, None, isolated_network1, True)
shared_network2 = self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, None, isolated_network2, True)
shared_network3 = self.create_shared_network_with_associated_network_for_caller(self.normaluser_apiclient, None, isolated_network3, True)
shared_network4 = self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, self.project, isolated_network4, True)
# Check state of isolated networks (should be Implemented)
self.check_network_state(self.apiclient, isolated_network1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, isolated_network2, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.normaluser_apiclient, isolated_network3, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, isolated_network4, self.project, NETWORK_STATE_IMPLEMENTED)
# Delete isolated networks (should fail)
self.delete_network(isolated_network1, self.apiclient, False)
self.delete_network(isolated_network2, self.apiclient, False)
self.delete_network(isolated_network3, self.apiclient, False)
self.delete_network(isolated_network4, self.apiclient, False)
# Create VPC
vpc1 = self.create_vpc_for_account(self.apiclient, None, None, None)
vpc2 = self.create_vpc_for_account(self.domainapiclient, None, None, None)
vpc3 = self.create_vpc_for_account(self.normaluser_apiclient, None, None, None)
vpc4 = self.create_vpc_for_account(self.domainapiclient, None, None, self.project)
# Create VPC tier
vpc1_tier1 = self.create_vpc_tier_for_account(self.apiclient, vpc1)
vpc2_tier1 = self.create_vpc_tier_for_account(self.domainapiclient, vpc2)
vpc3_tier1 = self.create_vpc_tier_for_account(self.normaluser_apiclient, vpc3)
vpc4_tier1 = self.create_vpc_tier_for_account(self.domainapiclient, vpc4, self.project)
# Create account-level shared network with associated vpc tier (caller must be root admin/domain admin, must be in same domain)
self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, None, vpc1_tier1, False)
self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, None, vpc3_tier1, False)
self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, None, vpc4_tier1, False)
self.create_shared_network_with_associated_network_for_caller(self.normaluser_apiclient, None, vpc1_tier1, False)
self.create_shared_network_with_associated_network_for_caller(self.normaluser_apiclient, None, vpc2_tier1, False)
self.create_shared_network_with_associated_network_for_caller(self.normaluser_apiclient, None, vpc4_tier1, False)
shared_network_vpctier1 = self.create_shared_network_with_associated_network_for_caller(self.apiclient, None, vpc1_tier1, True)
shared_network_vpctier2 = self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, None, vpc2_tier1, True)
shared_network_vpctier3 = self.create_shared_network_with_associated_network_for_caller(self.normaluser_apiclient, None, vpc3_tier1, True)
shared_network_vpctier4 = self.create_shared_network_with_associated_network_for_caller(self.domainapiclient, self.project, vpc4_tier1, True)
# Check state of vpc tiers (should be Implemented)
self.check_network_state(self.apiclient, vpc1_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, vpc2_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.normaluser_apiclient, vpc3_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, vpc4_tier1, self.project, NETWORK_STATE_IMPLEMENTED)
# Delete vpc tiers(should fail)
self.delete_network(vpc1_tier1, self.apiclient, False)
self.delete_network(vpc2_tier1, self.apiclient, False)
self.delete_network(vpc3_tier1, self.apiclient, False)
self.delete_network(vpc4_tier1, self.apiclient, False)
# Delete shared networks associated to domain admin's isolated network or vpc tier(should succeed)
self.delete_network(shared_network2, self.domainapiclient, True)
self.delete_network(shared_network_vpctier2, self.domainapiclient, True)
# Wait for network GC to shut down the isolated networks
gc_wait = Configurations.list(self.apiclient, name="network.gc.wait")
gc_interval = Configurations.list(self.apiclient, name="network.gc.interval")
total_sleep = 360
if gc_wait and gc_interval:
self.logger.debug("network.gc.wait is ==> %s", gc_wait[0].value)
self.logger.debug("network.gc.interval is ==> %s", gc_interval[0].value)
total_sleep = max(int(gc_wait[0].value), int(gc_interval[0].value)) * 2 + 60
else:
self.logger.debug("Could not retrieve the keys 'network.gc.interval' and 'network.gc.wait'. Sleeping for 6 minutes.")
time.sleep(total_sleep)
# Check state of isolated networks (1 should be Allocated, 3 should still be Implemented)
self.check_network_state(self.apiclient, isolated_network1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, isolated_network2, None, NETWORK_STATE_ALLOCATED)
self.check_network_state(self.normaluser_apiclient, isolated_network3, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, isolated_network4, self.project, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.apiclient, vpc1_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, vpc2_tier1, None, NETWORK_STATE_ALLOCATED)
self.check_network_state(self.normaluser_apiclient, vpc3_tier1, None, NETWORK_STATE_IMPLEMENTED)
self.check_network_state(self.domainapiclient, vpc4_tier1, self.project, NETWORK_STATE_IMPLEMENTED)
# Check state of shared network (should be Setup)
self.check_network_state(self.apiclient, shared_network1, None, NETWORK_STATE_SETUP)
self.check_network_state(self.normaluser_apiclient, shared_network3, None, NETWORK_STATE_SETUP)
self.check_network_state(self.domainapiclient, shared_network4, self.project, NETWORK_STATE_SETUP)
self.check_network_state(self.apiclient, shared_network_vpctier1, None, NETWORK_STATE_SETUP)
self.check_network_state(self.normaluser_apiclient, shared_network_vpctier3, None, NETWORK_STATE_SETUP)
self.check_network_state(self.domainapiclient, shared_network_vpctier4, self.project, NETWORK_STATE_SETUP)
# Delete admin's shared networks (should succeed)
self.delete_network(shared_network1, self.apiclient, True)
self.delete_network(shared_network_vpctier1, self.apiclient, True)
# Delete admin's and domain admin's isolated network, but keep the normal user's network
# normal user's shared network and isolated network should be removed in tearDown successfully
self.delete_network(isolated_network1, self.apiclient, True)
self.delete_network(isolated_network2, self.domainapiclient, True)
self.delete_network(vpc1_tier1, self.apiclient, True)
self.delete_vpc(self.apiclient, vpc1)
self.delete_network(vpc2_tier1, self.domainapiclient, True)
self.delete_vpc(self.domainapiclient, vpc2)
| [
"marvin.lib.base.Network.list",
"marvin.lib.utils.random_gen",
"marvin.lib.base.Domain.create",
"marvin.lib.base.Project.create",
"marvin.lib.base.Network.delete",
"marvin.lib.base.VpcOffering.create",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.VPC.create",
"marvin.lib.base.Network.c... | [((12612, 12662), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (12616, 12662), False, 'from nose.plugins.attrib import attr\n'), ((13993, 14043), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (13997, 14043), False, 'from nose.plugins.attrib import attr\n'), ((15470, 15520), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (15474, 15520), False, 'from nose.plugins.attrib import attr\n'), ((25312, 25362), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (25316, 25362), False, 'from nose.plugins.attrib import attr\n'), ((2135, 2154), 'marvin.lib.base.Zone', 'Zone', (['zone.__dict__'], {}), '(zone.__dict__)\n', (2139, 2154), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((2178, 2218), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id'], {}), '(cls.apiclient, cls.zone.id)\n', (2190, 2218), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((2267, 2310), 'logging.getLogger', 'logging.getLogger', (['"""TestUserSharedNetworks"""'], {}), "('TestUserSharedNetworks')\n", (2284, 2310), False, 'import logging\n'), ((2340, 2363), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2361, 2363), False, 'import logging\n'), ((2479, 2504), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2489, 2504), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((2578, 2664), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['small']"], {}), "(cls.apiclient, cls.services['service_offerings'][\n 'small'])\n", (2600, 2664), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((2863, 2941), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['network_offering_shared']"], {}), "(cls.apiclient, cls.services['network_offering_shared'])\n", (2885, 2941), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((3303, 3381), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['network_offering_shared']"], {}), "(cls.apiclient, cls.services['network_offering_shared'])\n", (3325, 3381), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((3645, 3716), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['network_offering']"], {}), "(cls.apiclient, cls.services['network_offering'])\n", (3667, 3716), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((3945, 4017), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['cls.apiclient', "cls.services['vpc_offering_multi_lb']"], {}), "(cls.apiclient, cls.services['vpc_offering_multi_lb'])\n", (3963, 4017), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((4237, 4341), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['nw_offering_isolated_vpc']"], {'conservemode': '(False)'}), "(cls.apiclient, cls.services[\n 'nw_offering_isolated_vpc'], conservemode=False)\n", (4259, 4341), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((4563, 4623), 'marvin.lib.base.Domain.create', 'Domain.create', (['cls.apiclient', "cls.services['acl']['domain1']"], {}), "(cls.apiclient, cls.services['acl']['domain1'])\n", (4576, 4623), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((4776, 4884), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['acl']['accountD1A']"], {'admin': '(True)', 'domainid': 'cls.sub_domain.id'}), "(cls.apiclient, cls.services['acl']['accountD1A'], admin=True,\n domainid=cls.sub_domain.id)\n", (4790, 4884), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((5012, 5109), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['acl']['accountD1B']"], {'domainid': 'cls.sub_domain.id'}), "(cls.apiclient, cls.services['acl']['accountD1B'], domainid=\n cls.sub_domain.id)\n", (5026, 5109), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((5244, 5370), 'marvin.lib.base.Project.create', 'Project.create', (['cls.apiclient', "cls.services['project']"], {'account': 'cls.domain_admin.name', 'domainid': 'cls.domain_admin.domainid'}), "(cls.apiclient, cls.services['project'], account=cls.\n domain_admin.name, domainid=cls.domain_admin.domainid)\n", (5258, 5370), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((10145, 10219), 'marvin.lib.base.Network.list', 'Network.list', (['apiclient'], {'listall': '(True)', 'projectid': 'project_id', 'id': 'network.id'}), '(apiclient, listall=True, projectid=project_id, id=network.id)\n', (10157, 10219), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((11293, 11481), 'marvin.lib.base.VPC.create', 'VPC.create', (['apiclient', "self.services['vpc']"], {'domainid': 'domain_id', 'accountid': 'account_name', 'projectid': 'project_id', 'vpcofferingid': 'self.vpc_offering.id', 'zoneid': 'self.zone.id', 'start': '(False)'}), "(apiclient, self.services['vpc'], domainid=domain_id, accountid=\n account_name, projectid=project_id, vpcofferingid=self.vpc_offering.id,\n zoneid=self.zone.id, start=False)\n", (11303, 11481), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((11872, 12079), 'marvin.lib.base.Network.create', 'Network.create', (['apiclient', "self.services['network']"], {'networkofferingid': 'self.network_offering_vpc.id', 'zoneid': 'self.zone.id', 'projectid': 'project_id', 'gateway': 'gateway', 'netmask': '"""255.255.255.0"""', 'vpcid': 'vpc.id'}), "(apiclient, self.services['network'], networkofferingid=self.\n network_offering_vpc.id, zoneid=self.zone.id, projectid=project_id,\n gateway=gateway, netmask='255.255.255.0', vpcid=vpc.id)\n", (11886, 12079), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((22093, 22152), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""network.gc.wait"""'}), "(self.apiclient, name='network.gc.wait')\n", (22112, 22152), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((22175, 22238), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""network.gc.interval"""'}), "(self.apiclient, name='network.gc.interval')\n", (22194, 22238), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((22704, 22727), 'time.sleep', 'time.sleep', (['total_sleep'], {}), '(total_sleep)\n', (22714, 22727), False, 'import time\n'), ((32191, 32250), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""network.gc.wait"""'}), "(self.apiclient, name='network.gc.wait')\n", (32210, 32250), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((32273, 32336), 'marvin.lib.base.Configurations.list', 'Configurations.list', (['self.apiclient'], {'name': '"""network.gc.interval"""'}), "(self.apiclient, name='network.gc.interval')\n", (32292, 32336), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((32802, 32825), 'time.sleep', 'time.sleep', (['total_sleep'], {}), '(total_sleep)\n', (32812, 32825), False, 'import time\n'), ((7120, 7132), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (7130, 7132), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((7724, 7915), 'marvin.lib.base.Network.create', 'Network.create', (['apiclient', "self.services['network2']"], {'domainid': 'domain_id', 'accountid': 'account_name', 'projectid': 'project_id', 'associatednetworkid': 'associated_network_id', 'zoneid': 'self.zone.id'}), "(apiclient, self.services['network2'], domainid=domain_id,\n accountid=account_name, projectid=project_id, associatednetworkid=\n associated_network_id, zoneid=self.zone.id)\n", (7738, 7915), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((8470, 8504), 'marvin.lib.base.Network.delete', 'Network.delete', (['network', 'apiclient'], {}), '(network, apiclient)\n', (8484, 8504), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((9021, 9033), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (9031, 9033), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((9317, 9517), 'marvin.lib.base.Network.create', 'Network.create', (['apiclient', "self.services['network']"], {'domainid': 'domain_id', 'accountid': 'account_name', 'projectid': 'project_id', 'networkofferingid': 'self.network_offering_isolated.id', 'zoneid': 'self.zone.id'}), "(apiclient, self.services['network'], domainid=domain_id,\n accountid=account_name, projectid=project_id, networkofferingid=self.\n network_offering_isolated.id, zoneid=self.zone.id)\n", (9331, 9517), False, 'from marvin.lib.base import Account, Domain, Project, Configurations, ServiceOffering, Zone, Network, NetworkOffering, VPC, VpcOffering\n'), ((10890, 10902), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (10900, 10902), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n'), ((11758, 11770), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (11768, 11770), False, 'from marvin.lib.utils import cleanup_resources, random_gen\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: <NAME>, <NAME>, and <NAME>
# @Date: 2018-07-20
# @Filename: test_quantities.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: andrews
# @Last modified time: 2018-10-19 14:10:15
import matplotlib
import numpy
import pytest
from astropy import units as u
from tests import marvin_test_if
from marvin.tools.quantities import DataCube, Spectrum
spaxel_unit = u.Unit('spaxel', represents=u.pixel, doc='A spectral pixel', parse_strict='silent')
@pytest.fixture(scope='function')
def datacube():
"""Produces a simple 3D array for datacube testing."""
flux = numpy.tile([numpy.arange(1, 1001, dtype=numpy.float32)],
(100, 1)).T.reshape(1000, 10, 10)
ivar = (1. / (flux / 100))**2
mask = numpy.zeros(flux.shape, dtype=numpy.int)
wave = numpy.arange(1, 1001)
redcorr = numpy.ones(1000) * 1.5
mask[50:100, 5, 5] = 2**10
mask[500:600, 3, 3] = 2**4
scale = 1e-3
datacube = DataCube(flux, wave, ivar=ivar, mask=mask, redcorr=redcorr, scale=scale,
unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
pixmask_flag='MANGA_DRP3PIXMASK')
yield datacube
@pytest.fixture(scope='function')
def spectrum():
"""Produces a simple 1D array for datacube testing."""
flux = numpy.arange(1, 1001, dtype=numpy.float32)
ivar = (1. / (flux / 100))**2
mask = numpy.zeros(flux.shape, dtype=numpy.int)
wave = numpy.arange(1, 1001)
mask[50:100] = 2**10
mask[500:600] = 2**4
scale = 1e-3
datacube = Spectrum(flux, wave, ivar=ivar, mask=mask, scale=scale,
unit=u.erg / u.s / (u.cm ** 2) / u.Angstrom / spaxel_unit,
pixmask_flag='MANGA_DRP3PIXMASK')
yield datacube
class TestDataCube(object):
def test_datacube(self, datacube):
assert datacube.value is not None
assert datacube.ivar is not None
assert datacube.mask is not None
numpy.testing.assert_array_equal(datacube.value.shape, datacube.ivar.shape)
numpy.testing.assert_array_equal(datacube.value.shape, datacube.mask.shape)
assert datacube.pixmask is not None
def test_masked(self, datacube):
assert isinstance(datacube.masked, numpy.ma.MaskedArray)
assert numpy.sum(datacube.masked.mask) == 50
datacube.pixmask_flag = None
assert numpy.sum(datacube.masked.mask) == 150
def test_snr(self, datacube):
assert datacube.snr[100, 5, 5] == pytest.approx(100)
def test_error(self, datacube):
numpy.testing.assert_almost_equal(datacube.error.value, numpy.sqrt(1 / datacube.ivar))
assert datacube.error.unit == datacube.unit
numpy.testing.assert_almost_equal(datacube.error.value, datacube.std.value)
def test_descale(self, datacube):
assert datacube.unit.scale == 1e-3
descaled = datacube.descale()
datacube.unit.scale == 1
numpy.testing.assert_almost_equal(descaled.value, datacube.value * datacube.unit.scale)
numpy.testing.assert_almost_equal(descaled.ivar, datacube.ivar / datacube.unit.scale**2)
def test_redcorr(self, datacube):
der = datacube.deredden()
assert isinstance(der, DataCube)
numpy.testing.assert_allclose(der.value, datacube.value * 1.5)
numpy.testing.assert_allclose(der.ivar, datacube.ivar / 1.5**2)
numpy.testing.assert_allclose(der.mask, datacube.mask)
assert der.redcorr is None
assert der.pixmask_flag == datacube.pixmask_flag
new_redcorr = (numpy.ones(1000) * 2.)
new_der = datacube.deredden(redcorr=new_redcorr)
numpy.testing.assert_allclose(new_der.value, datacube.value * 2)
numpy.testing.assert_allclose(new_der.ivar, datacube.ivar / 2**2)
datacube.redcorr = None
with pytest.raises(ValueError):
datacube.deredden()
def test_slice_datacube(self, datacube):
new_datacube = datacube[:, 3:5, 3:5]
assert isinstance(new_datacube, DataCube)
numpy.testing.assert_almost_equal(new_datacube.value, datacube.value[:, 3:5, 3:5])
numpy.testing.assert_almost_equal(new_datacube.ivar, datacube.ivar[:, 3:5, 3:5])
numpy.testing.assert_almost_equal(new_datacube.mask, datacube.mask[:, 3:5, 3:5])
numpy.testing.assert_almost_equal(new_datacube.redcorr, datacube.redcorr)
assert new_datacube.pixmask_flag == datacube.pixmask_flag
def test_slice_wave(self, datacube):
new_datacube = datacube[10:100]
assert isinstance(new_datacube, DataCube)
numpy.testing.assert_almost_equal(new_datacube.value, datacube.value[10:100, :, :])
numpy.testing.assert_almost_equal(new_datacube.ivar, datacube.ivar[10:100, :, :])
numpy.testing.assert_almost_equal(new_datacube.mask, datacube.mask[10:100, :, :])
numpy.testing.assert_almost_equal(new_datacube.redcorr, datacube.redcorr[10:100])
assert new_datacube.pixmask_flag == datacube.pixmask_flag
def test_slice_spectrum(self, datacube):
new_spectrum = datacube[:, 5, 5]
assert isinstance(new_spectrum, Spectrum)
numpy.testing.assert_almost_equal(new_spectrum.value, datacube.value[:, 5, 5])
numpy.testing.assert_almost_equal(new_spectrum.ivar, datacube.ivar[:, 5, 5])
numpy.testing.assert_almost_equal(new_spectrum.mask, datacube.mask[:, 5, 5])
assert new_spectrum.pixmask_flag == datacube.pixmask_flag
@marvin_test_if(mark='include', cube={'plateifu': '8485-1901',
'data_origin': 'file',
'initial_mode': 'local'})
def test_cube_quantities(self, cube):
assert cube.flux is not None
assert isinstance(cube.flux, numpy.ndarray)
assert isinstance(cube.flux, DataCube)
assert isinstance(cube.spectral_resolution, Spectrum)
if cube.release in ['MPL-4', 'MPL-5']:
with pytest.raises(AssertionError) as ee:
cube.spectral_resolution_prepixel
assert 'spectral_resolution_prepixel is not present in his MPL version' in str(ee)
else:
assert isinstance(cube.spectral_resolution_prepixel, Spectrum)
assert cube.flux.pixmask.values_to_bits(3) == [0, 1]
assert cube.flux.pixmask.values_to_labels(3) == ['NOCOV', 'LOWCOV']
@pytest.mark.parametrize('names, expected', [(['NOCOV', 'LOWCOV'], 3),
('DONOTUSE', 1024)])
def test_labels_to_value(self, cube, names, expected):
assert cube.flux.pixmask.labels_to_value(names) == expected
@marvin_test_if(mark='include', modelcube={'plateifu': '8485-1901',
'data_origin': 'file',
'initial_mode': 'local'})
def test_modelcube_quantities(self, modelcube):
for mc in modelcube.datamodel:
if hasattr(modelcube, mc.name):
modelcube_quantity = getattr(modelcube, mc.name)
assert isinstance(modelcube_quantity, DataCube)
assert modelcube_quantity.pixmask_flag == 'MANGA_DAPSPECMASK'
class TestSpectrum(object):
def test_spectrum(self, spectrum):
assert spectrum.value is not None
assert spectrum.ivar is not None
assert spectrum.mask is not None
numpy.testing.assert_array_equal(spectrum.value.shape, spectrum.ivar.shape)
numpy.testing.assert_array_equal(spectrum.value.shape, spectrum.mask.shape)
assert spectrum.pixmask is not None
def test_masked(self, spectrum):
assert isinstance(spectrum.masked, numpy.ma.MaskedArray)
assert numpy.sum(spectrum.masked.mask) == 50
spectrum.pixmask_flag = None
assert numpy.sum(spectrum.masked.mask) == 150
def test_snr(self, spectrum):
assert spectrum.snr[100] == pytest.approx(100)
def test_error(self, spectrum):
numpy.testing.assert_almost_equal(spectrum.error.value, numpy.sqrt(1 / spectrum.ivar))
assert spectrum.error.unit == spectrum.unit
numpy.testing.assert_almost_equal(spectrum.error.value, spectrum.std.value)
def test_descale(self, spectrum):
assert spectrum.unit.scale == 1e-3
descaled = spectrum.descale()
spectrum.unit.scale == 1
numpy.testing.assert_almost_equal(descaled.value, spectrum.value * spectrum.unit.scale)
numpy.testing.assert_almost_equal(descaled.ivar, spectrum.ivar / spectrum.unit.scale**2)
def test_slice_spectrum(self, spectrum):
new_spectrum = spectrum[10:100]
assert isinstance(new_spectrum, Spectrum)
numpy.testing.assert_almost_equal(new_spectrum.value, spectrum.value[10:100])
numpy.testing.assert_almost_equal(new_spectrum.ivar, spectrum.ivar[10:100])
numpy.testing.assert_almost_equal(new_spectrum.mask, spectrum.mask[10:100])
assert new_spectrum.pixmask_flag == spectrum.pixmask_flag
@marvin_test_if(mark='include', cube={'plateifu': '8485-1901',
'data_origin': 'file',
'initial_mode': 'local'})
def test_cube_quantities(self, cube):
for sp in cube.datamodel.spectra:
cube_quantity = getattr(cube, sp.name)
assert isinstance(cube_quantity, Spectrum)
assert cube_quantity.pixmask_flag is None
def test_plot(self, spectrum):
ax = spectrum.plot(show_std=True)
assert isinstance(ax, matplotlib.axes.Axes)
def test_plot_no_std_no_mask(self):
sp = Spectrum(numpy.random.randn(1000), wavelength=numpy.arange(1000))
sp.plot()
def test_plot_no_std(self):
mask = numpy.zeros(1000, dtype=numpy.int)
mask[50:100] = 2**10
mask[500:600] = 2**4
sp = Spectrum(
flux=numpy.random.randn(1000),
wavelength=numpy.arange(1000),
mask=mask,
pixmask_flag='MANGA_DRP3PIXMASK',
)
sp.plot()
def test_plot_no_mask(self):
flux = numpy.random.randn(1000)
ivar = (1. / (flux / 100))**2
sp = Spectrum(
flux=flux,
wavelength=numpy.arange(1000),
ivar=ivar,
)
sp.plot()
| [
"marvin.tools.quantities.Spectrum",
"marvin.tools.quantities.DataCube"
] | [((472, 560), 'astropy.units.Unit', 'u.Unit', (['"""spaxel"""'], {'represents': 'u.pixel', 'doc': '"""A spectral pixel"""', 'parse_strict': '"""silent"""'}), "('spaxel', represents=u.pixel, doc='A spectral pixel', parse_strict=\n 'silent')\n", (478, 560), True, 'from astropy import units as u\n'), ((559, 591), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (573, 591), False, 'import pytest\n'), ((1283, 1315), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1297, 1315), False, 'import pytest\n'), ((837, 877), 'numpy.zeros', 'numpy.zeros', (['flux.shape'], {'dtype': 'numpy.int'}), '(flux.shape, dtype=numpy.int)\n', (848, 877), False, 'import numpy\n'), ((889, 910), 'numpy.arange', 'numpy.arange', (['(1)', '(1001)'], {}), '(1, 1001)\n', (901, 910), False, 'import numpy\n'), ((1046, 1218), 'marvin.tools.quantities.DataCube', 'DataCube', (['flux', 'wave'], {'ivar': 'ivar', 'mask': 'mask', 'redcorr': 'redcorr', 'scale': 'scale', 'unit': '(u.erg / u.s / u.cm ** 2 / u.Angstrom / spaxel_unit)', 'pixmask_flag': '"""MANGA_DRP3PIXMASK"""'}), "(flux, wave, ivar=ivar, mask=mask, redcorr=redcorr, scale=scale,\n unit=u.erg / u.s / u.cm ** 2 / u.Angstrom / spaxel_unit, pixmask_flag=\n 'MANGA_DRP3PIXMASK')\n", (1054, 1218), False, 'from marvin.tools.quantities import DataCube, Spectrum\n'), ((1403, 1445), 'numpy.arange', 'numpy.arange', (['(1)', '(1001)'], {'dtype': 'numpy.float32'}), '(1, 1001, dtype=numpy.float32)\n', (1415, 1445), False, 'import numpy\n'), ((1491, 1531), 'numpy.zeros', 'numpy.zeros', (['flux.shape'], {'dtype': 'numpy.int'}), '(flux.shape, dtype=numpy.int)\n', (1502, 1531), False, 'import numpy\n'), ((1543, 1564), 'numpy.arange', 'numpy.arange', (['(1)', '(1001)'], {}), '(1, 1001)\n', (1555, 1564), False, 'import numpy\n'), ((1650, 1801), 'marvin.tools.quantities.Spectrum', 'Spectrum', (['flux', 'wave'], {'ivar': 'ivar', 'mask': 'mask', 'scale': 'scale', 'unit': '(u.erg / u.s / u.cm ** 2 / u.Angstrom / spaxel_unit)', 'pixmask_flag': '"""MANGA_DRP3PIXMASK"""'}), "(flux, wave, ivar=ivar, mask=mask, scale=scale, unit=u.erg / u.s / \n u.cm ** 2 / u.Angstrom / spaxel_unit, pixmask_flag='MANGA_DRP3PIXMASK')\n", (1658, 1801), False, 'from marvin.tools.quantities import DataCube, Spectrum\n'), ((5603, 5717), 'tests.marvin_test_if', 'marvin_test_if', ([], {'mark': '"""include"""', 'cube': "{'plateifu': '8485-1901', 'data_origin': 'file', 'initial_mode': 'local'}"}), "(mark='include', cube={'plateifu': '8485-1901', 'data_origin':\n 'file', 'initial_mode': 'local'})\n", (5617, 5717), False, 'from tests import marvin_test_if\n'), ((6522, 6617), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""names, expected"""', "[(['NOCOV', 'LOWCOV'], 3), ('DONOTUSE', 1024)]"], {}), "('names, expected', [(['NOCOV', 'LOWCOV'], 3), (\n 'DONOTUSE', 1024)])\n", (6545, 6617), False, 'import pytest\n'), ((6795, 6914), 'tests.marvin_test_if', 'marvin_test_if', ([], {'mark': '"""include"""', 'modelcube': "{'plateifu': '8485-1901', 'data_origin': 'file', 'initial_mode': 'local'}"}), "(mark='include', modelcube={'plateifu': '8485-1901',\n 'data_origin': 'file', 'initial_mode': 'local'})\n", (6809, 6914), False, 'from tests import marvin_test_if\n'), ((9180, 9294), 'tests.marvin_test_if', 'marvin_test_if', ([], {'mark': '"""include"""', 'cube': "{'plateifu': '8485-1901', 'data_origin': 'file', 'initial_mode': 'local'}"}), "(mark='include', cube={'plateifu': '8485-1901', 'data_origin':\n 'file', 'initial_mode': 'local'})\n", (9194, 9294), False, 'from tests import marvin_test_if\n'), ((926, 942), 'numpy.ones', 'numpy.ones', (['(1000)'], {}), '(1000)\n', (936, 942), False, 'import numpy\n'), ((2071, 2146), 'numpy.testing.assert_array_equal', 'numpy.testing.assert_array_equal', (['datacube.value.shape', 'datacube.ivar.shape'], {}), '(datacube.value.shape, datacube.ivar.shape)\n', (2103, 2146), False, 'import numpy\n'), ((2155, 2230), 'numpy.testing.assert_array_equal', 'numpy.testing.assert_array_equal', (['datacube.value.shape', 'datacube.mask.shape'], {}), '(datacube.value.shape, datacube.mask.shape)\n', (2187, 2230), False, 'import numpy\n'), ((2816, 2891), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['datacube.error.value', 'datacube.std.value'], {}), '(datacube.error.value, datacube.std.value)\n', (2849, 2891), False, 'import numpy\n'), ((3056, 3148), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['descaled.value', '(datacube.value * datacube.unit.scale)'], {}), '(descaled.value, datacube.value * datacube\n .unit.scale)\n', (3089, 3148), False, 'import numpy\n'), ((3152, 3247), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['descaled.ivar', '(datacube.ivar / datacube.unit.scale ** 2)'], {}), '(descaled.ivar, datacube.ivar / datacube.\n unit.scale ** 2)\n', (3185, 3247), False, 'import numpy\n'), ((3365, 3427), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['der.value', '(datacube.value * 1.5)'], {}), '(der.value, datacube.value * 1.5)\n', (3394, 3427), False, 'import numpy\n'), ((3436, 3501), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['der.ivar', '(datacube.ivar / 1.5 ** 2)'], {}), '(der.ivar, datacube.ivar / 1.5 ** 2)\n', (3465, 3501), False, 'import numpy\n'), ((3508, 3562), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['der.mask', 'datacube.mask'], {}), '(der.mask, datacube.mask)\n', (3537, 3562), False, 'import numpy\n'), ((3769, 3833), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['new_der.value', '(datacube.value * 2)'], {}), '(new_der.value, datacube.value * 2)\n', (3798, 3833), False, 'import numpy\n'), ((3842, 3909), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['new_der.ivar', '(datacube.ivar / 2 ** 2)'], {}), '(new_der.ivar, datacube.ivar / 2 ** 2)\n', (3871, 3909), False, 'import numpy\n'), ((4164, 4250), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_datacube.value', 'datacube.value[:, 3:5, 3:5]'], {}), '(new_datacube.value, datacube.value[:, 3:5,\n 3:5])\n', (4197, 4250), False, 'import numpy\n'), ((4255, 4340), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_datacube.ivar', 'datacube.ivar[:, 3:5, 3:5]'], {}), '(new_datacube.ivar, datacube.ivar[:, 3:5, 3:5]\n )\n', (4288, 4340), False, 'import numpy\n'), ((4344, 4429), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_datacube.mask', 'datacube.mask[:, 3:5, 3:5]'], {}), '(new_datacube.mask, datacube.mask[:, 3:5, 3:5]\n )\n', (4377, 4429), False, 'import numpy\n'), ((4433, 4506), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_datacube.redcorr', 'datacube.redcorr'], {}), '(new_datacube.redcorr, datacube.redcorr)\n', (4466, 4506), False, 'import numpy\n'), ((4715, 4802), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_datacube.value', 'datacube.value[10:100, :, :]'], {}), '(new_datacube.value, datacube.value[10:100,\n :, :])\n', (4748, 4802), False, 'import numpy\n'), ((4807, 4892), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_datacube.ivar', 'datacube.ivar[10:100, :, :]'], {}), '(new_datacube.ivar, datacube.ivar[10:100,\n :, :])\n', (4840, 4892), False, 'import numpy\n'), ((4897, 4982), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_datacube.mask', 'datacube.mask[10:100, :, :]'], {}), '(new_datacube.mask, datacube.mask[10:100,\n :, :])\n', (4930, 4982), False, 'import numpy\n'), ((4987, 5073), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_datacube.redcorr', 'datacube.redcorr[10:100]'], {}), '(new_datacube.redcorr, datacube.redcorr[10\n :100])\n', (5020, 5073), False, 'import numpy\n'), ((5282, 5360), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_spectrum.value', 'datacube.value[:, 5, 5]'], {}), '(new_spectrum.value, datacube.value[:, 5, 5])\n', (5315, 5360), False, 'import numpy\n'), ((5369, 5445), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_spectrum.ivar', 'datacube.ivar[:, 5, 5]'], {}), '(new_spectrum.ivar, datacube.ivar[:, 5, 5])\n', (5402, 5445), False, 'import numpy\n'), ((5454, 5530), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_spectrum.mask', 'datacube.mask[:, 5, 5]'], {}), '(new_spectrum.mask, datacube.mask[:, 5, 5])\n', (5487, 5530), False, 'import numpy\n'), ((7552, 7627), 'numpy.testing.assert_array_equal', 'numpy.testing.assert_array_equal', (['spectrum.value.shape', 'spectrum.ivar.shape'], {}), '(spectrum.value.shape, spectrum.ivar.shape)\n', (7584, 7627), False, 'import numpy\n'), ((7636, 7711), 'numpy.testing.assert_array_equal', 'numpy.testing.assert_array_equal', (['spectrum.value.shape', 'spectrum.mask.shape'], {}), '(spectrum.value.shape, spectrum.mask.shape)\n', (7668, 7711), False, 'import numpy\n'), ((8291, 8366), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['spectrum.error.value', 'spectrum.std.value'], {}), '(spectrum.error.value, spectrum.std.value)\n', (8324, 8366), False, 'import numpy\n'), ((8531, 8623), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['descaled.value', '(spectrum.value * spectrum.unit.scale)'], {}), '(descaled.value, spectrum.value * spectrum\n .unit.scale)\n', (8564, 8623), False, 'import numpy\n'), ((8627, 8722), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['descaled.ivar', '(spectrum.ivar / spectrum.unit.scale ** 2)'], {}), '(descaled.ivar, spectrum.ivar / spectrum.\n unit.scale ** 2)\n', (8660, 8722), False, 'import numpy\n'), ((8862, 8939), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_spectrum.value', 'spectrum.value[10:100]'], {}), '(new_spectrum.value, spectrum.value[10:100])\n', (8895, 8939), False, 'import numpy\n'), ((8948, 9023), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_spectrum.ivar', 'spectrum.ivar[10:100]'], {}), '(new_spectrum.ivar, spectrum.ivar[10:100])\n', (8981, 9023), False, 'import numpy\n'), ((9032, 9107), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['new_spectrum.mask', 'spectrum.mask[10:100]'], {}), '(new_spectrum.mask, spectrum.mask[10:100])\n', (9065, 9107), False, 'import numpy\n'), ((9938, 9972), 'numpy.zeros', 'numpy.zeros', (['(1000)'], {'dtype': 'numpy.int'}), '(1000, dtype=numpy.int)\n', (9949, 9972), False, 'import numpy\n'), ((10287, 10311), 'numpy.random.randn', 'numpy.random.randn', (['(1000)'], {}), '(1000)\n', (10305, 10311), False, 'import numpy\n'), ((2395, 2426), 'numpy.sum', 'numpy.sum', (['datacube.masked.mask'], {}), '(datacube.masked.mask)\n', (2404, 2426), False, 'import numpy\n'), ((2486, 2517), 'numpy.sum', 'numpy.sum', (['datacube.masked.mask'], {}), '(datacube.masked.mask)\n', (2495, 2517), False, 'import numpy\n'), ((2603, 2621), 'pytest.approx', 'pytest.approx', (['(100)'], {}), '(100)\n', (2616, 2621), False, 'import pytest\n'), ((2724, 2753), 'numpy.sqrt', 'numpy.sqrt', (['(1 / datacube.ivar)'], {}), '(1 / datacube.ivar)\n', (2734, 2753), False, 'import numpy\n'), ((3680, 3696), 'numpy.ones', 'numpy.ones', (['(1000)'], {}), '(1000)\n', (3690, 3696), False, 'import numpy\n'), ((3954, 3979), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3967, 3979), False, 'import pytest\n'), ((7876, 7907), 'numpy.sum', 'numpy.sum', (['spectrum.masked.mask'], {}), '(spectrum.masked.mask)\n', (7885, 7907), False, 'import numpy\n'), ((7967, 7998), 'numpy.sum', 'numpy.sum', (['spectrum.masked.mask'], {}), '(spectrum.masked.mask)\n', (7976, 7998), False, 'import numpy\n'), ((8078, 8096), 'pytest.approx', 'pytest.approx', (['(100)'], {}), '(100)\n', (8091, 8096), False, 'import pytest\n'), ((8199, 8228), 'numpy.sqrt', 'numpy.sqrt', (['(1 / spectrum.ivar)'], {}), '(1 / spectrum.ivar)\n', (8209, 8228), False, 'import numpy\n'), ((9814, 9838), 'numpy.random.randn', 'numpy.random.randn', (['(1000)'], {}), '(1000)\n', (9832, 9838), False, 'import numpy\n'), ((6106, 6135), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (6119, 6135), False, 'import pytest\n'), ((9851, 9869), 'numpy.arange', 'numpy.arange', (['(1000)'], {}), '(1000)\n', (9863, 9869), False, 'import numpy\n'), ((10072, 10096), 'numpy.random.randn', 'numpy.random.randn', (['(1000)'], {}), '(1000)\n', (10090, 10096), False, 'import numpy\n'), ((10121, 10139), 'numpy.arange', 'numpy.arange', (['(1000)'], {}), '(1000)\n', (10133, 10139), False, 'import numpy\n'), ((10420, 10438), 'numpy.arange', 'numpy.arange', (['(1000)'], {}), '(1000)\n', (10432, 10438), False, 'import numpy\n'), ((691, 733), 'numpy.arange', 'numpy.arange', (['(1)', '(1001)'], {'dtype': 'numpy.float32'}), '(1, 1001, dtype=numpy.float32)\n', (703, 733), False, 'import numpy\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Import Local Modules
from marvin.codes import FAILED, KVM, PASS, XEN_SERVER, RUNNING
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import random_gen, cleanup_resources, validateList, is_snapshot_on_nfs, isAlmostEqual
from marvin.lib.base import (Account,
Cluster,
Configurations,
ServiceOffering,
Snapshot,
StoragePool,
Template,
VirtualMachine,
VmSnapshot,
Volume,
SecurityGroup,
Role,
)
from marvin.lib.common import (get_zone,
get_domain,
get_template,
list_disk_offering,
list_hosts,
list_snapshots,
list_storage_pools,
list_volumes,
list_virtual_machines,
list_configurations,
list_service_offering,
list_clusters,
list_zones)
from marvin.cloudstackAPI import (listOsTypes,
listTemplates,
listHosts,
createTemplate,
createVolume,
getVolumeSnapshotDetails,
resizeVolume,
listZones)
import time
import pprint
import random
import subprocess
from storpool import spapi
from storpool import sptypes
from marvin.configGenerator import configuration
import uuid
from sp_util import (TestData, StorPoolHelper)
class TestStoragePool(cloudstackTestCase):
@classmethod
def setUpClass(cls):
super(TestStoragePool, cls).setUpClass()
try:
cls.setUpCloudStack()
except Exception:
cls.cleanUpCloudStack()
raise
@classmethod
def setUpCloudStack(cls):
testClient = super(TestStoragePool, cls).getClsTestClient()
cls._cleanup = []
cls.apiclient = testClient.getApiClient()
cls.helper = StorPoolHelper()
cls.unsupportedHypervisor = False
cls.hypervisor = testClient.getHypervisorInfo()
if cls.hypervisor.lower() in ("hyperv", "lxc"):
cls.unsupportedHypervisor = True
return
cls.services = testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = None
zones = list_zones(cls.apiclient)
for z in zones:
if z.name == cls.getClsConfig().mgtSvr[0].zone:
cls.zone = z
assert cls.zone is not None
cls.sp_template_1 = "ssd"
storpool_primary_storage = {
"name" : cls.sp_template_1,
"zoneid": cls.zone.id,
"url": "SP_API_HTTP=10.2.23.248:81;SP_AUTH_TOKEN=<PASSWORD>;SP_TEMPLATE=%s" % cls.sp_template_1,
"scope": "zone",
"capacitybytes": 564325555333,
"capacityiops": 155466,
"hypervisor": "kvm",
"provider": "StorPool",
"tags": cls.sp_template_1
}
cls.storpool_primary_storage = storpool_primary_storage
host, port, auth = cls.getCfgFromUrl(url = storpool_primary_storage["url"])
cls.spapi = spapi.Api(host=host, port=port, auth=auth, multiCluster=True)
storage_pool = list_storage_pools(
cls.apiclient,
name=storpool_primary_storage["name"]
)
if storage_pool is None:
newTemplate = sptypes.VolumeTemplateCreateDesc(name = storpool_primary_storage["name"],placeAll = "virtual", placeTail = "virtual", placeHead = "virtual", replication=1)
template_on_local = cls.spapi.volumeTemplateCreate(newTemplate)
storage_pool = StoragePool.create(cls.apiclient, storpool_primary_storage)
else:
storage_pool = storage_pool[0]
cls.primary_storage = storage_pool
storpool_service_offerings_ssd = {
"name": cls.sp_template_1,
"displaytext": "SP_CO_2 (Min IOPS = 10,000; Max IOPS = 15,000)",
"cpunumber": 1,
"cpuspeed": 500,
"memory": 512,
"storagetype": "shared",
"customizediops": False,
"hypervisorsnapshotreserve": 200,
"tags": cls.sp_template_1
}
service_offerings_ssd = list_service_offering(
cls.apiclient,
name=storpool_service_offerings_ssd["name"]
)
if service_offerings_ssd is None:
service_offerings_ssd = ServiceOffering.create(cls.apiclient, storpool_service_offerings_ssd)
else:
service_offerings_ssd = service_offerings_ssd[0]
cls.service_offering = service_offerings_ssd
cls.debug(pprint.pformat(cls.service_offering))
cls.sp_template_2 = "ssd2"
storpool_primary_storage2 = {
"name" : cls.sp_template_2,
"zoneid": cls.zone.id,
"url": "SP_API_HTTP=10.2.23.248:81;SP_AUTH_TOKEN=<PASSWORD>;SP_TEMPLATE=%s" % cls.sp_template_2,
"scope": "zone",
"capacitybytes": 564325555333,
"capacityiops": 1554,
"hypervisor": "kvm",
"provider": "StorPool",
"tags": cls.sp_template_2
}
cls.storpool_primary_storage2 = storpool_primary_storage2
storage_pool = list_storage_pools(
cls.apiclient,
name=storpool_primary_storage2["name"]
)
if storage_pool is None:
newTemplate = sptypes.VolumeTemplateCreateDesc(name = storpool_primary_storage2["name"],placeAll = "virtual", placeTail = "virtual", placeHead = "virtual", replication=1)
template_on_local = cls.spapi.volumeTemplateCreate(newTemplate)
storage_pool = StoragePool.create(cls.apiclient, storpool_primary_storage2)
else:
storage_pool = storage_pool[0]
cls.primary_storage2 = storage_pool
storpool_service_offerings_ssd2 = {
"name": cls.sp_template_2,
"displaytext": "SP_CO_2",
"cpunumber": 1,
"cpuspeed": 500,
"memory": 512,
"storagetype": "shared",
"customizediops": False,
"tags": cls.sp_template_2
}
service_offerings_ssd2 = list_service_offering(
cls.apiclient,
name=storpool_service_offerings_ssd2["name"]
)
if service_offerings_ssd2 is None:
service_offerings_ssd2 = ServiceOffering.create(cls.apiclient, storpool_service_offerings_ssd2)
else:
service_offerings_ssd2 = service_offerings_ssd2[0]
cls.service_offering2 = service_offerings_ssd2
disk_offerings = list_disk_offering(
cls.apiclient,
name="Small"
)
disk_offering_20 = list_disk_offering(
cls.apiclient,
name="Medium"
)
disk_offering_100 = list_disk_offering(
cls.apiclient,
name="Large"
)
cls.disk_offerings = disk_offerings[0]
cls.disk_offering_20 = disk_offering_20[0]
cls.disk_offering_100 = disk_offering_100[0]
#The version of CentOS has to be supported
template = get_template(
cls.apiclient,
cls.zone.id,
account = "system"
)
if template == FAILED:
assert False, "get_template() failed to return template\
with description %s" % cls.services["ostype"]
cls.services["domainid"] = cls.domain.id
cls.services["small"]["zoneid"] = cls.zone.id
cls.services["templates"]["ostypeid"] = template.ostypeid
cls.services["zoneid"] = cls.zone.id
cls.services["diskofferingid"] = cls.disk_offerings.id
role = Role.list(cls.apiclient, name='Admin')
# Create VMs, VMs etc
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id,
roleid = role[0].id
)
securitygroup = SecurityGroup.list(cls.apiclient, account = cls.account.name, domainid= cls.account.domainid)[0]
cls.helper.set_securityGroups(cls.apiclient, account = cls.account.name, domainid= cls.account.domainid, id = securitygroup.id)
cls._cleanup.append(cls.account)
cls.volume_1 = Volume.create(
cls.apiclient,
{"diskname":"StorPoolDisk-1" },
zoneid=cls.zone.id,
diskofferingid=disk_offerings[0].id,
account=cls.account.name,
domainid=cls.account.domainid,
)
cls.volume_2 = Volume.create(
cls.apiclient,
{"diskname":"StorPoolDisk-2" },
zoneid=cls.zone.id,
diskofferingid=disk_offerings[0].id,
account=cls.account.name,
domainid=cls.account.domainid,
)
cls.volume = Volume.create(
cls.apiclient,
{"diskname":"StorPoolDisk-3" },
zoneid=cls.zone.id,
diskofferingid=disk_offerings[0].id,
account=cls.account.name,
domainid=cls.account.domainid,
)
cls.virtual_machine = VirtualMachine.create(
cls.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=cls.account.name,
domainid=cls.account.domainid,
zoneid=cls.zone.id,
templateid=template.id,
serviceofferingid=cls.service_offering.id,
hypervisor=cls.hypervisor,
rootdisksize=10
)
cls.virtual_machine2 = VirtualMachine.create(
cls.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=cls.account.name,
domainid=cls.account.domainid,
zoneid=cls.zone.id,
templateid=template.id,
serviceofferingid=cls.service_offering.id,
hypervisor=cls.hypervisor,
rootdisksize=10
)
cls.vm_migrate = VirtualMachine.create(
cls.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=cls.account.name,
domainid=cls.account.domainid,
zoneid=cls.zone.id,
templateid=template.id,
serviceofferingid=cls.service_offering.id,
hypervisor=cls.hypervisor,
rootdisksize=10
)
cls.template = template
cls.hostid = cls.virtual_machine.hostid
cls.random_data_0 = random_gen(size=100)
cls.test_dir = "/tmp"
cls.random_data = "random.data"
return
@classmethod
def tearDownClass(cls):
cls.cleanUpCloudStack()
@classmethod
def cleanUpCloudStack(cls):
try:
# Cleanup resources used
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
if self.unsupportedHypervisor:
self.skipTest("Skipping test because unsupported hypervisor\
%s" % self.hypervisor)
return
def tearDown(self):
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_01_snapshot_to_template(self):
''' Create template from snapshot without bypass secondary storage
'''
volume = Volume.list(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "false")
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
self.assertIsNotNone(snapshot, "Could not create snapshot")
self.assertIsInstance(snapshot, Snapshot, "Snapshot is not an instance of Snapshot")
template = self.create_template_from_snapshot(
self.apiclient,
self.services,
snapshotid = snapshot.id
)
virtual_machine = VirtualMachine.create(self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
templateid=template.id,
serviceofferingid=self.service_offering.id,
hypervisor=self.hypervisor,
rootdisksize=10
)
ssh_client = virtual_machine.get_ssh_client()
self.assertIsNotNone(template, "Template is None")
self.assertIsInstance(template, Template, "Template is instance of template")
self._cleanup.append(template)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_02_snapshot_to_template_bypass_secondary(self):
''' Test Create Template from snapshot bypassing secondary storage
'''
##cls.virtual_machine
volume = list_volumes(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
try:
name = volume[0].path.split("/")[3]
sp_volume = self.spapi.volumeList(volumeName = "~" + name)
except spapi.ApiError as err:
raise Exception(err)
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "true")
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
if flag == False:
raise Exception("Could not find snasphot in snapshot_details")
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Could not create snapshot")
self.assertIsInstance(snapshot, Snapshot, "Snapshot is not an instance of Snapshot")
template = self.create_template_from_snapshot(
self.apiclient,
self.services,
snapshotid = snapshot.id
)
flag = False
sp_snapshots = self.spapi.snapshotsList()
for snap in sp_snapshots:
tags = snap.tags
for t in tags:
if tags[t] == template.id:
flag = True
break
else:
continue
break
if flag is False:
raise Exception("Template does not exists in Storpool")
virtual_machine = VirtualMachine.create(self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
templateid=template.id,
serviceofferingid=self.service_offering.id,
hypervisor=self.hypervisor,
rootdisksize=10
)
ssh_client = virtual_machine.get_ssh_client()
self.assertIsNotNone(template, "Template is None")
self.assertIsInstance(template, Template, "Template is instance of template")
self._cleanup.append(template)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_03_snapshot_volume_with_secondary(self):
'''
Test Create snapshot and backup to secondary
'''
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "false")
volume = list_volumes(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
if flag == False:
raise Exception("Could not find snapshot in snapshot_details")
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Could not create snapshot")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_04_snapshot_volume_bypass_secondary(self):
'''
Test snapshot bypassing secondary
'''
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "true")
volume = list_volumes(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
if flag == False:
raise Exception("Could not find snapshot in snapshot details")
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Could not create snapshot")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_05_delete_template_bypassed_secondary(self):
''' Test delete template from snapshot bypassed secondary storage
'''
volume = list_volumes(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
try:
name = volume[0].path.split("/")[3]
sp_volume = self.spapi.volumeList(volumeName = "~" + name)
except spapi.ApiError as err:
raise Exception(err)
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "true")
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
if flag == False:
raise Exception("Could not find snapshot in snapshot details")
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Could not create snapshot")
self.assertIsInstance(snapshot, Snapshot, "Snapshot is not an instance of Snapshot")
template = self.create_template_from_snapshot(
self.apiclient,
self.services,
snapshotid = snapshot.id
)
flag = False
storpoolGlId = None
sp_snapshots = self.spapi.snapshotsList()
for snap in sp_snapshots:
tags = snap.tags
for t in tags:
if tags[t] == template.id:
storpoolGlId = "~" + snap.globalId
flag = True
break
else:
continue
break
if flag is False:
raise Exception("Template does not exists in Storpool")
self.assertIsNotNone(template, "Template is None")
self.assertIsInstance(template, Template, "Template is instance of template")
temp = Template.delete(template, self.apiclient, self.zone.id)
self.assertIsNone(temp, "Template was not deleted")
try:
sp_snapshot = self.spapi.snapshotList(snapshotName = storpoolGlId)
if sp_snapshot is not None:
self.debug("Snapshot exists on StorPool name " + storpoolGlId)
except spapi.ApiError as err:
self.debug("Do nothing the template has to be deleted")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_06_template_from_snapshot(self):
''' Test create template bypassing secondary from snapshot which is backed up on secondary storage
'''
##cls.virtual_machine
volume = list_volumes(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
try:
name = volume[0].path.split("/")[3]
sp_volume = self.spapi.volumeList(volumeName = "~" + name)
except spapi.ApiError as err:
raise Exception(err)
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "false")
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
if flag == False:
raise Exception("Could not find snapshot in snapsho details")
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Could not create snapshot")
self.assertIsInstance(snapshot, Snapshot, "Snapshot is not an instance of Snapshot")
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "true")
template = self.create_template_from_snapshot(
self.apiclient,
self.services,
snapshotid = snapshot.id
)
flag = False
globalId = None
sp_snapshots = self.spapi.snapshotsList()
for snap in sp_snapshots:
tags = snap.tags
for t in tags:
if tags[t] == template.id:
flag = True
globalId = snap.globalId
break
else:
continue
break
if flag is False:
raise Exception("Template does not exists in Storpool")
self.assertIsNotNone(template, "Template is None")
self.assertIsInstance(template, Template, "Template is instance of template")
temp = Template.delete(template, self.apiclient, self.zone.id)
self.assertIsNone(temp, "Template was not deleted")
if globalId is not None:
try:
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + globalId)
if sp_snapshot is not None:
self.debug("Snapshot exists on Storpool name " + globalId)
except spapi.ApiError as err:
self.debug("Do nothing the template has to be deleted")
else:
flag = False
sp_snapshots = self.spapi.snapshotsList()
for snap in sp_snapshots:
tags = snap.tags
for t in tags:
if tags[t] == template.id:
flag = True
break
else:
continue
break
if flag is True:
raise Exception("Template should not exists in Storpool")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_07_delete_snapshot_of_deleted_volume(self):
''' Delete snapshot and template if volume is already deleted, not bypassing secondary
'''
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "false")
volume = Volume.create(
self.apiclient,
{"diskname":"StorPoolDisk-Delete" },
zoneid = self.zone.id,
diskofferingid = self.disk_offerings.id,
account=self.account.name,
domainid=self.account.domainid,
)
delete = volume
self.virtual_machine2.stop(self.apiclient, forced=True)
self.virtual_machine2.attach_volume(
self.apiclient,
volume
)
self.virtual_machine2.detach_volume(
self.apiclient,
volume
)
volume = list_volumes(self.apiclient, id = volume.id)
name = volume[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
except spapi.ApiError as err:
raise Exception(err)
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
try:
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
except spapi.ApiError as err:
raise Exception(err)
if flag == False:
raise Exception("Could not finad snapshot in snapshot details")
except Exception as err:
raise Exception(err)
template = self.create_template_from_snapshot(self.apiclient, self.services, snapshotid = snapshot.id)
template_from_volume = self.create_template_from_snapshot(self.apiclient, self.services, volumeid = volume[0].id)
Volume.delete(delete, self.apiclient, )
Snapshot.delete(snapshot, self.apiclient)
flag = False
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
if snapshot_details is not None:
try:
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
except spapi.ApiError as err:
flag = False
if flag is True:
raise Exception("Snapshot was not deleted")
except Exception as err:
self.debug('Snapshot was deleted %s' % err)
Template.delete(template, self.apiclient, zoneid = self.zone.id)
Template.delete(template_from_volume, self.apiclient, zoneid = self.zone.id)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_08_delete_snapshot_of_deleted_volume(self):
''' Delete snapshot and template if volume is already deleted, bypassing secondary
'''
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "true")
volume = Volume.create(
self.apiclient,
{"diskname":"StorPoolDisk-Delete" },
zoneid = self.zone.id,
diskofferingid = self.disk_offerings.id,
account=self.account.name,
domainid=self.account.domainid,
)
delete = volume
self.virtual_machine2.attach_volume(
self.apiclient,
volume
)
self.virtual_machine2.detach_volume(
self.apiclient,
volume
)
volume = list_volumes(self.apiclient, id = volume.id)
name = volume[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
except spapi.ApiError as err:
raise Exception(err)
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
if snapshot_details is not None:
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
try:
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
except spapi.ApiError as err:
raise Exception(err)
if flag == False:
raise Exception("Could not find snapshot in snapshot details")
except Exception as err:
raise Exception(err)
template = self.create_template_from_snapshot(self.apiclient, self.services, snapshotid = snapshot.id)
Volume.delete(delete, self.apiclient, )
Snapshot.delete(snapshot, self.apiclient)
flag = False
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
if snapshot_details is not None:
try:
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
except spapi.ApiError as err:
flag = False
if flag is True:
raise Exception("Snapshot was not deleted")
except Exception as err:
self.debug('Snapshot was deleted %s' % err)
Template.delete(template, self.apiclient, zoneid = self.zone.id)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_09_vm_from_bypassed_template(self):
'''Create virtual machine with sp.bypass.secondary.storage=false
from template created on StorPool and Secondary Storage'''
volume = list_volumes(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
name = volume[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
except spapi.ApiError as err:
raise Exception(err)
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "true")
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
try:
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
except spapi.ApiError as err:
raise Exception(err)
if flag == False:
raise Exception("Could not find snapshot in snapshot details")
except Exception as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Could not create snapshot")
self.assertIsInstance(snapshot, Snapshot, "Snapshot is not an instance of Snapshot")
template = self.create_template_from_snapshot(
self.apiclient,
self.services,
snapshotid = snapshot.id
)
self._cleanup.append(template)
flag = False
sp_snapshots = self.spapi.snapshotsList()
for snap in sp_snapshots:
tags = snap.tags
for t in tags:
if tags[t] == template.id:
flag = True
break
else:
continue
break
if flag is False:
raise Exception("Template does not exists in Storpool")
self.assertIsNotNone(template, "Template is None")
self.assertIsInstance(template, Template, "Template is instance of template")
backup_config = Configurations.update(self.apiclient,
name = "sp.bypass.secondary.storage",
value = "false")
vm = VirtualMachine.create(
self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
templateid = template.id,
serviceofferingid=self.service_offering.id,
hypervisor=self.hypervisor,
rootdisksize=10,
)
ssh_client = vm.get_ssh_client(reconnect=True)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_10_create_vm_snapshots(self):
"""Test to create VM snapshots
"""
volume_attached = self.virtual_machine.attach_volume(
self.apiclient,
self.volume
)
vol = list_volumes(self.apiclient, virtualmachineid=self.virtual_machine.id, id=volume_attached.id)
name = vol[0].path.split("/")[3]
sp_volume = self.spapi.volumeList(volumeName = "~" + name)
self.assertEqual(volume_attached.id, self.volume.id, "Is not the same volume ")
try:
# Login to VM and write data to file system
ssh_client = self.virtual_machine.get_ssh_client()
cmds = [
"echo %s > %s/%s" %
(self.random_data_0, self.test_dir, self.random_data),
"sync",
"sleep 1",
"sync",
"sleep 1",
"cat %s/%s" %
(self.test_dir, self.random_data)
]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
self.assertEqual(
self.random_data_0,
result[0],
"Check the random data has be write into temp file!"
)
time.sleep(30)
MemorySnapshot = False
vm_snapshot = VmSnapshot.create(
self.apiclient,
self.virtual_machine.id,
MemorySnapshot,
"TestSnapshot",
"Display Text"
)
self.assertEqual(
vm_snapshot.state,
"Ready",
"Check the snapshot of vm is ready!"
)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_11_revert_vm_snapshots(self):
"""Test to revert VM snapshots
"""
try:
ssh_client = self.virtual_machine.get_ssh_client()
cmds = [
"rm -rf %s/%s" % (self.test_dir, self.random_data),
"ls %s/%s" % (self.test_dir, self.random_data)
]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
if str(result[0]).index("No such file or directory") == -1:
self.fail("Check the random data has be delete from temp file!")
time.sleep(30)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=self.virtual_machine.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
self.assertEqual(
list_snapshot_response[0].state,
"Ready",
"Check the snapshot of vm is ready!"
)
self.virtual_machine.stop(self.apiclient, forced=True)
VmSnapshot.revertToSnapshot(
self.apiclient,
list_snapshot_response[0].id
)
self.virtual_machine.start(self.apiclient)
try:
ssh_client = self.virtual_machine.get_ssh_client(reconnect=True)
cmds = [
"cat %s/%s" % (self.test_dir, self.random_data)
]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
self.assertEqual(
self.random_data_0,
result[0],
"Check the random data is equal with the ramdom file!"
)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_12_delete_vm_snapshots(self):
"""Test to delete vm snapshots
"""
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=self.virtual_machine.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
VmSnapshot.deleteVMSnapshot(
self.apiclient,
list_snapshot_response[0].id)
time.sleep(30)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
#vmid=self.virtual_machine.id,
virtualmachineid=self.virtual_machine.id,
listall=False)
self.debug('list_snapshot_response -------------------- %s' % list_snapshot_response)
self.assertIsNone(list_snapshot_response, "snapshot is already deleted")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_13_detach_volume(self):
'''Attach volume on VM on 2nd zone'''
self.virtual_machine.stop(self.apiclient)
self.virtual_machine.detach_volume(
self.apiclient,
self.volume
)
vol = list_volumes(self.apiclient, id=self.volume.id)
name = vol[0].path.split("/")[3]
spvolume = self.spapi.volumeList(volumeName = "~" + name)
self.assertEqual(vol[0].id, self.volume.id, "Is not the same volume ")
tags = spvolume[0].tags
for t in tags:
self.assertFalse(t.lower() == 'cvm'.lower(), "cvm tag still set on detached volume")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_14_attach_detach_volume_to_running_vm(self):
''' Test Attach Volume To Running Virtual Machine
'''
time.sleep(60)
self.assertEqual(VirtualMachine.RUNNING, self.virtual_machine.state, "Running")
volume = self.virtual_machine.attach_volume(
self.apiclient,
self.volume_1
)
print(volume)
self.assertIsNotNone(volume, "Volume is not None")
list_vm_volumes = Volume.list(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
id= volume.id
)
print(list_vm_volumes)
self.assertEqual(volume.id, list_vm_volumes[0].id, "Is true")
name = list_vm_volumes[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
except spapi.ApiError as err:
raise Exception(err)
volume = self.virtual_machine.detach_volume(
self.apiclient,
self.volume_1
)
list_vm_volumes = Volume.list(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
id = volume.id
)
print(list_vm_volumes)
self.assertIsNone(list_vm_volumes, "Is None")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_15_resize_root_volume_on_working_vm(self):
''' Test Resize Root volume on Running Virtual Machine
'''
self.assertEqual(VirtualMachine.RUNNING, self.virtual_machine2.state, "Running")
volume = list_volumes(
self.apiclient,
virtualmachineid = self.virtual_machine2.id,
type = "ROOT",
listall = True,
)
volume = volume[0]
name = volume.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != volume.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
self.assertEqual(volume.type, 'ROOT', "Volume is not of ROOT type")
shrinkOk = False
if volume.size > int((self.disk_offering_20.disksize) * (1024**3)):
shrinkOk= True
cmd = resizeVolume.resizeVolumeCmd()
cmd.id = volume.id
cmd.size = 20
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=volume.id
)
self.assertTrue(
(new_size[0].size == int((self.disk_offering_20.disksize) * (1024**3))),
"New size is not int((self.disk_offering_20) * (1024**3)"
)
volume = new_size[0]
name = volume.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != volume.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
shrinkOk = False
if volume.size > int((self.disk_offering_100.disksize) * (1024**3)):
shrinkOk= True
cmd = resizeVolume.resizeVolumeCmd()
cmd.id = volume.id
cmd.size = 100
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=volume.id
)
volume = new_size[0]
name = volume.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != volume.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
self.assertTrue(
(new_size[0].size == int((self.disk_offering_100.disksize) * (1024**3))),
"New size is not int((self.disk_offering_20) * (1024**3)"
)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_16_resize_attached_volume_on_working_vm(self):
''' Test Resize Volume Attached To Running Virtual Machine
'''
self.assertEqual(VirtualMachine.RUNNING, self.virtual_machine.state, "Running")
volume = self.virtual_machine.attach_volume(
self.apiclient,
self.volume_1
)
listvol = Volume.list(
self.apiclient,
id=volume.id
)
name = listvol[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != listvol[0].size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
shrinkOk = False
if volume.size > int((self.disk_offering_20.disksize) * (1024**3)):
shrinkOk= True
cmd = resizeVolume.resizeVolumeCmd()
cmd.id = volume.id
cmd.diskofferingid = self.disk_offering_20.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=volume.id
)
self.assertTrue(
(new_size[0].size == int((self.disk_offering_20.disksize) * (1024**3))),
"New size is not int((self.disk_offering_20) * (1024**3)"
)
volume = new_size[0]
name = volume.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != volume.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
shrinkOk = False
if volume.size > int((self.disk_offering_100.disksize) * (1024**3)):
shrinkOk= True
cmd = resizeVolume.resizeVolumeCmd()
cmd.id = volume.id
cmd.diskofferingid = self.disk_offering_100.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=volume.id
)
self.assertTrue(
(new_size[0].size == int((self.disk_offering_100.disksize) * (1024**3))),
"New size is not int((self.disk_offering_20) * (1024**3)"
)
# return to small disk
volume = new_size[0]
name = volume.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != volume.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
shrinkOk = False
if volume.size > int((self.disk_offerings.disksize)* (1024**3)):
shrinkOk= True
cmd.diskofferingid = self.disk_offerings.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=volume.id
)
volume = new_size[0]
name = volume.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != volume.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
self.assertTrue(
(new_size[0].size == int((self.disk_offerings.disksize)*(1024**3))),
"Could not return to Small disk"
)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_17_attach_detach_volume_to_stopped_vm(self):
''' Test Attach Volume To Stopped Virtual Machine
'''
virtual_machine = self.virtual_machine.stop(
self.apiclient,
forced=True
)
time.sleep(60)
volume_2 = self.virtual_machine.attach_volume(
self.apiclient,
self.volume_2
)
list_vm_volumes = Volume.list(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
id= volume_2.id
)
name = list_vm_volumes[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
except spapi.ApiError as err:
raise Exception(err)
print(list_vm_volumes)
self.assertEqual(volume_2.id,list_vm_volumes[0].id, "Is true")
time.sleep(90)
volume_2 = self.virtual_machine.detach_volume(
self.apiclient,
self.volume_2
)
list_vm_volumes = Volume.list(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
id = volume_2.id
)
print(list_vm_volumes)
self.assertIsNone(list_vm_volumes, "Is None")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_18_resize_attached_volume(self):
''' Test Resize Volume Attached To Virtual Machine
'''
shrinkOk = False
if self.volume_1.size > int((self.disk_offering_20.disksize) * (1024**3)):
shrinkOk= True
cmd = resizeVolume.resizeVolumeCmd()
cmd.id = self.volume_1.id
cmd.diskofferingid = self.disk_offering_20.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=self.volume_1.id
)
self.assertTrue(
(new_size[0].size == int((self.disk_offering_20.disksize) * (1024**3))),
"New size is not int((self.disk_offering_20) * (1024**3)"
)
self.volume_1 = new_size[0]
name = self.volume_1.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != self.volume_1.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
shrinkOk = False
if self.volume_1.size > int((self.disk_offering_100.disksize) * (1024**3)):
shrinkOk= True
cmd = resizeVolume.resizeVolumeCmd()
cmd.id = self.volume_1.id
cmd.diskofferingid = self.disk_offering_100.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=self.volume_1.id
)
self.assertTrue(
(new_size[0].size == int((self.disk_offering_100.disksize) * (1024**3))),
"New size is not int((self.disk_offering_20) * (1024**3)"
)
# return to small disk
self.volume_1 = new_size[0]
name = self.volume_1.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != self.volume_1.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
shrinkOk = False
if self.volume_1.size > int((self.disk_offerings.disksize)* (1024**3)):
shrinkOk= True
cmd.diskofferingid = self.disk_offerings.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=self.volume_1.id
)
name = new_size[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != new_size[0].size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
self.assertTrue(
(new_size[0].size == int((self.disk_offerings.disksize)*(1024**3))),
"Could not return to Small disk"
)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_19_resize_detached_volume(self):
''' Test Resize Volume Detached To Virtual Machine
'''
list_vm_volumes = Volume.list(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
id= self.volume_2.id
)
#check that the volume is not attached to VM
self.assertIsNone(list_vm_volumes, "List volumes is not None")
shrinkOk = False
if self.volume_2.size > int((self.disk_offering_20.disksize) * (1024**3)):
shrinkOk= True
cmd = resizeVolume.resizeVolumeCmd()
cmd.id = self.volume_2.id
cmd.diskofferingid = self.disk_offering_20.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=self.volume_2.id
)
self.assertTrue(
(new_size[0].size == int((self.disk_offering_20.disksize) * (1024**3))),
"New size is not int((self.disk_offering_20) * (1024**3)"
)
self.volume_2 = new_size[0]
name = self.volume_2.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != self.volume_2.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
shrinkOk = False
if self.volume_2.size > int((self.disk_offering_100.disksize) * (1024**3)):
shrinkOk= True
cmd = resizeVolume.resizeVolumeCmd()
cmd.id = self.volume_2.id
cmd.diskofferingid = self.disk_offering_100.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=self.volume_2.id
)
self.assertTrue(
(new_size[0].size == int((self.disk_offering_100.disksize) * (1024**3))),
"New size is not int((self.disk_offering_20) * (1024**3)"
)
# return to small disk
self.volume_2 = new_size[0]
name = self.volume_2.path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != self.volume_2.size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
shrinkOk = False
if self.volume_2.size > int((self.disk_offerings.disksize)* (1024**3)):
shrinkOk= True
cmd.diskofferingid = self.disk_offerings.id
cmd.shrinkok = shrinkOk
self.apiclient.resizeVolume(cmd)
new_size = Volume.list(
self.apiclient,
id=self.volume_2.id
)
name = new_size[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
if spvolume[0].size != new_size[0].size:
raise Exception("Storpool volume size is not the same as CloudStack db size")
except spapi.ApiError as err:
raise Exception(err)
self.assertTrue(
(new_size[0].size == int((self.disk_offerings.disksize)*(1024**3))),
"Could not return to Small disk"
)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_20_snapshot_to_volume(self):
''' Create volume from snapshot
'''
snapshot = Snapshot.create(
self.apiclient,
volume_id = self.volume_2.id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
if flag == False:
raise Exception("Could not find snapshot in snapshot details")
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Could not create snapshot")
self.assertIsInstance(snapshot, Snapshot, "Snapshot is not an instance of Snapshot")
volume = self.create_volume(
self.apiclient,
zoneid = self.zone.id,
snapshotid = snapshot.id,
account=self.account.name,
domainid=self.account.domainid
)
listvol = Volume.list(
self.apiclient,
id=volume.id
)
name = listvol[0].path.split("/")[3]
try:
spvolume = self.spapi.volumeList(volumeName="~" + name)
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(volume, "Could not create volume from snapshot")
self.assertIsInstance(volume, Volume, "Volume is not instance of Volume")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_21_snapshot_detached_volume(self):
''' Test Snapshot Detached Volume
'''
self.virtual_machine.stop(
self.apiclient,
forced = True
)
self.volume = self.virtual_machine.attach_volume(
self.apiclient,
self.volume
)
self.assertIsNotNone(self.volume, "Attach: Is none")
self.volume = self.virtual_machine.detach_volume(
self.apiclient,
self.volume
)
self.assertIsNotNone(self.volume, "Detach: Is none")
snapshot = Snapshot.create(
self.apiclient,
self.volume.id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
if flag == False:
raise Exception("Could not find snapshot in snapshot details")
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Snapshot is None")
self.assertIsInstance(snapshot, Snapshot, "Snapshot is not Instance of Snappshot")
snapshot = Snapshot.delete(
snapshot,
self.apiclient
)
self.assertIsNone(snapshot, "Snapshot was not deleted")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_22_snapshot_root_disk(self):
''' Test ROOT Disk Snapshot
'''
vm = VirtualMachine.create(self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid = self.zone.id,
templateid = self.template.id,
serviceofferingid = self.service_offering.id,
hypervisor = self.hypervisor,
rootdisksize = 10
)
list_volumes_of_vm = list_volumes(
self.apiclient,
virtualmachineid = vm.id,
listall = True,
)
self.assertIs(len(list_volumes_of_vm), 1, "VM has more disk than 1")
snapshot = Snapshot.create(
self.apiclient,
list_volumes_of_vm[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
try:
cmd = getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd()
cmd.snapshotid = snapshot.id
snapshot_details = self.apiclient.getVolumeSnapshotDetails(cmd)
flag = False
for s in snapshot_details:
if s["snapshotDetailsName"] == snapshot.id:
name = s["snapshotDetailsValue"].split("/")[3]
sp_snapshot = self.spapi.snapshotList(snapshotName = "~" + name)
flag = True
if flag == False:
raise Exception("Could not find snapshot in snapshot details")
except spapi.ApiError as err:
raise Exception(err)
self.assertIsNotNone(snapshot, "Snapshot is None")
self.assertEqual(list_volumes_of_vm[0].id, snapshot.volumeid, "Snapshot is not for the same volume")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_23_volume_to_template(self):
''' Create Template From ROOT Volume
'''
volume = Volume.list(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
self.virtual_machine.stop(self.apiclient)
template = self.create_template_from_snapshot(
self.apiclient,
self.services,
volumeid = volume[0].id
)
virtual_machine = VirtualMachine.create(self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
templateid=template.id,
serviceofferingid=self.service_offering.id,
hypervisor=self.hypervisor,
rootdisksize=10
)
ssh_client = virtual_machine.get_ssh_client()
self.assertIsNotNone(template, "Template is None")
self.assertIsInstance(template, Template, "Template is instance of template")
self._cleanup.append(template)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_24_migrate_vm_to_another_storage(self):
''' Migrate VM to another Primary Storage
'''
list_volumes_of_vm = list_volumes(
self.apiclient,
virtualmachineid = self.vm_migrate.id,
listall = True,
)
self.assertTrue(len(list_volumes_of_vm) == 1, "There are more volumes attached to VM")
if list_volumes_of_vm[0].storageid is self.primary_storage.id:
cmd = migrateVirtualMachine.migrateVirtualMachineCmd()
cmd.virtualmachineid = self.vm_migrate.id
if hostid:
cmd.hostid = hostid
vm = apiclient.migrateVirtualMachine(cmd)
volume = list_volumes(
self.apiclient,
virtualmachineid = vm.id
)[0]
self.assertNotEqual(volume.storageid, self.primary_storage.id, "Could not migrate VM")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_25_migrate_volume_to_another_storage(self):
''' Migrate Volume To Another Primary Storage
'''
self.assertFalse(hasattr(self.volume, 'virtualmachineid') , "Volume is not detached")
self.assertFalse(hasattr(self.volume, 'storageid') , "Volume is not detached")
volume = Volume.migrate(
self.apiclient,
volumeid = self.volume.id,
storageid = self.primary_storage2.id
)
self.assertIsNotNone(volume, "Volume is None")
self.assertEqual(volume.storageid, self.primary_storage2.id, "Storage is the same")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_26_create_vm_on_another_storpool_storage(self):
""" Create Virtual Machine on another StorPool primary StoragePool"""
virtual_machine = VirtualMachine.create(self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
templateid=self.template.id,
serviceofferingid=self.service_offering2.id,
hypervisor=self.hypervisor,
rootdisksize=10
)
self.assertIsNotNone(virtual_machine, "Could not create virtual machine on another Storpool primary storage")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_27_snapshot_to_volume_of_root_disk(self):
''' Create volume from snapshot
'''
virtual_machine = VirtualMachine.create(self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
templateid=self.template.id,
serviceofferingid=self.service_offering.id,
hypervisor=self.hypervisor,
rootdisksize=10
)
volume1 = list_volumes(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
snapshot = Snapshot.create(
self.apiclient,
volume_id = volume1[0].id,
account=self.account.name,
domainid=self.account.domainid,
)
self.assertIsNotNone(snapshot, "Could not create snapshot")
self.assertIsInstance(snapshot, Snapshot, "Snapshot is not an instance of Snapshot")
volume = self.create_volume(
self.apiclient,
zoneid = self.zone.id,
snapshotid = snapshot.id,
account=self.account.name,
domainid=self.account.domainid
)
self.assertIsNotNone(volume, "Could not create volume from snapshot")
self.assertIsInstance(volume, Volume, "Volume is not instance of Volume")
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_28_download_volume(self):
vol = self.volume.extract(
self.apiclient,
volume_id = self.volume.id,
zoneid = self.zone.id,
mode = "HTTP_DOWNLOAD"
)
self.assertIsNotNone(vol, "Volume is None")
self.assertIsNotNone(vol.url, "No URL provided")
Volume.delete(vol, self.apiclient)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_29_create_vm_from_template_not_on_storpool(self):
''' Create virtual machine from template which for some reason is deleted from StorPool, but exists in template_spoool_ref DB tables '''
volume = Volume.list(
self.apiclient,
virtualmachineid = self.virtual_machine.id,
type = "ROOT",
listall = True,
)
self.virtual_machine.stop(self.apiclient)
template = self.create_template_from_snapshot(
self.apiclient,
self.services,
volumeid = volume[0].id
)
virtual_machine = VirtualMachine.create(self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
templateid=template.id,
serviceofferingid=self.service_offering.id,
hypervisor=self.hypervisor,
rootdisksize=10
)
ssh_client = virtual_machine.get_ssh_client(reconnect= True)
name = 'ssd-' + template.id
flag = False
storpoolGlId = None
sp_snapshots = self.spapi.snapshotsList()
for snap in sp_snapshots:
tags = snap.tags
for t in tags:
if tags[t] == template.id:
storpoolGlId = snap.globalId
flag = True
break
else:
continue
break
if flag is False:
try:
sp_snapshot = self.spapi.snapshotList(snapshotName = name)
except spapi.ApiError as err:
raise Exception(err)
self.spapi.snapshotDelete(snapshotName ="~" + storpoolGlId)
virtual_machine2 = VirtualMachine.create(self.apiclient,
{"name":"StorPool-%s" % uuid.uuid4() },
accountid=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id,
templateid=template.id,
serviceofferingid=self.service_offering.id,
hypervisor=self.hypervisor,
rootdisksize=10
)
ssh_client = virtual_machine2.get_ssh_client(reconnect= True)
self.assertIsNotNone(template, "Template is None")
self.assertIsInstance(template, Template, "Template is instance of template")
self._cleanup.append(template)
@classmethod
def create_volume(self, apiclient, zoneid=None, snapshotid=None, account=None, domainid=None):
"""Create Volume"""
cmd = createVolume.createVolumeCmd()
cmd.name = "Test"
if zoneid:
cmd.zoneid = zoneid
if snapshotid:
cmd.snapshotid = snapshotid
if account:
cmd.account=account
if domainid:
cmd.domainid=domainid
return Volume(apiclient.createVolume(cmd).__dict__)
@classmethod
def get_local_cluster(cls):
storpool_clusterid = subprocess.check_output(['storpool_confshow', 'CLUSTER_ID'])
clusterid = storpool_clusterid.split("=")
cls.debug(storpool_clusterid)
clusters = list_clusters(cls.apiclient)
for c in clusters:
configuration = list_configurations(
cls.apiclient,
clusterid = c.id
)
for conf in configuration:
if conf.name == 'sp.cluster.id' and (conf.value in clusterid[1]):
return c
@classmethod
def get_remote_cluster(cls):
storpool_clusterid = subprocess.check_output(['storpool_confshow', 'CLUSTER_ID'])
clusterid = storpool_clusterid.split("=")
cls.debug(storpool_clusterid)
clusters = list_clusters(cls.apiclient)
for c in clusters:
configuration = list_configurations(
cls.apiclient,
clusterid = c.id
)
for conf in configuration:
if conf.name == 'sp.cluster.id' and (conf.value not in clusterid[1]):
return c
@classmethod
def list_hosts_by_cluster_id(cls, clusterid):
"""List all Hosts matching criteria"""
cmd = listHosts.listHostsCmd()
cmd.clusterid = clusterid
return(cls.apiclient.listHosts(cmd))
def start(cls, vmid, hostid):
"""Start the instance"""
cmd = startVirtualMachine.startVirtualMachineCmd()
cmd.id = vmid
cmd.hostid = hostid
return (cls.apiclient.startVirtualMachine(cmd))
@classmethod
def create_template_from_snapshot(self, apiclient, services, snapshotid=None, volumeid=None):
"""Create template from Volume"""
# Create template from Virtual machine and Volume ID
cmd = createTemplate.createTemplateCmd()
cmd.displaytext = "StorPool_Template"
cmd.name = "-".join(["StorPool-", random_gen()])
if "ostypeid" in services:
cmd.ostypeid = services["ostypeid"]
elif "ostype" in services:
# Find OSTypeId from Os type
sub_cmd = listOsTypes.listOsTypesCmd()
sub_cmd.description = services["ostype"]
ostypes = apiclient.listOsTypes(sub_cmd)
if not isinstance(ostypes, list):
raise Exception(
"Unable to find Ostype id with desc: %s" %
services["ostype"])
cmd.ostypeid = ostypes[0].id
else:
raise Exception(
"Unable to find Ostype is required for creating template")
cmd.isfeatured = True
cmd.ispublic = True
cmd.isextractable = False
if snapshotid:
cmd.snapshotid = snapshotid
if volumeid:
cmd.volumeid = volumeid
return Template(apiclient.createTemplate(cmd).__dict__)
@classmethod
def getCfgFromUrl(cls, url):
cfg = dict([
option.split('=')
for option in url.split(';')
])
host, port = cfg['SP_API_HTTP'].split(':')
auth = cfg['SP_AUTH_TOKEN']
return host, int(port), auth
| [
"marvin.lib.base.Volume.delete",
"marvin.lib.common.list_service_offering",
"marvin.lib.utils.random_gen",
"marvin.lib.base.VmSnapshot.list",
"marvin.lib.base.Template.delete",
"marvin.lib.common.list_zones",
"marvin.lib.base.VmSnapshot.create",
"marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd",
"... | [((12928, 13000), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (12932, 13000), False, 'from nose.plugins.attrib import attr\n'), ((14631, 14703), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (14635, 14703), False, 'from nose.plugins.attrib import attr\n'), ((17759, 17831), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (17763, 17831), False, 'from nose.plugins.attrib import attr\n'), ((19315, 19387), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (19319, 19387), False, 'from nose.plugins.attrib import attr\n'), ((20861, 20933), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (20865, 20933), False, 'from nose.plugins.attrib import attr\n'), ((23988, 24060), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (23992, 24060), False, 'from nose.plugins.attrib import attr\n'), ((27829, 27901), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (27833, 27901), False, 'from nose.plugins.attrib import attr\n'), ((31443, 31515), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (31447, 31515), False, 'from nose.plugins.attrib import attr\n'), ((34868, 34940), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (34872, 34940), False, 'from nose.plugins.attrib import attr\n'), ((38271, 38343), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (38275, 38343), False, 'from nose.plugins.attrib import attr\n'), ((40180, 40252), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (40184, 40252), False, 'from nose.plugins.attrib import attr\n'), ((42541, 42613), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (42545, 42613), False, 'from nose.plugins.attrib import attr\n'), ((43695, 43767), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (43699, 43767), False, 'from nose.plugins.attrib import attr\n'), ((44417, 44489), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (44421, 44489), False, 'from nose.plugins.attrib import attr\n'), ((45779, 45851), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (45783, 45851), False, 'from nose.plugins.attrib import attr\n'), ((48618, 48690), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (48622, 48690), False, 'from nose.plugins.attrib import attr\n'), ((52383, 52455), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (52387, 52455), False, 'from nose.plugins.attrib import attr\n'), ((53727, 53799), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (53731, 53799), False, 'from nose.plugins.attrib import attr\n'), ((56896, 56968), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (56900, 56968), False, 'from nose.plugins.attrib import attr\n'), ((60360, 60432), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (60364, 60432), False, 'from nose.plugins.attrib import attr\n'), ((62280, 62352), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (62284, 62352), False, 'from nose.plugins.attrib import attr\n'), ((64133, 64205), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (64137, 64205), False, 'from nose.plugins.attrib import attr\n'), ((66002, 66074), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (66006, 66074), False, 'from nose.plugins.attrib import attr\n'), ((67222, 67294), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (67226, 67294), False, 'from nose.plugins.attrib import attr\n'), ((68212, 68284), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (68216, 68284), False, 'from nose.plugins.attrib import attr\n'), ((68908, 68980), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (68912, 68980), False, 'from nose.plugins.attrib import attr\n'), ((69659, 69731), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (69663, 69731), False, 'from nose.plugins.attrib import attr\n'), ((71201, 71273), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (71205, 71273), False, 'from nose.plugins.attrib import attr\n'), ((71658, 71730), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (71662, 71730), False, 'from nose.plugins.attrib import attr\n'), ((3302, 3318), 'sp_util.StorPoolHelper', 'StorPoolHelper', ([], {}), '()\n', (3316, 3318), False, 'from sp_util import TestData, StorPoolHelper\n'), ((3662, 3687), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (3672, 3687), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((3728, 3753), 'marvin.lib.common.list_zones', 'list_zones', (['cls.apiclient'], {}), '(cls.apiclient)\n', (3738, 3753), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((4559, 4620), 'storpool.spapi.Api', 'spapi.Api', ([], {'host': 'host', 'port': 'port', 'auth': 'auth', 'multiCluster': '(True)'}), '(host=host, port=port, auth=auth, multiCluster=True)\n', (4568, 4620), False, 'from storpool import spapi\n'), ((4645, 4717), 'marvin.lib.common.list_storage_pools', 'list_storage_pools', (['cls.apiclient'], {'name': "storpool_primary_storage['name']"}), "(cls.apiclient, name=storpool_primary_storage['name'])\n", (4663, 4717), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((5718, 5804), 'marvin.lib.common.list_service_offering', 'list_service_offering', (['cls.apiclient'], {'name': "storpool_service_offerings_ssd['name']"}), "(cls.apiclient, name=storpool_service_offerings_ssd[\n 'name'])\n", (5739, 5804), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((6749, 6822), 'marvin.lib.common.list_storage_pools', 'list_storage_pools', (['cls.apiclient'], {'name': "storpool_primary_storage2['name']"}), "(cls.apiclient, name=storpool_primary_storage2['name'])\n", (6767, 6822), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((7740, 7827), 'marvin.lib.common.list_service_offering', 'list_service_offering', (['cls.apiclient'], {'name': "storpool_service_offerings_ssd2['name']"}), "(cls.apiclient, name=storpool_service_offerings_ssd2[\n 'name'])\n", (7761, 7827), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((8172, 8219), 'marvin.lib.common.list_disk_offering', 'list_disk_offering', (['cls.apiclient'], {'name': '"""Small"""'}), "(cls.apiclient, name='Small')\n", (8190, 8219), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((8286, 8334), 'marvin.lib.common.list_disk_offering', 'list_disk_offering', (['cls.apiclient'], {'name': '"""Medium"""'}), "(cls.apiclient, name='Medium')\n", (8304, 8334), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((8402, 8449), 'marvin.lib.common.list_disk_offering', 'list_disk_offering', (['cls.apiclient'], {'name': '"""Large"""'}), "(cls.apiclient, name='Large')\n", (8420, 8449), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((8712, 8770), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id'], {'account': '"""system"""'}), "(cls.apiclient, cls.zone.id, account='system')\n", (8724, 8770), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((9281, 9319), 'marvin.lib.base.Role.list', 'Role.list', (['cls.apiclient'], {'name': '"""Admin"""'}), "(cls.apiclient, name='Admin')\n", (9290, 9319), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((9373, 9475), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id', 'roleid': 'role[0].id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.\n id, roleid=role[0].id)\n", (9387, 9475), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((9938, 10121), 'marvin.lib.base.Volume.create', 'Volume.create', (['cls.apiclient', "{'diskname': 'StorPoolDisk-1'}"], {'zoneid': 'cls.zone.id', 'diskofferingid': 'disk_offerings[0].id', 'account': 'cls.account.name', 'domainid': 'cls.account.domainid'}), "(cls.apiclient, {'diskname': 'StorPoolDisk-1'}, zoneid=cls.\n zone.id, diskofferingid=disk_offerings[0].id, account=cls.account.name,\n domainid=cls.account.domainid)\n", (9951, 10121), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((10220, 10403), 'marvin.lib.base.Volume.create', 'Volume.create', (['cls.apiclient', "{'diskname': 'StorPoolDisk-2'}"], {'zoneid': 'cls.zone.id', 'diskofferingid': 'disk_offerings[0].id', 'account': 'cls.account.name', 'domainid': 'cls.account.domainid'}), "(cls.apiclient, {'diskname': 'StorPoolDisk-2'}, zoneid=cls.\n zone.id, diskofferingid=disk_offerings[0].id, account=cls.account.name,\n domainid=cls.account.domainid)\n", (10233, 10403), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((10500, 10683), 'marvin.lib.base.Volume.create', 'Volume.create', (['cls.apiclient', "{'diskname': 'StorPoolDisk-3'}"], {'zoneid': 'cls.zone.id', 'diskofferingid': 'disk_offerings[0].id', 'account': 'cls.account.name', 'domainid': 'cls.account.domainid'}), "(cls.apiclient, {'diskname': 'StorPoolDisk-3'}, zoneid=cls.\n zone.id, diskofferingid=disk_offerings[0].id, account=cls.account.name,\n domainid=cls.account.domainid)\n", (10513, 10683), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((12111, 12131), 'marvin.lib.utils.random_gen', 'random_gen', ([], {'size': '(100)'}), '(size=100)\n', (12121, 12131), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList, is_snapshot_on_nfs, isAlmostEqual\n'), ((13149, 13250), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall=True)\n", (13160, 13250), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((13340, 13432), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""false"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='false')\n", (13361, 13432), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((13476, 13595), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (13491, 13595), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((14899, 15001), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='ROOT', listall=True)\n", (14911, 15001), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((15355, 15446), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""true"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='true')\n", (15376, 15446), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((15491, 15610), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (15506, 15610), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((17991, 18083), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""false"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='false')\n", (18012, 18083), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((18125, 18227), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='ROOT', listall=True)\n", (18137, 18227), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((18371, 18490), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (18386, 18490), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((19538, 19629), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""true"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='true')\n", (19559, 19629), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((19671, 19773), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='ROOT', listall=True)\n", (19683, 19773), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((19917, 20036), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (19932, 20036), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((21095, 21197), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='ROOT', listall=True)\n", (21107, 21197), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((21550, 21641), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""true"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='true')\n", (21571, 21641), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((21686, 21805), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (21701, 21805), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((23544, 23599), 'marvin.lib.base.Template.delete', 'Template.delete', (['template', 'self.apiclient', 'self.zone.id'], {}), '(template, self.apiclient, self.zone.id)\n', (23559, 23599), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((24273, 24375), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='ROOT', listall=True)\n", (24285, 24375), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((24728, 24820), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""false"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='false')\n", (24749, 24820), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((24865, 24984), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (24880, 24984), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((25921, 26012), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""true"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='true')\n", (25942, 26012), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((26849, 26904), 'marvin.lib.base.Template.delete', 'Template.delete', (['template', 'self.apiclient', 'self.zone.id'], {}), '(template, self.apiclient, self.zone.id)\n', (26864, 26904), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((28091, 28183), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""false"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='false')\n", (28112, 28183), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((28218, 28413), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "{'diskname': 'StorPoolDisk-Delete'}"], {'zoneid': 'self.zone.id', 'diskofferingid': 'self.disk_offerings.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, {'diskname': 'StorPoolDisk-Delete'}, zoneid=\n self.zone.id, diskofferingid=self.disk_offerings.id, account=self.\n account.name, domainid=self.account.domainid)\n", (28231, 28413), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((28813, 28855), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (28825, 28855), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((29074, 29193), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (29089, 29193), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((30315, 30352), 'marvin.lib.base.Volume.delete', 'Volume.delete', (['delete', 'self.apiclient'], {}), '(delete, self.apiclient)\n', (30328, 30352), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((30363, 30404), 'marvin.lib.base.Snapshot.delete', 'Snapshot.delete', (['snapshot', 'self.apiclient'], {}), '(snapshot, self.apiclient)\n', (30378, 30404), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((31287, 31349), 'marvin.lib.base.Template.delete', 'Template.delete', (['template', 'self.apiclient'], {'zoneid': 'self.zone.id'}), '(template, self.apiclient, zoneid=self.zone.id)\n', (31302, 31349), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((31360, 31434), 'marvin.lib.base.Template.delete', 'Template.delete', (['template_from_volume', 'self.apiclient'], {'zoneid': 'self.zone.id'}), '(template_from_volume, self.apiclient, zoneid=self.zone.id)\n', (31375, 31434), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((31701, 31792), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""true"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='true')\n", (31722, 31792), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((31827, 32022), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "{'diskname': 'StorPoolDisk-Delete'}"], {'zoneid': 'self.zone.id', 'diskofferingid': 'self.disk_offerings.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, {'diskname': 'StorPoolDisk-Delete'}, zoneid=\n self.zone.id, diskofferingid=self.disk_offerings.id, account=self.\n account.name, domainid=self.account.domainid)\n", (31840, 32022), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((32358, 32400), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (32370, 32400), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((32619, 32738), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (32634, 32738), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((33825, 33862), 'marvin.lib.base.Volume.delete', 'Volume.delete', (['delete', 'self.apiclient'], {}), '(delete, self.apiclient)\n', (33838, 33862), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((33873, 33914), 'marvin.lib.base.Snapshot.delete', 'Snapshot.delete', (['snapshot', 'self.apiclient'], {}), '(snapshot, self.apiclient)\n', (33888, 33914), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((34797, 34859), 'marvin.lib.base.Template.delete', 'Template.delete', (['template', 'self.apiclient'], {'zoneid': 'self.zone.id'}), '(template, self.apiclient, zoneid=self.zone.id)\n', (34812, 34859), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((35148, 35250), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='ROOT', listall=True)\n", (35160, 35250), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((35596, 35687), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""true"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='true')\n", (35617, 35687), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((35732, 35851), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (35747, 35851), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((37679, 37771), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""sp.bypass.secondary.storage"""', 'value': '"""false"""'}), "(self.apiclient, name='sp.bypass.secondary.storage',\n value='false')\n", (37700, 37771), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((38581, 38679), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'id': 'volume_attached.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id, id=\n volume_attached.id)\n', (38593, 38679), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((39776, 39790), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (39786, 39790), False, 'import time\n'), ((39844, 39954), 'marvin.lib.base.VmSnapshot.create', 'VmSnapshot.create', (['self.apiclient', 'self.virtual_machine.id', 'MemorySnapshot', '"""TestSnapshot"""', '"""Display Text"""'], {}), "(self.apiclient, self.virtual_machine.id, MemorySnapshot,\n 'TestSnapshot', 'Display Text')\n", (39861, 39954), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((41028, 41042), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (41038, 41042), False, 'import time\n'), ((41077, 41168), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id,\n listall=True)\n', (41092, 41168), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((41739, 41812), 'marvin.lib.base.VmSnapshot.revertToSnapshot', 'VmSnapshot.revertToSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (41766, 41812), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((42742, 42833), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id,\n listall=True)\n', (42757, 42833), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((43187, 43260), 'marvin.lib.base.VmSnapshot.deleteVMSnapshot', 'VmSnapshot.deleteVMSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (43214, 43260), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((43295, 43309), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (43305, 43309), False, 'import time\n'), ((43344, 43436), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'listall': '(False)'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id,\n listall=False)\n', (43359, 43436), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((44025, 44072), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'id': 'self.volume.id'}), '(self.apiclient, id=self.volume.id)\n', (44037, 44072), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((44626, 44640), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (44636, 44640), False, 'import time\n'), ((44958, 45046), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'id': 'volume.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id, id=\n volume.id)\n', (44969, 45046), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((45549, 45637), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'id': 'volume.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id, id=\n volume.id)\n', (45560, 45637), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((46089, 46191), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine2.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine2.id,\n type='ROOT', listall=True)\n", (46101, 46191), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((46839, 46869), 'marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd', 'resizeVolume.resizeVolumeCmd', ([], {}), '()\n', (46867, 46869), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((47013, 47054), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (47024, 47054), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((47797, 47827), 'marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd', 'resizeVolume.resizeVolumeCmd', ([], {}), '()\n', (47825, 47827), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((47971, 48012), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (47982, 48012), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((49059, 49100), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (49070, 49100), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((49625, 49655), 'marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd', 'resizeVolume.resizeVolumeCmd', ([], {}), '()\n', (49653, 49655), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((49831, 49872), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (49842, 49872), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((50615, 50645), 'marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd', 'resizeVolume.resizeVolumeCmd', ([], {}), '()\n', (50643, 50645), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((50821, 50862), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (50832, 50862), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((51765, 51806), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (51776, 51806), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((52712, 52726), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (52722, 52726), False, 'import time\n'), ((52876, 52966), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'id': 'volume_2.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id, id=\n volume_2.id)\n', (52887, 52966), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((53332, 53346), 'time.sleep', 'time.sleep', (['(90)'], {}), '(90)\n', (53342, 53346), False, 'import time\n'), ((53496, 53586), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'id': 'volume_2.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id, id=\n volume_2.id)\n', (53507, 53586), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((54069, 54099), 'marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd', 'resizeVolume.resizeVolumeCmd', ([], {}), '()\n', (54097, 54099), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((54282, 54330), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'self.volume_1.id'}), '(self.apiclient, id=self.volume_1.id)\n', (54293, 54330), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((55101, 55131), 'marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd', 'resizeVolume.resizeVolumeCmd', ([], {}), '()\n', (55129, 55131), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((55314, 55362), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'self.volume_1.id'}), '(self.apiclient, id=self.volume_1.id)\n', (55325, 55362), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((56293, 56341), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'self.volume_1.id'}), '(self.apiclient, id=self.volume_1.id)\n', (56304, 56341), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((57112, 57207), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'id': 'self.volume_2.id'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id, id=\n self.volume_2.id)\n', (57123, 57207), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((57532, 57562), 'marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd', 'resizeVolume.resizeVolumeCmd', ([], {}), '()\n', (57560, 57562), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((57745, 57793), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'self.volume_2.id'}), '(self.apiclient, id=self.volume_2.id)\n', (57756, 57793), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((58564, 58594), 'marvin.cloudstackAPI.resizeVolume.resizeVolumeCmd', 'resizeVolume.resizeVolumeCmd', ([], {}), '()\n', (58592, 58594), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((58777, 58825), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'self.volume_2.id'}), '(self.apiclient, id=self.volume_2.id)\n', (58788, 58825), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((59756, 59804), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'self.volume_2.id'}), '(self.apiclient, id=self.volume_2.id)\n', (59767, 59804), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((60546, 60669), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'self.volume_2.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=self.volume_2.id, account=self.\n account.name, domainid=self.account.domainid)\n', (60561, 60669), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((61837, 61878), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'id': 'volume.id'}), '(self.apiclient, id=volume.id)\n', (61848, 61878), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((62949, 63059), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'self.volume.id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, self.volume.id, account=self.account.name,\n domainid=self.account.domainid)\n', (62964, 63059), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((63982, 64023), 'marvin.lib.base.Snapshot.delete', 'Snapshot.delete', (['snapshot', 'self.apiclient'], {}), '(snapshot, self.apiclient)\n', (63997, 64023), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((64735, 64801), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'vm.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=vm.id, listall=True)\n', (64747, 64801), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((64954, 65075), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient', 'list_volumes_of_vm[0].id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, list_volumes_of_vm[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (64969, 65075), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((66191, 66292), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall=True)\n", (66202, 66292), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((67439, 67518), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.vm_migrate.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=self.vm_migrate.id, listall=True)\n', (67451, 67518), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((68607, 68703), 'marvin.lib.base.Volume.migrate', 'Volume.migrate', (['self.apiclient'], {'volumeid': 'self.volume.id', 'storageid': 'self.primary_storage2.id'}), '(self.apiclient, volumeid=self.volume.id, storageid=self.\n primary_storage2.id)\n', (68621, 68703), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((70270, 70372), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type\n ='ROOT', listall=True)\n", (70282, 70372), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((70456, 70576), 'marvin.lib.base.Snapshot.create', 'Snapshot.create', (['self.apiclient'], {'volume_id': 'volume1[0].id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, volume_id=volume1[0].id, account=self.\n account.name, domainid=self.account.domainid)\n', (70471, 70576), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((71617, 71651), 'marvin.lib.base.Volume.delete', 'Volume.delete', (['vol', 'self.apiclient'], {}), '(vol, self.apiclient)\n', (71630, 71651), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((71957, 72058), 'marvin.lib.base.Volume.list', 'Volume.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'type': '"""ROOT"""', 'listall': '(True)'}), "(self.apiclient, virtualmachineid=self.virtual_machine.id, type=\n 'ROOT', listall=True)\n", (71968, 72058), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((74342, 74372), 'marvin.cloudstackAPI.createVolume.createVolumeCmd', 'createVolume.createVolumeCmd', ([], {}), '()\n', (74370, 74372), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((74762, 74822), 'subprocess.check_output', 'subprocess.check_output', (["['storpool_confshow', 'CLUSTER_ID']"], {}), "(['storpool_confshow', 'CLUSTER_ID'])\n", (74785, 74822), False, 'import subprocess\n'), ((74927, 74955), 'marvin.lib.common.list_clusters', 'list_clusters', (['cls.apiclient'], {}), '(cls.apiclient)\n', (74940, 74955), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((75336, 75396), 'subprocess.check_output', 'subprocess.check_output', (["['storpool_confshow', 'CLUSTER_ID']"], {}), "(['storpool_confshow', 'CLUSTER_ID'])\n", (75359, 75396), False, 'import subprocess\n'), ((75501, 75529), 'marvin.lib.common.list_clusters', 'list_clusters', (['cls.apiclient'], {}), '(cls.apiclient)\n', (75514, 75529), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((75964, 75988), 'marvin.cloudstackAPI.listHosts.listHostsCmd', 'listHosts.listHostsCmd', ([], {}), '()\n', (75986, 75988), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((76536, 76570), 'marvin.cloudstackAPI.createTemplate.createTemplateCmd', 'createTemplate.createTemplateCmd', ([], {}), '()\n', (76568, 76570), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((4816, 4973), 'storpool.sptypes.VolumeTemplateCreateDesc', 'sptypes.VolumeTemplateCreateDesc', ([], {'name': "storpool_primary_storage['name']", 'placeAll': '"""virtual"""', 'placeTail': '"""virtual"""', 'placeHead': '"""virtual"""', 'replication': '(1)'}), "(name=storpool_primary_storage['name'],\n placeAll='virtual', placeTail='virtual', placeHead='virtual', replication=1\n )\n", (4848, 4973), False, 'from storpool import sptypes\n'), ((5076, 5135), 'marvin.lib.base.StoragePool.create', 'StoragePool.create', (['cls.apiclient', 'storpool_primary_storage'], {}), '(cls.apiclient, storpool_primary_storage)\n', (5094, 5135), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((5917, 5986), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', 'storpool_service_offerings_ssd'], {}), '(cls.apiclient, storpool_service_offerings_ssd)\n', (5939, 5986), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((6134, 6170), 'pprint.pformat', 'pprint.pformat', (['cls.service_offering'], {}), '(cls.service_offering)\n', (6148, 6170), False, 'import pprint\n'), ((6921, 7079), 'storpool.sptypes.VolumeTemplateCreateDesc', 'sptypes.VolumeTemplateCreateDesc', ([], {'name': "storpool_primary_storage2['name']", 'placeAll': '"""virtual"""', 'placeTail': '"""virtual"""', 'placeHead': '"""virtual"""', 'replication': '(1)'}), "(name=storpool_primary_storage2['name'],\n placeAll='virtual', placeTail='virtual', placeHead='virtual', replication=1\n )\n", (6953, 7079), False, 'from storpool import sptypes\n'), ((7183, 7243), 'marvin.lib.base.StoragePool.create', 'StoragePool.create', (['cls.apiclient', 'storpool_primary_storage2'], {}), '(cls.apiclient, storpool_primary_storage2)\n', (7201, 7243), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((7942, 8012), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', 'storpool_service_offerings_ssd2'], {}), '(cls.apiclient, storpool_service_offerings_ssd2)\n', (7964, 8012), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((9640, 9735), 'marvin.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['cls.apiclient'], {'account': 'cls.account.name', 'domainid': 'cls.account.domainid'}), '(cls.apiclient, account=cls.account.name, domainid=cls.\n account.domainid)\n', (9658, 9735), False, 'from marvin.lib.base import Account, Cluster, Configurations, ServiceOffering, Snapshot, StoragePool, Template, VirtualMachine, VmSnapshot, Volume, SecurityGroup, Role\n'), ((12407, 12453), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (12424, 12453), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList, is_snapshot_on_nfs, isAlmostEqual\n'), ((15701, 15755), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (15753, 15755), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((18581, 18635), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (18633, 18635), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((20127, 20181), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (20179, 20181), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((21897, 21951), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (21949, 21951), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((25076, 25130), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (25128, 25130), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((29288, 29342), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (29340, 29342), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((30459, 30513), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (30511, 30513), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((32833, 32887), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (32885, 32887), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((33968, 34022), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (34020, 34022), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((35943, 35997), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (35995, 35997), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((60762, 60816), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (60814, 60816), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((63151, 63205), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (63203, 63205), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((65166, 65220), 'marvin.cloudstackAPI.getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', 'getVolumeSnapshotDetails.getVolumeSnapshotDetailsCmd', ([], {}), '()\n', (65218, 65220), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((75009, 75059), 'marvin.lib.common.list_configurations', 'list_configurations', (['cls.apiclient'], {'clusterid': 'c.id'}), '(cls.apiclient, clusterid=c.id)\n', (75028, 75059), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((75583, 75633), 'marvin.lib.common.list_configurations', 'list_configurations', (['cls.apiclient'], {'clusterid': 'c.id'}), '(cls.apiclient, clusterid=c.id)\n', (75602, 75633), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((67999, 68051), 'marvin.lib.common.list_volumes', 'list_volumes', (['self.apiclient'], {'virtualmachineid': 'vm.id'}), '(self.apiclient, virtualmachineid=vm.id)\n', (68011, 68051), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_disk_offering, list_hosts, list_snapshots, list_storage_pools, list_volumes, list_virtual_machines, list_configurations, list_service_offering, list_clusters, list_zones\n'), ((76659, 76671), 'marvin.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (76669, 76671), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList, is_snapshot_on_nfs, isAlmostEqual\n'), ((76855, 76883), 'marvin.cloudstackAPI.listOsTypes.listOsTypesCmd', 'listOsTypes.listOsTypesCmd', ([], {}), '()\n', (76881, 76883), False, 'from marvin.cloudstackAPI import listOsTypes, listTemplates, listHosts, createTemplate, createVolume, getVolumeSnapshotDetails, resizeVolume, listZones\n'), ((10875, 10887), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (10885, 10887), False, 'import uuid\n'), ((11292, 11304), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (11302, 11304), False, 'import uuid\n'), ((11703, 11715), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (11713, 11715), False, 'import uuid\n'), ((14078, 14090), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (14088, 14090), False, 'import uuid\n'), ((17207, 17219), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (17217, 17219), False, 'import uuid\n'), ((37897, 37909), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (37907, 37909), False, 'import uuid\n'), ((64383, 64395), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (64393, 64395), False, 'import uuid\n'), ((66670, 66682), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (66680, 66682), False, 'import uuid\n'), ((69220, 69232), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (69230, 69232), False, 'import uuid\n'), ((69939, 69951), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (69949, 69951), False, 'import uuid\n'), ((72436, 72448), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (72446, 72448), False, 'import uuid\n'), ((73620, 73632), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (73630, 73632), False, 'import uuid\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import (ServiceOffering,
VirtualMachine,
Account)
from marvin.lib.common import get_test_template, get_zone, list_virtual_machines
from marvin.lib.utils import cleanup_resources
from nose.plugins.attrib import attr
from marvin.codes import FAILED
import random
import string
class TestDeployVmWithUserData(cloudstackTestCase):
"""Tests for UserData
"""
@classmethod
def setUpClass(cls):
testClient = super(TestDeployVmWithUserData, cls).getClsTestClient()
cls.apiClient = testClient.getApiClient()
cls.services = testClient.getParsedTestDataConfig()
cls.zone = get_zone(cls.apiClient, testClient.getZoneForTests())
cls.hypervisor = testClient.getHypervisorInfo()
if cls.zone.localstorageenabled:
#For devcloud since localstroage is enabled
cls.services["service_offerings"]["tiny"]["storagetype"] = "local"
cls.service_offering = ServiceOffering.create(
cls.apiClient,
cls.services["service_offerings"]["tiny"]
)
cls.account = Account.create(cls.apiClient, services=cls.services["account"])
cls.cleanup = [cls.account]
cls.template = get_test_template(
cls.apiClient,
cls.zone.id,
cls.hypervisor
)
if cls.template == FAILED:
assert False, "get_test_template() failed to return template"
cls.debug("Successfully created account: %s, id: \
%s" % (cls.account.name,\
cls.account.id))
# Generate userdata of 2500 bytes. This is larger than the 2048 bytes limit.
# CS however allows for upto 4K bytes in the code. So this must succeed.
# Overall, the query length must not exceed 4K, for then the json decoder
# will fail this operation at the marvin client side itcls.
user_data = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(2500))
cls.services["virtual_machine"]["userdata"] = user_data
def setup(self):
self.hypervisor = self.testClient.getHypervisorInfo()
@attr(tags=["devcloud", "basic", "advanced", "post"], required_hardware="true")
def test_deployvm_userdata_post(self):
"""Test userdata as POST, size > 2k
"""
deployVmResponse = VirtualMachine.create(
self.apiClient,
services=self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id,
method='POST'
)
vms = list_virtual_machines(
self.apiClient,
account=self.account.name,
domainid=self.account.domainid,
id=deployVmResponse.id
)
self.assertTrue(len(vms) > 0, "There are no Vms deployed in the account %s" % self.account.name)
vm = vms[0]
self.assertTrue(vm.id == str(deployVmResponse.id), "Vm deployed is different from the test")
self.assertTrue(vm.state == "Running", "VM is not in Running state")
@attr(tags=["devcloud", "basic", "advanced"], required_hardware="true")
def test_deployvm_userdata(self):
"""Test userdata as GET, size > 2k
"""
deployVmResponse = VirtualMachine.create(
self.apiClient,
services=self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id
)
vms = list_virtual_machines(
self.apiClient,
account=self.account.name,
domainid=self.account.domainid,
id=deployVmResponse.id
)
self.assertTrue(len(vms) > 0, "There are no Vms deployed in the account %s" % self.account.name)
vm = vms[0]
self.assertTrue(vm.id == str(deployVmResponse.id), "Vm deployed is different from the test")
self.assertTrue(vm.state == "Running", "VM is not in Running state")
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.apiClient, cls.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
| [
"marvin.lib.base.Account.create",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.common.list_virtual_machines",
"marvin.lib.base.VirtualMachine.create",
"marvin.lib.common.get_test_template"
] | [((3078, 3156), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'basic', 'advanced', 'post']", 'required_hardware': '"""true"""'}), "(tags=['devcloud', 'basic', 'advanced', 'post'], required_hardware='true')\n", (3082, 3156), False, 'from nose.plugins.attrib import attr\n'), ((4142, 4212), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['devcloud', 'basic', 'advanced']", 'required_hardware': '"""true"""'}), "(tags=['devcloud', 'basic', 'advanced'], required_hardware='true')\n", (4146, 4212), False, 'from nose.plugins.attrib import attr\n'), ((1876, 1961), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiClient', "cls.services['service_offerings']['tiny']"], {}), "(cls.apiClient, cls.services['service_offerings']['tiny']\n )\n", (1898, 1961), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account\n'), ((2013, 2076), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiClient'], {'services': "cls.services['account']"}), "(cls.apiClient, services=cls.services['account'])\n", (2027, 2076), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account\n'), ((2136, 2197), 'marvin.lib.common.get_test_template', 'get_test_template', (['cls.apiClient', 'cls.zone.id', 'cls.hypervisor'], {}), '(cls.apiClient, cls.zone.id, cls.hypervisor)\n', (2153, 2197), False, 'from marvin.lib.common import get_test_template, get_zone, list_virtual_machines\n'), ((3283, 3548), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiClient'], {'services': "self.services['virtual_machine']", 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'method': '"""POST"""'}), "(self.apiClient, services=self.services[\n 'virtual_machine'], accountid=self.account.name, domainid=self.account.\n domainid, serviceofferingid=self.service_offering.id, templateid=self.\n template.id, zoneid=self.zone.id, method='POST')\n", (3304, 3548), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account\n'), ((3654, 3779), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiClient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'id': 'deployVmResponse.id'}), '(self.apiClient, account=self.account.name, domainid=\n self.account.domainid, id=deployVmResponse.id)\n', (3675, 3779), False, 'from marvin.lib.common import get_test_template, get_zone, list_virtual_machines\n'), ((4333, 4583), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiClient'], {'services': "self.services['virtual_machine']", 'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id'}), "(self.apiClient, services=self.services[\n 'virtual_machine'], accountid=self.account.name, domainid=self.account.\n domainid, serviceofferingid=self.service_offering.id, templateid=self.\n template.id, zoneid=self.zone.id)\n", (4354, 4583), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account\n'), ((4677, 4802), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiClient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'id': 'deployVmResponse.id'}), '(self.apiClient, account=self.account.name, domainid=\n self.account.domainid, id=deployVmResponse.id)\n', (4698, 4802), False, 'from marvin.lib.common import get_test_template, get_zone, list_virtual_machines\n'), ((5266, 5311), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiClient', 'cls.cleanup'], {}), '(cls.apiClient, cls.cleanup)\n', (5283, 5311), False, 'from marvin.lib.utils import cleanup_resources\n'), ((2848, 2901), 'random.choice', 'random.choice', (['(string.ascii_uppercase + string.digits)'], {}), '(string.ascii_uppercase + string.digits)\n', (2861, 2901), False, 'import random\n')] |
#!/usr/bin/env python
# encoding: utf-8
# Created by <NAME> on 2016-05-10 20:17:52
# Licensed under a 3-clause BSD license.
# Revision History:
# Initial Version: 2016-05-10 20:17:52 by <NAME>
# Last Modified On: 2016-05-10 20:17:52 by Brian
from __future__ import absolute_import, division, print_function
import os
import sys
import warnings
import random
import itertools
import requests
import PIL
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import EllipseCollection
from astropy.io import fits
import marvin
from marvin.tools.mixins import MMAMixIn
from marvin.core.exceptions import MarvinError, MarvinUserWarning
from marvin.utils.general import (getWCSFromPng, Bundle, Cutout, target_is_mastar,
get_plates, check_versions)
try:
from sdss_access import HttpAccess
except ImportError:
HttpAccess = None
if sys.version_info.major == 2:
from cStringIO import StringIO as stringio
else:
from io import BytesIO as stringio
__all__ = ['Image']
class Image(MMAMixIn):
'''A class to interface with MaNGA images.
This class represents a MaNGA image object initialised either
from a file, or remotely via the Marvin API.
TODO: what kinds of images should this handle? optical, maps, nsa preimaging?
TODO: should this be subclasses into different kinds of images? DRPImage, MapImage, NSAImage?
Attributes:
header (`astropy.io.fits.Header`):
The header of the datacube.
ra,dec (float):
Coordinates of the target.
wcs (`astropy.wcs.WCS`):
The WCS solution for this plate
bundle (object):
A Bundle of fibers associated with the IFU
'''
def __init__(self, input=None, filename=None, mangaid=None, plateifu=None,
mode=None, data=None, release=None, download=None):
MMAMixIn.__init__(self, input=input, filename=filename, mangaid=mangaid,
plateifu=plateifu, mode=mode, data=data, release=release,
download=download, ignore_db=True)
if self.data_origin == 'file':
self._load_image_from_file()
elif self.data_origin == 'db':
raise MarvinError('Images cannot currently be accessed from the db')
elif self.data_origin == 'api':
self._load_image_from_api()
# initialize attributes
self._init_attributes()
# create the hex bundle
if self.ra and self.dec:
self.bundle = Bundle(self.ra, self.dec, plateifu=self.plateifu, size=int(str(self.ifu)[:-2]))
def __repr__(self):
'''Image representation.'''
return '<Marvin Image (plateifu={0}, mode={1}, data-origin={2})>'.format(repr(self.plateifu), repr(self.mode), repr(self.data_origin))
def _init_attributes(self):
''' Initialize some attributes '''
self.ra = None
self.dec = None
# try to create a header
try:
self.header = fits.header.Header(self.data.info)
except Exception:
warnings.warn('No proper header found image', MarvinUserWarning)
self.header = None
# try to set the RA, Dec
if self.header:
self.ra = float(self.header["RA"]) if 'RA' in self.header else None
self.dec = float(self.header["DEC"]) if 'DEC' in self.header else None
# try to set the WCS
try:
self.wcs = getWCSFromPng(image=self.data)
except MarvinError:
self.wcs = None
warnings.warn('No proper WCS info for this image')
def _get_image_dir(self):
''' Gets the correct images directory by release and mastar target '''
# all images in MPL-4 are in stack dirs
if self.release == 'MPL-4':
return 'stack'
# get the appropriate image directory
is_mastar = target_is_mastar(self.plateifu, drpver=self._drpver)
image_dir = 'mastar' if is_mastar else 'stack'
return image_dir
def _getFullPath(self):
"""Returns the full path of the file in the tree."""
if not self.plateifu:
return None
plate, ifu = self.plateifu.split('-')
dir3d = self._get_image_dir()
# use version to toggle old/new images path
isMPL8 = check_versions(self._drpver, 'v2_5_3')
name = 'mangaimagenew' if isMPL8 else 'mangaimage'
return super(Image, self)._getFullPath(name, ifu=ifu, dir3d=dir3d,
drpver=self._drpver, plate=plate)
def download(self):
"""Downloads the image using sdss_access - Rsync,"""
if not self.plateifu:
return None
plate, ifu = self.plateifu.split('-')
dir3d = self._get_image_dir()
# use version to toggle old/new images path
isMPL8 = check_versions(self._drpver, 'v2_5_3')
name = 'mangaimagenew' if isMPL8 else 'mangaimage'
return super(Image, self).download(name, ifu=ifu, dir3d=dir3d,
drpver=self._drpver, plate=plate)
def _load_image_from_file(self):
''' Load an image from a local file '''
filepath = self._getFullPath()
if os.path.exists(filepath):
self._filepath = filepath
self.data = self._open_image(filepath)
else:
raise MarvinError('Error: local filepath {0} does not exist. '.format(filepath))
def _load_image_from_api(self):
''' Load an image from a remote location '''
filepath = self._getFullPath()
response = requests.get(self.url)
if not response.ok:
raise MarvinError('Error: remote filepath {0} does not exist'.format(filepath))
else:
fileobj = stringio(response.content)
self.data = self._open_image(fileobj, filepath=self.url)
@property
def url(self):
if not HttpAccess:
raise MarvinError('sdss_access not installed')
filepath = self._getFullPath()
http = HttpAccess(verbose=False)
url = http.url("", full=filepath)
return url
@staticmethod
def _open_image(fileobj, filepath=None):
''' Open the Image using PIL '''
try:
image = PIL.Image.open(fileobj)
except IOError as e:
warnings.warn('Error: cannot open image', MarvinUserWarning)
image = None
else:
image.filename = filepath or fileobj
return image
def show(self):
''' Show the image '''
if self.data:
self.data.show()
def save(self, filename, filetype='png', **kwargs):
''' Save the image to a file
This only saves the original image. To save the Matplotlib plot, use
the savefig method on the matplotlib.pyplot.figure object
Parameters:
filename (str):
The filename of the output image
filetype (str):
The filetype, e.g. png
kwargs:
Additional keyword arguments to the PIL.Image.save method
'''
__, fileext = os.path.splitext(filename)
assert filetype or fileext, 'Filename must have an extension or specify the filetype'
if self.data:
self.data.save(filename, format=filetype, **kwargs)
def plot(self, return_figure=True, dpi=100, with_axes=None, fibers=None, skies=None, **kwargs):
''' Creates a Matplotlib plot the image
Parameters:
fibers (bool):
If True, overlays the fiber positions. Default is False.
skies (bool):
If True, overlays the sky fibers if possible. Default is False.
return_figure (bool):
If True, returns the figure axis object. Default is True
dpi (int):
The dots per inch for the matplotlib figure
with_axes (bool):
If True, plots the image with axes
kwargs:
Keyword arguments for overlay_fibers and overlay_skies
'''
pix_size = np.array(self.data.size)
figsize = np.ceil(pix_size / dpi)
if with_axes:
fig = plt.figure()
ax = plt.subplot(projection=self.wcs)
ax.set_xlabel('Declination')
ax.set_ylabel('Right Ascension')
aspect = None
else:
fig = plt.figure(figsize=figsize)
ax = fig.add_axes([0., 0., 1., 1.], projection=self.wcs)
ax.set_axis_off()
plt.axis('off')
aspect = 'auto'
ax.imshow(self.data, origin='lower', aspect=aspect)
# overlay the IFU fibers
if fibers:
self.overlay_fibers(ax, return_figure=return_figure, skies=skies, **kwargs)
if return_figure:
return ax
def overlay_fibers(self, ax, diameter=None, skies=None, return_figure=True, **kwargs):
""" Overlay the individual fibers within an IFU on a plot.
Parameters:
ax (Axis):
The matplotlib axis object
diameter (float):
The fiber diameter in arcsec. Default is 2".
skies (bool):
Set to True to additionally overlay the sky fibers. Default if False
return_figure (bool):
If True, returns the figure axis object. Default is True
kwargs:
Any keyword arguments accepted by Matplotlib EllipseCollection
"""
if self.wcs is None:
raise MarvinError('No WCS found. Cannot overlay fibers.')
# check the diameter
if diameter:
assert isinstance(diameter, (float, int)), 'diameter must be a number'
diameter = (diameter or 2.0) / float(self.header['SCALE'])
# get the fiber pixel coordinates
fibers = self.bundle.fibers[:, [1, 2]]
fiber_pix = self.wcs.wcs_world2pix(fibers, 1)
# some matplotlib kwargs
kwargs['edgecolor'] = kwargs.get('edgecolor', 'Orange')
kwargs['facecolor'] = kwargs.get('facecolor', 'none')
kwargs['linewidth'] = kwargs.get('linewidth', 0.4)
ec = EllipseCollection(diameter, diameter, 0.0, units='xy',
offsets=fiber_pix, transOffset=ax.transData,
**kwargs)
ax.add_collection(ec)
# overlay the sky fibers
if skies:
self.overlay_skies(ax, diameter=diameter, return_figure=return_figure, **kwargs)
if return_figure:
return ax
def overlay_hexagon(self, ax, return_figure=True, **kwargs):
""" Overlay the IFU hexagon on a plot
Parameters:
ax (Axis):
The matplotlib axis object
return_figure (bool):
If True, returns the figure axis object. Default is True
kwargs:
Any keyword arguments accepted by Matplotlib plot
"""
if self.wcs is None:
raise MarvinError('No WCS found. Cannot overlay hexagon.')
# get IFU hexagon pixel coordinates
hexagon_pix = self.wcs.wcs_world2pix(self.bundle.hexagon, 1)
# reconnect the last point to the first point.
hexagon_pix = np.concatenate((hexagon_pix, [hexagon_pix[0]]), axis=0)
# some matplotlib kwargs
kwargs['color'] = kwargs.get('color', 'magenta')
kwargs['linestyle'] = kwargs.get('linestyle', 'solid')
kwargs['linewidth'] = kwargs.get('linewidth', 0.8)
ax.plot(hexagon_pix[:, 0], hexagon_pix[:, 1], **kwargs)
if return_figure:
return ax
def overlay_skies(self, ax, diameter=None, return_figure=True, **kwargs):
""" Overlay the sky fibers on a plot
Parameters:
ax (Axis):
The matplotlib axis object
diameter (float):
The fiber diameter in arcsec
return_figure (bool):
If True, returns the figure axis object. Default is True
kwargs:
Any keyword arguments accepted by Matplotlib EllipseCollection
"""
if self.wcs is None:
raise MarvinError('No WCS found. Cannot overlay sky fibers.')
# check for sky coordinates
if self.bundle.skies is None:
self.bundle.get_sky_coordinates()
# check the diameter
if diameter:
assert isinstance(diameter, (float, int)), 'diameter must be a number'
diameter = (diameter or 2.0) / float(self.header['SCALE'])
# get sky fiber pixel positions
fiber_pix = self.wcs.wcs_world2pix(self.bundle.skies, 1)
outside_range = ((fiber_pix < 0) | (fiber_pix > self.data.size[0])).any()
if outside_range:
raise MarvinError('Cannot overlay sky fibers. Image is too small. '
'Please retrieve a bigger image cutout')
# some matplotlib kwargs
kwargs['edgecolor'] = kwargs.get('edgecolor', 'Orange')
kwargs['facecolor'] = kwargs.get('facecolor', 'none')
kwargs['linewidth'] = kwargs.get('linewidth', 0.7)
# draw the sky fibers
ec = EllipseCollection(diameter, diameter, 0.0, units='xy',
offsets=fiber_pix, transOffset=ax.transData,
**kwargs)
ax.add_collection(ec)
# Add a larger circle to help identify the sky fiber locations in large images.
if (self.data.size[0] > 1000) or (self.data.size[1] > 1000):
ec = EllipseCollection(diameter * 5, diameter * 5, 0.0, units='xy',
offsets=fiber_pix, transOffset=ax.transData,
**kwargs)
ax.add_collection(ec)
if return_figure:
return ax
def get_new_cutout(self, width, height, scale=None, **kwargs):
''' Get a new Image Cutout using Skyserver
Replaces the current Image with a new image cutout. The
data, header, and wcs attributes are updated accordingly.
Parameters:
width (int):
Cutout image width in arcsec
height (int):
Cutout image height in arcsec
scale (float):
arcsec/pixel scale of the image
kwargs:
Any additional keywords for Cutout
'''
cutout = Cutout(self.ra, self.dec, width, height, scale=scale, **kwargs)
self.data = cutout.image
self._init_attributes()
@classmethod
def from_list(cls, values, release=None):
''' Generate a list of Marvin Image objects
Class method to generate a list of Marvin Images from an
input list of targets
Parameters:
values (list):
A list of target ids (i.e. plateifus, mangaids, or filenames)
release (str):
The release of Images to get
Returns:
a list of Marvin Image objects
Example:
>>> from marvin.tools.image import Image
>>> targets = ['8485-1901', '7443-1201']
>>> images = Image.from_list(targets)
'''
images = []
for item in values:
images.append(cls(item, release=release))
return images
@classmethod
def by_plate(cls, plateid, minis=None, release=None):
''' Generate a list of Marvin Images by plate
Class method to generate a list of Marvin Images from
a single plateid.
Parameters:
plateid (int):
The plate id to grab
minis (bool):
If True, includes the mini-bundles
release (str):
The release of Images to get
Returns:
a list of Marvin Image objects
Example:
>>> from marvin.tools.image import Image
>>> images = Image.by_plate(8485)
'''
ifus = cls._get_ifus(minis=minis)
plateifus = ['{0}-{1}'.format(plateid, i) for i in ifus]
images = cls.from_list(plateifus, release=release)
return images
@classmethod
def get_random(cls, num=5, minis=None, release=None):
''' Generate a set of random Marvin Images
Class method to generate a random list of Marvin Images
Parameters:
num (int):
The number to grab. Default is 5
minis (bool):
If True, includes the mini-bundles
release (str):
The release of Images to get
Returns:
a list of Marvin Image objects
Example:
>>> from marvin.tools.image import Image
>>> images = Image.get_random(5)
'''
ifus = cls._get_ifus(minis=minis)
plates = get_plates(release=release)
rand_samp = random.sample(list(itertools.product(map(str, plates), ifus)), num)
plateifus = ['-'.join(r) for r in rand_samp]
images = cls.from_list(plateifus, release=release)
return images
def getCube(self):
"""Returns the :class:`~marvin.tools.cube.Cube` for this Image."""
return marvin.tools.cube.Cube(plateifu=self.plateifu,
release=self.release)
def getMaps(self, **kwargs):
"""Retrieves the DAP :class:`~marvin.tools.maps.Maps` for this Image.
If called without additional ``kwargs``, :func:`getMaps` will initialize
the :class:`~marvin.tools.maps.Maps` using the ``plateifu`` of this
:class:`~marvin.tools.image.Image`. Otherwise, the ``kwargs`` will be
passed when initialising the :class:`~marvin.tools.maps.Maps`.
"""
if len(kwargs.keys()) == 0 or 'filename' not in kwargs:
kwargs.update({'plateifu': self.plateifu, 'release': self._release})
maps = marvin.tools.maps.Maps(**kwargs)
return maps
| [
"marvin.utils.general.getWCSFromPng",
"marvin.tools.maps.Maps",
"marvin.tools.mixins.MMAMixIn.__init__",
"marvin.utils.general.target_is_mastar",
"marvin.utils.general.Cutout",
"marvin.core.exceptions.MarvinError",
"marvin.tools.cube.Cube",
"marvin.utils.general.check_versions",
"marvin.utils.genera... | [((1903, 2077), 'marvin.tools.mixins.MMAMixIn.__init__', 'MMAMixIn.__init__', (['self'], {'input': 'input', 'filename': 'filename', 'mangaid': 'mangaid', 'plateifu': 'plateifu', 'mode': 'mode', 'data': 'data', 'release': 'release', 'download': 'download', 'ignore_db': '(True)'}), '(self, input=input, filename=filename, mangaid=mangaid,\n plateifu=plateifu, mode=mode, data=data, release=release, download=\n download, ignore_db=True)\n', (1920, 2077), False, 'from marvin.tools.mixins import MMAMixIn\n'), ((3935, 3987), 'marvin.utils.general.target_is_mastar', 'target_is_mastar', (['self.plateifu'], {'drpver': 'self._drpver'}), '(self.plateifu, drpver=self._drpver)\n', (3951, 3987), False, 'from marvin.utils.general import getWCSFromPng, Bundle, Cutout, target_is_mastar, get_plates, check_versions\n'), ((4368, 4406), 'marvin.utils.general.check_versions', 'check_versions', (['self._drpver', '"""v2_5_3"""'], {}), "(self._drpver, 'v2_5_3')\n", (4382, 4406), False, 'from marvin.utils.general import getWCSFromPng, Bundle, Cutout, target_is_mastar, get_plates, check_versions\n'), ((4919, 4957), 'marvin.utils.general.check_versions', 'check_versions', (['self._drpver', '"""v2_5_3"""'], {}), "(self._drpver, 'v2_5_3')\n", (4933, 4957), False, 'from marvin.utils.general import getWCSFromPng, Bundle, Cutout, target_is_mastar, get_plates, check_versions\n'), ((5303, 5327), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (5317, 5327), False, 'import os\n'), ((5674, 5696), 'requests.get', 'requests.get', (['self.url'], {}), '(self.url)\n', (5686, 5696), False, 'import requests\n'), ((6124, 6149), 'sdss_access.HttpAccess', 'HttpAccess', ([], {'verbose': '(False)'}), '(verbose=False)\n', (6134, 6149), False, 'from sdss_access import HttpAccess\n'), ((7222, 7248), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (7238, 7248), False, 'import os\n'), ((8201, 8225), 'numpy.array', 'np.array', (['self.data.size'], {}), '(self.data.size)\n', (8209, 8225), True, 'import numpy as np\n'), ((8244, 8267), 'numpy.ceil', 'np.ceil', (['(pix_size / dpi)'], {}), '(pix_size / dpi)\n', (8251, 8267), True, 'import numpy as np\n'), ((10295, 10408), 'matplotlib.collections.EllipseCollection', 'EllipseCollection', (['diameter', 'diameter', '(0.0)'], {'units': '"""xy"""', 'offsets': 'fiber_pix', 'transOffset': 'ax.transData'}), "(diameter, diameter, 0.0, units='xy', offsets=fiber_pix,\n transOffset=ax.transData, **kwargs)\n", (10312, 10408), False, 'from matplotlib.collections import EllipseCollection\n'), ((11389, 11444), 'numpy.concatenate', 'np.concatenate', (['(hexagon_pix, [hexagon_pix[0]])'], {'axis': '(0)'}), '((hexagon_pix, [hexagon_pix[0]]), axis=0)\n', (11403, 11444), True, 'import numpy as np\n'), ((13334, 13447), 'matplotlib.collections.EllipseCollection', 'EllipseCollection', (['diameter', 'diameter', '(0.0)'], {'units': '"""xy"""', 'offsets': 'fiber_pix', 'transOffset': 'ax.transData'}), "(diameter, diameter, 0.0, units='xy', offsets=fiber_pix,\n transOffset=ax.transData, **kwargs)\n", (13351, 13447), False, 'from matplotlib.collections import EllipseCollection\n'), ((14573, 14636), 'marvin.utils.general.Cutout', 'Cutout', (['self.ra', 'self.dec', 'width', 'height'], {'scale': 'scale'}), '(self.ra, self.dec, width, height, scale=scale, **kwargs)\n', (14579, 14636), False, 'from marvin.utils.general import getWCSFromPng, Bundle, Cutout, target_is_mastar, get_plates, check_versions\n'), ((16997, 17024), 'marvin.utils.general.get_plates', 'get_plates', ([], {'release': 'release'}), '(release=release)\n', (17007, 17024), False, 'from marvin.utils.general import getWCSFromPng, Bundle, Cutout, target_is_mastar, get_plates, check_versions\n'), ((17362, 17430), 'marvin.tools.cube.Cube', 'marvin.tools.cube.Cube', ([], {'plateifu': 'self.plateifu', 'release': 'self.release'}), '(plateifu=self.plateifu, release=self.release)\n', (17384, 17430), False, 'import marvin\n'), ((18063, 18095), 'marvin.tools.maps.Maps', 'marvin.tools.maps.Maps', ([], {}), '(**kwargs)\n', (18085, 18095), False, 'import marvin\n'), ((3040, 3074), 'astropy.io.fits.header.Header', 'fits.header.Header', (['self.data.info'], {}), '(self.data.info)\n', (3058, 3074), False, 'from astropy.io import fits\n'), ((3496, 3526), 'marvin.utils.general.getWCSFromPng', 'getWCSFromPng', ([], {'image': 'self.data'}), '(image=self.data)\n', (3509, 3526), False, 'from marvin.utils.general import getWCSFromPng, Bundle, Cutout, target_is_mastar, get_plates, check_versions\n'), ((5853, 5879), 'io.BytesIO', 'stringio', (['response.content'], {}), '(response.content)\n', (5861, 5879), True, 'from io import BytesIO as stringio\n'), ((6028, 6068), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""sdss_access not installed"""'], {}), "('sdss_access not installed')\n", (6039, 6068), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning\n'), ((6350, 6373), 'PIL.Image.open', 'PIL.Image.open', (['fileobj'], {}), '(fileobj)\n', (6364, 6373), False, 'import PIL\n'), ((8308, 8320), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8318, 8320), True, 'import matplotlib.pyplot as plt\n'), ((8338, 8370), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {'projection': 'self.wcs'}), '(projection=self.wcs)\n', (8349, 8370), True, 'import matplotlib.pyplot as plt\n'), ((8515, 8542), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (8525, 8542), True, 'import matplotlib.pyplot as plt\n'), ((8654, 8669), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (8662, 8669), True, 'import matplotlib.pyplot as plt\n'), ((9664, 9716), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No WCS found. Cannot overlay fibers."""'], {}), "('No WCS found. Cannot overlay fibers.')\n", (9675, 9716), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning\n'), ((11144, 11197), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No WCS found. Cannot overlay hexagon."""'], {}), "('No WCS found. Cannot overlay hexagon.')\n", (11155, 11197), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning\n'), ((12325, 12381), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No WCS found. Cannot overlay sky fibers."""'], {}), "('No WCS found. Cannot overlay sky fibers.')\n", (12336, 12381), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning\n'), ((12936, 13047), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""Cannot overlay sky fibers. Image is too small. Please retrieve a bigger image cutout"""'], {}), "(\n 'Cannot overlay sky fibers. Image is too small. Please retrieve a bigger image cutout'\n )\n", (12947, 13047), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning\n'), ((13711, 13833), 'matplotlib.collections.EllipseCollection', 'EllipseCollection', (['(diameter * 5)', '(diameter * 5)', '(0.0)'], {'units': '"""xy"""', 'offsets': 'fiber_pix', 'transOffset': 'ax.transData'}), "(diameter * 5, diameter * 5, 0.0, units='xy', offsets=\n fiber_pix, transOffset=ax.transData, **kwargs)\n", (13728, 13833), False, 'from matplotlib.collections import EllipseCollection\n'), ((2259, 2321), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""Images cannot currently be accessed from the db"""'], {}), "('Images cannot currently be accessed from the db')\n", (2270, 2321), False, 'from marvin.core.exceptions import MarvinError, MarvinUserWarning\n'), ((3113, 3177), 'warnings.warn', 'warnings.warn', (['"""No proper header found image"""', 'MarvinUserWarning'], {}), "('No proper header found image', MarvinUserWarning)\n", (3126, 3177), False, 'import warnings\n'), ((3595, 3645), 'warnings.warn', 'warnings.warn', (['"""No proper WCS info for this image"""'], {}), "('No proper WCS info for this image')\n", (3608, 3645), False, 'import warnings\n'), ((6415, 6475), 'warnings.warn', 'warnings.warn', (['"""Error: cannot open image"""', 'MarvinUserWarning'], {}), "('Error: cannot open image', MarvinUserWarning)\n", (6428, 6475), False, 'import warnings\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: <NAME>, <NAME>, and <NAME>
# @Date: 2017-11-01
# @Filename: modelcube.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: <NAME> (<EMAIL>)
# @Last modified time: 2018-11-14 11:48:16
from __future__ import absolute_import, division, print_function
import distutils
import warnings
import numpy as np
from pkg_resources import parse_version
from astropy.io import fits
from astropy.wcs import WCS
import marvin
import marvin.core.exceptions
import marvin.tools.maps
import marvin.tools.spaxel
import marvin.utils.general.general
from marvin.core.exceptions import MarvinError
from marvin.tools.quantities import DataCube, Map, Spectrum
from marvin.utils.datamodel.dap import Model, datamodel
from marvin.utils.general import FuzzyDict, gunzip, check_versions
from .core import MarvinToolsClass
from .mixins import DAPallMixIn, GetApertureMixIn, NSAMixIn
class ModelCube(MarvinToolsClass, NSAMixIn, DAPallMixIn, GetApertureMixIn):
"""A class to interface with MaNGA DAP model cubes.
This class represents a DAP model cube, initialised either from a file,
a database, or remotely via the Marvin API. In addition to
the parameters and variables defined for `~.MarvinToolsClass`, the
following parameters and attributes are specific to `.Maps`.
Parameters:
bintype (str or None):
The binning type. For MPL-4, one of the following: ``'NONE',
'RADIAL', 'STON'`` (if ``None`` defaults to ``'NONE'``).
For MPL-5, one of, ``'ALL', 'NRE', 'SPX', 'VOR10'``
(defaults to ``'SPX'``). MPL-6 also accepts the ``'HYB10'`` binning
schema.
template (str or None):
The stellar template used. For MPL-4, one of
``'M11-STELIB-ZSOL', 'MILES-THIN', 'MIUSCAT-THIN'`` (if ``None``,
defaults to ``'MIUSCAT-THIN'``). For MPL-5 and successive, the only
option in ``'GAU-MILESHC'`` (``None`` defaults to it).
Attributes:
header (`astropy.io.fits.Header`):
The header of the datacube.
wcs (`astropy.wcs.WCS`):
The WCS solution for this plate
"""
def __init__(self, input=None, filename=None, mangaid=None, plateifu=None,
mode=None, data=None, release=None,
drpall=None, download=None, nsa_source='auto',
bintype=None, template=None, template_kin=None):
if template_kin is not None:
warnings.warn('template_kin is deprecated and will be removed in a future version.',
DeprecationWarning)
template = template_kin if template is None else template
# _set_datamodel will replace these strings with datamodel objects.
self.bintype = bintype
self.template = template
self.datamodel = None
self._bitmasks = None
MarvinToolsClass.__init__(self, input=input, filename=filename,
mangaid=mangaid, plateifu=plateifu,
mode=mode, data=data, release=release,
drpall=drpall, download=download)
NSAMixIn.__init__(self, nsa_source=nsa_source)
# Checks that DAP is at least MPL-5
MPL5 = distutils.version.StrictVersion('2.0.2')
if self.filename is None and distutils.version.StrictVersion(self._dapver) < MPL5:
raise MarvinError('ModelCube requires at least dapver=\'2.0.2\'')
self.header = None
self.wcs = None
self._wavelength = None
self._redcorr = None
self._shape = None
# Model extensions
self._extension_data = {}
self._binned_flux = None
self._redcorr = None
self._full_fit = None
self._emline_fit = None
self._stellarcont_fit = None
if self.data_origin == 'file':
self._load_modelcube_from_file()
elif self.data_origin == 'db':
self._load_modelcube_from_db()
elif self.data_origin == 'api':
self._load_modelcube_from_api()
else:
raise marvin.core.exceptions.MarvinError(
'data_origin={0} is not valid'.format(self.data_origin))
# Confirm that drpver and dapver match the ones from the header.
marvin.tools.maps.Maps._check_versions(self)
def __repr__(self):
"""Representation for ModelCube."""
return ('<Marvin ModelCube (plateifu={0!r}, mode={1!r}, data_origin={2!r}, '
'bintype={3!r}, template={4!r})>'.format(self.plateifu,
self.mode,
self.data_origin,
str(self.bintype),
str(self.template)))
def __getitem__(self, xy):
"""Returns the spaxel for ``(x, y)``"""
return self.getSpaxel(x=xy[1], y=xy[0], xyorig='lower')
def _set_datamodel(self):
"""Sets the datamodel, template, and bintype."""
self.datamodel = datamodel[self.release].models
self._bitmasks = datamodel[self.release].bitmasks
self.bintype = self.datamodel.parent.get_bintype(self.bintype)
self.template = self.datamodel.parent.get_template(self.template)
def _getFullPath(self):
"""Returns the full path of the file in the tree."""
if not self.plateifu:
return None
plate, ifu = self.plateifu.split('-')
daptype = '{0}-{1}'.format(self.bintype, self.template)
return super(ModelCube, self)._getFullPath('mangadap', ifu=ifu,
drpver=self._drpver,
dapver=self._dapver,
plate=plate, mode='LOGCUBE',
daptype=daptype)
def download(self):
"""Downloads the cube using sdss_access - Rsync"""
if not self.plateifu:
return None
plate, ifu = self.plateifu.split('-')
daptype = '{0}-{1}'.format(self.bintype, self.template)
return super(ModelCube, self).download('mangadap', ifu=ifu,
drpver=self._drpver,
dapver=self._dapver,
plate=plate, mode='LOGCUBE',
daptype=daptype)
def _load_modelcube_from_file(self):
"""Initialises a model cube from a file."""
if self.data is not None:
assert isinstance(self.data, fits.HDUList), 'data is not an HDUList object'
else:
try:
with gunzip(self.filename) as gg:
self.data = fits.open(gg.name)
except IOError as err:
raise IOError('filename {0} cannot be found: {1}'.format(self.filename, err))
self.header = self.data[0].header
self._check_file(self.header, self.data, 'ModelCube')
self.wcs = WCS(self.data['FLUX'].header)
self._wavelength = self.data['WAVE'].data
self._redcorr = self.data['REDCORR'].data
self._shape = (self.data['FLUX'].header['NAXIS2'],
self.data['FLUX'].header['NAXIS1'])
self.plateifu = self.header['PLATEIFU']
self.mangaid = self.header['MANGAID']
# Checks and populates release.
file_drpver = self.header['VERSDRP3']
file_drpver = 'v1_5_1' if file_drpver == 'v1_5_0' else file_drpver
file_ver = marvin.config.lookUpRelease(file_drpver)
assert file_ver is not None, 'cannot find file version.'
if file_drpver != self._drpver:
warnings.warn('mismatch between file version={0} and object release={1}. '
'Setting object release to {0}'.format(file_ver, self._release),
marvin.core.exceptions.MarvinUserWarning)
self._release = file_ver
self._drpver, self._dapver = marvin.config.lookUpVersions(release=self._release)
# Updates datamodel, bintype, and template with the versions from the header.
self.datamodel = datamodel[self._dapver].models
self.bintype = self.datamodel.parent.get_bintype(self.header['BINKEY'].strip().upper())
if check_versions(self._dapver, datamodel['MPL-8'].release):
tempkey = self.header['DAPTYPE'].split('-', 1)[-1]
else:
tempkey = self.header['SCKEY']
self.template = self.datamodel.parent.get_template(tempkey.strip().upper())
def _load_modelcube_from_db(self):
"""Initialises a model cube from the DB."""
mdb = marvin.marvindb
plate, ifu = self.plateifu.split('-')
if not mdb.isdbconnected:
raise MarvinError('No db connected')
else:
datadb = mdb.datadb
dapdb = mdb.dapdb
dm = datamodel[self.release]
if dm.db_only:
if self.bintype not in dm.db_only:
raise marvin.core.exceptions.MarvinError(
'Specified bintype {0} is not '
'available in the DB'.format(self.bintype.name))
if self.data:
assert isinstance(self.data, dapdb.ModelCube), \
'data is not an instance of marvindb.dapdb.ModelCube.'
else:
# Initial query for version
version_query = mdb.session.query(dapdb.ModelCube).join(
dapdb.File,
datadb.PipelineInfo,
datadb.PipelineVersion).filter(
datadb.PipelineVersion.version == self._dapver).from_self()
# Query for model cube parameters
db_modelcube = version_query.join(
dapdb.File,
datadb.Cube,
datadb.IFUDesign).filter(
datadb.Cube.plate == plate,
datadb.IFUDesign.name == str(ifu)).from_self().join(
dapdb.File,
dapdb.FileType).filter(dapdb.FileType.value == 'LOGCUBE').join(
dapdb.Structure, dapdb.BinType).join(
dapdb.Template,
dapdb.Structure.template_kin_pk == dapdb.Template.pk).filter(
dapdb.BinType.name == self.bintype.name,
dapdb.Template.name == self.template.name).use_cache(self.cache_region).all()
if len(db_modelcube) > 1:
raise MarvinError('more than one ModelCube found for '
'this combination of parameters.')
elif len(db_modelcube) == 0:
raise MarvinError('no ModelCube found for this combination of parameters.')
self.data = db_modelcube[0]
self.header = self.data.file.primary_header
self.wcs = WCS(self.data.file.cube.wcs.makeHeader())
self._wavelength = np.array(self.data.file.cube.wavelength.wavelength, dtype=np.float)
self._redcorr = np.array(self.data.redcorr[0].value, dtype=np.float)
self._shape = self.data.file.cube.shape.shape
self.plateifu = str(self.header['PLATEIFU'].strip())
self.mangaid = str(self.header['MANGAID'].strip())
def _load_modelcube_from_api(self):
"""Initialises a model cube from the API."""
url = marvin.config.urlmap['api']['getModelCube']['url']
url_full = url.format(name=self.plateifu, bintype=self.bintype.name,
template=self.template.name)
try:
response = self._toolInteraction(url_full)
except Exception as ee:
raise MarvinError('found a problem when checking if remote model cube '
'exists: {0}'.format(str(ee)))
data = response.getData()
self.header = fits.Header.fromstring(data['header'])
self.wcs = WCS(fits.Header.fromstring(data['wcs_header']))
self._wavelength = np.array(data['wavelength'])
self._redcorr = np.array(data['redcorr'])
self._shape = tuple(data['shape'])
self.plateifu = str(self.header['PLATEIFU'].strip())
self.mangaid = str(self.header['MANGAID'].strip())
def getSpaxel(self, x=None, y=None, ra=None, dec=None,
cube=False, maps=False, **kwargs):
"""Returns the :class:`~marvin.tools.spaxel.Spaxel` matching certain coordinates.
The coordinates of the spaxel to return can be input as ``x, y`` pixels
relative to``xyorig`` in the cube, or as ``ra, dec`` celestial
coordinates.
If ``spectrum=True``, the returned |spaxel| will be instantiated with the
DRP spectrum of the spaxel for the DRP cube associated with this
ModelCube. The same is true for ``properties=True`` for the DAP
properties of the spaxel in the Maps associated with these coordinates.
Parameters:
x,y (int or array):
The spaxel coordinates relative to ``xyorig``. If ``x`` is an
array of coordinates, the size of ``x`` must much that of
``y``.
ra,dec (float or array):
The coordinates of the spaxel to return. The closest spaxel to
those coordinates will be returned. If ``ra`` is an array of
coordinates, the size of ``ra`` must much that of ``dec``.
xyorig ({'center', 'lower'}):
The reference point from which ``x`` and ``y`` are measured.
Valid values are ``'center'`` (default), for the centre of the
spatial dimensions of the cube, or ``'lower'`` for the
lower-left corner. This keyword is ignored if ``ra`` and
``dec`` are defined.
cube (bool):
If ``True``, the |spaxel| will be initialised with the
corresponding DRP cube data.
maps (bool):
If ``True``, the |spaxel| will be initialised with the
corresponding DAP Maps properties for this spaxel.
Returns:
spaxels (list):
The |spaxel|_ objects for this cube/maps corresponding to the
input coordinates. The length of the list is equal to the
number of input coordinates.
.. |spaxel| replace:: :class:`~marvin.tools.spaxel.Spaxel`
"""
for old_param in ['drp', 'properties']:
if old_param in kwargs:
raise marvin.core.exceptions.MarvinDeprecationError(
'the {0} parameter has been deprecated. '
'Use cube or maps.'.format(old_param))
return marvin.utils.general.general.getSpaxel(
x=x, y=y, ra=ra, dec=dec,
cube=cube, maps=maps, modelcube=self, **kwargs)
def _get_extension_data(self, name, ext=None):
"""Returns the data from an extension."""
model = self.datamodel[name]
ext_name = model.fits_extension(ext)
if ext_name in self._extension_data:
return self._extension_data[ext_name]
if self.data_origin == 'file':
ext_data = self.data[model.fits_extension(ext)].data
elif self.data_origin == 'db':
# If the table is "spaxel", this must be a 3D cube. If it is "cube",
# uses self.data, which is basically the DataModelClass.Cube instance.
ext_data = self.data.get3DCube(model.db_column(ext))
elif self.data_origin == 'api':
params = {'release': self._release}
url = marvin.config.urlmap['api']['getModelCubeExtension']['url']
try:
response = self._toolInteraction(
url.format(name=self.plateifu,
modelcube_extension=model.fits_extension(ext).lower(),
bintype=self.bintype.name, template=self.template.name),
params=params)
except Exception as ee:
raise MarvinError('found a problem when checking if remote '
'modelcube exists: {0}'.format(str(ee)))
data = response.getData()
cube_ext_data = data['extension_data']
ext_data = np.array(cube_ext_data) if cube_ext_data is not None else None
self._extension_data[ext_name] = ext_data
return ext_data
def _get_spaxel_quantities(self, x, y, spaxel=None):
"""Returns a dictionary of spaxel quantities."""
modelcube_quantities = FuzzyDict({})
if self.data_origin == 'db':
session = marvin.marvindb.session
dapdb = marvin.marvindb.dapdb
if self.data_origin == 'file' or self.data_origin == 'db':
_db_row = None
for dm in self.datamodel:
data = {'value': None, 'ivar': None, 'mask': None}
for key in data:
if key == 'ivar' and not dm.has_ivar():
continue
if key == 'mask' and not dm.has_mask():
continue
if self.data_origin == 'file':
extname = dm.fits_extension(None if key == 'value' else key)
data[key] = self.data[extname].data[:, y, x]
elif self.data_origin == 'db':
colname = dm.db_column(None if key == 'value' else key)
if not _db_row:
_db_row = session.query(dapdb.ModelSpaxel).filter(
dapdb.ModelSpaxel.modelcube_pk == self.data.pk,
dapdb.ModelSpaxel.x == x, dapdb.ModelSpaxel.y == y).use_cache(self.cache_region).one()
data[key] = np.array(getattr(_db_row, colname))
quantity = Spectrum(data['value'], ivar=data['ivar'], mask=data['mask'],
wavelength=self._wavelength, unit=dm.unit,
pixmask_flag=dm.pixmask_flag)
if spaxel:
quantity._init_bin(spaxel=spaxel, parent=self, datamodel=dm)
modelcube_quantities[dm.full()] = quantity
if self.data_origin == 'api':
params = {'release': self._release}
url = marvin.config.urlmap['api']['getModelCubeQuantitiesSpaxel']['url']
try:
response = self._toolInteraction(url.format(name=self.plateifu,
x=x, y=y,
bintype=self.bintype.name,
template=self.template.name,
params=params))
except Exception as ee:
raise MarvinError('found a problem when checking if remote modelcube '
'exists: {0}'.format(str(ee)))
data = response.getData()
for dm in self.datamodel:
quantity = Spectrum(data[dm.name]['value'], ivar=data[dm.name]['ivar'],
mask=data[dm.name]['mask'], wavelength=data['wavelength'],
unit=dm.unit, pixmask_flag=dm.pixmask_flag)
if spaxel:
quantity._init_bin(spaxel=spaxel, parent=self, datamodel=dm)
modelcube_quantities[dm.full()] = quantity
return modelcube_quantities
def get_binid(self, model=None):
"""Returns the binid map associated with a model.
Parameters
----------
model : `datamodel.Model` or None
The model for which the associated binid map will be returned.
If ``binid=None``, the default binid is returned.
Returns
-------
binid : `Map`
A `Map` with the binid associated with ``model`` or the default
binid.
"""
assert model is None or isinstance(model, Model), 'invalid model type.'
if model is not None:
binid_prop = model.binid
else:
binid_prop = self.datamodel.parent.default_binid
# Before MPL-6, the modelcube does not include the binid extension,
# so we need to get the binid map from the associated MAPS.
if (distutils.version.StrictVersion(self._dapver) <
distutils.version.StrictVersion('2.1')):
return self.getMaps().get_binid()
if self.data_origin == 'file':
if binid_prop.channel is None:
binid_map_data = self.data[binid_prop.name].data[:, :]
else:
binid_map_data = self.data[binid_prop.name].data[binid_prop.channel.idx, :, :]
elif self.data_origin == 'db':
mdb = marvin.marvindb
table = mdb.dapdb.ModelSpaxel
column = getattr(table, binid_prop.db_column())
binid_list = mdb.session.query(column).filter(
table.modelcube_pk == self.data.pk).order_by(table.x, table.y).all()
nx = ny = int(np.sqrt(len(binid_list)))
binid_array = np.array(binid_list)
binid_map_data = binid_array.transpose().reshape((ny, nx)).transpose(1, 0)
elif self.data_origin == 'api':
params = {'release': self._release}
url = marvin.config.urlmap['api']['getModelCubeBinid']['url']
extension = model.fits_extension().lower() if model is not None else 'flux'
try:
response = self._toolInteraction(
url.format(name=self.plateifu,
modelcube_extension=extension,
bintype=self.bintype.name,
template=self.template.name), params=params)
except Exception as ee:
raise MarvinError('found a problem when checking if remote '
'modelcube exists: {0}'.format(str(ee)))
if response.results['error'] is not None:
raise MarvinError('found a problem while getting the binid from API: {}'
.format(str(response.results['error'])))
binid_map_data = np.array(response.getData()['binid'])
binid_map = Map(binid_map_data, unit=binid_prop.unit)
binid_map._datamodel = binid_prop
return binid_map
@property
def binned_flux(self):
"""Returns the binned flux datacube."""
model = self.datamodel['binned_flux']
binned_flux_array = self._get_extension_data('flux')
binned_flux_ivar = self._get_extension_data('flux', 'ivar')
binned_flux_mask = self._get_extension_data('flux', 'mask')
return DataCube(binned_flux_array,
np.array(self._wavelength),
ivar=binned_flux_ivar,
mask=binned_flux_mask,
redcorr=self._redcorr,
binid=self.get_binid(model),
unit=model.unit,
pixmask_flag=model.pixmask_flag)
@property
def full_fit(self):
"""Returns the full fit datacube."""
model = self.datamodel['full_fit']
model_array = self._get_extension_data('full_fit')
model_mask = self._get_extension_data('flux', 'mask')
return DataCube(model_array,
np.array(self._wavelength),
ivar=None,
mask=model_mask,
redcorr=self._redcorr,
binid=self.get_binid(model),
unit=model.unit,
pixmask_flag=model.pixmask_flag)
@property
def emline_fit(self):
"""Returns the emission line fit."""
model = self.datamodel['emline_fit']
emline_array = self._get_extension_data('emline_fit')
if model.has_mask():
emline_mask = self._get_extension_data('emline_fit', 'mask')
else:
emline_mask = None
return DataCube(emline_array,
np.array(self._wavelength),
ivar=None,
mask=emline_mask,
redcorr=self._redcorr,
binid=self.get_binid(model),
unit=model.unit,
pixmask_flag=model.pixmask_flag)
@property
def stellarcont_fit(self):
"""Returns the stellar continuum fit."""
isMPL8 = check_versions(self._dapver, datamodel['MPL-8'].release)
if isMPL8:
array = self._get_extension_data('stellar_fit')
model = self.datamodel['stellar_fit']
mask = self._get_extension_data('stellar_fit', 'mask')
else:
array = (self._get_extension_data('full_fit') -
self._get_extension_data('emline_fit') -
self._get_extension_data('emline_base_fit'))
model = self.datamodel['full_fit']
mask = self._get_extension_data('flux', 'mask')
return DataCube(array,
np.array(self._wavelength),
ivar=None,
mask=mask,
redcorr=self._redcorr,
binid=self.get_binid(model),
unit=model.unit,
pixmask_flag=model.pixmask_flag)
@property
def lsf(self):
"""Returns the pre-pixelized LSF"""
isMPL10 = check_versions(self._dapver, datamodel['MPL-10'].release)
if not isMPL10:
raise MarvinError('LSF property only available for MPLs >= 10')
model = self.datamodel['lsf']
lsf_array = self._get_extension_data('lsf')
if model.has_mask():
lsf_mask = self._get_extension_data('lsf', 'mask')
else:
lsf_mask = None
return DataCube(lsf_array,
np.array(self._wavelength),
ivar=None,
mask=lsf_mask,
redcorr=self._redcorr,
binid=self.get_binid(model),
unit=model.unit,
pixmask_flag=model.pixmask_flag)
def getCube(self):
"""Returns the associated `~marvin.tools.cube.Cube`."""
if self.data_origin == 'db':
cube_data = self.data.file.cube
else:
cube_data = None
return marvin.tools.cube.Cube(data=cube_data,
plateifu=self.plateifu,
release=self.release)
def getMaps(self):
"""Returns the associated`~marvin.tools.maps.Maps`."""
return marvin.tools.maps.Maps(plateifu=self.plateifu,
bintype=self.bintype,
template=self.template,
release=self.release)
def is_binned(self):
"""Returns True if the ModelCube is not unbinned."""
return self.bintype.binned
def get_unbinned(self):
"""Returns a version of ``self`` corresponding to the unbinned ModelCube."""
if not self.is_binned:
return self
else:
unbinned = self.datamodel.parent.get_unbinned()
if self.datamodel.parent.db_only:
in_db = unbinned in self.datamodel.parent.db_only
else:
in_db = unbinned in self.datamodel.parent.bintypes
if self.mode == 'remote' and not in_db:
raise marvin.core.exceptions.MarvinError(
"Bintype {0} for release {1} not available in remote database. Use "
"Marvin's local file access mode instead.".format(unbinned.name, self.release))
return ModelCube(plateifu=self.plateifu, release=self.release,
bintype=self.datamodel.parent.get_unbinned(),
template=self.template,
mode=self.mode)
| [
"marvin.tools.quantities.Map",
"marvin.utils.general.gunzip",
"marvin.tools.maps.Maps._check_versions",
"marvin.config.lookUpVersions",
"marvin.utils.general.general.getSpaxel",
"marvin.tools.quantities.Spectrum",
"marvin.tools.maps.Maps",
"marvin.config.lookUpRelease",
"marvin.core.exceptions.Marvi... | [((3346, 3386), 'distutils.version.StrictVersion', 'distutils.version.StrictVersion', (['"""2.0.2"""'], {}), "('2.0.2')\n", (3377, 3386), False, 'import distutils\n'), ((4393, 4437), 'marvin.tools.maps.Maps._check_versions', 'marvin.tools.maps.Maps._check_versions', (['self'], {}), '(self)\n', (4431, 4437), False, 'import marvin\n'), ((7273, 7302), 'astropy.wcs.WCS', 'WCS', (["self.data['FLUX'].header"], {}), "(self.data['FLUX'].header)\n", (7276, 7302), False, 'from astropy.wcs import WCS\n'), ((7798, 7838), 'marvin.config.lookUpRelease', 'marvin.config.lookUpRelease', (['file_drpver'], {}), '(file_drpver)\n', (7825, 7838), False, 'import marvin\n'), ((8266, 8317), 'marvin.config.lookUpVersions', 'marvin.config.lookUpVersions', ([], {'release': 'self._release'}), '(release=self._release)\n', (8294, 8317), False, 'import marvin\n'), ((8568, 8624), 'marvin.utils.general.check_versions', 'check_versions', (['self._dapver', "datamodel['MPL-8'].release"], {}), "(self._dapver, datamodel['MPL-8'].release)\n", (8582, 8624), False, 'from marvin.utils.general import FuzzyDict, gunzip, check_versions\n'), ((12343, 12381), 'astropy.io.fits.Header.fromstring', 'fits.Header.fromstring', (["data['header']"], {}), "(data['header'])\n", (12365, 12381), False, 'from astropy.io import fits\n'), ((12476, 12504), 'numpy.array', 'np.array', (["data['wavelength']"], {}), "(data['wavelength'])\n", (12484, 12504), True, 'import numpy as np\n'), ((12529, 12554), 'numpy.array', 'np.array', (["data['redcorr']"], {}), "(data['redcorr'])\n", (12537, 12554), True, 'import numpy as np\n'), ((15197, 15313), 'marvin.utils.general.general.getSpaxel', 'marvin.utils.general.general.getSpaxel', ([], {'x': 'x', 'y': 'y', 'ra': 'ra', 'dec': 'dec', 'cube': 'cube', 'maps': 'maps', 'modelcube': 'self'}), '(x=x, y=y, ra=ra, dec=dec, cube=cube,\n maps=maps, modelcube=self, **kwargs)\n', (15235, 15313), False, 'import marvin\n'), ((17073, 17086), 'marvin.utils.general.FuzzyDict', 'FuzzyDict', (['{}'], {}), '({})\n', (17082, 17086), False, 'from marvin.utils.general import FuzzyDict, gunzip, check_versions\n'), ((22955, 22996), 'marvin.tools.quantities.Map', 'Map', (['binid_map_data'], {'unit': 'binid_prop.unit'}), '(binid_map_data, unit=binid_prop.unit)\n', (22958, 22996), False, 'from marvin.tools.quantities import DataCube, Map, Spectrum\n'), ((25223, 25279), 'marvin.utils.general.check_versions', 'check_versions', (['self._dapver', "datamodel['MPL-8'].release"], {}), "(self._dapver, datamodel['MPL-8'].release)\n", (25237, 25279), False, 'from marvin.utils.general import FuzzyDict, gunzip, check_versions\n'), ((26235, 26292), 'marvin.utils.general.check_versions', 'check_versions', (['self._dapver', "datamodel['MPL-10'].release"], {}), "(self._dapver, datamodel['MPL-10'].release)\n", (26249, 26292), False, 'from marvin.utils.general import FuzzyDict, gunzip, check_versions\n'), ((27208, 27297), 'marvin.tools.cube.Cube', 'marvin.tools.cube.Cube', ([], {'data': 'cube_data', 'plateifu': 'self.plateifu', 'release': 'self.release'}), '(data=cube_data, plateifu=self.plateifu, release=self\n .release)\n', (27230, 27297), False, 'import marvin\n'), ((27472, 27590), 'marvin.tools.maps.Maps', 'marvin.tools.maps.Maps', ([], {'plateifu': 'self.plateifu', 'bintype': 'self.bintype', 'template': 'self.template', 'release': 'self.release'}), '(plateifu=self.plateifu, bintype=self.bintype,\n template=self.template, release=self.release)\n', (27494, 27590), False, 'import marvin\n'), ((2543, 2656), 'warnings.warn', 'warnings.warn', (['"""template_kin is deprecated and will be removed in a future version."""', 'DeprecationWarning'], {}), "(\n 'template_kin is deprecated and will be removed in a future version.',\n DeprecationWarning)\n", (2556, 2656), False, 'import warnings\n'), ((3496, 3553), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""ModelCube requires at least dapver=\'2.0.2\'"""'], {}), '("ModelCube requires at least dapver=\'2.0.2\'")\n', (3507, 3553), False, 'from marvin.core.exceptions import MarvinError\n'), ((9052, 9082), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""No db connected"""'], {}), "('No db connected')\n", (9063, 9082), False, 'from marvin.core.exceptions import MarvinError\n'), ((11407, 11474), 'numpy.array', 'np.array', (['self.data.file.cube.wavelength.wavelength'], {'dtype': 'np.float'}), '(self.data.file.cube.wavelength.wavelength, dtype=np.float)\n', (11415, 11474), True, 'import numpy as np\n'), ((11503, 11555), 'numpy.array', 'np.array', (['self.data.redcorr[0].value'], {'dtype': 'np.float'}), '(self.data.redcorr[0].value, dtype=np.float)\n', (11511, 11555), True, 'import numpy as np\n'), ((12405, 12447), 'astropy.io.fits.Header.fromstring', 'fits.Header.fromstring', (["data['wcs_header']"], {}), "(data['wcs_header'])\n", (12427, 12447), False, 'from astropy.io import fits\n'), ((20961, 21006), 'distutils.version.StrictVersion', 'distutils.version.StrictVersion', (['self._dapver'], {}), '(self._dapver)\n', (20992, 21006), False, 'import distutils\n'), ((21025, 21063), 'distutils.version.StrictVersion', 'distutils.version.StrictVersion', (['"""2.1"""'], {}), "('2.1')\n", (21056, 21063), False, 'import distutils\n'), ((23468, 23494), 'numpy.array', 'np.array', (['self._wavelength'], {}), '(self._wavelength)\n', (23476, 23494), True, 'import numpy as np\n'), ((24100, 24126), 'numpy.array', 'np.array', (['self._wavelength'], {}), '(self._wavelength)\n', (24108, 24126), True, 'import numpy as np\n'), ((24807, 24833), 'numpy.array', 'np.array', (['self._wavelength'], {}), '(self._wavelength)\n', (24815, 24833), True, 'import numpy as np\n'), ((25842, 25868), 'numpy.array', 'np.array', (['self._wavelength'], {}), '(self._wavelength)\n', (25850, 25868), True, 'import numpy as np\n'), ((26335, 26392), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""LSF property only available for MPLs >= 10"""'], {}), "('LSF property only available for MPLs >= 10')\n", (26346, 26392), False, 'from marvin.core.exceptions import MarvinError\n'), ((26679, 26705), 'numpy.array', 'np.array', (['self._wavelength'], {}), '(self._wavelength)\n', (26687, 26705), True, 'import numpy as np\n'), ((3424, 3469), 'distutils.version.StrictVersion', 'distutils.version.StrictVersion', (['self._dapver'], {}), '(self._dapver)\n', (3455, 3469), False, 'import distutils\n'), ((18398, 18537), 'marvin.tools.quantities.Spectrum', 'Spectrum', (["data['value']"], {'ivar': "data['ivar']", 'mask': "data['mask']", 'wavelength': 'self._wavelength', 'unit': 'dm.unit', 'pixmask_flag': 'dm.pixmask_flag'}), "(data['value'], ivar=data['ivar'], mask=data['mask'], wavelength=\n self._wavelength, unit=dm.unit, pixmask_flag=dm.pixmask_flag)\n", (18406, 18537), False, 'from marvin.tools.quantities import DataCube, Map, Spectrum\n'), ((19661, 19833), 'marvin.tools.quantities.Spectrum', 'Spectrum', (["data[dm.name]['value']"], {'ivar': "data[dm.name]['ivar']", 'mask': "data[dm.name]['mask']", 'wavelength': "data['wavelength']", 'unit': 'dm.unit', 'pixmask_flag': 'dm.pixmask_flag'}), "(data[dm.name]['value'], ivar=data[dm.name]['ivar'], mask=data[dm.\n name]['mask'], wavelength=data['wavelength'], unit=dm.unit,\n pixmask_flag=dm.pixmask_flag)\n", (19669, 19833), False, 'from marvin.tools.quantities import DataCube, Map, Spectrum\n'), ((21782, 21802), 'numpy.array', 'np.array', (['binid_list'], {}), '(binid_list)\n', (21790, 21802), True, 'import numpy as np\n'), ((6940, 6961), 'marvin.utils.general.gunzip', 'gunzip', (['self.filename'], {}), '(self.filename)\n', (6946, 6961), False, 'from marvin.utils.general import FuzzyDict, gunzip, check_versions\n'), ((7001, 7019), 'astropy.io.fits.open', 'fits.open', (['gg.name'], {}), '(gg.name)\n', (7010, 7019), False, 'from astropy.io import fits\n'), ((10945, 11030), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""more than one ModelCube found for this combination of parameters."""'], {}), "('more than one ModelCube found for this combination of parameters.'\n )\n", (10956, 11030), False, 'from marvin.core.exceptions import MarvinError\n'), ((11139, 11208), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""no ModelCube found for this combination of parameters."""'], {}), "('no ModelCube found for this combination of parameters.')\n", (11150, 11208), False, 'from marvin.core.exceptions import MarvinError\n'), ((16787, 16810), 'numpy.array', 'np.array', (['cube_ext_data'], {}), '(cube_ext_data)\n', (16795, 16810), True, 'import numpy as np\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for IP reservation feature
Test Plan: https://cwiki.apache.org/confluence/display/CLOUDSTACK/IP+Range+Reservation+within+a+Network+Test+Cases
Issue Link: https://issues.apache.org/jira/browse/CLOUDSTACK-2266
Feature Specifications: https://cwiki.apache.org/confluence/display/CLOUDSTACK/FS+-+IP+Range+Reservation+within+a+Network
"""
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState
from marvin.lib.base import (Account,
Network,
VirtualMachine,
Router,
ServiceOffering,
NetworkOffering)
from marvin.lib.common import (get_zone,
get_template,
get_domain,
wait_for_cleanup,
createEnabledNetworkOffering,
createNetworkRulesForVM,
verifyNetworkState)
from marvin.codes import (PASS, FAIL, FAILED, UNKNOWN, FAULT, MASTER,
NAT_RULE, STATIC_NAT_RULE)
import netaddr
import random
from nose.plugins.attrib import attr
from ddt import ddt, data
def createIsolatedNetwork(self, network_offering_id, gateway=None):
"""Create isolated network with given network offering and gateway if provided
and return"""
try:
isolated_network = Network.create(self.apiclient, self.testData["isolated_network"],
networkofferingid=network_offering_id,accountid=self.account.name,
domainid=self.domain.id,zoneid=self.zone.id,
gateway=gateway, netmask='255.255.255.0' if gateway else None)
except Exception as e:
return [FAIL, e]
return [PASS, isolated_network]
def matchNetworkGuestVmCIDR(self, networkid, guestvmcidr):
"""List networks with given network id and check if the guestvmcidr matches
with the given cidr"""
networks = Network.list(self.apiclient, id=networkid, listall=True)
self.assertEqual(validateList(networks)[0], PASS, "network list validation failed")
self.assertEqual(str(networks[0].cidr), guestvmcidr, "guestvmcidr of network %s \
does not match with the given value %s" % (networks[0].cidr, guestvmcidr))
return
def createVirtualMachine(self, network_id=None, ip_address=None):
"""Create and return virtual machine within network and ipaddress"""
virtual_machine = VirtualMachine.create(self.apiclient,
self.testData["virtual_machine"],
networkids=network_id,
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.domain.id,
ipaddress=ip_address)
return virtual_machine
def CreateEnabledNetworkOffering(apiclient, networkServices):
"""Create network offering of given test data and enable it"""
result = createEnabledNetworkOffering(apiclient, networkServices)
assert result[0] == PASS, "Network offering creation/enabling failed due to %s" % result[2]
return result[1]
@ddt
class TestIpReservation(cloudstackTestCase):
"""Test IP Range Reservation with a Network
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestIpReservation, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.testData = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testData["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.testData["ostype"]
cls.testData["domainid"] = cls.domain.id
cls.testData["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
try:
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testData["service_offering"]
)
cls._cleanup.append(cls.service_offering)
cls.isolated_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["isolated_network_offering"])
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_persistent_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["nw_off_isolated_persistent"])
cls._cleanup.append(cls.isolated_persistent_network_offering)
cls.isolated_network_offering_RVR = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["nw_off_isolated_RVR"])
cls._cleanup.append(cls.isolated_network_offering_RVR)
except Exception as e:
cls.tearDownClass()
raise unittest.SkipTest("Failure in setUpClass: %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
try:
self.account = Account.create(self.apiclient, self.testData["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
except Exception as e:
self.skipTest("Failed to create account: %s" % e)
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced"])
def test_vm_create_after_reservation(self):
""" Test creating VM in network after IP reservation
# steps
# 1. Create vm in isolated network (LB through VR or Netscaler) with ip in guestvmcidr
# 2. Update guestvmcidr
# 3. Create another VM
# validation
# 1. Guest vm cidr should be successfully updated with correct value
# 2. Existing guest vm ip should not be changed after reservation
# 3. Newly created VM should get ip in guestvmcidr"""
networkOffering = self.isolated_network_offering
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, networkOffering.id, gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network = resultSet[1]
guest_vm_cidr = subnet +".0/29"
try:
virtual_machine_1 = createVirtualMachine(self, network_id=isolated_network.id,
ip_address = subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network.id, guest_vm_cidr)
vms = VirtualMachine.list(self.apiclient,
id=virtual_machine_1.id)
self.assertEqual(validateList(vms)[0], PASS, "vm list validation failed")
self.assertEqual(vms[0].nic[0].ipaddress,
virtual_machine_1.ipaddress,
"VM IP should not change after reservation")
try:
virtual_machine_2 = createVirtualMachine(self, network_id=isolated_network.id)
if netaddr.IPAddress(virtual_machine_2.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
return
@attr(tags=["advanced"])
def test_vm_create_outside_cidr_after_reservation(self):
""" Test create VM outside the range of reserved IPs
# steps
# 1. update guestvmcidr of persistent isolated network (LB through VR or
# Netscaler
# 2. create another VM with ip outside guestvmcidr
"""
# validation
# 1. guest vm cidr should be successfully updated with correct value
# 2 newly created VM should not be created and result in exception
networkOffering = self.isolated_persistent_network_offering
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, networkOffering.id, gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network = resultSet[1]
guest_vm_cidr = subnet+".0/29"
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network.id, guest_vm_cidr)
try:
createVirtualMachine(self, network_id=self.isolated_network.id,
ip_address=subnet+".9")
self.fail("vm should not be created ")
except Exception as e:
self.debug("exception as IP is outside of guestvmcidr %s" % e)
return
@attr(tags=["advanced"])
def test_update_cidr_multiple_vms_not_all_inclusive(self):
""" Test reserve IP range such that one of the VM is not included
# steps
# 1. Create two vms in isolated network
# 2. Update guestvmcidr of network such that only one of the ipaddress of vms
# is in the given range
# validation
# 1. Network updation with this new range should fail"""
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, self.isolated_network_offering.id,
gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network = resultSet[1]
guest_vm_cidr = subnet+".0/29"
try:
createVirtualMachine(self, network_id=isolated_network.id,
ip_address=subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
try:
createVirtualMachine(self, network_id=isolated_network.id,
ip_address=subnet+".9")
except Exception as e:
self.fail("VM creation failed: %s" % e)
with self.assertRaises(Exception):
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
return
@attr(tags=["advanced"])
def test_update_cidr_single_vm_not_inclusive(self):
""" Test reserving IP range in network such that existing VM is outside the range
# steps
# 1. Create vm in isolated network
# 2. Update guestvmcidr of network such that ip address of vm
# is outside the given range
#
# validation
# 1. Network updation with this new range should fail"""
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, self.isolated_network_offering.id,
gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network = resultSet[1]
guest_vm_cidr = subnet+".0/29"
try:
createVirtualMachine(self, network_id=isolated_network.id,
ip_address=subnet+".9")
except Exception as e:
self.fail("VM creation failed: %s" % e)
with self.assertRaises(Exception):
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
return
@data(NAT_RULE, STATIC_NAT_RULE)
@attr(tags=["advanced"], required_hardware="true")
def test_nat_rules(self, value):
""" Test NAT rules working with IP reservation
# steps
# 1. Create vm in persistent isolated network with ip in guestvmcidr
# 2. Create NAT/static NAT rule for this VM
# 3. Update guestvmcidr
# 4. Create another VM and create network rules for this vm too
#
# validation
# 1. Guest vm cidr should be successfully updated with correct value
# 2. Existing guest vm ip should not be changed after reservation
# 3. Newly created VM should get ip in guestvmcidr
# 4. The network rules should be working"""
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, self.isolated_network_offering.id,
gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network = resultSet[1]
guest_vm_cidr = subnet+".0/29"
try:
virtual_machine_1 = createVirtualMachine(self, network_id=isolated_network.id,
ip_address=subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
result = createNetworkRulesForVM(self.apiclient, virtual_machine_1,value,
self.account, self.testData)
if result[0] == FAIL:
self.fail("Failed to create network rules for VM: %s" % result[1])
else:
ipaddress_1 = result[1]
virtual_machine_1.get_ssh_client(ipaddress=ipaddress_1.ipaddress.ipaddress)
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network.id, guest_vm_cidr)
vms = VirtualMachine.list(self.apiclient, id=virtual_machine_1.id)
self.assertEqual(validateList(vms)[0], PASS, "vm list validation failed")
self.assertEqual(vms[0].nic[0].ipaddress,
virtual_machine_1.ipaddress,
"VM IP should not change after reservation")
try:
virtual_machine_2 = createVirtualMachine(self, network_id=isolated_network.id)
if netaddr.IPAddress(virtual_machine_2.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
result = createNetworkRulesForVM(self.apiclient, virtual_machine_2, value,
self.account, self.testData)
if result[0] == FAIL:
self.fail("Failed to create network rules for VM: %s" % result[1])
else:
ipaddress_2 = result[1]
virtual_machine_2.get_ssh_client(ipaddress=ipaddress_2.ipaddress.ipaddress)
return
@unittest.skip("Skip - WIP")
@attr(tags=["advanced"])
def test_RVR_network(self):
""" Test IP reservation in network with RVR
# steps
# 1. create vm in isolated network with RVR and ip in guestvmcidr
# 2. update guestvmcidr
# 3. List routers and stop the master router, wait till backup router comes up
# 4. create another VM
#
# validation
# 1. Guest vm cidr should be successfully updated with correct value
# 2. Existing guest vm ip should not be changed after reservation
# 3. Newly created VM should get ip in guestvmcidr
# 4. Verify that the network has two routers associated with it
# 5. Backup router should come up when master router is stopped"""
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, self.isolated_network_offering_RVR.id,
gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network_RVR= resultSet[1]
guest_vm_cidr = subnet+".0/29"
try:
virtual_machine_1 = createVirtualMachine(self, network_id=isolated_network_RVR.id,
ip_address=subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
isolated_network_RVR.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network_RVR.id, guest_vm_cidr)
vms = VirtualMachine.list(self.apiclient,
id=virtual_machine_1.id)
self.assertEqual(validateList(vms)[0], PASS, "vm list validation failed")
self.assertEqual(vms[0].nic[0].ipaddress,
virtual_machine_1.ipaddress,
"VM IP should not change after reservation")
self.debug("Listing routers for network: %s" % isolated_network_RVR.name)
routers = Router.list(self.apiclient, networkid=isolated_network_RVR.id, listall=True)
self.assertEqual(validateList(routers)[0], PASS, "Routers list validation failed")
self.assertEqual(len(routers), 2, "Length of the list router should be 2 (Backup & master)")
if routers[0].redundantstate == MASTER:
master_router = routers[0]
backup_router = routers[1]
else:
master_router = routers[1]
backup_router = routers[0]
self.debug("Stopping router ID: %s" % master_router.id)
try:
Router.stop(self.apiclient, id=master_router.id)
except Exception as e:
self.fail("Failed to stop master router due to error %s" % e)
# wait for VR to update state
wait_for_cleanup(self.apiclient, ["router.check.interval"])
result = verifyRouterState(master_router.id, [UNKNOWN,FAULT])
if result[0] == FAIL:
self.fail(result[1])
result = verifyRouterState(backup_router.id, [MASTER])
if result[0] == FAIL:
self.fail(result[1])
try:
virtual_machine_2 = createVirtualMachine(self, network_id=isolated_network_RVR.id)
if netaddr.IPAddress(virtual_machine_2.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
return
@attr(tags=["advanced"])
def test_ip_reservation_in_multiple_networks_same_account(self):
""" Test IP reservation in multiple networks created in same account
# steps
# 1. Create two isolated networks with user defined cidr in same account
# Test below conditions for both the networks in the account
# 2. Create vm in persistent isolated network with ip in guestvmcidr
# 3. Update guestvmcidr
# 4. Create another VM
#
# validation
# 1. Guest vm cidr should be successfully updated with correct value
# 2. Existing guest vm ip should not be changed after reservation
# 3. Newly created VM should get ip in guestvmcidr"""
account_1 = Account.create(self.apiclient, self.testData["account"],
domainid=self.domain.id)
self.cleanup.append(account_1)
random_subnet = str(random.randrange(1,254))
gateway = "10.1." + random_subnet +".1"
isolated_network_1 = Network.create(self.apiclient, self.testData["isolated_network"],
networkofferingid=self.isolated_network_offering.id,accountid=account_1.name,
domainid=self.domain.id,zoneid=self.zone.id,
gateway=gateway, netmask='255.255.255.0')
guest_vm_cidr = "10.1."+random_subnet+".0/29"
try:
virtual_machine_1 = VirtualMachine.create(self.apiclient, self.testData["virtual_machine"],
networkids=isolated_network_1.id, serviceofferingid=self.service_offering.id,
accountid=account_1.name, domainid=self.domain.id,
ipaddress="10.1."+random_subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
isolated_network_1.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network_1.id, guest_vm_cidr)
vms = VirtualMachine.list(self.apiclient,
id=virtual_machine_1.id)
self.assertEqual(validateList(vms)[0], PASS, "vm list validation failed")
self.assertEqual(vms[0].nic[0].ipaddress,
virtual_machine_1.ipaddress,
"VM IP should not change after reservation")
try:
virtual_machine_2 = VirtualMachine.create(self.apiclient, self.testData["virtual_machine"],
networkids=isolated_network_1.id, serviceofferingid=self.service_offering.id,
accountid=account_1.name, domainid=self.domain.id)
if netaddr.IPAddress(virtual_machine_2.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
random_subnet = str(random.randrange(1,254))
gateway = "10.1." + random_subnet +".1"
isolated_network_2 = Network.create(self.apiclient, self.testData["isolated_network"],
networkofferingid=self.isolated_network_offering.id,accountid=account_1.name,
domainid=self.domain.id,zoneid=self.zone.id,
gateway=gateway, netmask='255.255.255.0')
guest_vm_cidr = "10.1."+random_subnet+".0/29"
try:
virtual_machine_3 = VirtualMachine.create(self.apiclient, self.testData["virtual_machine"],
networkids=isolated_network_2.id, serviceofferingid=self.service_offering.id,
accountid=account_1.name, domainid=self.domain.id,
ipaddress="10.1."+random_subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
isolated_network_2.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network_2.id, guest_vm_cidr)
vms = VirtualMachine.list(self.apiclient,
id=virtual_machine_3.id)
self.assertEqual(validateList(vms)[0], PASS, "vm list validation failed")
self.assertEqual(vms[0].nic[0].ipaddress,
virtual_machine_3.ipaddress,
"VM IP should not change after reservation")
try:
virtual_machine_4 = VirtualMachine.create(self.apiclient, self.testData["virtual_machine"],
networkids=isolated_network_2.id, serviceofferingid=self.service_offering.id,
accountid=account_1.name, domainid=self.domain.id)
if netaddr.IPAddress(virtual_machine_4.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
return
@ddt
class TestRestartNetwork(cloudstackTestCase):
"""Test Restart Network
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestRestartNetwork, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.testData = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testData["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.testData["ostype"]
cls.testData["domainid"] = cls.domain.id
cls.testData["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
try:
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testData["service_offering"]
)
cls._cleanup.append(cls.service_offering)
cls.isolated_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["isolated_network_offering"])
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_persistent_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["nw_off_isolated_persistent"])
cls._cleanup.append(cls.isolated_persistent_network_offering)
except Exception as e:
cls.tearDownClass()
raise unittest.SkipTest("Failure in setUpClass: %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
try:
self.account = Account.create(self.apiclient, self.testData["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
except Exception as e:
self.skipTest("Failed to create account: %s" % e)
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@data(True, False)
@attr(tags=["advanced"])
def test_restart_network_with_cleanup(self, value):
""" Test IP reservation rules with network restart operation
# steps
# 1. Create vm in isolated network with ip in guestvmcidr
# 2. Update guestvmcidr
# 3. Restart network with cleanup True/False
# 4. Deploy another VM in the network
#
# validation
# 1. Guest vm cidr should be successfully updated with correct value
# 2. Existing guest vm ip should not be changed after reservation
# 3. Network should be restarted successfully with and without cleanup
# 4. Newly created VM should get ip in guestvmcidr"""
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, self.isolated_network_offering.id,
gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network= resultSet[1]
guest_vm_cidr = subnet+".0/29"
try:
virtual_machine_1 = createVirtualMachine(self, network_id=isolated_network.id,
ip_address=subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network.id, guest_vm_cidr)
vms = VirtualMachine.list(self.apiclient,
id=virtual_machine_1.id)
self.assertEqual(validateList(vms)[0], PASS, "vm list validation failed")
self.assertEqual(vms[0].nic[0].ipaddress,
virtual_machine_1.ipaddress,
"VM IP should not change after reservation")
#Restart Network
isolated_network.restart(self.apiclient, cleanup=value)
try:
virtual_machine_2 = createVirtualMachine(self, network_id=isolated_network.id)
if netaddr.IPAddress(virtual_machine_2.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
return
@ddt
class TestUpdateIPReservation(cloudstackTestCase):
"""Test Updating IP reservation multiple times
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestUpdateIPReservation, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.testData = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testData["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.testData["ostype"]
cls.testData["domainid"] = cls.domain.id
cls.testData["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
try:
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testData["service_offering"]
)
cls._cleanup.append(cls.service_offering)
cls.isolated_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["isolated_network_offering"])
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_persistent_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["nw_off_isolated_persistent"])
cls._cleanup.append(cls.isolated_persistent_network_offering)
except Exception as e:
cls.tearDownClass()
raise unittest.SkipTest("Failure in setUpClass: %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
try:
self.account = Account.create(self.apiclient, self.testData["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
except Exception as e:
self.skipTest("Failed to create account: %s" % e)
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@data("existingVmInclusive", "existingVmExclusive")
@attr(tags=["advanced"])
def test_update_network_guestvmcidr(self, value):
""" Test updating guest vm cidr of the network after
VMs are already deployed in previous guest VM cidr
# steps
# 1. Create isolated network with user defined cidr
# 2. Deploy VM in the network
# 3. Try to update the guestvmcidr of the network with VM ip in the guestvmcidr and
# deploy another VM
# 4. Try to update the guestvmcidr of the network with VM ip outside the guestvmcidr
#
# validation
# 1. When vm IP is in the guestvmcidr, updation should be successful and
# new VM should get IP from this range
# 2. When VM IP is outside the guestvmcidr, updation should be unsuccessful"""
random_subnet = str(random.randrange(1,254))
gateway = "10.1." + random_subnet +".1"
resultSet = createIsolatedNetwork(self, self.isolated_network_offering.id,
gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network= resultSet[1]
guest_vm_cidr = "10.1."+random_subnet+".0/29"
try:
virtual_machine_1 = createVirtualMachine(self, network_id=isolated_network.id,
ip_address="10.1."+random_subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network.id, guest_vm_cidr)
vms = VirtualMachine.list(self.apiclient,
id=virtual_machine_1.id)
self.assertEqual(validateList(vms)[0], PASS, "vm list validation failed")
self.assertEqual(vms[0].nic[0].ipaddress,
virtual_machine_1.ipaddress,
"VM IP should not change after reservation")
try:
virtual_machine_2 = createVirtualMachine(self, network_id=isolated_network.id)
if netaddr.IPAddress(virtual_machine_2.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
# Update guest vm cidr of network again
if value == "existingVmExclusive":
guest_vm_cidr = "10.1."+random_subnet+".10/29"
try:
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
self.fail("Network updation should fail")
except Exception as e:
self.debug("Failed to update guest VM cidr of network: %s" % e)
elif value == "existingVmInclusive":
guest_vm_cidr = "10.1."+random_subnet+".0/28"
try:
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
except Exception as e:
self.fail("Failed to update guest VM cidr of network: %s" % e)
matchNetworkGuestVmCIDR(self, isolated_network.id, guest_vm_cidr)
try:
virtual_machine_3 = createVirtualMachine(self, network_id=isolated_network.id)
if netaddr.IPAddress(virtual_machine_3.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
return
@ddt
class TestRouterOperations(cloudstackTestCase):
"""Test Router operations of network with IP reservation
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestRouterOperations, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.testData = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testData["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.testData["ostype"]
cls.testData["domainid"] = cls.domain.id
cls.testData["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
try:
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testData["service_offering"]
)
cls._cleanup.append(cls.service_offering)
cls.isolated_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["isolated_network_offering"])
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_persistent_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["nw_off_isolated_persistent"])
cls._cleanup.append(cls.isolated_persistent_network_offering)
except Exception as e:
cls.tearDownClass()
raise unittest.SkipTest("Failure in setUpClass: %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
try:
self.account = Account.create(self.apiclient, self.testData["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
except Exception as e:
self.skipTest("Failed to create account: %s" % e)
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced"])
def test_reservation_after_router_restart(self):
""" Test IP reservation working before and after router is restarted
# steps
# 1. Update guestvmcidr of persistent isolated network
# 2. Reboot router
#
# validation
# 1. Guest vm cidr should be successfully updated with correct value
# 2. Network cidr should remain same after router restart"""
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, self.isolated_persistent_network_offering.id,
gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network= resultSet[1]
guest_vm_cidr = subnet+".0/29"
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network.id, guest_vm_cidr)
routers = Router.list(self.apiclient,
networkid=isolated_network.id,
listall=True)
self.assertEqual(validateList(routers)[0], PASS, "routers list validation failed")
if not routers:
self.fail("Router list should not be empty")
Router.reboot(self.apiclient, routers[0].id)
networks = Network.list(self.apiclient, id=isolated_network.id)
self.assertEqual(validateList(networks)[0], PASS, "networks list validation failed")
self.assertEqual(networks[0].cidr, guest_vm_cidr, "guestvmcidr should match after router reboot")
return
@attr(tags=["advanced"])
def test_destroy_recreate_router(self):
""" Test IP reservation working after destroying and recreating router
# steps
# 1. Create isolated network and deploy VM in it and update network with
# guestvmcidr
# 2. List the router associated with network and destroy the router
# 3. Restart the network
# 3. Deploy another VM in the network
#
# validation
# 1. Guest vm cidr should be successfully updated with correct value
# 2. existing guest vm ip should not be changed after reservation
# 3. Router should be destroyed and recreated when network is restarted
# 4. New VM should be deployed in the guestvmcidr"""
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet +".1"
resultSet = createIsolatedNetwork(self, self.isolated_network_offering.id,
gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network= resultSet[1]
guest_vm_cidr = subnet+".0/29"
try:
virtual_machine_1 = createVirtualMachine(self, network_id=isolated_network.id,
ip_address=subnet+".3")
except Exception as e:
self.fail("VM creation failed: %s" % e)
isolated_network.update(self.apiclient, guestvmcidr=guest_vm_cidr)
matchNetworkGuestVmCIDR(self, isolated_network.id, guest_vm_cidr)
vms = VirtualMachine.list(self.apiclient,
id=virtual_machine_1.id)
self.assertEqual(validateList(vms)[0], PASS, "vm list validation failed")
self.assertEqual(vms[0].nic[0].ipaddress,
virtual_machine_1.ipaddress,
"VM IP should not change after reservation")
# List router and destroy it
routers = Router.list(self.apiclient, networkid=isolated_network.id, listall=True)
self.assertEqual(validateList(routers)[0], PASS, "Routers list validation failed")
# Destroy Router
Router.destroy(self.apiclient, id=routers[0].id)
#Restart Network
isolated_network.restart(self.apiclient)
try:
virtual_machine_2 = createVirtualMachine(self, network_id=isolated_network.id)
if netaddr.IPAddress(virtual_machine_2.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.fail("VM creation failed, cannot validate the condition: %s" % e)
return
@ddt
class TestFailureScnarios(cloudstackTestCase):
"""Test failure scenarios related to IP reservation in network
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestFailureScnarios, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
# Fill services from the external config file
cls.testData = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.testData["ostype"]
)
if cls.template == FAILED:
assert False, "get_template() failed to return template with description %s" % cls.testData["ostype"]
cls.testData["domainid"] = cls.domain.id
cls.testData["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["zoneid"] = cls.zone.id
cls.testData["virtual_machine"]["template"] = cls.template.id
cls._cleanup = []
try:
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testData["service_offering"]
)
cls._cleanup.append(cls.service_offering)
cls.isolated_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["isolated_network_offering"])
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_persistent_network_offering = CreateEnabledNetworkOffering(cls.api_client,
cls.testData["nw_off_isolated_persistent"])
cls._cleanup.append(cls.isolated_persistent_network_offering)
cls.testData["shared_network_offering"]["specifyVlan"] = "True"
cls.testData["shared_network_offering"]["specifyIpRanges"] = "True"
#Create Network Offering
cls.shared_network_offering = NetworkOffering.create(cls.api_client,
cls.testData["shared_network_offering"],
conservemode=False)
cls._cleanup.append(cls.shared_network_offering)
#Update network offering state from disabled to enabled.
NetworkOffering.update(cls.shared_network_offering,cls.api_client,state="enabled")
except Exception as e:
cls.tearDownClass()
raise unittest.SkipTest("Failure in setUpClass: %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
try:
self.account = Account.create(self.apiclient, self.testData["account"],
domainid=self.domain.id)
self.cleanup.append(self.account)
except Exception as e:
self.skipTest("Failed to create account: %s" % e)
return
def tearDown(self):
try:
# Clean up, terminate the resources created
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced"], required_hardware="false")
def test_network_not_implemented(self):
# steps
# 1. update guestvmcidr of isolated network (non persistent)
#
# validation
# should throw exception as network is not in implemented state as no vm is created
networkOffering = self.isolated_network_offering
resultSet = createIsolatedNetwork(self, networkOffering.id)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_network = resultSet[1]
with self.assertRaises(Exception):
isolated_network.update(self.apiclient, guestvmcidr="10.1.1.0/26")
return
@attr(tags=["advanced"], required_hardware="false")
def test_vm_create_after_reservation(self):
# steps
# 1. create vm in persistent isolated network with ip in guestvmcidr
# 2. update guestvmcidr
# 3. create another VM
#
# validation
# 1. guest vm cidr should be successfully updated with correct value
# 2. existing guest vm ip should not be changed after reservation
# 3. newly created VM should get ip in guestvmcidr
networkOffering = self.isolated_persistent_network_offering
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet + ".1"
isolated_persistent_network = None
resultSet = createIsolatedNetwork(self, networkOffering.id, gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_persistent_network = resultSet[1]
guest_vm_cidr = subnet +".0/29"
virtual_machine_1 = None
try:
virtual_machine_1 = VirtualMachine.create(self.apiclient,
self.testData["virtual_machine"],
networkids=isolated_persistent_network.id,
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.domain.id,
ipaddress=subnet+".3"
)
except Exception as e:
self.fail("VM creation fails in network: %s" % e)
update_response = Network.update(isolated_persistent_network, self.apiclient, id=isolated_persistent_network.id, guestvmcidr=guest_vm_cidr)
self.assertEqual(guest_vm_cidr, update_response.cidr, "cidr in response is not as expected")
vm_list = VirtualMachine.list(self.apiclient,
id=virtual_machine_1.id)
self.assertEqual(isinstance(vm_list, list),
True,
"VM list response in not a valid list")
self.assertEqual(vm_list[0].nic[0].ipaddress,
virtual_machine_1.ipaddress,
"VM IP should not change after reservation")
try:
virtual_machine_2 = VirtualMachine.create(self.apiclient,
self.testData["virtual_machine"],
networkids=isolated_persistent_network.id,
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.domain.id
)
if netaddr.IPAddress(virtual_machine_2.ipaddress) not in netaddr.IPNetwork(guest_vm_cidr):
self.fail("Newly created VM doesn't get IP from reserverd CIDR")
except Exception as e:
self.skipTest("VM creation fails, cannot validate the condition: %s" % e)
return
@attr(tags=["advanced"], required_hardware="false")
def test_reservation_after_router_restart(self):
# steps
# 1. update guestvmcidr of persistent isolated network
# 2. reboot router
#
# validation
# 1. guest vm cidr should be successfully updated with correct value
# 2. network cidr should remain same after router restart
networkOffering = self.isolated_persistent_network_offering
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet + ".1"
isolated_persistent_network = None
resultSet = createIsolatedNetwork(self, networkOffering.id, gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_persistent_network = resultSet[1]
response = verifyNetworkState(self.apiclient, isolated_persistent_network.id,\
"implemented")
exceptionOccured = response[0]
isNetworkInDesiredState = response[1]
exceptionMessage = response[2]
if (exceptionOccured or (not isNetworkInDesiredState)):
self.fail(exceptionMessage)
guest_vm_cidr = subnet +".0/29"
update_response = Network.update(isolated_persistent_network, self.apiclient, id=isolated_persistent_network.id, guestvmcidr=guest_vm_cidr)
self.assertEqual(guest_vm_cidr, update_response.cidr, "cidr in response is not as expected")
routers = Router.list(self.apiclient,
networkid=isolated_persistent_network.id,
listall=True)
self.assertEqual(
isinstance(routers, list),
True,
"list router should return valid response"
)
if not routers:
self.skipTest("Router list should not be empty, skipping test")
Router.reboot(self.apiclient, routers[0].id)
networks = Network.list(self.apiclient, id=isolated_persistent_network.id)
self.assertEqual(
isinstance(networks, list),
True,
"list Networks should return valid response"
)
self.assertEqual(networks[0].cidr, guest_vm_cidr, "guestvmcidr should match after router reboot")
return
@attr(tags=["advanced"], required_hardware="false")
def test_vm_create_outside_cidr_after_reservation(self):
# steps
# 1. update guestvmcidr of persistent isolated network
# 2. create another VM with ip outside guestvmcidr
#
# validation
# 1. guest vm cidr should be successfully updated with correct value
# 2 newly created VM should not be created and result in exception
networkOffering = self.isolated_persistent_network_offering
subnet = "10.1."+str(random.randrange(1,254))
gateway = subnet + ".1"
isolated_persistent_network = None
resultSet = createIsolatedNetwork(self, networkOffering.id, gateway=gateway)
if resultSet[0] == FAIL:
self.fail("Failed to create isolated network")
else:
isolated_persistent_network = resultSet[1]
guest_vm_cidr = subnet +".0/29"
update_response = Network.update(isolated_persistent_network, self.apiclient, id=isolated_persistent_network.id, guestvmcidr=guest_vm_cidr)
self.assertEqual(guest_vm_cidr, update_response.cidr, "cidr in response is not as expected")
with self.assertRaises(Exception):
VirtualMachine.create(self.apiclient,
self.testData["virtual_machine"],
networkids=isolated_persistent_network.id,
serviceofferingid=self.service_offering.id,
accountid=self.account.name,
domainid=self.domain.id,
ipaddress="10.1.1.9"
)
return
| [
"marvin.lib.base.Router.reboot",
"marvin.lib.base.Network.list",
"marvin.lib.utils.validateList",
"marvin.lib.common.wait_for_cleanup",
"marvin.lib.common.createEnabledNetworkOffering",
"marvin.lib.base.NetworkOffering.update",
"marvin.lib.common.createNetworkRulesForVM",
"marvin.lib.base.Network.upda... | [((2902, 2958), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'networkid', 'listall': '(True)'}), '(self.apiclient, id=networkid, listall=True)\n', (2914, 2958), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((3398, 3620), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testData['virtual_machine']"], {'networkids': 'network_id', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.domain.id', 'ipaddress': 'ip_address'}), "(self.apiclient, self.testData['virtual_machine'],\n networkids=network_id, serviceofferingid=self.service_offering.id,\n accountid=self.account.name, domainid=self.domain.id, ipaddress=ip_address)\n", (3419, 3620), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((4048, 4104), 'marvin.lib.common.createEnabledNetworkOffering', 'createEnabledNetworkOffering', (['apiclient', 'networkServices'], {}), '(apiclient, networkServices)\n', (4076, 4104), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((7623, 7646), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (7627, 7646), False, 'from nose.plugins.attrib import attr\n'), ((9762, 9785), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (9766, 9785), False, 'from nose.plugins.attrib import attr\n'), ((11175, 11198), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (11179, 11198), False, 'from nose.plugins.attrib import attr\n'), ((12592, 12615), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (12596, 12615), False, 'from nose.plugins.attrib import attr\n'), ((13799, 13830), 'ddt.data', 'data', (['NAT_RULE', 'STATIC_NAT_RULE'], {}), '(NAT_RULE, STATIC_NAT_RULE)\n', (13803, 13830), False, 'from ddt import ddt, data\n'), ((13836, 13885), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (13840, 13885), False, 'from nose.plugins.attrib import attr\n'), ((16869, 16896), 'unittest.skip', 'unittest.skip', (['"""Skip - WIP"""'], {}), "('Skip - WIP')\n", (16882, 16896), False, 'import unittest\n'), ((16902, 16925), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (16906, 16925), False, 'from nose.plugins.attrib import attr\n'), ((20458, 20481), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (20462, 20481), False, 'from nose.plugins.attrib import attr\n'), ((28833, 28850), 'ddt.data', 'data', (['(True)', '(False)'], {}), '(True, False)\n', (28837, 28850), False, 'from ddt import ddt, data\n'), ((28856, 28879), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (28860, 28879), False, 'from nose.plugins.attrib import attr\n'), ((34407, 34457), 'ddt.data', 'data', (['"""existingVmInclusive"""', '"""existingVmExclusive"""'], {}), "('existingVmInclusive', 'existingVmExclusive')\n", (34411, 34457), False, 'from ddt import ddt, data\n'), ((34463, 34486), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (34467, 34486), False, 'from nose.plugins.attrib import attr\n'), ((41320, 41343), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (41324, 41343), False, 'from nose.plugins.attrib import attr\n'), ((43001, 43024), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']"}), "(tags=['advanced'])\n", (43005, 43024), False, 'from nose.plugins.attrib import attr\n'), ((49553, 49603), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (49557, 49603), False, 'from nose.plugins.attrib import attr\n'), ((50276, 50326), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (50280, 50326), False, 'from nose.plugins.attrib import attr\n'), ((53696, 53746), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (53700, 53746), False, 'from nose.plugins.attrib import attr\n'), ((56065, 56115), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""false"""'}), "(tags=['advanced'], required_hardware='false')\n", (56069, 56115), False, 'from nose.plugins.attrib import attr\n'), ((2315, 2570), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.testData['isolated_network']"], {'networkofferingid': 'network_offering_id', 'accountid': 'self.account.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id', 'gateway': 'gateway', 'netmask': "('255.255.255.0' if gateway else None)"}), "(self.apiclient, self.testData['isolated_network'],\n networkofferingid=network_offering_id, accountid=self.account.name,\n domainid=self.domain.id, zoneid=self.zone.id, gateway=gateway, netmask=\n '255.255.255.0' if gateway else None)\n", (2329, 2570), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((4682, 4708), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (4692, 4708), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((4810, 4875), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.testData['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.testData['ostype'])\n", (4822, 4875), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((8980, 9040), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_1.id'}), '(self.apiclient, id=virtual_machine_1.id)\n', (8999, 9040), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((15187, 15286), 'marvin.lib.common.createNetworkRulesForVM', 'createNetworkRulesForVM', (['self.apiclient', 'virtual_machine_1', 'value', 'self.account', 'self.testData'], {}), '(self.apiclient, virtual_machine_1, value, self.\n account, self.testData)\n', (15210, 15286), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((15729, 15789), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_1.id'}), '(self.apiclient, id=virtual_machine_1.id)\n', (15748, 15789), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((16469, 16568), 'marvin.lib.common.createNetworkRulesForVM', 'createNetworkRulesForVM', (['self.apiclient', 'virtual_machine_2', 'value', 'self.account', 'self.testData'], {}), '(self.apiclient, virtual_machine_2, value, self.\n account, self.testData)\n', (16492, 16568), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((18470, 18530), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_1.id'}), '(self.apiclient, id=virtual_machine_1.id)\n', (18489, 18530), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((18930, 19006), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'isolated_network_RVR.id', 'listall': '(True)'}), '(self.apiclient, networkid=isolated_network_RVR.id, listall=True)\n', (18941, 19006), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((19710, 19769), 'marvin.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.apiclient', "['router.check.interval']"], {}), "(self.apiclient, ['router.check.interval'])\n", (19726, 19769), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((19788, 19841), 'marvin.lib.utils.verifyRouterState', 'verifyRouterState', (['master_router.id', '[UNKNOWN, FAULT]'], {}), '(master_router.id, [UNKNOWN, FAULT])\n', (19805, 19841), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((19921, 19966), 'marvin.lib.utils.verifyRouterState', 'verifyRouterState', (['backup_router.id', '[MASTER]'], {}), '(backup_router.id, [MASTER])\n', (19938, 19966), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((21199, 21285), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testData['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['account'], domainid=self.\n domain.id)\n", (21213, 21285), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((21489, 21735), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.testData['isolated_network']"], {'networkofferingid': 'self.isolated_network_offering.id', 'accountid': 'account_1.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id', 'gateway': 'gateway', 'netmask': '"""255.255.255.0"""'}), "(self.apiclient, self.testData['isolated_network'],\n networkofferingid=self.isolated_network_offering.id, accountid=\n account_1.name, domainid=self.domain.id, zoneid=self.zone.id, gateway=\n gateway, netmask='255.255.255.0')\n", (21503, 21735), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((22517, 22577), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_1.id'}), '(self.apiclient, id=virtual_machine_1.id)\n', (22536, 22577), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((23640, 23886), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.testData['isolated_network']"], {'networkofferingid': 'self.isolated_network_offering.id', 'accountid': 'account_1.name', 'domainid': 'self.domain.id', 'zoneid': 'self.zone.id', 'gateway': 'gateway', 'netmask': '"""255.255.255.0"""'}), "(self.apiclient, self.testData['isolated_network'],\n networkofferingid=self.isolated_network_offering.id, accountid=\n account_1.name, domainid=self.domain.id, zoneid=self.zone.id, gateway=\n gateway, netmask='255.255.255.0')\n", (23654, 23886), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((24668, 24728), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_3.id'}), '(self.apiclient, id=virtual_machine_3.id)\n', (24687, 24728), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((26117, 26143), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (26127, 26143), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((26245, 26310), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.testData['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.testData['ostype'])\n", (26257, 26310), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((30353, 30413), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_1.id'}), '(self.apiclient, id=virtual_machine_1.id)\n', (30372, 30413), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((31695, 31721), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (31705, 31721), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((31823, 31888), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.testData['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.testData['ostype'])\n", (31835, 31888), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((36099, 36159), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_1.id'}), '(self.apiclient, id=virtual_machine_1.id)\n', (36118, 36159), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((38604, 38630), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (38614, 38630), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((38732, 38797), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.testData['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.testData['ostype'])\n", (38744, 38797), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((42352, 42424), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'isolated_network.id', 'listall': '(True)'}), '(self.apiclient, networkid=isolated_network.id, listall=True)\n', (42363, 42424), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((42664, 42708), 'marvin.lib.base.Router.reboot', 'Router.reboot', (['self.apiclient', 'routers[0].id'], {}), '(self.apiclient, routers[0].id)\n', (42677, 42708), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((42728, 42780), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'isolated_network.id'}), '(self.apiclient, id=isolated_network.id)\n', (42740, 42780), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((44560, 44620), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_1.id'}), '(self.apiclient, id=virtual_machine_1.id)\n', (44579, 44620), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((44975, 45047), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'isolated_network.id', 'listall': '(True)'}), '(self.apiclient, networkid=isolated_network.id, listall=True)\n', (44986, 45047), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((45173, 45221), 'marvin.lib.base.Router.destroy', 'Router.destroy', (['self.apiclient'], {'id': 'routers[0].id'}), '(self.apiclient, id=routers[0].id)\n', (45187, 45221), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((46198, 46224), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (46208, 46224), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((46326, 46391), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.testData['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.testData['ostype'])\n", (46338, 46391), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((52097, 52223), 'marvin.lib.base.Network.update', 'Network.update', (['isolated_persistent_network', 'self.apiclient'], {'id': 'isolated_persistent_network.id', 'guestvmcidr': 'guest_vm_cidr'}), '(isolated_persistent_network, self.apiclient, id=\n isolated_persistent_network.id, guestvmcidr=guest_vm_cidr)\n', (52111, 52223), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((52338, 52398), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine_1.id'}), '(self.apiclient, id=virtual_machine_1.id)\n', (52357, 52398), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((54543, 54628), 'marvin.lib.common.verifyNetworkState', 'verifyNetworkState', (['self.apiclient', 'isolated_persistent_network.id', '"""implemented"""'], {}), "(self.apiclient, isolated_persistent_network.id,\n 'implemented')\n", (54561, 54628), False, 'from marvin.lib.common import get_zone, get_template, get_domain, wait_for_cleanup, createEnabledNetworkOffering, createNetworkRulesForVM, verifyNetworkState\n'), ((54946, 55072), 'marvin.lib.base.Network.update', 'Network.update', (['isolated_persistent_network', 'self.apiclient'], {'id': 'isolated_persistent_network.id', 'guestvmcidr': 'guest_vm_cidr'}), '(isolated_persistent_network, self.apiclient, id=\n isolated_persistent_network.id, guestvmcidr=guest_vm_cidr)\n', (54960, 55072), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((55188, 55275), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'isolated_persistent_network.id', 'listall': '(True)'}), '(self.apiclient, networkid=isolated_persistent_network.id,\n listall=True)\n', (55199, 55275), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((55623, 55667), 'marvin.lib.base.Router.reboot', 'Router.reboot', (['self.apiclient', 'routers[0].id'], {}), '(self.apiclient, routers[0].id)\n', (55636, 55667), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((55687, 55750), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'isolated_persistent_network.id'}), '(self.apiclient, id=isolated_persistent_network.id)\n', (55699, 55750), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((57008, 57134), 'marvin.lib.base.Network.update', 'Network.update', (['isolated_persistent_network', 'self.apiclient'], {'id': 'isolated_persistent_network.id', 'guestvmcidr': 'guest_vm_cidr'}), '(isolated_persistent_network, self.apiclient, id=\n isolated_persistent_network.id, guestvmcidr=guest_vm_cidr)\n', (57022, 57134), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((2980, 3002), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (2992, 3002), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((5441, 5513), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.testData['service_offering']"], {}), "(cls.api_client, cls.testData['service_offering'])\n", (5463, 5513), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((6699, 6746), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (6716, 6746), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((7069, 7155), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testData['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['account'], domainid=self.\n domain.id)\n", (7083, 7155), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((7449, 7496), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (7466, 7496), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((19509, 19557), 'marvin.lib.base.Router.stop', 'Router.stop', (['self.apiclient'], {'id': 'master_router.id'}), '(self.apiclient, id=master_router.id)\n', (19520, 19557), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((21387, 21411), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (21403, 21411), False, 'import random\n'), ((21895, 22150), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testData['virtual_machine']"], {'networkids': 'isolated_network_1.id', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account_1.name', 'domainid': 'self.domain.id', 'ipaddress': "('10.1.' + random_subnet + '.3')"}), "(self.apiclient, self.testData['virtual_machine'],\n networkids=isolated_network_1.id, serviceofferingid=self.\n service_offering.id, accountid=account_1.name, domainid=self.domain.id,\n ipaddress='10.1.' + random_subnet + '.3')\n", (21916, 22150), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((22922, 23131), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testData['virtual_machine']"], {'networkids': 'isolated_network_1.id', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account_1.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['virtual_machine'],\n networkids=isolated_network_1.id, serviceofferingid=self.\n service_offering.id, accountid=account_1.name, domainid=self.domain.id)\n", (22943, 23131), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((23538, 23562), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (23554, 23562), False, 'import random\n'), ((24046, 24301), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testData['virtual_machine']"], {'networkids': 'isolated_network_2.id', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account_1.name', 'domainid': 'self.domain.id', 'ipaddress': "('10.1.' + random_subnet + '.3')"}), "(self.apiclient, self.testData['virtual_machine'],\n networkids=isolated_network_2.id, serviceofferingid=self.\n service_offering.id, accountid=account_1.name, domainid=self.domain.id,\n ipaddress='10.1.' + random_subnet + '.3')\n", (24067, 24301), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((25073, 25282), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testData['virtual_machine']"], {'networkids': 'isolated_network_2.id', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'account_1.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['virtual_machine'],\n networkids=isolated_network_2.id, serviceofferingid=self.\n service_offering.id, accountid=account_1.name, domainid=self.domain.id)\n", (25094, 25282), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((26876, 26948), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.testData['service_offering']"], {}), "(cls.api_client, cls.testData['service_offering'])\n", (26898, 26948), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((27909, 27956), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (27926, 27956), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((28279, 28365), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testData['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['account'], domainid=self.\n domain.id)\n", (28293, 28365), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((28659, 28706), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (28676, 28706), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((32454, 32526), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.testData['service_offering']"], {}), "(cls.api_client, cls.testData['service_offering'])\n", (32476, 32526), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((33483, 33530), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (33500, 33530), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((33853, 33939), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testData['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['account'], domainid=self.\n domain.id)\n", (33867, 33939), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((34233, 34280), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (34250, 34280), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((35270, 35294), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (35286, 35294), False, 'import random\n'), ((39363, 39435), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.testData['service_offering']"], {}), "(cls.api_client, cls.testData['service_offering'])\n", (39385, 39435), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((40396, 40443), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (40413, 40443), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((40766, 40852), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testData['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['account'], domainid=self.\n domain.id)\n", (40780, 40852), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((41146, 41193), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (41163, 41193), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((46957, 47029), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.testData['service_offering']"], {}), "(cls.api_client, cls.testData['service_offering'])\n", (46979, 47029), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((47968, 48072), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.testData['shared_network_offering']"], {'conservemode': '(False)'}), "(cls.api_client, cls.testData[\n 'shared_network_offering'], conservemode=False)\n", (47990, 48072), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((48291, 48380), 'marvin.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['cls.shared_network_offering', 'cls.api_client'], {'state': '"""enabled"""'}), "(cls.shared_network_offering, cls.api_client, state=\n 'enabled')\n", (48313, 48380), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((48629, 48676), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (48646, 48676), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((48999, 49085), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.testData['account']"], {'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['account'], domainid=self.\n domain.id)\n", (49013, 49085), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((49379, 49426), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (49396, 49426), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((51334, 51585), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testData['virtual_machine']"], {'networkids': 'isolated_persistent_network.id', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.domain.id', 'ipaddress': "(subnet + '.3')"}), "(self.apiclient, self.testData['virtual_machine'],\n networkids=isolated_persistent_network.id, serviceofferingid=self.\n service_offering.id, accountid=self.account.name, domainid=self.domain.\n id, ipaddress=subnet + '.3')\n", (51355, 51585), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((52812, 53033), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testData['virtual_machine']"], {'networkids': 'isolated_persistent_network.id', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.domain.id'}), "(self.apiclient, self.testData['virtual_machine'],\n networkids=isolated_persistent_network.id, serviceofferingid=self.\n service_offering.id, accountid=self.account.name, domainid=self.domain.id)\n", (52833, 53033), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((57286, 57534), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.testData['virtual_machine']"], {'networkids': 'isolated_persistent_network.id', 'serviceofferingid': 'self.service_offering.id', 'accountid': 'self.account.name', 'domainid': 'self.domain.id', 'ipaddress': '"""10.1.1.9"""'}), "(self.apiclient, self.testData['virtual_machine'],\n networkids=isolated_persistent_network.id, serviceofferingid=self.\n service_offering.id, accountid=self.account.name, domainid=self.domain.\n id, ipaddress='10.1.1.9')\n", (57307, 57534), False, 'from marvin.lib.base import Account, Network, VirtualMachine, Router, ServiceOffering, NetworkOffering\n'), ((6525, 6575), 'unittest.SkipTest', 'unittest.SkipTest', (["('Failure in setUpClass: %s' % e)"], {}), "('Failure in setUpClass: %s' % e)\n", (6542, 6575), False, 'import unittest\n'), ((8251, 8275), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (8267, 8275), False, 'import random\n'), ((9105, 9122), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (9117, 9122), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((9458, 9504), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_2.ipaddress'], {}), '(virtual_machine_2.ipaddress)\n', (9475, 9504), False, 'import netaddr\n'), ((9512, 9544), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (9529, 9544), False, 'import netaddr\n'), ((10371, 10395), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (10387, 10395), False, 'import random\n'), ((11637, 11661), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (11653, 11661), False, 'import random\n'), ((13056, 13080), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (13072, 13080), False, 'import random\n'), ((14550, 14574), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (14566, 14574), False, 'import random\n'), ((15815, 15832), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (15827, 15832), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((16168, 16214), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_2.ipaddress'], {}), '(virtual_machine_2.ipaddress)\n', (16185, 16214), False, 'import netaddr\n'), ((16222, 16254), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (16239, 16254), False, 'import netaddr\n'), ((17668, 17692), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (17684, 17692), False, 'import random\n'), ((18595, 18612), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (18607, 18612), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((19032, 19053), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (19044, 19053), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((20154, 20200), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_2.ipaddress'], {}), '(virtual_machine_2.ipaddress)\n', (20171, 20200), False, 'import netaddr\n'), ((20208, 20240), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (20225, 20240), False, 'import netaddr\n'), ((22642, 22659), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (22654, 22659), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((23226, 23272), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_2.ipaddress'], {}), '(virtual_machine_2.ipaddress)\n', (23243, 23272), False, 'import netaddr\n'), ((23280, 23312), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (23297, 23312), False, 'import netaddr\n'), ((24793, 24810), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (24805, 24810), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((25377, 25423), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_4.ipaddress'], {}), '(virtual_machine_4.ipaddress)\n', (25394, 25423), False, 'import netaddr\n'), ((25431, 25463), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (25448, 25463), False, 'import netaddr\n'), ((27735, 27785), 'unittest.SkipTest', 'unittest.SkipTest', (["('Failure in setUpClass: %s' % e)"], {}), "('Failure in setUpClass: %s' % e)\n", (27752, 27785), False, 'import unittest\n'), ((29571, 29595), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (29587, 29595), False, 'import random\n'), ((30478, 30495), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (30490, 30495), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((30922, 30968), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_2.ipaddress'], {}), '(virtual_machine_2.ipaddress)\n', (30939, 30968), False, 'import netaddr\n'), ((30976, 31008), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (30993, 31008), False, 'import netaddr\n'), ((33309, 33359), 'unittest.SkipTest', 'unittest.SkipTest', (["('Failure in setUpClass: %s' % e)"], {}), "('Failure in setUpClass: %s' % e)\n", (33326, 33359), False, 'import unittest\n'), ((36224, 36241), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (36236, 36241), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((36578, 36624), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_2.ipaddress'], {}), '(virtual_machine_2.ipaddress)\n', (36595, 36624), False, 'import netaddr\n'), ((36632, 36664), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (36649, 36664), False, 'import netaddr\n'), ((40222, 40272), 'unittest.SkipTest', 'unittest.SkipTest', (["('Failure in setUpClass: %s' % e)"], {}), "('Failure in setUpClass: %s' % e)\n", (40239, 40272), False, 'import unittest\n'), ((41786, 41810), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (41802, 41810), False, 'import random\n'), ((42508, 42529), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (42520, 42529), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((42806, 42828), 'marvin.lib.utils.validateList', 'validateList', (['networks'], {}), '(networks)\n', (42818, 42828), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((43778, 43802), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (43794, 43802), False, 'import random\n'), ((44685, 44702), 'marvin.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (44697, 44702), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((45073, 45094), 'marvin.lib.utils.validateList', 'validateList', (['routers'], {}), '(routers)\n', (45085, 45094), False, 'from marvin.lib.utils import validateList, cleanup_resources, verifyRouterState\n'), ((45417, 45463), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_2.ipaddress'], {}), '(virtual_machine_2.ipaddress)\n', (45434, 45463), False, 'import netaddr\n'), ((45471, 45503), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (45488, 45503), False, 'import netaddr\n'), ((48455, 48505), 'unittest.SkipTest', 'unittest.SkipTest', (["('Failure in setUpClass: %s' % e)"], {}), "('Failure in setUpClass: %s' % e)\n", (48472, 48505), False, 'import unittest\n'), ((50870, 50894), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (50886, 50894), False, 'import random\n'), ((53389, 53435), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_2.ipaddress'], {}), '(virtual_machine_2.ipaddress)\n', (53406, 53435), False, 'import netaddr\n'), ((53443, 53475), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (53460, 53475), False, 'import netaddr\n'), ((54177, 54201), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (54193, 54201), False, 'import random\n'), ((56596, 56620), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (56612, 56620), False, 'import random\n'), ((37815, 37861), 'netaddr.IPAddress', 'netaddr.IPAddress', (['virtual_machine_3.ipaddress'], {}), '(virtual_machine_3.ipaddress)\n', (37832, 37861), False, 'import netaddr\n'), ((37869, 37901), 'netaddr.IPNetwork', 'netaddr.IPNetwork', (['guest_vm_cidr'], {}), '(guest_vm_cidr)\n', (37886, 37901), False, 'import netaddr\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for networks in advanced zone with security groups
"""
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from ddt import ddt, data
from marvin.integration.lib.base import (Zone,
ServiceOffering,
Account,
NetworkOffering,
Network,
VirtualMachine,
Domain,
VpcOffering,
VPC,
SecurityGroup)
from marvin.integration.lib.common import (get_domain,
get_zone,
get_template,
get_free_vlan,
list_virtual_machines,
wait_for_cleanup)
from marvin.integration.lib.utils import (cleanup_resources,
random_gen,
validateList)
from marvin.cloudstackAPI import (authorizeSecurityGroupIngress,
revokeSecurityGroupIngress)
from nose.plugins.attrib import attr
from marvin.codes import PASS
import time
import random
class TestCreateZoneSG(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cloudstackTestClient = super(TestCreateZoneSG,cls).getClsTestClient()
cls.api_client = cloudstackTestClient.getApiClient()
# Fill services from the external config file
cls.services = cloudstackTestClient.getConfigParser().parsedDict
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls._cleanup = []
return
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.api_client = self.testClient.getApiClient()
self.debug(self.services)
self.cleanup = []
return
def tearDown(self):
try:
#Clean up, terminate the created network offerings
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def createzone(self, sec_grps=True):
self.services["advanced_sg"]["zone"]["name"] = "AdvZoneSG-" + random_gen(size=6)
self.services["advanced_sg"]["zone"]["securitygroupenabled"] = sec_grps
self.debug(self.services["advanced_sg"]["zone"]["securitygroupenabled"])
try:
zone = Zone.create(self.api_client, self.services["advanced_sg"]["zone"])
self.cleanup.append(zone)
except Exception as e:
self.fail("Exception while creating zone: %s" % e)
return zone
def assert_on_sg_flag(self, flag, listzones):
self.assertEqual(listzones[0].securitygroupsenabled, flag,
"Security Group enabled flag is %s with created Zone"
% listzones[0].securitygroupsenabled)
return
@attr(tags = ["advancedsg"])
def test_01_createZone_secGrp_enabled(self):
""" Test to verify Advance Zone with security group enabled can be created"""
# Validate:
# Create Advance Zone SG enabled using API
self.debug("Creating zone with secGrps Enabled")
zone = self.createzone()
self.debug("Created zone : %s" % zone.id)
listzones = Zone.list(self.api_client, id=zone.id)
self.debug("Checking if SecGroup flag is enabled for the zone")
self.assert_on_sg_flag(True, listzones)
return
@attr(tags = ["advancedsg"])
def test_02_createZone_secGrp_disabled(self):
""" Test to verify Advance Zone created with flag
securitygroupsenabled=False"""
# Validate:
# Create Advance Zone without SG enabled
# Verify that the SG enabled flag is false
self.debug("Creating zone with secGrps Enabled")
zone = self.createzone(sec_grps=False)
self.debug("Created zone : %s" % zone.id)
listzones = Zone.list(self.api_client, id=zone.id)
self.debug("Checking if SecGroup flag is False for the zone")
self.assert_on_sg_flag(False, listzones)
return
class TestNetworksInAdvancedSG(cloudstackTestCase):
"""Test Creation of different types of networks in SG enabled advanced zone"""
@classmethod
def setUpClass(cls):
cloudstackTestClient = super(TestNetworksInAdvancedSG,cls).getClsTestClient()
cls.api_client = cloudstackTestClient.getApiClient()
cls.services = cloudstackTestClient.getConfigParser().parsedDict
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.template = get_template(cls.api_client, cls.zone.id,
cls.services["ostype"])
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(cls.api_client,cls.services["service_offering"])
cls._cleanup = [
cls.service_offering,
]
return
@classmethod
def tearDownClass(cls):
try:
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.api_client = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
self.cleanup_networks = []
self.cleanup_accounts = []
self.cleanup_domains = []
self.cleanup_projects = []
self.cleanup_vms = []
self.cleanup_nwOfferings = []
self.services["shared_network_offering_sg"]["specifyVlan"] = "True"
self.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
#Create Network Offering
self.shared_network_offering_sg = NetworkOffering.create(self.api_client, self.services["shared_network_offering_sg"],
conservemode=False)
self.cleanup_nwOfferings.append(self.shared_network_offering_sg)
#Update network offering state from disabled to enabled.
NetworkOffering.update(self.shared_network_offering_sg,self.api_client,state="enabled")
return
def tearDown(self):
# all exceptions during cleanup will be appended to this list
exceptions = []
try:
#Clean up, terminate the created network offerings
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
self.debug("Warning: Exception during cleanup : %s" % e)
exceptions.append(e)
#below components is not a part of cleanup because to mandate the order and to cleanup network
try:
for vm in self.cleanup_vms:
vm.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during virtual machines cleanup : %s" % e)
exceptions.append(e)
# Wait for VMs to expunge
wait_for_cleanup(self.api_client, ["expunge.delay", "expunge.interval"])
try:
for project in self.cleanup_projects:
project.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during project cleanup : %s" % e)
exceptions.append(e)
try:
for account in self.cleanup_accounts:
account.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during account cleanup : %s" % e)
exceptions.append(e)
#Wait till all resources created are cleaned up completely and then attempt to delete Network
time.sleep(self.services["sleep"])
try:
for network in self.cleanup_networks:
network.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during network cleanup : %s" % e)
exceptions.append(e)
try:
for domain in self.cleanup_domains:
domain.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during domain cleanup : %s" % e)
exceptions.append(e)
try:
for network_offering in self.cleanup_nwOfferings:
network_offering.update(self.api_client, state="disabled")
network_offering.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during network cleanup : %s" % e)
exceptions.append(e)
if len(exceptions) > 0:
self.fail("There were exceptions during cleanup: %s" % exceptions)
return
def setSharedNetworkParams(self, network, range=20):
# @range: range decides the endip. Pass the range as "x" if you want the difference between the startip
# and endip as "x"
# Set the subnet number of shared networks randomly prior to execution
# of each test case to avoid overlapping of ip addresses
shared_network_subnet_number = random.randrange(1,254)
self.services[network]["gateway"] = "172.16."+str(shared_network_subnet_number)+".1"
self.services[network]["startip"] = "172.16."+str(shared_network_subnet_number)+".2"
self.services[network]["endip"] = "172.16."+str(shared_network_subnet_number)+"."+str(range+1)
self.services[network]["netmask"] = "255.255.255.0"
return
@attr(tags = ["advancedsg"])
def test_03_createIsolatedNetwork(self):
""" Test Isolated Network """
# Steps,
# 1. create Isolated Network Offering
# 2. Enable network offering - updateNetworkOffering - state=Enabled
# 3. Try to create Isolated Network
# Validations,
# 1. Network creation should FAIL since isolated network is not supported in advanced zone with security groups.
#Create Network Offering
self.debug("Creating Isolated network offering")
self.isolated_network_offering = NetworkOffering.create(self.api_client, self.services["isolated_network_offering"],
conservemode=False)
self.cleanup.append(self.isolated_network_offering)
self.debug("Isolated Network offering created: %s" % self.isolated_network_offering.id)
#Update network offering state from disabled to enabled.
self.isolated_network_offering.update( self.api_client, state="enabled")
#create network using the isolated network offering created
try:
self.debug("Trying to create Isolated network, this should fail")
self.isolated_network = Network.create(self.api_client, self.services["isolated_network"],
networkofferingid=self.isolated_network_offering.id,
zoneid=self.zone.id)
self.cleanup_networks.append(self.isolated_network)
self.fail("Create isolated network is invalid in advanced zone with security groups.")
except Exception as e:
self.debug("Network creation failed because creating isolated network is invalid in advanced zone with security groups.\
Exception: %s" % e)
return
@attr(tags = ["advancedsg"])
def test_04_createSharedNetwork_withoutSG(self):
""" Test Shared Network creation without Security Group Service Provider in Network Offering"""
# Steps,
# 1. Create a shared Network offering without SG
# 2. Enable the network offering
# 3. Try to create shared network using the above offering
# Validations,
# 1. Network creation should FAIL since there is no SecurityProvider in the network offering
self.services["shared_network_offering"]["specifyVlan"] = "True"
self.services["shared_network_offering"]["specifyIpRanges"] = "True"
#Create Network Offering
self.shared_network_offering = NetworkOffering.create(self.api_client, self.services["shared_network_offering"],
conservemode=False)
self.cleanup_nwOfferings.append(self.shared_network_offering)
#Update network offering state from disabled to enabled.
NetworkOffering.update(self.shared_network_offering,self.api_client,state="enabled")
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network"]["acltype"] = "domain"
self.services["shared_network"]["vlan"] = vlan
self.services["shared_network"]["networkofferingid"] = self.shared_network_offering.id
self.services["shared_network"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network")
try:
self.shared_network = Network.create(self.api_client, self.services["shared_network"],
networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)
self.cleanup_networks.append(self.shared_network)
self.fail("Network created without SecurityProvider , which is invalid")
except Exception as e:
self.debug("Network creation failed because there is no SecurityProvider in the network offering.\
Exception: %s" % e)
return
@attr(tags = ["advancedsg"])
def test_05_deployVM_SharedwithSG(self):
""" Test VM deployment in shared networks with SecurityGroup Provider """
# Steps,
# 1. create an account
# 2. Create one shared Network with sec group
# 3. deployVirtualMachine in the above networkid within the user account
# 4. delete the user account
# Validations,
# 1. shared network should be created successfully
# 2. VM should deploy successfully
#Create admin account
self.admin_account = Account.create(self.api_client, self.services["account"], admin=True,
domainid=self.domain.id)
self.cleanup_accounts.append(self.admin_account)
self.debug("Admin type account created: %s" % self.admin_account.name)
self.services["shared_network_offering_sg"]["specifyVlan"] = "True"
self.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
#Create Network Offering
self.shared_network_offering_sg = NetworkOffering.create(self.api_client,self.services["shared_network_offering_sg"],
conservemode=False)
self.cleanup_nwOfferings.append(self.shared_network_offering_sg)
self.debug("Shared Network offering created: %s" % self.shared_network_offering_sg.id)
#Update network offering state from disabled to enabled.
self.shared_network_offering_sg.update(self.api_client,state="enabled")
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "domain"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
self.shared_network_sg = Network.create(self.api_client, self.services["shared_network_sg"], domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering_sg.id, zoneid=self.zone.id)
self.cleanup_networks.append(self.shared_network_sg)
list_networks_response = Network.list(
self.api_client,
id=self.shared_network_sg.id
)
self.assertEqual(validateList(list_networks_response)[0], PASS, "Networks list validation failed, list is %s" %
list_networks_response)
self.assertEqual(
list_networks_response[0].specifyipranges,
True,
"The network is created with ip range but the flag is set to False."
)
self.debug("Shared Network created: %s" % self.shared_network_sg.id)
try:
virtual_machine = VirtualMachine.create(self.api_client,self.services["virtual_machine"],accountid=self.admin_account.name,
domainid=self.admin_account.domainid, networkids=[self.shared_network_sg.id],
serviceofferingid=self.service_offering.id
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.cleanup_vms.append(virtual_machine)
vms = VirtualMachine.list(self.api_client, id=virtual_machine.id,listall=True)
self.assertEqual(validateList(vms)[0], PASS, "vms list validation failed, list is %s" % vms)
self.debug("Virtual Machine created: %s" % virtual_machine.id)
return
@attr(tags = ["advancedsg"])
def test_06_SharedNwSGAccountSpecific(self):
""" Test Account specific shared network creation with SG"""
# Steps,
# 1. create a user account
# 2. Create one shared Network (scope=Account) specific to this account
# Validations,
# 1. shared network should be created successfully
#Create admin account
self.admin_account = Account.create(self.api_client,self.services["account"],admin=True,
domainid=self.domain.id)
self.cleanup_accounts.append(self.admin_account)
#Create user account
self.user_account = Account.create(self.api_client,self.services["account"],domainid=self.domain.id)
self.cleanup_accounts.append(self.user_account)
self.services["shared_network_offering_sg"]["specifyVlan"] = "True"
self.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "account"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
try:
self.shared_network_sg_admin_account = Network.create(self.api_client, self.services["shared_network_sg"],
accountid=self.admin_account.name, domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
except Exception as e:
self.fail("Exception while creating account specific shared network: %s" % e)
self.debug("Created shared network %s with admin account" % self.shared_network_sg_admin_account.id)
list_networks_response = Network.list(
self.api_client,
id=self.shared_network_sg_admin_account.id
)
self.assertEqual(validateList(list_networks_response)[0], PASS, "networks list validation failed, list is %s" %
list_networks_response)
self.debug("Shared Network created: %s" % self.shared_network_sg_admin_account.id)
self.debug("Creating shared account in user account: %s" % self.user_account.id)
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["vlan"] = vlan
self.setSharedNetworkParams("shared_network_sg")
try:
self.shared_network_sg_user_account = Network.create(self.api_client,self.services["shared_network_sg"],
accountid=self.user_account.name,domainid=self.user_account.domainid,
networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
except Exception as e:
self.fail("Exception while creating account specific shared network: %s" % e)
self.debug("Created shared network %s with user account" % self.shared_network_sg_user_account.id)
list_networks_response = Network.list(self.api_client,id=self.shared_network_sg_user_account.id)
self.assertEqual(validateList(list_networks_response)[0], PASS, "networks list validation failed, list is %s" %
list_networks_response)
self.debug("Shared Network created: %s" % self.shared_network_sg_user_account.id)
return
@attr(tags = ["advancedsg"])
def test_07_SharedNwSG_DomainWide_SubdomainAcccess(self):
""" Test Domain wide shared network with SG, with subdomain access set True"""
# Steps,
# 1. create a Domain and subdomain
# 2. Create one shared Network in parent domain with SG and set subdomain access True
# 3. Deploy a VM in subdomain using the shared network
# Validations,
# 1. shared network should be created successfully
# 2. Shared network should be able to be accessed within subdomain (VM should be deployed)
#Create Domain
self.debug("Creating parent domain")
self.parent_domain = Domain.create(self.api_client, services=self.services["domain"],
parentdomainid=self.domain.id)
self.debug("Created domain %s" % self.parent_domain.id)
self.debug("Creating child domain under this domain")
self.child_domain = Domain.create(self.api_client,services=self.services["domain"],
parentdomainid=self.parent_domain)
self.debug("Created child domain: %s" % self.child_domain.id)
self.services["shared_network_offering_sg"]["specifyVlan"] = "True"
self.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "domain"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
try:
self.shared_network_sg = Network.create(self.api_client,self.services["shared_network_sg"],
domainid=self.parent_domain.id,networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id,subdomainaccess=True)
except Exception as e:
self.fail("Exception whle creating domain wide shared network: %s" % e)
self.debug("Created shared network: %s" % self.shared_network_sg.id)
self.cleanup_networks.append(self.shared_network_sg)
list_networks_response = Network.list(self.api_client,id=self.shared_network_sg.id,listall=True)
self.debug("network response: %s" % list_networks_response)
self.assertEqual(validateList(list_networks_response)[0], PASS, "networks list validation failed")
self.debug("Shared Network created: %s" % self.shared_network_sg.id)
try:
virtual_machine = VirtualMachine.create(self.api_client, self.services["virtual_machine"],
domainid=self.child_domain.id,networkids=[self.shared_network_sg.id],
serviceofferingid=self.service_offering.id)
except Exception as e:
self.fail("Exception while deploying VM in domain wide shared network: %s" % e)
self.debug("Created virtual machine %s within the shared network" % virtual_machine.id)
self.cleanup_vms.append(virtual_machine)
return
@unittest.skip("Skip - Failing - WIP")
@attr(tags = ["advancedsg"])
def test_08_SharedNwSGAccountSpecific_samevlan_samesubnet(self):
""" Test Account specific shared network creation with SG in multiple accounts
with same subnet and vlan"""
# Steps,
# 1. create two different accouts
# 2. create account specific shared networks in both accounts with same subnet and vlan id
# Validations,
# 1. shared networks should be created successfully
#Create domain 1
domain1 = Domain.create(self.api_client,services=self.services["domain"],parentdomainid=self.domain.id)
self.debug("Created domain: %s" % domain1.id)
self.cleanup_domains.append(domain1)
account1 = Account.create(self.api_client,self.services["account"],domainid=domain1.id)
self.debug("Created account %s under domain %s" % (account1.id, domain1.id))
self.cleanup_accounts.append(account1)
domain2 = Domain.create(self.api_client, services=self.services["domain"],parentdomainid=self.domain.id)
self.debug("Created domain %s" % domain2.id)
self.cleanup_domains.append(domain1)
account2 = Account.create(self.api_client,self.services["account"],domainid=domain2.id)
self.debug("Created account %s under domain %s" % (account2.id, domain2.id))
self.cleanup_accounts.append(account1)
self.services["shared_network_offering_sg"]["specifyVlan"] = "True"
self.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "account"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
self.debug("Creating shared network in account 1: %s" % account1.name)
self.shared_network_sg_account1 = Network.create(self.api_client,self.services["shared_network_sg"],
accountid=account1.name,domainid=account1.domainid,
networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
self.debug("Created shared network: %s" % self.shared_network_sg_account1.id)
self.debug("Creating shared network in account 2 with same subnet and vlan: %s" % account1.name)
try:
self.shared_network_sg_account2 = Network.create(self.api_client,self.services["shared_network_sg"],
accountid=account2.name,domainid=account2.domainid,
networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
except Exception as e:
self.fail("Exception while creating account specific shared network with same subnet and vlan: %s" % e)
self.debug("Created shared network: %s" % self.shared_network_sg_account2.id)
return
@unittest.skip("Skip - Failing - WIP")
@attr(tags = ["advancedsg"])
def test_09_SharedNwDomainWide_samevlan_samesubnet(self):
""" Test Domain wide shared network creation with SG in different domains
with same vlan and same subnet"""
# Steps,
# 1. create two different domains
# 2. Create domain specific shared networks in both the domains using same subnet and vlan id
# Validations,
# 1. Shared networks should be created successfully
#Create domain 1
domain1 = Domain.create(self.api_client,services=self.services["domain"],parentdomainid=self.domain.id)
self.debug("Created domain: %s" % domain1.id)
self.cleanup_domains.append(domain1)
account1 = Account.create(self.api_client,self.services["account"],
domainid=domain1.id)
self.debug("Created account %s under domain %s" % (account1.id, domain1.id))
self.cleanup_accounts.append(account1)
domain2 = Domain.create(self.api_client,services=self.services["domain"],parentdomainid=self.domain.id)
self.debug("Created domain %s" % domain2.id)
self.cleanup_domains.append(domain2)
account2 = Account.create(self.api_client,self.services["account"],domainid=domain2.id)
self.debug("Created account %s under domain %s" % (account2.id, domain2.id))
self.cleanup_accounts.append(account2)
self.services["shared_network_offering_sg"]["specifyVlan"] = "True"
self.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "domain"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
self.debug("Creating shared network domain 1: %s" % domain1.name)
self.shared_network_sg_domain1 = Network.create(self.api_client,self.services["shared_network_sg"],
domainid=domain1.id,networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id, subdomainaccess=True)
self.debug("Created shared network: %s" % self.shared_network_sg_domain1.id)
list_networks_response = Network.list(self.api_client,id=self.shared_network_sg_domain1.id,listall=True)
self.assertEqual(validateList(list_networks_response)[0], PASS, "networks list validation failed, list: %s" %
list_networks_response)
self.debug("Creating shared network in domain 2 with same subnet and vlan: %s" % domain2.name)
try:
self.shared_network_sg_domain2 = Network.create(self.api_client,self.services["shared_network_sg"],
domainid=domain2.id,networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id,subdomainaccess=True)
except Exception as e:
self.fail("Exception while creating domain wide shared network with same subnet and vlan: %s" % e)
self.debug("Created shared network: %s" % self.shared_network_sg_domain2.id)
list_networks_response = Network.list(self.api_client,id=self.shared_network_sg_domain2.id)
self.assertEqual(validateList(list_networks_response)[0], PASS, "networks list validation failed, list: %s" %
list_networks_response)
return
@attr(tags = ["advancedsg"])
def test_10_deleteSharedNwSGAccountSpecific_InUse(self):
""" Test delete Account specific shared network creation with SG which is in use"""
# Steps,
# 1. create a user account
# 2. Create account specific sg enabled shared network
# 3. Deply vm in the shared network
# 4. Try to delete shared network while it's stil in use by the vm
# Validations,
# 1. shared network deletion should fail
#Create admin account
self.admin_account = Account.create(self.api_client,self.services["account"],admin=True,
domainid=self.domain.id)
self.cleanup_accounts.append(self.admin_account)
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "account"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
shared_network_sg_account = Network.create(self.api_client,self.services["shared_network_sg"],
accountid=self.admin_account.name,domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
self.debug("Shared Network created: %s" % shared_network_sg_account.id)
self.debug("Deploying vm in the shared network: %s" % shared_network_sg_account.id)
vm = VirtualMachine.create(self.api_client, self.services["virtual_machine"],
accountid=self.admin_account.name,domainid=self.admin_account.domainid,
networkids=[shared_network_sg_account.id,],serviceofferingid=self.service_offering.id)
self.debug("Created vm %s" % vm.id)
self.debug("Trying to delete shared network: %s" % shared_network_sg_account.id)
try:
shared_network_sg_account.delete(self.api_client)
self.fail("Exception not raised while deleting network")
except Exception as e:
self.debug("Network deletion failed with exception: %s" % e)
return
@attr(tags = ["advancedsg"])
def test_11_deleteSharedNwSG_DomainWide_InUse(self):
""" Test delete Domain wide shared network with SG which is in use"""
# Steps,
# 1. create a domain and its admin account
# 2. Create domain wide shared network with sg and subdomainaccess enabled
# 3. Deploy vm in the domain
# 4. Try to delete the shared network while its still in use
# Validations,
# 1. shared network deletion should fail
domain = Domain.create(self.api_client, services=self.services["domain"],
parentdomainid=self.domain.id)
self.debug("Created domain: %s" % domain.id)
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "domain"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
self.debug("Creating shared network domain: %s" % domain.name)
shared_network_sg_domain = Network.create(self.api_client,self.services["shared_network_sg"],
domainid=domain.id,networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id,subdomainaccess=True)
self.debug("Created shared network: %s" % shared_network_sg_domain.id)
self.debug("Deploying vm in the shared network: %s" % shared_network_sg_domain.id)
vm = VirtualMachine.create(self.api_client,self.services["virtual_machine"],domainid=domain.id,
networkids=[shared_network_sg_domain.id,],serviceofferingid=self.service_offering.id)
self.debug("Created vm %s" % vm.id)
self.debug("Trying to delete shared network: %s" % shared_network_sg_domain.id)
try:
shared_network_sg_domain.delete(self.api_client)
self.fail("Exception not raised while deleting network")
except Exception as e:
self.debug("Network deletion failed with exception: %s" % e)
self.cleanup_networks.append(shared_network_sg_domain)
self.cleanup_vms.append(vm)
self.cleanup_domains.append(domain)
return
@attr(tags = ["advancedsg"])
def test_12_deleteSharedNwSGAccountSpecific_NotInUse(self):
""" Test delete Account specific shared network creation with SG which is not in use"""
# Steps,
# 1. create a user account
# 2. Create account specific sg enabled shared network
# 3. Try to delete shared network
# Validations,
# 1. shared network deletion should succeed
#Create admin account
self.admin_account = Account.create(self.api_client,self.services["account"],
admin=True,domainid=self.domain.id)
self.cleanup_accounts.append(self.admin_account)
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "account"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
shared_network_sg_account = Network.create(self.api_client,self.services["shared_network_sg"],
accountid=self.admin_account.name,domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
self.debug("Shared Network created: %s" % shared_network_sg_account.id)
try:
shared_network_sg_account.delete(self.api_client)
except Exception as e:
self.fail("Network deletion failed with exception: %s" % e)
return
@attr(tags = ["advancedsg"])
def test_13_deleteSharedNwSG_DomainWide_NotInUse(self):
""" Test delete Domain wide shared network with SG which is not in use"""
# Steps,
# 1. create a domain and its admin account
# 2. Create domain wide shared network with sg and subdomainaccess enabled
# 4. Try to delete the shared network
# Validations,
# 1. shared network deletion should succeed
domain = Domain.create(self.api_client,services=self.services["domain"],
parentdomainid=self.domain.id)
self.debug("Created domain: %s" % domain.id)
self.cleanup_domains.append(domain)
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "domain"
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
self.debug("Creating shared network domain: %s" % domain.name)
shared_network_sg_domain = Network.create(self.api_client,self.services["shared_network_sg"],
domainid=domain.id,networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id,subdomainaccess=True)
self.debug("Created shared network: %s" % shared_network_sg_domain.id)
self.debug("Trying to delete shared network: %s" % shared_network_sg_domain.id)
try:
shared_network_sg_domain.delete(self.api_client)
except Exception as e:
self.fail("Network deletion failed with exception: %s" % e)
return
@attr(tags = ["advancedsg"])
def test__14_createSharedNwWithSG_withoutParams(self):
""" Test create shared network with SG without specifying necessary parameters"""
# Steps,
# 1. Test create shared network with SG without specoifying necessary parameters
# such as vlan, startip, endip, gateway, netmask
# Validations,
# 1. shared network creation should fail
#Create admin account
self.admin_account = Account.create(self.api_client,self.services["account"], admin=True,
domainid=self.domain.id)
self.cleanup_accounts.append(self.admin_account)
self.services["shared_network_offering_sg"]["specifyVlan"] = "True"
self.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["acltype"] = "domain"
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["gateway"] = ""
self.services["shared_network_sg"]["startip"] = ""
self.services["shared_network_sg"]["endip"] = ""
self.services["shared_network_sg"]["netmask"] = ""
try:
self.shared_network_sg = Network.create(self.api_client,self.services["shared_network_sg"],
domainid=self.admin_account.domainid,
networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
self.cleanup_networks.append(self.shared_network_sg)
self.fail("Shared network created successfully without specifying essential parameters")
except Exception as e:
self.debug("Shared network creation failed as expected with exception: %s" % e)
return
@attr(tags = ["advancedsg"])
def test__15_createVPC(self):
""" Test create VPC in advanced SG enabled zone"""
# Steps,
# 1. Try to create VPC in SG enabled advanced zone
# Validations,
# 1. VPC creation should fail
vpc_off = VpcOffering.create(self.api_client,self.services["vpc_offering"])
vpc_off.update(self.api_client, state='Enabled')
self.services["vpc"]["cidr"] = "10.1.1.1/16"
self.debug("Trying to create a VPC network in SG enabled zone: %s" %
self.zone.id)
try:
vpc_1 = VPC.create(self.api_client,self.services["vpc"],
vpcofferingid=vpc_off.id,zoneid=self.zone.id)
vpc_1.delete(self.api_client)
self.fail("VPC creation should fail in Security Group Enabled zone")
except Exception as e:
self.debug("VPC creation failed as expected with exception: %s" % e)
finally:
vpc_off.update(self.api_client, state="Disabled")
vpc_off.delete(self.api_client)
return
@ddt
class TestNetworksInAdvancedSG_VmOperations(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cloudstackTestClient = super(TestNetworksInAdvancedSG_VmOperations,cls).getClsTestClient()
cls.api_client = cloudstackTestClient.getApiClient()
cls.services = cloudstackTestClient.getConfigParser().parsedDict
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.template = get_template(cls.api_client,cls.zone.id,cls.services["ostype"])
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(cls.api_client,cls.services["service_offering"])
cls.services["shared_network_offering_sg"]["specifyVlan"] = "True"
cls.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
#Create Network Offering
cls.shared_network_offering_sg = NetworkOffering.create(cls.api_client,cls.services["shared_network_offering_sg"],conservemode=False)
#Update network offering state from disabled to enabled.
NetworkOffering.update(cls.shared_network_offering_sg,cls.api_client,state="enabled")
cls._cleanup = [
cls.service_offering,
cls.shared_network_offering_sg
]
return
@classmethod
def tearDownClass(cls):
try:
#Update network offering state from enabled to disabled.
cls.shared_network_offering_sg.update(cls.api_client,state="disabled")
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.api_client = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
self.cleanup_networks = []
self.cleanup_accounts = []
self.cleanup_domains = []
self.cleanup_projects = []
self.cleanup_vms = []
self.cleanup_secGrps = []
return
def tearDown(self):
exceptions = []
try:
#Clean up, terminate the created network offerings
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
self.debug("Warning: Exception during cleanup : %s" % e)
exceptions.append(e)
#below components is not a part of cleanup because to mandate the order and to cleanup network
try:
for vm in self.cleanup_vms:
vm.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during virtual machines cleanup : %s" % e)
exceptions.append(e)
# Wait for VMs to expunge
wait_for_cleanup(self.api_client, ["expunge.delay", "expunge.interval"])
try:
for sec_grp in self.cleanup_secGrps:
sec_grp.delete(self.api_client)
except Exception as e:
self.debug("Warning : Exception during security groups cleanup: %s" % e)
exceptions.append(e)
try:
for project in self.cleanup_projects:
project.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during project cleanup : %s" % e)
exceptions.append(e)
try:
for account in self.cleanup_accounts:
account.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during account cleanup : %s" % e)
exceptions.append(e)
#Wait till all resources created are cleaned up completely and then attempt to delete Network
time.sleep(self.services["sleep"])
try:
for network in self.cleanup_networks:
network.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during network cleanup : %s" % e)
exceptions.append(e)
try:
for domain in self.cleanup_domains:
domain.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during domain cleanup : %s" % e)
exceptions.append(e)
if len(exceptions) > 0:
self.faill("There were exceptions during cleanup: %s" % exceptions)
return
def setSharedNetworkParams(self, network, range=20):
# @range: range decides the endip. Pass the range as "x" if you want the difference between the startip
# and endip as "x"
# Set the subnet number of shared networks randomly prior to execution
# of each test case to avoid overlapping of ip addresses
shared_network_subnet_number = random.randrange(1,254)
self.services[network]["gateway"] = "172.16."+str(shared_network_subnet_number)+".1"
self.services[network]["startip"] = "172.16."+str(shared_network_subnet_number)+".2"
self.services[network]["endip"] = "172.16."+str(shared_network_subnet_number)+"."+str(range+1)
self.services[network]["netmask"] = "255.255.255.0"
return
@attr(tags = ["advancedsg"])
def test__16_AccountSpecificNwAccess(self):
""" Test account specific network access of users"""
# Steps,
# 1. create multiple accounts/users and their account specific SG enabled shared networks
# 2. Deploy VM in the account specific network with user of that account
# 3. Try to deploy VM in one account specific network from other account user
# Validations,
# 1. VM deployment should be allowed for the users of the same account only for their account
# specific networks respectively
self.debug("Creating user account 1")
account_1 = Account.create(self.api_client,self.services["account"],
domainid=self.domain.id)
self.debug("Created account : %s" % account_1.name)
self.cleanup_accounts.append(account_1)
self.debug("Creating user account 2")
account_2 = Account.create(self.api_client,self.services["account"],
domainid=self.domain.id)
self.debug("Created account: %s" % account_2.name)
self.cleanup_accounts.append(account_2)
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["acltype"] = "account"
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
shared_network_account_1 = Network.create(self.api_client,self.services["shared_network_sg"],
accountid=account_1.name,domainid=account_1.domainid,
networkofferingid=self.shared_network_offering_sg.id,zoneid=self.zone.id)
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
shared_network_account_2 = Network.create(self.api_client,self.services["shared_network_sg"],
accountid=account_2.name,domainid=account_2.domainid,
networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
# Creaint user API client of account 1
api_client_account_1 = self.testClient.createUserApiClient(UserName=account_1.name,
DomainName=account_1.domain)
# Creaint user API client of account 2
api_client_account_2 = self.testClient.createUserApiClient(UserName=account_2.name,
DomainName=account_2.domain)
self.debug("Creating virtual machine in account %s with account specific shared network %s" %
(account_1.name, shared_network_account_1.id))
VirtualMachine.create(api_client_account_1,self.services["virtual_machine"],
templateid=self.template.id,accountid=account_1.name,
domainid=account_1.domainid,networkids=[shared_network_account_1.id,],
serviceofferingid=self.service_offering.id)
self.debug("Creating virtual machine in account %s with account specific shared network %s" %
(account_2.name, shared_network_account_2.id))
VirtualMachine.create(api_client_account_2,self.services["virtual_machine"],
templateid=self.template.id,accountid=account_2.name,
domainid=account_2.domainid,networkids=[shared_network_account_2.id,],
serviceofferingid=self.service_offering.id)
try:
self.debug("Trying to create virtual machine in account specific shared network of\
account %s using the api client of account %s, this should fail" %
(account_2.name, account_1.name))
VirtualMachine.create(api_client_account_2,self.services["virtual_machine"],
templateid=self.template.id,accountid=account_1.name,
domainid=account_1.domainid,networkids=[shared_network_account_1.id,],
serviceofferingid=self.service_offering.id)
self.fail("Vm creation succeded, should have failed")
except Exception as e:
self.debug("VM creation failed as expected with exception: %s" % e)
return
@attr(tags = ["advancedsg"])
def test__17_DomainSpecificNwAccess(self):
""" Test domain specific network access of users"""
# Steps,
# 1. create multiple domains with accounts/users in them and their domain wide SG enabled shared networks
# 2. Deploy VMs in the domain wide network with user belonging to that domain
# 3. Try to deploy VM in domain wide network with user of other domain
# Validations,
# 1. VM deployment should be allowed only for the users of the same domain for their domain
# wide networks respectively
self.debug("Creating domain 1")
domain_1 = Domain.create(self.api_client,services=self.services["domain"],
parentdomainid=self.domain.id)
self.debug("Created domain %s" % domain_1.name)
self.cleanup_domains.append(domain_1)
self.debug("Creating domain 2")
domain_2 = Domain.create(self.api_client,services=self.services["domain"],
parentdomainid=self.domain.id)
self.debug("Created domain: %s" % domain_2.name)
self.cleanup_domains.append(domain_2)
self.debug("Creating user account under domain %s" % domain_1.name)
account_1 = Account.create(self.api_client,self.services["account"],
domainid=domain_1.id)
self.debug("Created account : %s" % account_1.name)
self.cleanup_accounts.append(account_1)
self.debug("Creating user account under domain %s" % domain_2.name)
account_2 = Account.create(self.api_client,self.services["account"],
domainid=domain_2.id)
self.debug("Created account: %s" % account_2.name)
self.cleanup_accounts.append(account_2)
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.services["shared_network_sg"]["acltype"] = "domain"
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
shared_network_domain_1 = Network.create(self.api_client,self.services["shared_network_sg"],
domainid=domain_1.id,networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
self.debug("Created network: %s" % shared_network_domain_1)
self.cleanup_networks.append(shared_network_domain_1)
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg")
shared_network_domain_2 = Network.create(self.api_client,self.services["shared_network_sg"],
domainid=domain_2.id,networkofferingid=self.shared_network_offering_sg.id,
zoneid=self.zone.id)
self.debug("Created network: %s" % shared_network_domain_2.name)
self.cleanup_networks.append(shared_network_domain_2)
# Creaint user API client of account 1
api_client_domain_1 = self.testClient.createUserApiClient(UserName=account_1.name,
DomainName=account_1.domain)
# Creaint user API client of account 2
api_client_domain_2 = self.testClient.createUserApiClient(UserName=account_2.name,
DomainName=account_2.domain)
self.debug("Creating virtual machine in domain %s with domain wide shared network %s" %
(domain_1.name, shared_network_domain_1.id))
vm_1 = VirtualMachine.create(api_client_domain_1,self.services["virtual_machine"],
templateid=self.template.id,domainid=domain_1.id,
networkids=[shared_network_domain_1.id,],
serviceofferingid=self.service_offering.id)
self.debug("created vm: %s" % vm_1.id)
self.debug("Creating virtual machine in domain %s with domain wide shared network %s" %
(domain_2.name, shared_network_domain_2.id))
vm_2 = VirtualMachine.create(api_client_domain_2,self.services["virtual_machine"],
templateid=self.template.id,domainid=domain_2.id,
networkids=[shared_network_domain_2.id,],
serviceofferingid=self.service_offering.id)
self.debug("created vnm: %s" % vm_2.id)
try:
self.debug("Trying to create virtual machine in domain wide shared network of\
domain %s using the api client of account in domain %s, this should fail" %
(domain_2.name, domain_1.name))
VirtualMachine.create(api_client_domain_2,self.services["virtual_machine"],
templateid=self.template.id,domainid=domain_1.id,
networkids=[shared_network_domain_1.id,],
serviceofferingid=self.service_offering.id)
self.fail("Vm creation succeded, should have failed")
except Exception as e:
self.debug("VM creation failed as expected with exception: %s" % e)
return
@data("account", "domain")
@attr(tags = ["advancedsg"])
def test_18_DeployVM_NoFreeIPs(self, value):
""" Test deploy VM in account/domain specific SG enabled shared network when no free IPs are available"""
# Steps,
# 1. Create account/domain wide shared network in SG enabled zone.
# 2. Exhaust the free IPs in the network (by deploying vm in it)
# 3. Try to deploy VM when no free IPs are available
# Validations,
# 1. VM deployment should fail when no free IPs are available
self.debug("Creating domain")
domain = Domain.create(self.api_client,services=self.services["domain"],parentdomainid=self.domain.id)
self.cleanup_domains.append(domain)
self.debug("Created domain: %s" % domain.name)
self.debug("Creating account")
account = Account.create(self.api_client,self.services["account"],domainid=domain.id)
self.debug("Created account : %s" % account.name)
self.cleanup_accounts.append(account)
self.services["shared_network_sg"]["acltype"] = value
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.setSharedNetworkParams("shared_network_sg", range=2)
shared_network = Network.create(self.api_client,self.services["shared_network_sg"],
accountid=account.name,domainid=domain.id,
networkofferingid=self.shared_network_offering_sg.id,zoneid=self.zone.id)
if value == "domain":
self.cleanup_networks.append(shared_network)
# Deploying 1 VM will exhaust the IP range because we are passing range as 2, and one of the IPs
# already gets consumed by the virtual router of the shared network
self.debug("Creating virtual machine in %s wide shared network %s" %
(value, shared_network.id))
VirtualMachine.create(self.api_client,self.services["virtual_machine"],
templateid=self.template.id,accountid=account.name,
domainid=domain.id,networkids=[shared_network.id,],
serviceofferingid=self.service_offering.id)
try:
self.debug("Trying to create virtual machine when all the IPs are consumed")
vm = VirtualMachine.create(self.api_client,self.services["virtual_machine"],
templateid=self.template.id,accountid=account.name,
domainid=domain.id,networkids=[shared_network.id,],
serviceofferingid=self.service_offering.id)
self.cleanup_vms.append(vm)
self.fail("Vm creation succeded, should have failed")
except Exception as e:
self.debug("VM creation failed as expected with exception: %s" % e)
return
@attr(tags = ["advancedsg"])
def test_19_DeployVM_DefaultSG(self):
""" Test deploy VM in default security group"""
# Steps,
# 1. List security groups with root admin api
# 2. Deploy VM with the default security group
# Validations,
# 1. VM deployment should be successful with default security group
self.debug("Listing security groups")
securitygroups = SecurityGroup.list(self.api_client)
self.assertEqual(validateList(securitygroups)[0], PASS, "securitygroups list validation\
failed, securitygroups list is %s" % securitygroups)
defaultSecurityGroup = securitygroups[0]
self.debug("Default security group: %s" % defaultSecurityGroup.id)
try:
self.debug("Trying to create virtual machine with the default security group")
vm = VirtualMachine.create(self.api_client,self.services["virtual_machine"],
templateid=self.template.id,securitygroupids=[defaultSecurityGroup.id,],
serviceofferingid=self.service_offering.id)
self.debug("Deployed Vm: %s" % vm.name)
self.cleanup_vms.append(vm)
self.debug("Listing vms")
vm_list = list_virtual_machines(self.api_client, id=vm.id)
self.assertEqual(validateList(vm_list)[0], PASS, "vm list validation failed,\
vm list is %s" % vm_list)
self.assertTrue(defaultSecurityGroup.id in [secgrp.id for secgrp in vm_list[0].securitygroup],
"default sec group %s not present in the vm's sec group list %s" %
(defaultSecurityGroup.id, vm_list[0].securitygroup))
except Exception as e:
self.fail("VM creation with default security group failed with exception: %s" % e)
return
@data("default", "custom")
@attr(tags = ["advancedsg"])
def test_20_DeployVM_SecGrp_sharedNetwork(self, value):
""" Test deploy VM in default/custom security group and shared network"""
# Steps,
# 1. Create shared network with SG provider
# 2. Deploy VM with the default/(or custom) security group and above created shared network
# Validations,
# 1. VM deployment should be successful with default security group and shared network
securityGroup = None
if value == "default":
self.debug("Listing security groups")
securitygroups = SecurityGroup.list(self.api_client)
self.assertEqual(validateList(securitygroups)[0], PASS, "securitygroups list validation\
failed, securitygroups list is %s" % securitygroups)
securityGroup = securitygroups[0]
else:
self.services["security_group"]["name"] = "Custom_sec_grp_" + random_gen()
securityGroup = SecurityGroup.create(self.api_client, self.services["security_group"])
self.cleanup_secGrps.append(securityGroup)
self.debug("%s security group: %s" % (value,securityGroup.id))
physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)
#create network using the shared network offering created
self.services["shared_network_sg"]["vlan"] = vlan
self.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
self.services["shared_network_sg"]["acltype"] = "domain"
self.services["shared_network_sg"]["networkofferingid"] = self.shared_network_offering_sg.id
self.setSharedNetworkParams("shared_network_sg")
self.debug("Creating shared network")
shared_network = Network.create(self.api_client,self.services["shared_network_sg"],
networkofferingid=self.shared_network_offering_sg.id,zoneid=self.zone.id)
self.debug("Created shared network: %s" % shared_network.id)
self.cleanup_networks.append(shared_network)
try:
self.debug("Trying to create virtual machine with the default security group %s and\
shared network %s" % (securityGroup.id, shared_network.id))
vm = VirtualMachine.create(self.api_client,self.services["virtual_machine"],
templateid=self.template.id,securitygroupids=[securityGroup.id,],
serviceofferingid=self.service_offering.id, networkids=[shared_network.id,])
self.debug("Deployed Vm: %s" % vm.name)
self.cleanup_vms.append(vm)
except Exception as e:
self.fail("VM creation failed with exception: %s" % e)
return
class TestSecurityGroups_BasicSanity(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cloudstackTestClient = super(TestSecurityGroups_BasicSanity,cls).getClsTestClient()
cls.api_client = cloudstackTestClient.getApiClient()
cls.services = cloudstackTestClient.getConfigParser().parsedDict
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.template = get_template(cls.api_client,cls.zone.id,cls.services["ostype"])
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.service_offering = ServiceOffering.create(cls.api_client,cls.services["service_offering"])
cls.services["shared_network_offering_sg"]["specifyVlan"] = "True"
cls.services["shared_network_offering_sg"]["specifyIpRanges"] = "True"
#Create Network Offering
cls.shared_network_offering_sg = NetworkOffering.create(cls.api_client,cls.services["shared_network_offering_sg"],conservemode=False)
#Update network offering state from disabled to enabled.
NetworkOffering.update(cls.shared_network_offering_sg,cls.api_client,state="enabled")
physical_network, vlan = get_free_vlan(cls.api_client, cls.zone.id)
#create network using the shared network offering created
cls.services["shared_network_sg"]["vlan"] = vlan
cls.services["shared_network_sg"]["physicalnetworkid"] = physical_network.id
cls.services["shared_network_sg"]["acltype"] = "domain"
cls.services["shared_network_sg"]["networkofferingid"] = cls.shared_network_offering_sg.id
cls.setSharedNetworkParams("shared_network_sg")
cls.shared_network = Network.create(cls.api_client,cls.services["shared_network_sg"],
networkofferingid=cls.shared_network_offering_sg.id,zoneid=cls.zone.id)
cls._cleanup = [
cls.service_offering,
cls.shared_network,
cls.shared_network_offering_sg,
]
return
@classmethod
def tearDownClass(cls):
try:
#Update network offering state from enabled to disabled.
cls.shared_network_offering_sg.update(cls.api_client,state="disabled")
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.api_client = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
self.cleanup_networks = []
self.cleanup_accounts = []
self.cleanup_domains = []
self.cleanup_projects = []
self.cleanup_vms = []
self.cleanup_secGrps = []
return
def tearDown(self):
exceptions = []
try:
#Clean up, terminate the created network offerings
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
self.debug("Warning: Exception during cleanup : %s" % e)
exceptions.append(e)
#below components is not a part of cleanup because to mandate the order and to cleanup network
try:
for vm in self.cleanup_vms:
vm.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during virtual machines cleanup : %s" % e)
exceptions.append(e)
# Wait for VMs to expunge
wait_for_cleanup(self.api_client, ["expunge.delay", "expunge.interval"])
try:
for sec_grp in self.cleanup_secGrps:
sec_grp.delete(self.api_client)
except Exception as e:
self.debug("Warning : Exception during security groups cleanup: %s" % e)
exceptions.append(e)
try:
for project in self.cleanup_projects:
project.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during project cleanup : %s" % e)
exceptions.append(e)
try:
for account in self.cleanup_accounts:
account.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during account cleanup : %s" % e)
exceptions.append(e)
#Wait till all resources created are cleaned up completely and then attempt to delete Network
time.sleep(self.services["sleep"])
try:
for network in self.cleanup_networks:
network.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during network cleanup : %s" % e)
exceptions.append(e)
try:
for domain in self.cleanup_domains:
domain.delete(self.api_client)
except Exception as e:
self.debug("Warning: Exception during domain cleanup : %s" % e)
exceptions.append(e)
if len(exceptions) > 0:
self.fail("There were exceptions during cleanup: %s" % exceptions)
return
@classmethod
def setSharedNetworkParams(cls, network, range=20):
# @range: range decides the endip. Pass the range as "x" if you want the difference between the startip
# and endip as "x"
# Set the subnet number of shared networks randomly prior to execution
# of each test case to avoid overlapping of ip addresses
shared_network_subnet_number = random.randrange(1,254)
cls.services[network]["gateway"] = "172.16."+str(shared_network_subnet_number)+".1"
cls.services[network]["startip"] = "172.16."+str(shared_network_subnet_number)+".2"
cls.services[network]["endip"] = "172.16."+str(shared_network_subnet_number)+"."+str(range+1)
cls.services[network]["netmask"] = "255.255.255.0"
return
@attr(tags = ["advancedsg"])
def test_21_DeployVM_WithoutSG(self):
""" Test deploy VM without passing any security group id"""
# Steps,
# 1. List security groups and authorize ingress rule for the default security group
# 2. Create custom security group and authorize ingress rule for this security group
# 3. Deploy VM without passing any security group
# 4. SSH to VM and try pinging outside world from VM
# Validations,
# 1. VM deployment should be successful
# 2. VM should be deployed in default security group and not in custom security group
# 3. VM should be reached through SSH using any IP and ping to outside world should be successful
ingress_rule_ids = []
self.debug("Listing security groups")
securitygroups = SecurityGroup.list(self.api_client)
self.assertEqual(validateList(securitygroups)[0], PASS, "securitygroups list validation\
failed, securitygroups list is %s" % securitygroups)
defaultSecurityGroup = securitygroups[0]
self.debug("Default security group: %s" % defaultSecurityGroup.id)
# Authorize ingress rule for the default security group
cmd = authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd()
cmd.securitygroupid = defaultSecurityGroup.id
cmd.protocol = 'TCP'
cmd.startport = 22
cmd.endport = 80
cmd.cidrlist = '0.0.0.0/0'
ingress_rule_1 = self.api_client.authorizeSecurityGroupIngress(cmd)
ingress_rule_ids.append(ingress_rule_1.ingressrule[0].ruleid)
# Create custom security group
self.services["security_group"]["name"] = "Custom_sec_grp_" + random_gen()
custom_sec_grp = SecurityGroup.create(self.api_client,self.services["security_group"])
self.debug("Created security groups: %s" % custom_sec_grp.id)
self.cleanup_secGrps.append(custom_sec_grp)
# Authorize Security group to for allowing SSH to VM
ingress_rule_2 = custom_sec_grp.authorize(self.api_client,self.services["ingress_rule"])
ingress_rule_ids.append(ingress_rule_2["ingressrule"][0].ruleid)
self.debug("Authorized ingress rule for security group: %s" % custom_sec_grp.id)
self.debug(ingress_rule_ids)
# Create virtual machine without passing any security group id
vm = VirtualMachine.create(self.api_client,self.services["virtual_machine"],
templateid=self.template.id,
serviceofferingid=self.service_offering.id)
self.debug("Created VM : %s" % vm.id)
self.cleanup_vms.append(vm)
self.debug("listing virtual machines")
vm_list = list_virtual_machines(self.api_client, id=vm.id)
self.assertEqual(validateList(vm_list)[0], PASS, "vm list validation failed, list is %s" % vm_list)
self.assertEqual(len(vm_list[0].securitygroup), 1, "There should be exactly one security group associated \
with the vm, vm security group list is : %s" % vm_list[0].securitygroup)
self.assertEqual(defaultSecurityGroup.id, vm_list[0].securitygroup[0].id, "Vm should be deployed in default security group %s \
instead it is deployed in security group %s" % (defaultSecurityGroup.id, vm_list[0].securitygroup[0].id))
# Should be able to SSH VM
try:
self.debug("SSH into VM: %s" % vm.nic[0].ipaddress)
ssh = vm.get_ssh_client(ipaddress=vm.nic[0].ipaddress)
# Ping to outsite world
res = ssh.execute("ping -c 1 www.google.com")
except Exception as e:
self.fail("SSH Access failed for %s: %s" % \
(vm.ssh_ip, e)
)
finally:
cmd = revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd()
self.debug("ingress_rules: %s" % ingress_rule_ids)
for rule_id in ingress_rule_ids:
cmd.id = rule_id
self.api_client.revokeSecurityGroupIngress(cmd)
result = str(res)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
return
@attr(tags = ["advancedsg"])
def test_22_DeployVM_WithoutSG(self):
""" Test deploy VM without passing any security group id"""
# Steps,
# 1. List security groups and authorize ingress rule for the default security group
# 2. Create custom security group and authorize ingress rule for this security group
# 3. Deploy VM by passing only custom security group id
# 4. SSH to VM and try pinging outside world from VM
# Validations,
# 1. VM deployment should be successful
# 2. VM should be deployed in custom security group and not in any other security group
# 3. VM should be reached through SSH using any IP and ping to outside world should be successful
ingress_rule_ids = []
self.debug("Listing security groups")
securitygroups = SecurityGroup.list(self.api_client)
self.assertEqual(validateList(securitygroups)[0], PASS, "securitygroups list validation\
failed, securitygroups list is %s" % securitygroups)
defaultSecurityGroup = securitygroups[0]
self.debug("Default security group: %s" % defaultSecurityGroup.id)
# Authorize ingress rule for the default security group
cmd = authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd()
cmd.securitygroupid = defaultSecurityGroup.id
cmd.protocol = 'TCP'
cmd.startport = 22
cmd.endport = 80
cmd.cidrlist = '0.0.0.0/0'
ingress_rule_1 = self.api_client.authorizeSecurityGroupIngress(cmd)
ingress_rule_ids.append(ingress_rule_1.ingressrule[0].ruleid)
# Create custom security group
self.services["security_group"]["name"] = "Custom_sec_grp_" + random_gen()
custom_sec_grp = SecurityGroup.create(self.api_client,self.services["security_group"])
self.debug("Created security groups: %s" % custom_sec_grp.id)
self.cleanup_secGrps.append(custom_sec_grp)
# Authorize Security group to for allowing SSH to VM
ingress_rule_2 = custom_sec_grp.authorize(self.api_client,self.services["ingress_rule"])
ingress_rule_ids.append(ingress_rule_2["ingressrule"][0].ruleid)
self.debug("Authorized ingress rule for security group: %s" % custom_sec_grp.id)
# Create virtual machine without passing any security group id
vm = VirtualMachine.create(self.api_client,self.services["virtual_machine"],
templateid=self.template.id,
serviceofferingid=self.service_offering.id,
securitygroupids = [custom_sec_grp.id,])
self.debug("Created VM : %s" % vm.id)
self.cleanup_vms.append(vm)
self.debug("listing virtual machines")
vm_list = list_virtual_machines(self.api_client, id=vm.id)
self.assertEqual(validateList(vm_list)[0], PASS, "vm list validation failed, list is %s" % vm_list)
self.assertEqual(len(vm_list[0].securitygroup), 1, "There should be exactly one security group associated \
with the vm, vm security group list is : %s" % vm_list[0].securitygroup)
self.assertEqual(custom_sec_grp.id, vm_list[0].securitygroup[0].id, "Vm should be deployed in custom security group %s \
instead it is deployed in security group %s" % (custom_sec_grp.id, vm_list[0].securitygroup[0].id))
# Should be able to SSH VM
try:
self.debug("SSH into VM: %s" % vm.nic[0].ipaddress)
ssh = vm.get_ssh_client(ipaddress=vm.nic[0].ipaddress)
# Ping to outsite world
res = ssh.execute("ping -c 1 www.google.com")
except Exception as e:
self.fail("SSH Access failed for %s: %s" % \
(vm.ssh_ip, e)
)
finally:
cmd = revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd()
for rule_id in ingress_rule_ids:
cmd.id = rule_id
self.api_client.revokeSecurityGroupIngress(cmd)
result = str(res)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
return
@attr(tags = ["advancedsg"])
def test_23_DeployVM_MultipleSG(self):
""" Test deploy VM in multiple security groups"""
# Steps,
# 1. Create multiple security groups
# 2. Authorize ingress rule for all these security groups
# 3. Deploy VM with all the security groups
# 4. SSH to VM
# Validations,
# 1. VM deployment should be successful
# 2. VM should list all the security groups
# 3. VM should be reached through SSH using any IP in the mentioned CIDRs of the ingress rules
ingress_rule_ids = []
self.services["security_group"]["name"] = "Custom_sec_grp_" + random_gen()
sec_grp_1 = SecurityGroup.create(self.api_client,self.services["security_group"])
self.debug("Created security groups: %s" % sec_grp_1.id)
self.cleanup_secGrps.append(sec_grp_1)
self.services["security_group"]["name"] = "Custom_sec_grp_" + random_gen()
sec_grp_2 = SecurityGroup.create(self.api_client,self.services["security_group"])
self.debug("Created security groups: %s" % sec_grp_2.id)
self.cleanup_secGrps.append(sec_grp_2)
self.services["security_group"]["name"] = "Custom_sec_grp_" + random_gen()
sec_grp_3 = SecurityGroup.create(self.api_client,self.services["security_group"])
self.debug("Created security groups: %s" % sec_grp_3.id)
self.cleanup_secGrps.append(sec_grp_3)
# Authorize Security group to for allowing SSH to VM
ingress_rule_1 = sec_grp_1.authorize(self.api_client,self.services["ingress_rule"])
ingress_rule_ids.append(ingress_rule_1["ingressrule"][0].ruleid)
self.debug("Authorized ingress rule for security group: %s" % sec_grp_1.id)
ingress_rule_2 = sec_grp_2.authorize(self.api_client,self.services["ingress_rule"])
ingress_rule_ids.append(ingress_rule_2["ingressrule"][0].ruleid)
self.debug("Authorized ingress rule for security group: %s" % sec_grp_2.id)
ingress_rule_3 = sec_grp_3.authorize(self.api_client,self.services["ingress_rule"])
ingress_rule_ids.append(ingress_rule_3["ingressrule"][0].ruleid)
self.debug("Authorized ingress rule for security group: %s" % sec_grp_3.id)
vm = VirtualMachine.create(self.api_client,self.services["virtual_machine"],
templateid=self.template.id,
securitygroupids=[sec_grp_1.id, sec_grp_2.id, sec_grp_3.id,],
serviceofferingid=self.service_offering.id)
self.debug("Created VM : %s" % vm.id)
self.cleanup_vms.append(vm)
self.debug("listing virtual machines")
vm_list = list_virtual_machines(self.api_client, id=vm.id)
self.assertEqual(validateList(vm_list)[0], PASS, "vm list validation failed, list is %s" % vm_list)
sec_grp_list = [sec_grp.id for sec_grp in vm_list[0].securitygroup]
self.assertTrue(sec_grp_1.id in sec_grp_list, "%s not present in security groups of vm: %s" %
(sec_grp_1.id, sec_grp_list))
self.assertTrue(sec_grp_2.id in sec_grp_list, "%s not present in security groups of vm: %s" %
(sec_grp_2.id, sec_grp_list))
self.assertTrue(sec_grp_3.id in sec_grp_list, "%s not present in security groups of vm: %s" %
(sec_grp_3.id, sec_grp_list))
# Should be able to SSH VM
try:
self.debug("SSH into VM: %s" % vm.ssh_ip)
ssh = vm.get_ssh_client(ipaddress=vm.nic[0].ipaddress)
# Ping to outsite world
res = ssh.execute("ping -c 1 www.google.com")
except Exception as e:
self.fail("SSH Access failed for %s: %s" % \
(vm.ssh_ip, e)
)
finally:
cmd = revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd()
for rule_id in ingress_rule_ids:
cmd.id = rule_id
self.api_client.revokeSecurityGroupIngress(cmd)
result = str(res)
self.assertEqual(
result.count("1 received"),
1,
"Ping to outside world from VM should be successful"
)
return
| [
"marvin.integration.lib.base.SecurityGroup.list",
"marvin.integration.lib.common.get_domain",
"marvin.cloudstackAPI.revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd",
"marvin.integration.lib.base.VirtualMachine.list",
"marvin.integration.lib.base.Account.create",
"marvin.integration.lib.base.Secur... | [((4254, 4279), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (4258, 4279), False, 'from nose.plugins.attrib import attr\n'), ((4833, 4858), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (4837, 4858), False, 'from nose.plugins.attrib import attr\n'), ((11084, 11109), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (11088, 11109), False, 'from nose.plugins.attrib import attr\n'), ((12965, 12990), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (12969, 12990), False, 'from nose.plugins.attrib import attr\n'), ((15166, 15191), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (15170, 15191), False, 'from nose.plugins.attrib import attr\n'), ((19036, 19061), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (19040, 19061), False, 'from nose.plugins.attrib import attr\n'), ((23130, 23155), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (23134, 23155), False, 'from nose.plugins.attrib import attr\n'), ((26573, 26610), 'marvin.cloudstackTestCase.unittest.skip', 'unittest.skip', (['"""Skip - Failing - WIP"""'], {}), "('Skip - Failing - WIP')\n", (26586, 26610), False, 'from marvin.cloudstackTestCase import cloudstackTestCase, unittest\n'), ((26616, 26641), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (26620, 26641), False, 'from nose.plugins.attrib import attr\n'), ((30041, 30078), 'marvin.cloudstackTestCase.unittest.skip', 'unittest.skip', (['"""Skip - Failing - WIP"""'], {}), "('Skip - Failing - WIP')\n", (30054, 30078), False, 'from marvin.cloudstackTestCase import cloudstackTestCase, unittest\n'), ((30084, 30109), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (30088, 30109), False, 'from nose.plugins.attrib import attr\n'), ((33928, 33953), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (33932, 33953), False, 'from nose.plugins.attrib import attr\n'), ((36491, 36516), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (36495, 36516), False, 'from nose.plugins.attrib import attr\n'), ((39036, 39061), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (39040, 39061), False, 'from nose.plugins.attrib import attr\n'), ((40915, 40940), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (40919, 40940), False, 'from nose.plugins.attrib import attr\n'), ((42874, 42899), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (42878, 42899), False, 'from nose.plugins.attrib import attr\n'), ((45093, 45118), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (45097, 45118), False, 'from nose.plugins.attrib import attr\n'), ((51641, 51666), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (51645, 51666), False, 'from nose.plugins.attrib import attr\n'), ((56689, 56714), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (56693, 56714), False, 'from nose.plugins.attrib import attr\n'), ((62553, 62578), 'ddt.data', 'data', (['"""account"""', '"""domain"""'], {}), "('account', 'domain')\n", (62557, 62578), False, 'from ddt import ddt, data\n'), ((62584, 62609), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (62588, 62609), False, 'from nose.plugins.attrib import attr\n'), ((65801, 65826), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (65805, 65826), False, 'from nose.plugins.attrib import attr\n'), ((67700, 67725), 'ddt.data', 'data', (['"""default"""', '"""custom"""'], {}), "('default', 'custom')\n", (67704, 67725), False, 'from ddt import ddt, data\n'), ((67731, 67756), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (67735, 67756), False, 'from nose.plugins.attrib import attr\n'), ((76661, 76686), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (76665, 76686), False, 'from nose.plugins.attrib import attr\n'), ((81042, 81067), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (81046, 81067), False, 'from nose.plugins.attrib import attr\n'), ((85395, 85420), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advancedsg']"}), "(tags=['advancedsg'])\n", (85399, 85420), False, 'from nose.plugins.attrib import attr\n'), ((2633, 2673), 'marvin.integration.lib.common.get_domain', 'get_domain', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (2643, 2673), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((4651, 4689), 'marvin.integration.lib.base.Zone.list', 'Zone.list', (['self.api_client'], {'id': 'zone.id'}), '(self.api_client, id=zone.id)\n', (4660, 4689), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((5309, 5347), 'marvin.integration.lib.base.Zone.list', 'Zone.list', (['self.api_client'], {'id': 'zone.id'}), '(self.api_client, id=zone.id)\n', (5318, 5347), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((5947, 5987), 'marvin.integration.lib.common.get_domain', 'get_domain', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (5957, 5987), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((6007, 6045), 'marvin.integration.lib.common.get_zone', 'get_zone', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (6015, 6045), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((6069, 6134), 'marvin.integration.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (6081, 6134), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((6338, 6410), 'marvin.integration.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (6360, 6410), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((7401, 7510), 'marvin.integration.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.services['shared_network_offering_sg']"], {'conservemode': '(False)'}), "(self.api_client, self.services[\n 'shared_network_offering_sg'], conservemode=False)\n", (7423, 7510), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((7719, 7812), 'marvin.integration.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering_sg', 'self.api_client'], {'state': '"""enabled"""'}), "(self.shared_network_offering_sg, self.api_client,\n state='enabled')\n", (7741, 7812), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((8604, 8676), 'marvin.integration.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['expunge.delay', 'expunge.interval']"], {}), "(self.api_client, ['expunge.delay', 'expunge.interval'])\n", (8620, 8676), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((9294, 9328), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (9304, 9328), False, 'import time\n'), ((10688, 10712), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (10704, 10712), False, 'import random\n'), ((11661, 11769), 'marvin.integration.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.services['isolated_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.services[\n 'isolated_network_offering'], conservemode=False)\n", (11683, 11769), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((13685, 13791), 'marvin.integration.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.services['shared_network_offering']"], {'conservemode': '(False)'}), "(self.api_client, self.services[\n 'shared_network_offering'], conservemode=False)\n", (13707, 13791), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((13997, 14088), 'marvin.integration.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['self.shared_network_offering', 'self.api_client'], {'state': '"""enabled"""'}), "(self.shared_network_offering, self.api_client, state\n ='enabled')\n", (14019, 14088), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((14116, 14160), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (14129, 14160), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((15733, 15831), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (15747, 15831), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((16243, 16352), 'marvin.integration.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.api_client', "self.services['shared_network_offering_sg']"], {'conservemode': '(False)'}), "(self.api_client, self.services[\n 'shared_network_offering_sg'], conservemode=False)\n", (16265, 16352), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((16762, 16806), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (16775, 16806), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((17273, 17462), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=self.admin_account.domainid, networkofferingid=self.\n shared_network_offering_sg.id, zoneid=self.zone.id)\n", (17287, 17462), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((17598, 17657), 'marvin.integration.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.shared_network_sg.id'}), '(self.api_client, id=self.shared_network_sg.id)\n', (17610, 17657), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((18769, 18842), 'marvin.integration.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.api_client'], {'id': 'virtual_machine.id', 'listall': '(True)'}), '(self.api_client, id=virtual_machine.id, listall=True)\n', (18788, 18842), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((19461, 19559), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (19475, 19559), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((19714, 19801), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (19728, 19801), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((20043, 20087), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (20056, 20087), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((21265, 21338), 'marvin.integration.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.shared_network_sg_admin_account.id'}), '(self.api_client, id=self.shared_network_sg_admin_account.id)\n', (21277, 21338), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((21837, 21881), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (21850, 21881), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((22784, 22856), 'marvin.integration.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.shared_network_sg_user_account.id'}), '(self.api_client, id=self.shared_network_sg_user_account.id)\n', (22796, 22856), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((23808, 23907), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (23821, 23907), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((24102, 24205), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.parent_domain'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.parent_domain)\n", (24115, 24205), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((24505, 24549), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (24518, 24549), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((25620, 25693), 'marvin.integration.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.shared_network_sg.id', 'listall': '(True)'}), '(self.api_client, id=self.shared_network_sg.id, listall=True)\n', (25632, 25693), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((27132, 27231), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (27145, 27231), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((27346, 27424), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'domain1.id'}), "(self.api_client, self.services['account'], domainid=domain1.id)\n", (27360, 27424), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((27575, 27674), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (27588, 27674), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((27789, 27867), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'domain2.id'}), "(self.api_client, self.services['account'], domainid=domain2.id)\n", (27803, 27867), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((28190, 28234), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (28203, 28234), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((28790, 28994), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'account1.name', 'domainid': 'account1.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=account1.name, domainid=account1.domainid, networkofferingid=\n self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (28804, 28994), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((30596, 30695), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (30609, 30695), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((30810, 30888), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'domain1.id'}), "(self.api_client, self.services['account'], domainid=domain1.id)\n", (30824, 30888), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((31074, 31173), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (31087, 31173), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((31287, 31365), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'domain2.id'}), "(self.api_client, self.services['account'], domainid=domain2.id)\n", (31301, 31365), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((31688, 31732), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (31701, 31732), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((32281, 32475), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'domain1.id', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id', 'subdomainaccess': '(True)'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=domain1.id, networkofferingid=self.shared_network_offering_sg.\n id, zoneid=self.zone.id, subdomainaccess=True)\n", (32295, 32475), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((32697, 32783), 'marvin.integration.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.shared_network_sg_domain1.id', 'listall': '(True)'}), '(self.api_client, id=self.shared_network_sg_domain1.id, listall\n =True)\n', (32709, 32783), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((33672, 33739), 'marvin.integration.lib.base.Network.list', 'Network.list', (['self.api_client'], {'id': 'self.shared_network_sg_domain2.id'}), '(self.api_client, id=self.shared_network_sg_domain2.id)\n', (33684, 33739), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((34482, 34580), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (34496, 34580), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((34711, 34755), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (34724, 34755), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((35226, 35449), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkofferingid=self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (35240, 35449), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((35782, 36027), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkids': '[shared_network_sg_account.id]', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkids=[shared_network_sg_account.id], serviceofferingid=self.\n service_offering.id)\n", (35803, 36027), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((37008, 37107), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (37021, 37107), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((37223, 37267), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (37236, 37267), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((37807, 38000), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'domain.id', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id', 'subdomainaccess': '(True)'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=domain.id, networkofferingid=self.shared_network_offering_sg.\n id, zoneid=self.zone.id, subdomainaccess=True)\n", (37821, 38000), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((38276, 38462), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'domainid': 'domain.id', 'networkids': '[shared_network_sg_domain.id]', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n domainid=domain.id, networkids=[shared_network_sg_domain.id],\n serviceofferingid=self.service_offering.id)\n", (38297, 38462), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((39522, 39620), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (39536, 39620), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((39751, 39795), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (39764, 39795), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((40266, 40489), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkofferingid=self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (40280, 40489), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((41381, 41480), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (41394, 41480), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((41639, 41683), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (41652, 41683), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((42223, 42416), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'domain.id', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id', 'subdomainaccess': '(True)'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=domain.id, networkofferingid=self.shared_network_offering_sg.\n id, zoneid=self.zone.id, subdomainaccess=True)\n", (42237, 42416), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((43353, 43451), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (43367, 43451), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((43740, 43784), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (43753, 43784), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((45373, 45439), 'marvin.integration.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.api_client', "self.services['vpc_offering']"], {}), "(self.api_client, self.services['vpc_offering'])\n", (45391, 45439), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((46645, 46685), 'marvin.integration.lib.common.get_domain', 'get_domain', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (46655, 46685), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((46705, 46743), 'marvin.integration.lib.common.get_zone', 'get_zone', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (46713, 46743), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((46767, 46832), 'marvin.integration.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (46779, 46832), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((46998, 47070), 'marvin.integration.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (47020, 47070), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((47299, 47406), 'marvin.integration.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['shared_network_offering_sg']"], {'conservemode': '(False)'}), "(cls.api_client, cls.services[\n 'shared_network_offering_sg'], conservemode=False)\n", (47321, 47406), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((47474, 47565), 'marvin.integration.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['cls.shared_network_offering_sg', 'cls.api_client'], {'state': '"""enabled"""'}), "(cls.shared_network_offering_sg, cls.api_client,\n state='enabled')\n", (47496, 47565), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((49248, 49320), 'marvin.integration.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['expunge.delay', 'expunge.interval']"], {}), "(self.api_client, ['expunge.delay', 'expunge.interval'])\n", (49264, 49320), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((50198, 50232), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (50208, 50232), False, 'import time\n'), ((51245, 51269), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (51261, 51269), False, 'import random\n'), ((52302, 52389), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (52316, 52389), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((52595, 52682), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'self.domain.id'}), "(self.api_client, self.services['account'], domainid=self.\n domain.id)\n", (52609, 52682), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((53022, 53066), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (53035, 53066), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((53369, 53574), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'account_1.name', 'domainid': 'account_1.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=account_1.name, domainid=account_1.domainid,\n networkofferingid=self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (53383, 53574), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((53698, 53742), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (53711, 53742), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((54045, 54250), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'account_2.name', 'domainid': 'account_2.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=account_2.name, domainid=account_2.domainid,\n networkofferingid=self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (54059, 54250), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((55020, 55281), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['api_client_account_1', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'accountid': 'account_1.name', 'domainid': 'account_1.domainid', 'networkids': '[shared_network_account_1.id]', 'serviceofferingid': 'self.service_offering.id'}), "(api_client_account_1, self.services['virtual_machine'\n ], templateid=self.template.id, accountid=account_1.name, domainid=\n account_1.domainid, networkids=[shared_network_account_1.id],\n serviceofferingid=self.service_offering.id)\n", (55041, 55281), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((55533, 55794), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['api_client_account_2', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'accountid': 'account_2.name', 'domainid': 'account_2.domainid', 'networkids': '[shared_network_account_2.id]', 'serviceofferingid': 'self.service_offering.id'}), "(api_client_account_2, self.services['virtual_machine'\n ], templateid=self.template.id, accountid=account_2.name, domainid=\n account_2.domainid, networkids=[shared_network_account_2.id],\n serviceofferingid=self.service_offering.id)\n", (55554, 55794), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((57350, 57449), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (57363, 57449), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((57641, 57740), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (57654, 57740), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((57970, 58049), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'domain_1.id'}), "(self.api_client, self.services['account'], domainid=domain_1.id)\n", (57984, 58049), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((58288, 58367), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'domain_2.id'}), "(self.api_client, self.services['account'], domainid=domain_2.id)\n", (58302, 58367), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((58711, 58755), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (58724, 58755), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((59057, 59230), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'domain_1.id', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=domain_1.id, networkofferingid=self.shared_network_offering_sg\n .id, zoneid=self.zone.id)\n", (59071, 59230), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((59483, 59527), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (59496, 59527), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((59829, 60002), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'domain_2.id', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=domain_2.id, networkofferingid=self.shared_network_offering_sg\n .id, zoneid=self.zone.id)\n", (59843, 60002), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((60851, 61072), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['api_client_domain_1', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'domainid': 'domain_1.id', 'networkids': '[shared_network_domain_1.id]', 'serviceofferingid': 'self.service_offering.id'}), "(api_client_domain_1, self.services['virtual_machine'],\n templateid=self.template.id, domainid=domain_1.id, networkids=[\n shared_network_domain_1.id], serviceofferingid=self.service_offering.id)\n", (60872, 61072), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((61396, 61617), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['api_client_domain_2', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'domainid': 'domain_2.id', 'networkids': '[shared_network_domain_2.id]', 'serviceofferingid': 'self.service_offering.id'}), "(api_client_domain_2, self.services['virtual_machine'],\n templateid=self.template.id, domainid=domain_2.id, networkids=[\n shared_network_domain_2.id], serviceofferingid=self.service_offering.id)\n", (61417, 61617), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((63156, 63255), 'marvin.integration.lib.base.Domain.create', 'Domain.create', (['self.api_client'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.api_client, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (63169, 63255), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((63407, 63484), 'marvin.integration.lib.base.Account.create', 'Account.create', (['self.api_client', "self.services['account']"], {'domainid': 'domain.id'}), "(self.api_client, self.services['account'], domainid=domain.id)\n", (63421, 63484), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((63785, 63829), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (63798, 63829), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((64131, 64326), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'account.name', 'domainid': 'domain.id', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=account.name, domainid=domain.id, networkofferingid=self.\n shared_network_offering_sg.id, zoneid=self.zone.id)\n", (64145, 64326), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((64795, 65024), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'accountid': 'account.name', 'domainid': 'domain.id', 'networkids': '[shared_network.id]', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n templateid=self.template.id, accountid=account.name, domainid=domain.id,\n networkids=[shared_network.id], serviceofferingid=self.service_offering.id)\n", (64816, 65024), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((66229, 66264), 'marvin.integration.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.api_client'], {}), '(self.api_client)\n', (66247, 66264), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((68947, 68991), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['self.api_client', 'self.zone.id'], {}), '(self.api_client, self.zone.id)\n', (68960, 68991), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((69497, 69643), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n networkofferingid=self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (69511, 69643), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((70899, 70939), 'marvin.integration.lib.common.get_domain', 'get_domain', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (70909, 70939), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((70959, 70997), 'marvin.integration.lib.common.get_zone', 'get_zone', (['cls.api_client', 'cls.services'], {}), '(cls.api_client, cls.services)\n', (70967, 70997), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((71021, 71086), 'marvin.integration.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (71033, 71086), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((71252, 71324), 'marvin.integration.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (71274, 71324), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((71553, 71660), 'marvin.integration.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['shared_network_offering_sg']"], {'conservemode': '(False)'}), "(cls.api_client, cls.services[\n 'shared_network_offering_sg'], conservemode=False)\n", (71575, 71660), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((71728, 71819), 'marvin.integration.lib.base.NetworkOffering.update', 'NetworkOffering.update', (['cls.shared_network_offering_sg', 'cls.api_client'], {'state': '"""enabled"""'}), "(cls.shared_network_offering_sg, cls.api_client,\n state='enabled')\n", (71750, 71819), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((71848, 71890), 'marvin.integration.lib.common.get_free_vlan', 'get_free_vlan', (['cls.api_client', 'cls.zone.id'], {}), '(cls.api_client, cls.zone.id)\n', (71861, 71890), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((72347, 72489), 'marvin.integration.lib.base.Network.create', 'Network.create', (['cls.api_client', "cls.services['shared_network_sg']"], {'networkofferingid': 'cls.shared_network_offering_sg.id', 'zoneid': 'cls.zone.id'}), "(cls.api_client, cls.services['shared_network_sg'],\n networkofferingid=cls.shared_network_offering_sg.id, zoneid=cls.zone.id)\n", (72361, 72489), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((74257, 74329), 'marvin.integration.lib.common.wait_for_cleanup', 'wait_for_cleanup', (['self.api_client', "['expunge.delay', 'expunge.interval']"], {}), "(self.api_client, ['expunge.delay', 'expunge.interval'])\n", (74273, 74329), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((75207, 75241), 'time.sleep', 'time.sleep', (["self.services['sleep']"], {}), "(self.services['sleep'])\n", (75217, 75241), False, 'import time\n'), ((76269, 76293), 'random.randrange', 'random.randrange', (['(1)', '(254)'], {}), '(1, 254)\n', (76285, 76293), False, 'import random\n'), ((77500, 77535), 'marvin.integration.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.api_client'], {}), '(self.api_client)\n', (77518, 77535), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((77908, 77972), 'marvin.cloudstackAPI.authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd', 'authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd', ([], {}), '()\n', (77970, 77972), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, revokeSecurityGroupIngress\n'), ((78437, 78507), 'marvin.integration.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.api_client', "self.services['security_group']"], {}), "(self.api_client, self.services['security_group'])\n", (78457, 78507), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((79073, 79222), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n templateid=self.template.id, serviceofferingid=self.service_offering.id)\n", (79094, 79222), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((79438, 79486), 'marvin.integration.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.api_client'], {'id': 'vm.id'}), '(self.api_client, id=vm.id)\n', (79459, 79486), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((81889, 81924), 'marvin.integration.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.api_client'], {}), '(self.api_client)\n', (81907, 81924), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((82297, 82361), 'marvin.cloudstackAPI.authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd', 'authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd', ([], {}), '()\n', (82359, 82361), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, revokeSecurityGroupIngress\n'), ((82826, 82896), 'marvin.integration.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.api_client', "self.services['security_group']"], {}), "(self.api_client, self.services['security_group'])\n", (82846, 82896), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((83424, 83615), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'serviceofferingid': 'self.service_offering.id', 'securitygroupids': '[custom_sec_grp.id]'}), "(self.api_client, self.services['virtual_machine'],\n templateid=self.template.id, serviceofferingid=self.service_offering.id,\n securitygroupids=[custom_sec_grp.id])\n", (83445, 83615), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((83865, 83913), 'marvin.integration.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.api_client'], {'id': 'vm.id'}), '(self.api_client, id=vm.id)\n', (83886, 83913), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((86094, 86164), 'marvin.integration.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.api_client', "self.services['security_group']"], {}), "(self.api_client, self.services['security_group'])\n", (86114, 86164), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((86380, 86450), 'marvin.integration.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.api_client', "self.services['security_group']"], {}), "(self.api_client, self.services['security_group'])\n", (86400, 86450), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((86666, 86736), 'marvin.integration.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.api_client', "self.services['security_group']"], {}), "(self.api_client, self.services['security_group'])\n", (86686, 86736), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((87673, 87888), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'securitygroupids': '[sec_grp_1.id, sec_grp_2.id, sec_grp_3.id]', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n templateid=self.template.id, securitygroupids=[sec_grp_1.id, sec_grp_2.\n id, sec_grp_3.id], serviceofferingid=self.service_offering.id)\n", (87694, 87888), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((88135, 88183), 'marvin.integration.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.api_client'], {'id': 'vm.id'}), '(self.api_client, id=vm.id)\n', (88156, 88183), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((2823, 2870), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (2840, 2870), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((3258, 3306), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['self.api_client', 'self.cleanup'], {}), '(self.api_client, self.cleanup)\n', (3275, 3306), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((3541, 3559), 'marvin.integration.lib.utils.random_gen', 'random_gen', ([], {'size': '(6)'}), '(size=6)\n', (3551, 3559), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((3755, 3821), 'marvin.integration.lib.base.Zone.create', 'Zone.create', (['self.api_client', "self.services['advanced_sg']['zone']"], {}), "(self.api_client, self.services['advanced_sg']['zone'])\n", (3766, 3821), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((6630, 6677), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (6647, 6677), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((8029, 8077), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['self.api_client', 'self.cleanup'], {}), '(self.api_client, self.cleanup)\n', (8046, 8077), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((12330, 12474), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['isolated_network']"], {'networkofferingid': 'self.isolated_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['isolated_network'],\n networkofferingid=self.isolated_network_offering.id, zoneid=self.zone.id)\n", (12344, 12474), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((14626, 14766), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network']"], {'networkofferingid': 'self.shared_network_offering.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network'],\n networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)\n", (14640, 14766), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((18256, 18498), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkids': '[self.shared_network_sg.id]', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkids=[self.shared_network_sg.id], serviceofferingid=self.\n service_offering.id)\n", (18277, 18498), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((20586, 20809), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'self.admin_account.name', 'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=self.admin_account.name, domainid=self.admin_account.domainid,\n networkofferingid=self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (20600, 20809), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((22126, 22347), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'self.user_account.name', 'domainid': 'self.user_account.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=self.user_account.name, domainid=self.user_account.domainid,\n networkofferingid=self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (22140, 22347), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((25033, 25238), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'self.parent_domain.id', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id', 'subdomainaccess': '(True)'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=self.parent_domain.id, networkofferingid=self.\n shared_network_offering_sg.id, zoneid=self.zone.id, subdomainaccess=True)\n", (25047, 25238), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((25990, 26185), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'domainid': 'self.child_domain.id', 'networkids': '[self.shared_network_sg.id]', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n domainid=self.child_domain.id, networkids=[self.shared_network_sg.id],\n serviceofferingid=self.service_offering.id)\n", (26011, 26185), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((29408, 29612), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'accountid': 'account2.name', 'domainid': 'account2.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n accountid=account2.name, domainid=account2.domainid, networkofferingid=\n self.shared_network_offering_sg.id, zoneid=self.zone.id)\n", (29422, 29612), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((33107, 33301), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'domain2.id', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id', 'subdomainaccess': '(True)'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=domain2.id, networkofferingid=self.shared_network_offering_sg.\n id, zoneid=self.zone.id, subdomainaccess=True)\n", (33121, 33301), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((44445, 44634), 'marvin.integration.lib.base.Network.create', 'Network.create', (['self.api_client', "self.services['shared_network_sg']"], {'domainid': 'self.admin_account.domainid', 'networkofferingid': 'self.shared_network_offering_sg.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['shared_network_sg'],\n domainid=self.admin_account.domainid, networkofferingid=self.\n shared_network_offering_sg.id, zoneid=self.zone.id)\n", (44459, 44634), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((45734, 45834), 'marvin.integration.lib.base.VPC.create', 'VPC.create', (['self.api_client', "self.services['vpc']"], {'vpcofferingid': 'vpc_off.id', 'zoneid': 'self.zone.id'}), "(self.api_client, self.services['vpc'], vpcofferingid=vpc_off.id,\n zoneid=self.zone.id)\n", (45744, 45834), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((47987, 48034), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (48004, 48034), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((48673, 48721), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['self.api_client', 'self.cleanup'], {}), '(self.api_client, self.cleanup)\n', (48690, 48721), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((56141, 56402), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['api_client_account_2', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'accountid': 'account_1.name', 'domainid': 'account_1.domainid', 'networkids': '[shared_network_account_1.id]', 'serviceofferingid': 'self.service_offering.id'}), "(api_client_account_2, self.services['virtual_machine'\n ], templateid=self.template.id, accountid=account_1.name, domainid=\n account_1.domainid, networkids=[shared_network_account_1.id],\n serviceofferingid=self.service_offering.id)\n", (56162, 56402), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((62040, 62261), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['api_client_domain_2', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'domainid': 'domain_1.id', 'networkids': '[shared_network_domain_1.id]', 'serviceofferingid': 'self.service_offering.id'}), "(api_client_domain_2, self.services['virtual_machine'],\n templateid=self.template.id, domainid=domain_1.id, networkids=[\n shared_network_domain_1.id], serviceofferingid=self.service_offering.id)\n", (62061, 62261), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((65225, 65454), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'accountid': 'account.name', 'domainid': 'domain.id', 'networkids': '[shared_network.id]', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n templateid=self.template.id, accountid=account.name, domainid=domain.id,\n networkids=[shared_network.id], serviceofferingid=self.service_offering.id)\n", (65246, 65454), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((66679, 66876), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'securitygroupids': '[defaultSecurityGroup.id]', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n templateid=self.template.id, securitygroupids=[defaultSecurityGroup.id],\n serviceofferingid=self.service_offering.id)\n", (66700, 66876), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((67099, 67147), 'marvin.integration.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.api_client'], {'id': 'vm.id'}), '(self.api_client, id=vm.id)\n', (67120, 67147), False, 'from marvin.integration.lib.common import get_domain, get_zone, get_template, get_free_vlan, list_virtual_machines, wait_for_cleanup\n'), ((68333, 68368), 'marvin.integration.lib.base.SecurityGroup.list', 'SecurityGroup.list', (['self.api_client'], {}), '(self.api_client)\n', (68351, 68368), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((68715, 68785), 'marvin.integration.lib.base.SecurityGroup.create', 'SecurityGroup.create', (['self.api_client', "self.services['security_group']"], {}), "(self.api_client, self.services['security_group'])\n", (68735, 68785), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((70008, 70230), 'marvin.integration.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'templateid': 'self.template.id', 'securitygroupids': '[securityGroup.id]', 'serviceofferingid': 'self.service_offering.id', 'networkids': '[shared_network.id]'}), "(self.api_client, self.services['virtual_machine'],\n templateid=self.template.id, securitygroupids=[securityGroup.id],\n serviceofferingid=self.service_offering.id, networkids=[shared_network.id])\n", (70029, 70230), False, 'from marvin.integration.lib.base import Zone, ServiceOffering, Account, NetworkOffering, Network, VirtualMachine, Domain, VpcOffering, VPC, SecurityGroup\n'), ((72996, 73043), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (73013, 73043), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((73682, 73730), 'marvin.integration.lib.utils.cleanup_resources', 'cleanup_resources', (['self.api_client', 'self.cleanup'], {}), '(self.api_client, self.cleanup)\n', (73699, 73730), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((78399, 78411), 'marvin.integration.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (78409, 78411), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((80519, 80577), 'marvin.cloudstackAPI.revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd', 'revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd', ([], {}), '()\n', (80575, 80577), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, revokeSecurityGroupIngress\n'), ((82788, 82800), 'marvin.integration.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (82798, 82800), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((84933, 84991), 'marvin.cloudstackAPI.revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd', 'revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd', ([], {}), '()\n', (84989, 84991), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, revokeSecurityGroupIngress\n'), ((86061, 86073), 'marvin.integration.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (86071, 86073), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((86347, 86359), 'marvin.integration.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (86357, 86359), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((86633, 86645), 'marvin.integration.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (86643, 86645), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((89264, 89322), 'marvin.cloudstackAPI.revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd', 'revokeSecurityGroupIngress.revokeSecurityGroupIngressCmd', ([], {}), '()\n', (89320, 89322), False, 'from marvin.cloudstackAPI import authorizeSecurityGroupIngress, revokeSecurityGroupIngress\n'), ((17805, 17841), 'marvin.integration.lib.utils.validateList', 'validateList', (['list_networks_response'], {}), '(list_networks_response)\n', (17817, 17841), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((18868, 18885), 'marvin.integration.lib.utils.validateList', 'validateList', (['vms'], {}), '(vms)\n', (18880, 18885), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((21486, 21522), 'marvin.integration.lib.utils.validateList', 'validateList', (['list_networks_response'], {}), '(list_networks_response)\n', (21498, 21522), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((22882, 22918), 'marvin.integration.lib.utils.validateList', 'validateList', (['list_networks_response'], {}), '(list_networks_response)\n', (22894, 22918), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((25786, 25822), 'marvin.integration.lib.utils.validateList', 'validateList', (['list_networks_response'], {}), '(list_networks_response)\n', (25798, 25822), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((32803, 32839), 'marvin.integration.lib.utils.validateList', 'validateList', (['list_networks_response'], {}), '(list_networks_response)\n', (32815, 32839), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((33765, 33801), 'marvin.integration.lib.utils.validateList', 'validateList', (['list_networks_response'], {}), '(list_networks_response)\n', (33777, 33801), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((66291, 66319), 'marvin.integration.lib.utils.validateList', 'validateList', (['securitygroups'], {}), '(securitygroups)\n', (66303, 66319), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((68674, 68686), 'marvin.integration.lib.utils.random_gen', 'random_gen', ([], {}), '()\n', (68684, 68686), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((77562, 77590), 'marvin.integration.lib.utils.validateList', 'validateList', (['securitygroups'], {}), '(securitygroups)\n', (77574, 77590), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((79513, 79534), 'marvin.integration.lib.utils.validateList', 'validateList', (['vm_list'], {}), '(vm_list)\n', (79525, 79534), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((81951, 81979), 'marvin.integration.lib.utils.validateList', 'validateList', (['securitygroups'], {}), '(securitygroups)\n', (81963, 81979), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((83940, 83961), 'marvin.integration.lib.utils.validateList', 'validateList', (['vm_list'], {}), '(vm_list)\n', (83952, 83961), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((88210, 88231), 'marvin.integration.lib.utils.validateList', 'validateList', (['vm_list'], {}), '(vm_list)\n', (88222, 88231), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((67177, 67198), 'marvin.integration.lib.utils.validateList', 'validateList', (['vm_list'], {}), '(vm_list)\n', (67189, 67198), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n'), ((68399, 68427), 'marvin.integration.lib.utils.validateList', 'validateList', (['securitygroups'], {}), '(securitygroups)\n', (68411, 68427), False, 'from marvin.integration.lib.utils import cleanup_resources, random_gen, validateList\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" tests for Resource count of only running vms in cloudstack 4.14.0.0
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (validateList,
cleanup_resources)
from marvin.lib.base import (Account,
Domain,
Configurations,
Network,
NetworkOffering,
VirtualMachine,
Resources,
ServiceOffering,
Zone)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
matchResourceCount,
isAccountResourceCountEqualToExpectedCount)
from marvin.codes import (PASS, FAILED, RESOURCE_CPU, RESOURCE_MEMORY)
import logging
import random
import time
class TestResourceCountRunningVMs(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(
TestResourceCountRunningVMs,
cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.zone = Zone(zone.__dict__)
cls._cleanup = []
cls.logger = logging.getLogger("TestResourceCountRunningVMs")
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
# Get Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.template = get_template(cls.apiclient, cls.zone.id, hypervisor="KVM")
if cls.template == FAILED:
sys.exit(1)
cls.templatesize = (cls.template.size / (1024 ** 3))
cls.services['mode'] = cls.zone.networktype
# Create Account
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
accounts = Account.list(cls.apiclient, id=cls.account.id)
cls.expectedCpu = int(accounts[0].cputotal)
cls.expectedMemory = int(accounts[0].memorytotal)
if cls.zone.securitygroupsenabled:
cls.services["shared_network_offering"]["specifyVlan"] = 'True'
cls.services["shared_network_offering"]["specifyIpRanges"] = 'True'
cls.network_offering = NetworkOffering.create(
cls.apiclient,
cls.services["shared_network_offering"]
)
cls.network_offering.update(cls.apiclient, state='Enabled')
cls.account_network = Network.create(
cls.apiclient,
cls.services["network2"],
networkofferingid=cls.network_offering.id,
zoneid=cls.zone.id,
accountid=cls.account.name,
domainid=cls.account.domainid
)
else:
cls.network_offering = NetworkOffering.create(
cls.apiclient,
cls.services["isolated_network_offering"],
)
# Enable Network offering
cls.network_offering.update(cls.apiclient, state='Enabled')
# Create account network
cls.services["network"]["zoneid"] = cls.zone.id
cls.services["network"]["networkoffering"] = cls.network_offering.id
cls.account_network = Network.create(
cls.apiclient,
cls.services["network"],
cls.account.name,
cls.account.domainid
)
cls._cleanup.append(cls.account);
cls._cleanup.append(cls.network_offering)
@classmethod
def tearDownClass(self):
try:
cleanup_resources(self.apiclient, self._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.cleanup = []
return
def tearDown(self):
try:
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def verify_resource_count_cpu_memory(self, expectedCpu, expectedMemory, account=None):
if account is None:
account = self.account
response = matchResourceCount(
self.apiclient, expectedCpu,
RESOURCE_CPU,
accountid=account.id)
self.assertEqual(response[0], PASS, response[1])
response = matchResourceCount(
self.apiclient, expectedMemory,
RESOURCE_MEMORY,
accountid=account.id)
self.assertEqual(response[0], PASS, response[1])
result = isAccountResourceCountEqualToExpectedCount(
self.apiclient, account.domainid, account.name,
expectedCpu, RESOURCE_CPU)
self.assertFalse(result[0], result[1])
self.assertTrue(result[2], "Resource count of cpu does not match")
result = isAccountResourceCountEqualToExpectedCount(
self.apiclient, account.domainid, account.name,
expectedMemory, RESOURCE_MEMORY)
self.assertFalse(result[0], result[1])
self.assertTrue(result[2], "Resource count of memory does not match")
def update_account_resource_limitation(self, maxCpu, maxMemory):
Resources.updateLimit(self.apiclient,
resourcetype=RESOURCE_CPU,
max=maxCpu,
domainid=self.account.domainid,
account=self.account.name)
Resources.updateLimit(self.apiclient,
resourcetype=RESOURCE_MEMORY,
max=maxMemory,
domainid=self.account.domainid,
account=self.account.name)
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_01_resource_count_vm_with_normal_offering_in_all_states(self):
"""Create VM with normal offering. Take resources of vm in all states into calculation of resource count.
Steps:
# 1. update resource.count.running.vms.only to false
# 2. create normal service offering
# 3. deploy vm, resource count of cpu/ram increases
# 4. stop vm, resource count of cpu/ram is not changed
# 5. update vm with displayvm=false, resource count decreases
# 6. update vm with displayvm=true, resource count increases
# 7. start vm, resource count of cpu/ram is not changed
# 8. reboot vm, resource count of cpu/ram is not changed
# 9. destroy vm, resource count of cpu/ram decreases
# 10. expunge vm, resource count of cpu/ram is not changed
"""
Configurations.update(self.apiclient,
name="resource.count.running.vms.only",
value="false" )
# Create small service offering
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["small"]
)
self.cleanup.append(self.service_offering)
# deploy vm
try:
virtual_machine_1 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCpu = self.expectedCpu + virtual_machine_1.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_1.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# stop vm
virtual_machine_1.stop(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# update vm with displayvm=false
virtual_machine_1.update(self.apiclient, displayvm=False)
self.expectedCpu = self.expectedCpu - virtual_machine_1.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_1.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# update vm with displayvm=false
virtual_machine_1.update(self.apiclient, displayvm=True)
self.expectedCpu = self.expectedCpu + virtual_machine_1.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_1.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# start vm
virtual_machine_1.start(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# reboot vm
virtual_machine_1.reboot(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# destroy vm
virtual_machine_1.delete(self.apiclient, expunge=False)
self.expectedCpu = self.expectedCpu - virtual_machine_1.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_1.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# expunge vm
virtual_machine_1.expunge(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_02_resource_count_vm_with_dynamic_offering_in_all_states(self):
"""Create VM with dynamic service offering. Take resources of vm in all states into calculation of resource count.
Steps:
# 1. update resource.count.running.vms.only to false
# 2. create dynamic service offering
# 3. deploy vm, resource count of cpu/ram increases
# 4. stop vm, resource count of cpu/ram is not changed
# 5. update vm with displayvm=false, resource count decreases
# 6. update vm with displayvm=true, resource count increases
# 7. start vm, resource count of cpu/ram is not changed
# 8. reboot vm, resource count of cpu/ram is not changed
# 9. destroy vm, resource count of cpu/ram decreases
# 10. expunge vm, resource count of cpu/ram is not changed
"""
Configurations.update(self.apiclient,
name="resource.count.running.vms.only",
value="false" )
# Create dynamic service offering
self.services["service_offering"]["cpunumber"] = ""
self.services["service_offering"]["cpuspeed"] = ""
self.services["service_offering"]["memory"] = ""
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offering"])
self.cleanup.append(self.service_offering)
# deploy vm
try:
virtual_machine_2 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
customcpunumber=1,
customcpuspeed=100,
custommemory=256,
templateid=self.template.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCpu = self.expectedCpu + virtual_machine_2.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_2.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# stop vm
virtual_machine_2.stop(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# update vm with displayvm=false
virtual_machine_2.update(self.apiclient, displayvm=False)
self.expectedCpu = self.expectedCpu - virtual_machine_2.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_2.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# update vm with displayvm=false
virtual_machine_2.update(self.apiclient, displayvm=True)
self.expectedCpu = self.expectedCpu + virtual_machine_2.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_2.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# start vm
virtual_machine_2.start(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# reboot vm
virtual_machine_2.reboot(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# destroy vm
virtual_machine_2.delete(self.apiclient, expunge=False)
self.expectedCpu = self.expectedCpu - virtual_machine_2.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_2.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# expunge vm
virtual_machine_2.expunge(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_03_resource_count_vm_with_normal_offering_in_running_state(self):
"""Create VM with normal service offering. Take resources of vm in running state into calculation of resource count.
Steps:
# 1. update resource.count.running.vms.only to true
# 2. create normal service offering
# 3. deploy vm, resource count of cpu/ram increases
# 4. stop vm, resource count of cpu/ram decreases
# 5. start vm, resource count of cpu/ram increases
# 6. reboot vm, resource count of cpu/ram is not changed
# 7. destroy vm, resource count of cpu/ram decreases
# 8. recover vm, resource count of cpu/ram is not changed
# 9. update vm with displayvm=false, resource count of cpu/ram is not changed
# 10. destroy vm with expunge = true, resource count of cpu/ram is not changed
"""
Configurations.update(self.apiclient,
name="resource.count.running.vms.only",
value="true" )
# Create service offering
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["small"]
)
self.cleanup.append(self.service_offering)
# deploy vm
try:
virtual_machine_3 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
templateid=self.template.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCpu = self.expectedCpu + virtual_machine_3.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_3.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# stop vm
virtual_machine_3.stop(self.apiclient)
self.expectedCpu = self.expectedCpu - virtual_machine_3.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_3.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# start vm
virtual_machine_3.start(self.apiclient)
self.expectedCpu = self.expectedCpu + virtual_machine_3.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_3.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# reboot vm
virtual_machine_3.reboot(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# destroy vm
virtual_machine_3.delete(self.apiclient, expunge=False)
self.expectedCpu = self.expectedCpu - virtual_machine_3.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_3.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# recover vm
virtual_machine_3.recover(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# update vm with displayvm=false
virtual_machine_3.update(self.apiclient, displayvm=False)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# expunge vm
virtual_machine_3.delete(self.apiclient, expunge=True)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_04_resource_count_vm_with_dynamic_offering_in_running_state(self):
"""Create VM with dynamic service offering. Take resources of vm in running state into calculation of resource count.
Steps:
# 1. update resource.count.running.vms.only to true
# 2. create dynamic service offering
# 3. deploy vm, resource count of cpu/ram increases
# 4. stop vm, resource count of cpu/ram decreases
# 5. start vm, resource count of cpu/ram increases
# 6. reboot vm, resource count of cpu/ram is not changed
# 7. destroy vm, resource count of cpu/ram decreases
# 8. recover vm, resource count of cpu/ram is not changed
# 9. update vm with displayvm=false, resource count of cpu/ram is not changed
# 10. destroy vm with expunge = true, resource count of cpu/ram is not changed
"""
Configurations.update(self.apiclient,
name="resource.count.running.vms.only",
value="true" )
# Create dynamic service offering
self.services["service_offering"]["cpunumber"] = ""
self.services["service_offering"]["cpuspeed"] = ""
self.services["service_offering"]["memory"] = ""
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offering"])
self.cleanup.append(self.service_offering)
# deploy vm
try:
virtual_machine_4 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
customcpunumber=1,
customcpuspeed=100,
custommemory=256,
templateid=self.template.id,
zoneid=self.zone.id,
mode=self.zone.networktype
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCpu = self.expectedCpu + virtual_machine_4.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_4.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# stop vm
virtual_machine_4.stop(self.apiclient)
self.expectedCpu = self.expectedCpu - virtual_machine_4.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_4.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# start vm
virtual_machine_4.start(self.apiclient)
self.expectedCpu = self.expectedCpu + virtual_machine_4.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_4.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# reboot vm
virtual_machine_4.reboot(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# destroy vm
virtual_machine_4.delete(self.apiclient, expunge=False)
self.expectedCpu = self.expectedCpu - virtual_machine_4.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_4.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# recover vm
virtual_machine_4.recover(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# update vm with displayvm=false
virtual_machine_4.update(self.apiclient, displayvm=False)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# expunge vm
virtual_machine_4.delete(self.apiclient, expunge=True)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_05_resource_count_vm_with_dynamic_offering_in_running_state_failed_cases(self):
"""Create VM with dynamic service offering. Take resources of vm in running state into calculation of resource count. Test failed cases
Steps:
# 1. update resource.count.running.vms.only to true
# 2. create dynamic service offering
# 3. update account cpu/ram limitation to current value
# 4. deploy vm (startvm=false), resource count of cpu/ram is not changed
# 5. start vm, it should fail
# 6. increase cpu limitation, start vm, it should fail
# 7. increase memory limitation, start vm, it should succeed. resource count of cpu/ram increases
# 8. restore vm, it should succeed. resource count of cpu/ram is not changed
# 9. destroy vm, resource count of cpu/ram decreases
# 10. expunge vm, resource count of cpu/ram is not changed
"""
Configurations.update(self.apiclient,
name="resource.count.running.vms.only",
value="true" )
# Create dynamic service offering
self.services["service_offering"]["cpunumber"] = ""
self.services["service_offering"]["cpuspeed"] = ""
self.services["service_offering"]["memory"] = ""
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offering"])
self.cleanup.append(self.service_offering)
# update resource limitation
self.update_account_resource_limitation(self.expectedCpu, self.expectedMemory)
# deploy vm (startvm=false)
try:
virtual_machine_5 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
customcpunumber=1,
customcpuspeed=100,
custommemory=256,
templateid=self.template.id,
zoneid=self.zone.id,
startvm=False,
mode=self.zone.networktype
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# start vm
try:
virtual_machine_5.start(self.apiclient)
self.fail("Start VM should fail as there is not enough cpu")
except Exception:
self.debug("Start VM failed as expected")
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# increase cpu limitation, and start vm
self.update_account_resource_limitation(self.expectedCpu + virtual_machine_5.cpunumber, self.expectedMemory)
try:
virtual_machine_5.start(self.apiclient)
self.fail("Start VM should fail as there is not enough memory")
except Exception:
self.debug("Start VM failed as expected")
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# increase memory limitation, and start vm
self.update_account_resource_limitation(self.expectedCpu + virtual_machine_5.cpunumber, self.expectedMemory + virtual_machine_5.memory)
try:
virtual_machine_5.start(self.apiclient)
self.debug("Start VM succeed as expected")
except Exception:
self.fail("Start VM should succeed as there is enough cpu and memory")
self.expectedCpu = self.expectedCpu + virtual_machine_5.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_5.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# restore running vm
virtual_machine_5.restore(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# expunge vm
virtual_machine_5.delete(self.apiclient, expunge=True)
self.expectedCpu = self.expectedCpu - virtual_machine_5.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_5.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_06_resource_count_vm_with_dynamic_offering_in_all_states_failed_cases(self):
"""Create VM with dynamic service offering. Take resources of vm in all states into calculation of resource count. Test failed cases
Steps:
# 1. update resource.count.running.vms.only to false
# 2. create dynamic service offering
# 3. update account cpu/ram limitation to current value
# 4. deploy vm (startvm=false), it should fail
# 5. increase cpu limitation, deploy vm, it should fail
# 6. increase memory limitation, deploy vm, it should succeed. resource count of cpu/ram increases
# 7. start vm, resource count of cpu/ram is not changed
# 8. restore vm, it should succeed. resource count of cpu/ram is not changed
# 9. destroy vm, resource count of cpu/ram decreases
# 10. expunge vm, resource count of cpu/ram is not changed
"""
Configurations.update(self.apiclient,
name="resource.count.running.vms.only",
value="false" )
# Create dynamic service offering
self.services["service_offering"]["cpunumber"] = ""
self.services["service_offering"]["cpuspeed"] = ""
self.services["service_offering"]["memory"] = ""
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offering"])
self.cleanup.append(self.service_offering)
# update resource limitation
self.update_account_resource_limitation(self.expectedCpu, self.expectedMemory)
# deploy vm (startvm=false)
try:
virtual_machine_6 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
customcpunumber=1,
customcpuspeed=100,
custommemory=256,
templateid=self.template.id,
zoneid=self.zone.id,
startvm=False,
mode=self.zone.networktype
)
self.fail("Deploy VM should fail as there is not enough cpu")
except Exception as e:
self.debug("Deploy VM failed as expected")
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# increase cpu limitation, and deploy vm
self.update_account_resource_limitation(self.expectedCpu + 1, self.expectedMemory)
try:
virtual_machine_6 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
customcpunumber=1,
customcpuspeed=100,
custommemory=256,
templateid=self.template.id,
zoneid=self.zone.id,
startvm=False,
mode=self.zone.networktype
)
self.fail("Deploy VM should fail as there is not enough memory")
except Exception as e:
self.debug("Deploy VM failed as expected")
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# increase memory limitation, and deploy vm
self.update_account_resource_limitation(self.expectedCpu + 1, self.expectedMemory + 256)
try:
virtual_machine_6 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
customcpunumber=1,
customcpuspeed=100,
custommemory=256,
templateid=self.template.id,
zoneid=self.zone.id,
startvm=False,
mode=self.zone.networktype
)
self.debug("Deploy VM succeed as expected")
except Exception:
self.fail("Deploy VM should succeed as there is enough cpu and memory")
self.expectedCpu = self.expectedCpu + virtual_machine_6.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_6.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# start vm
virtual_machine_6.start(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# restore running vm
virtual_machine_6.restore(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# expunge vm
virtual_machine_6.delete(self.apiclient, expunge=True)
self.expectedCpu = self.expectedCpu - virtual_machine_6.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_6.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_07_resource_count_vm_in_running_state_and_move_and_upgrade(self):
"""Create VM with dynamic service offering. Take resources of vm in running state into calculation. Move vm to another account and upgrade it.
Steps:
# 1. update resource.count.running.vms.only to true
# 2. create dynamic service offering
# 3. deploy vm, resource count of cpu/ram increases
# 4. stop vm, resource count of cpu/ram decreases
# 5. create another account
# 6. move vm to new account. resource count of cpu/ram of current account is not changed. resource count of cpu/ram of new account is not changed.
# 7. create another service offering.
# 8. upgrade vm. resource count of cpu/ram of new account is not changed.
# 9. start vm, resource count of cpu/ram of new account increases with cpu/ram of new service offering.
# 10. destroy vm, resource count of cpu/ram decreases
# 11. expunge vm, resource count of cpu/ram is not changed
"""
Configurations.update(self.apiclient,
name="resource.count.running.vms.only",
value="true" )
# Create dynamic service offering
self.services["service_offering"]["cpunumber"] = ""
self.services["service_offering"]["cpuspeed"] = ""
self.services["service_offering"]["memory"] = ""
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offering"])
self.cleanup.append(self.service_offering)
# deploy vm
try:
virtual_machine_7 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
customcpunumber=1,
customcpuspeed=100,
custommemory=256,
templateid=self.template.id,
zoneid=self.zone.id
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCpu = self.expectedCpu + virtual_machine_7.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_7.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# stop vm
virtual_machine_7.stop(self.apiclient)
self.expectedCpu = self.expectedCpu - virtual_machine_7.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_7.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# create another account
self.account2 = Account.create(
self.apiclient,
self.services["account2"],
admin=True,
domainid=self.domain.id
)
accounts = Account.list(self.apiclient, id=self.account2.id)
self.account2Cpu = int(accounts[0].cputotal)
self.account2Memory = int(accounts[0].memorytotal)
# move vm to new account. resource count of cpu/ram of current account is not changed. resource count of cpu/ram of new account is not changed.
oldcpunumber = virtual_machine_7.cpunumber
oldmemory = virtual_machine_7.memory
virtual_machine_7.assign_virtual_machine(self.apiclient, self.account2.name, self.account2.domainid)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
self.verify_resource_count_cpu_memory(self.account2Cpu, self.account2Memory, account=self.account2);
# create another service offering
self.service_offering_big = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["big"]
)
self.cleanup.append(self.service_offering_big)
# upgrade vm
virtual_machine_7.change_service_offering(self.apiclient, self.service_offering_big.id)
self.verify_resource_count_cpu_memory(self.account2Cpu, self.account2Memory, account=self.account2);
# start vm, resource count of cpu/ram of new account increases with cpu/ram of new service offering.
virtual_machine_7.start(self.apiclient)
self.account2Cpu = self.account2Cpu + self.service_offering_big.cpunumber
self.account2Memory = self.account2Memory + self.service_offering_big.memory
self.verify_resource_count_cpu_memory(self.account2Cpu, self.account2Memory, account=self.account2);
# expunge vm
virtual_machine_7.delete(self.apiclient, expunge=True)
self.account2Cpu = self.account2Cpu - self.service_offering_big.cpunumber
self.account2Memory = self.account2Memory - self.service_offering_big.memory
self.verify_resource_count_cpu_memory(self.account2Cpu, self.account2Memory, account=self.account2);
@attr(tags=["advanced", "advancedsg"], required_hardware="false")
def test_08_resource_count_vm_in_all_states_and_move_and_upgrade(self):
"""Create VM with dynamic service offering. Take resources of vm in all states into calculation. Move vm to another account and upgrade it.
Steps:
# 1. update resource.count.running.vms.only to true
# 2. create dynamic service offering
# 3. deploy vm, resource count of cpu/ram increases
# 4. stop vm, resource count of cpu/ram is not changed
# 5. create another account
# 6. move vm to new account. resource count of cpu/ram of current account decreases. resource count of cpu/ram of new account increases.
# 7. create another service offering.
# 8. upgrade vm. resource count of cpu/ram of new account is changed.
# 9. start vm, resource count of cpu/ram is not changed
# 10. destroy vm, resource count of cpu/ram decreases
# 11. expunge vm, resource count of cpu/ram is not changed
"""
Configurations.update(self.apiclient,
name="resource.count.running.vms.only",
value="false" )
# Create dynamic service offering
self.services["service_offering"]["cpunumber"] = ""
self.services["service_offering"]["cpuspeed"] = ""
self.services["service_offering"]["memory"] = ""
self.service_offering = ServiceOffering.create(
self.apiclient,
self.services["service_offering"])
self.cleanup.append(self.service_offering)
# deploy vm
try:
virtual_machine_8 = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
customcpunumber=1,
customcpuspeed=100,
custommemory=256,
templateid=self.template.id,
zoneid=self.zone.id
)
except Exception as e:
self.fail("Exception while deploying virtual machine: %s" % e)
self.expectedCpu = self.expectedCpu + virtual_machine_8.cpunumber
self.expectedMemory = self.expectedMemory + virtual_machine_8.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# stop vm
virtual_machine_8.stop(self.apiclient)
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
# create another account
self.account2 = Account.create(
self.apiclient,
self.services["account2"],
admin=True,
domainid=self.domain.id
)
self.cleanup.append(self.account2)
accounts = Account.list(self.apiclient, id=self.account2.id)
self.account2Cpu = int(accounts[0].cputotal)
self.account2Memory = int(accounts[0].memorytotal)
# move vm to new account. resource count of cpu/ram of current account decreases. resource count of cpu/ram of new account increases.
oldcpunumber = virtual_machine_8.cpunumber
oldmemory = virtual_machine_8.memory
virtual_machine_8.assign_virtual_machine(self.apiclient, self.account2.name, self.account2.domainid)
self.expectedCpu = self.expectedCpu - virtual_machine_8.cpunumber
self.expectedMemory = self.expectedMemory - virtual_machine_8.memory
self.verify_resource_count_cpu_memory(self.expectedCpu, self.expectedMemory);
self.account2Cpu = self.account2Cpu + virtual_machine_8.cpunumber
self.account2Memory = self.account2Memory + virtual_machine_8.memory
self.verify_resource_count_cpu_memory(self.account2Cpu, self.account2Memory, account=self.account2);
# create another service offering
self.service_offering_big = ServiceOffering.create(
self.apiclient,
self.services["service_offerings"]["big"]
)
self.cleanup.append(self.service_offering_big)
# upgrade vm
virtual_machine_8.change_service_offering(self.apiclient, self.service_offering_big.id)
self.account2Cpu = self.account2Cpu + self.service_offering_big.cpunumber - oldcpunumber
self.account2Memory = self.account2Memory + self.service_offering_big.memory - oldmemory
self.verify_resource_count_cpu_memory(self.account2Cpu, self.account2Memory, account=self.account2);
# start vm
virtual_machine_8.start(self.apiclient)
self.verify_resource_count_cpu_memory(self.account2Cpu, self.account2Memory, account=self.account2);
# expunge vm
virtual_machine_8.delete(self.apiclient, expunge=True)
self.account2Cpu = self.account2Cpu - self.service_offering_big.cpunumber
self.account2Memory = self.account2Memory - self.service_offering_big.memory
self.verify_resource_count_cpu_memory(self.account2Cpu, self.account2Memory, account=self.account2);
| [
"marvin.lib.common.get_domain",
"marvin.lib.base.Zone",
"marvin.lib.base.Configurations.update",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.NetworkOffering.create",
"marvin.lib.base.Account.list",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.common.matchResourceCount",
"marvin.l... | [((7066, 7130), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (7070, 7130), False, 'from nose.plugins.attrib import attr\n'), ((10839, 10903), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (10843, 10903), False, 'from nose.plugins.attrib import attr\n'), ((14887, 14951), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (14891, 14951), False, 'from nose.plugins.attrib import attr\n'), ((18666, 18730), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (18670, 18730), False, 'from nose.plugins.attrib import attr\n'), ((22719, 22783), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (22723, 22783), False, 'from nose.plugins.attrib import attr\n'), ((27187, 27251), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (27191, 27251), False, 'from nose.plugins.attrib import attr\n'), ((32500, 32564), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (32504, 32564), False, 'from nose.plugins.attrib import attr\n'), ((37584, 37648), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedsg']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'advancedsg'], required_hardware='false')\n", (37588, 37648), False, 'from nose.plugins.attrib import attr\n'), ((2226, 2245), 'marvin.lib.base.Zone', 'Zone', (['zone.__dict__'], {}), '(zone.__dict__)\n', (2230, 2245), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((2294, 2342), 'logging.getLogger', 'logging.getLogger', (['"""TestResourceCountRunningVMs"""'], {}), "('TestResourceCountRunningVMs')\n", (2311, 2342), False, 'import logging\n'), ((2372, 2395), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2393, 2395), False, 'import logging\n'), ((2546, 2571), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2556, 2571), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((2596, 2654), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id'], {'hypervisor': '"""KVM"""'}), "(cls.apiclient, cls.zone.id, hypervisor='KVM')\n", (2608, 2654), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((2875, 2970), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (2889, 2970), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((3043, 3089), 'marvin.lib.base.Account.list', 'Account.list', (['cls.apiclient'], {'id': 'cls.account.id'}), '(cls.apiclient, id=cls.account.id)\n', (3055, 3089), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((5474, 5562), 'marvin.lib.common.matchResourceCount', 'matchResourceCount', (['self.apiclient', 'expectedCpu', 'RESOURCE_CPU'], {'accountid': 'account.id'}), '(self.apiclient, expectedCpu, RESOURCE_CPU, accountid=\n account.id)\n', (5492, 5562), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((5708, 5801), 'marvin.lib.common.matchResourceCount', 'matchResourceCount', (['self.apiclient', 'expectedMemory', 'RESOURCE_MEMORY'], {'accountid': 'account.id'}), '(self.apiclient, expectedMemory, RESOURCE_MEMORY,\n accountid=account.id)\n', (5726, 5801), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((5946, 6067), 'marvin.lib.common.isAccountResourceCountEqualToExpectedCount', 'isAccountResourceCountEqualToExpectedCount', (['self.apiclient', 'account.domainid', 'account.name', 'expectedCpu', 'RESOURCE_CPU'], {}), '(self.apiclient, account.domainid,\n account.name, expectedCpu, RESOURCE_CPU)\n', (5988, 6067), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((6229, 6356), 'marvin.lib.common.isAccountResourceCountEqualToExpectedCount', 'isAccountResourceCountEqualToExpectedCount', (['self.apiclient', 'account.domainid', 'account.name', 'expectedMemory', 'RESOURCE_MEMORY'], {}), '(self.apiclient, account.domainid,\n account.name, expectedMemory, RESOURCE_MEMORY)\n', (6271, 6356), False, 'from marvin.lib.common import get_domain, get_zone, get_template, matchResourceCount, isAccountResourceCountEqualToExpectedCount\n'), ((6581, 6720), 'marvin.lib.base.Resources.updateLimit', 'Resources.updateLimit', (['self.apiclient'], {'resourcetype': 'RESOURCE_CPU', 'max': 'maxCpu', 'domainid': 'self.account.domainid', 'account': 'self.account.name'}), '(self.apiclient, resourcetype=RESOURCE_CPU, max=maxCpu,\n domainid=self.account.domainid, account=self.account.name)\n', (6602, 6720), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((6822, 6968), 'marvin.lib.base.Resources.updateLimit', 'Resources.updateLimit', (['self.apiclient'], {'resourcetype': 'RESOURCE_MEMORY', 'max': 'maxMemory', 'domainid': 'self.account.domainid', 'account': 'self.account.name'}), '(self.apiclient, resourcetype=RESOURCE_MEMORY, max=\n maxMemory, domainid=self.account.domainid, account=self.account.name)\n', (6843, 6968), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((8026, 8123), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""resource.count.running.vms.only"""', 'value': '"""false"""'}), "(self.apiclient, name=\n 'resource.count.running.vms.only', value='false')\n", (8047, 8123), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((8225, 8313), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['small']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'small'])\n", (8247, 8313), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((11809, 11906), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""resource.count.running.vms.only"""', 'value': '"""false"""'}), "(self.apiclient, name=\n 'resource.count.running.vms.only', value='false')\n", (11830, 11906), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((12187, 12260), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {}), "(self.apiclient, self.services['service_offering'])\n", (12209, 12260), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((15882, 15978), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""resource.count.running.vms.only"""', 'value': '"""true"""'}), "(self.apiclient, name=\n 'resource.count.running.vms.only', value='true')\n", (15903, 15978), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((16074, 16162), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['small']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'small'])\n", (16096, 16162), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((19664, 19760), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""resource.count.running.vms.only"""', 'value': '"""true"""'}), "(self.apiclient, name=\n 'resource.count.running.vms.only', value='true')\n", (19685, 19760), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((20041, 20114), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {}), "(self.apiclient, self.services['service_offering'])\n", (20063, 20114), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((23771, 23867), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""resource.count.running.vms.only"""', 'value': '"""true"""'}), "(self.apiclient, name=\n 'resource.count.running.vms.only', value='true')\n", (23792, 23867), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((24148, 24221), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {}), "(self.apiclient, self.services['service_offering'])\n", (24170, 24221), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((28236, 28333), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""resource.count.running.vms.only"""', 'value': '"""false"""'}), "(self.apiclient, name=\n 'resource.count.running.vms.only', value='false')\n", (28257, 28333), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((28614, 28687), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {}), "(self.apiclient, self.services['service_offering'])\n", (28636, 28687), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((33662, 33758), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""resource.count.running.vms.only"""', 'value': '"""true"""'}), "(self.apiclient, name=\n 'resource.count.running.vms.only', value='true')\n", (33683, 33758), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((34039, 34112), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {}), "(self.apiclient, self.services['service_offering'])\n", (34061, 34112), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((35418, 35516), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account2']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account2'], admin=True,\n domainid=self.domain.id)\n", (35432, 35516), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((35590, 35639), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'id': 'self.account2.id'}), '(self.apiclient, id=self.account2.id)\n', (35602, 35639), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((36385, 36471), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['big']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'big'])\n", (36407, 36471), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((38683, 38780), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['self.apiclient'], {'name': '"""resource.count.running.vms.only"""', 'value': '"""false"""'}), "(self.apiclient, name=\n 'resource.count.running.vms.only', value='false')\n", (38704, 38780), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((39061, 39134), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offering']"], {}), "(self.apiclient, self.services['service_offering'])\n", (39083, 39134), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((40289, 40387), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account2']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account2'], admin=True,\n domainid=self.domain.id)\n", (40303, 40387), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((40504, 40553), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'id': 'self.account2.id'}), '(self.apiclient, id=self.account2.id)\n', (40516, 40553), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((41592, 41678), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['self.apiclient', "self.services['service_offerings']['big']"], {}), "(self.apiclient, self.services['service_offerings'][\n 'big'])\n", (41614, 41678), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((3436, 3514), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['shared_network_offering']"], {}), "(cls.apiclient, cls.services['shared_network_offering'])\n", (3458, 3514), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((3668, 3854), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network2']"], {'networkofferingid': 'cls.network_offering.id', 'zoneid': 'cls.zone.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid'}), "(cls.apiclient, cls.services['network2'], networkofferingid=\n cls.network_offering.id, zoneid=cls.zone.id, accountid=cls.account.name,\n domainid=cls.account.domainid)\n", (3682, 3854), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((4005, 4090), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.apiclient', "cls.services['isolated_network_offering']"], {}), "(cls.apiclient, cls.services['isolated_network_offering']\n )\n", (4027, 4090), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((4456, 4554), 'marvin.lib.base.Network.create', 'Network.create', (['cls.apiclient', "cls.services['network']", 'cls.account.name', 'cls.account.domainid'], {}), "(cls.apiclient, cls.services['network'], cls.account.name,\n cls.account.domainid)\n", (4470, 4554), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((4794, 4842), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self._cleanup'], {}), '(self.apiclient, self._cleanup)\n', (4811, 4842), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((5132, 5179), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (5149, 5179), False, 'from marvin.lib.utils import validateList, cleanup_resources\n'), ((8460, 8726), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, templateid=self.template.id,\n zoneid=self.zone.id, mode=self.zone.networktype)\n", (8481, 8726), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((12403, 12730), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'customcpunumber': '(1)', 'customcpuspeed': '(100)', 'custommemory': '(256)', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, customcpunumber=1,\n customcpuspeed=100, custommemory=256, templateid=self.template.id,\n zoneid=self.zone.id, mode=self.zone.networktype)\n", (12424, 12730), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((16309, 16575), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, templateid=self.template.id,\n zoneid=self.zone.id, mode=self.zone.networktype)\n", (16330, 16575), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((20257, 20584), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'customcpunumber': '(1)', 'customcpuspeed': '(100)', 'custommemory': '(256)', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, customcpunumber=1,\n customcpuspeed=100, custommemory=256, templateid=self.template.id,\n zoneid=self.zone.id, mode=self.zone.networktype)\n", (20278, 20584), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((24505, 24847), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'customcpunumber': '(1)', 'customcpuspeed': '(100)', 'custommemory': '(256)', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'startvm': '(False)', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, customcpunumber=1,\n customcpuspeed=100, custommemory=256, templateid=self.template.id,\n zoneid=self.zone.id, startvm=False, mode=self.zone.networktype)\n", (24526, 24847), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((28971, 29313), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'customcpunumber': '(1)', 'customcpuspeed': '(100)', 'custommemory': '(256)', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'startvm': '(False)', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, customcpunumber=1,\n customcpuspeed=100, custommemory=256, templateid=self.template.id,\n zoneid=self.zone.id, startvm=False, mode=self.zone.networktype)\n", (28992, 29313), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((29937, 30279), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'customcpunumber': '(1)', 'customcpuspeed': '(100)', 'custommemory': '(256)', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'startvm': '(False)', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, customcpunumber=1,\n customcpuspeed=100, custommemory=256, templateid=self.template.id,\n zoneid=self.zone.id, startvm=False, mode=self.zone.networktype)\n", (29958, 30279), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((30915, 31257), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'customcpunumber': '(1)', 'customcpuspeed': '(100)', 'custommemory': '(256)', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id', 'startvm': '(False)', 'mode': 'self.zone.networktype'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, customcpunumber=1,\n customcpuspeed=100, custommemory=256, templateid=self.template.id,\n zoneid=self.zone.id, startvm=False, mode=self.zone.networktype)\n", (30936, 31257), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((34255, 34554), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'customcpunumber': '(1)', 'customcpuspeed': '(100)', 'custommemory': '(256)', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, customcpunumber=1,\n customcpuspeed=100, custommemory=256, templateid=self.template.id,\n zoneid=self.zone.id)\n", (34276, 34554), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n'), ((39277, 39576), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.apiclient', "self.services['virtual_machine']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'serviceofferingid': 'self.service_offering.id', 'customcpunumber': '(1)', 'customcpuspeed': '(100)', 'custommemory': '(256)', 'templateid': 'self.template.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['virtual_machine'],\n accountid=self.account.name, domainid=self.account.domainid,\n serviceofferingid=self.service_offering.id, customcpunumber=1,\n customcpuspeed=100, custommemory=256, templateid=self.template.id,\n zoneid=self.zone.id)\n", (39298, 39576), False, 'from marvin.lib.base import Account, Domain, Configurations, Network, NetworkOffering, VirtualMachine, Resources, ServiceOffering, Zone\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Import Local Modules
from marvin.codes import FAILED, KVM, PASS, XEN_SERVER, RUNNING
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import random_gen, cleanup_resources, validateList, is_snapshot_on_nfs, isAlmostEqual
from marvin.lib.base import (Account,
Configurations,
ServiceOffering,
StoragePool,
Template,
VirtualMachine,
VmSnapshot,
Host)
from marvin.lib.common import (get_zone,
get_domain,
get_template,
list_snapshots,
list_virtual_machines,
list_configurations)
from marvin.cloudstackAPI import (listTemplates)
import time
import unittest
class TestVmSnapshot(cloudstackTestCase):
@classmethod
def setUpClass(cls):
testClient = super(TestVmSnapshot, cls).getClsTestClient()
cls.apiclient = testClient.getApiClient()
cls._cleanup = []
cls.unsupportedHypervisor = False
cls.hypervisor = testClient.getHypervisorInfo()
if cls.hypervisor.lower() != "kvm":
cls.unsupportedHypervisor = True
return
cls.services = testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
hosts = Host.list(
cls.apiclient,
zoneid=cls.zone.id,
type='Routing',
hypervisor='KVM')
pools = StoragePool.list(
cls.apiclient,
zoneid=cls.zone.id)
for pool in pools:
if pool.type == "NetworkFilesystem" or pool.type == "Filesystem":
raise unittest.SkipTest("Storage-based snapshots functionality is not supported for NFS/Local primary storage")
for host in hosts:
if host.details['Host.OS'] in ['CentOS']:
raise unittest.SkipTest("The standard `qemu-kvm` which is the default for CentOS does not support the new functionality. It has to be installed `qemu-kvm-ev`")
Configurations.update(cls.apiclient,
name = "kvm.vmstoragesnapshot.enabled",
value = "true")
#The version of CentOS has to be supported
templ = {
"name": "CentOS8",
"displaytext": "CentOS 8",
"format": "QCOW2",
"url": "http://download.cloudstack.org/releases/4.14/default-tmpl-centos8.0.qcow2.bz2",
"ispublic": "True",
"isextractable": "True",
"hypervisor": cls.hypervisor,
"zoneid": cls.zone.id,
"ostype": "CentOS 8",
"directdownload": True,
}
template = Template.register(cls.apiclient, templ, zoneid=cls.zone.id, hypervisor=cls.hypervisor)
if template == FAILED:
assert False, "get_template() failed to return template\
with description %s" % cls.services["ostype"]
cls.services["domainid"] = cls.domain.id
cls.services["small"]["zoneid"] = cls.zone.id
cls.services["templates"]["ostypeid"] = template.ostypeid
cls.services["zoneid"] = cls.zone.id
cls.account = Account.create(
cls.apiclient,
cls.services["account"],
domainid=cls.domain.id
)
cls._cleanup.append(cls.account)
service_offerings_nfs = {
"name": "nfs",
"displaytext": "nfs",
"cpunumber": 1,
"cpuspeed": 500,
"memory": 512,
"storagetype": "shared",
"customizediops": False,
}
cls.service_offering = ServiceOffering.create(
cls.apiclient,
service_offerings_nfs,
)
cls._cleanup.append(cls.service_offering)
cls.virtual_machine = VirtualMachine.create(
cls.apiclient,
cls.services,
zoneid=cls.zone.id,
templateid=template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
mode=cls.zone.networktype,
hypervisor=cls.hypervisor,
rootdisksize=20,
)
cls.random_data_0 = random_gen(size=100)
cls.test_dir = "/tmp"
cls.random_data = "random.data"
return
@classmethod
def tearDownClass(cls):
try:
Configurations.update(cls.apiclient,
name = "kvm.vmstoragesnapshot.enabled",
value = "false")
# Cleanup resources used
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
if self.unsupportedHypervisor:
self.skipTest("Skipping test because unsupported hypervisor\
%s" % self.hypervisor)
return
def tearDown(self):
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_01_create_vm_snapshots(self):
"""Test to create VM snapshots
"""
try:
# Login to VM and write data to file system
ssh_client = self.virtual_machine.get_ssh_client()
cmds = [
"echo %s > %s/%s" %
(self.random_data_0, self.test_dir, self.random_data),
"cat %s/%s" %
(self.test_dir, self.random_data)]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
self.assertEqual(
self.random_data_0,
result[0],
"Check the random data has be write into temp file!"
)
time.sleep(30)
MemorySnapshot = False
vm_snapshot = VmSnapshot.create(
self.apiclient,
self.virtual_machine.id,
MemorySnapshot,
"TestSnapshot",
"Display Text"
)
self.assertEqual(
vm_snapshot.state,
"Ready",
"Check the snapshot of vm is ready!"
)
return
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_02_revert_vm_snapshots(self):
"""Test to revert VM snapshots
"""
try:
ssh_client = self.virtual_machine.get_ssh_client()
cmds = [
"rm -rf %s/%s" % (self.test_dir, self.random_data),
"ls %s/%s" % (self.test_dir, self.random_data)
]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
if str(result[0]).index("No such file or directory") == -1:
self.fail("Check the random data has be delete from temp file!")
time.sleep(30)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=self.virtual_machine.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
self.assertEqual(
list_snapshot_response[0].state,
"Ready",
"Check the snapshot of vm is ready!"
)
self.virtual_machine.stop(self.apiclient)
VmSnapshot.revertToSnapshot(
self.apiclient,
list_snapshot_response[0].id)
self.virtual_machine.start(self.apiclient)
try:
ssh_client = self.virtual_machine.get_ssh_client(reconnect=True)
cmds = [
"cat %s/%s" % (self.test_dir, self.random_data)
]
for c in cmds:
self.debug(c)
result = ssh_client.execute(c)
self.debug(result)
except Exception:
self.fail("SSH failed for Virtual machine: %s" %
self.virtual_machine.ipaddress)
self.assertEqual(
self.random_data_0,
result[0],
"Check the random data is equal with the ramdom file!"
)
@attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true")
def test_03_delete_vm_snapshots(self):
"""Test to delete vm snapshots
"""
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=self.virtual_machine.id,
listall=True)
self.assertEqual(
isinstance(list_snapshot_response, list),
True,
"Check list response returns a valid list"
)
self.assertNotEqual(
list_snapshot_response,
None,
"Check if snapshot exists in ListSnapshot"
)
VmSnapshot.deleteVMSnapshot(
self.apiclient,
list_snapshot_response[0].id)
time.sleep(30)
list_snapshot_response = VmSnapshot.list(
self.apiclient,
virtualmachineid=self.virtual_machine.id,
listall=False)
self.debug('list_snapshot_response -------------------- %s' % list_snapshot_response)
self.assertIsNone(list_snapshot_response, "snapshot is already deleted")
| [
"marvin.lib.common.get_domain",
"marvin.lib.base.VmSnapshot.create",
"marvin.lib.base.Account.create",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.VmSnapshot.revertToSnapshot",
"marvin.lib.base.Host.list",
"marvin.lib.base.Template.register",
"mar... | [((6245, 6317), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (6249, 6317), False, 'from nose.plugins.attrib import attr\n'), ((7606, 7678), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (7610, 7678), False, 'from nose.plugins.attrib import attr\n'), ((9941, 10013), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'smoke'], required_hardware='true')\n", (9945, 10013), False, 'from nose.plugins.attrib import attr\n'), ((2323, 2348), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2333, 2348), False, 'from marvin.lib.common import get_zone, get_domain, get_template, list_snapshots, list_virtual_machines, list_configurations\n'), ((2439, 2517), 'marvin.lib.base.Host.list', 'Host.list', (['cls.apiclient'], {'zoneid': 'cls.zone.id', 'type': '"""Routing"""', 'hypervisor': '"""KVM"""'}), "(cls.apiclient, zoneid=cls.zone.id, type='Routing', hypervisor='KVM')\n", (2448, 2517), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((2584, 2635), 'marvin.lib.base.StoragePool.list', 'StoragePool.list', (['cls.apiclient'], {'zoneid': 'cls.zone.id'}), '(cls.apiclient, zoneid=cls.zone.id)\n', (2600, 2635), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((3162, 3254), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient'], {'name': '"""kvm.vmstoragesnapshot.enabled"""', 'value': '"""true"""'}), "(cls.apiclient, name='kvm.vmstoragesnapshot.enabled',\n value='true')\n", (3183, 3254), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((3795, 3886), 'marvin.lib.base.Template.register', 'Template.register', (['cls.apiclient', 'templ'], {'zoneid': 'cls.zone.id', 'hypervisor': 'cls.hypervisor'}), '(cls.apiclient, templ, zoneid=cls.zone.id, hypervisor=cls.\n hypervisor)\n', (3812, 3886), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((4286, 4364), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], domainid=cls.domain.id)\n", (4300, 4364), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((4776, 4836), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', 'service_offerings_nfs'], {}), '(cls.apiclient, service_offerings_nfs)\n', (4798, 4836), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((4954, 5235), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', 'cls.services'], {'zoneid': 'cls.zone.id', 'templateid': 'template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id', 'mode': 'cls.zone.networktype', 'hypervisor': 'cls.hypervisor', 'rootdisksize': '(20)'}), '(cls.apiclient, cls.services, zoneid=cls.zone.id,\n templateid=template.id, accountid=cls.account.name, domainid=cls.\n account.domainid, serviceofferingid=cls.service_offering.id, mode=cls.\n zone.networktype, hypervisor=cls.hypervisor, rootdisksize=20)\n', (4975, 5235), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((5381, 5401), 'marvin.lib.utils.random_gen', 'random_gen', ([], {'size': '(100)'}), '(size=100)\n', (5391, 5401), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList, is_snapshot_on_nfs, isAlmostEqual\n'), ((7200, 7214), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (7210, 7214), False, 'import time\n'), ((7270, 7380), 'marvin.lib.base.VmSnapshot.create', 'VmSnapshot.create', (['self.apiclient', 'self.virtual_machine.id', 'MemorySnapshot', '"""TestSnapshot"""', '"""Display Text"""'], {}), "(self.apiclient, self.virtual_machine.id, MemorySnapshot,\n 'TestSnapshot', 'Display Text')\n", (7287, 7380), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((8454, 8468), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (8464, 8468), False, 'import time\n'), ((8503, 8594), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id,\n listall=True)\n', (8518, 8594), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((9152, 9225), 'marvin.lib.base.VmSnapshot.revertToSnapshot', 'VmSnapshot.revertToSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (9179, 9225), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((10142, 10233), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id,\n listall=True)\n', (10157, 10233), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((10587, 10660), 'marvin.lib.base.VmSnapshot.deleteVMSnapshot', 'VmSnapshot.deleteVMSnapshot', (['self.apiclient', 'list_snapshot_response[0].id'], {}), '(self.apiclient, list_snapshot_response[0].id)\n', (10614, 10660), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((10695, 10709), 'time.sleep', 'time.sleep', (['(30)'], {}), '(30)\n', (10705, 10709), False, 'import time\n'), ((10744, 10836), 'marvin.lib.base.VmSnapshot.list', 'VmSnapshot.list', (['self.apiclient'], {'virtualmachineid': 'self.virtual_machine.id', 'listall': '(False)'}), '(self.apiclient, virtualmachineid=self.virtual_machine.id,\n listall=False)\n', (10759, 10836), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((5558, 5651), 'marvin.lib.base.Configurations.update', 'Configurations.update', (['cls.apiclient'], {'name': '"""kvm.vmstoragesnapshot.enabled"""', 'value': '"""false"""'}), "(cls.apiclient, name='kvm.vmstoragesnapshot.enabled',\n value='false')\n", (5579, 5651), False, 'from marvin.lib.base import Account, Configurations, ServiceOffering, StoragePool, Template, VirtualMachine, VmSnapshot, Host\n'), ((5725, 5771), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (5742, 5771), False, 'from marvin.lib.utils import random_gen, cleanup_resources, validateList, is_snapshot_on_nfs, isAlmostEqual\n'), ((2789, 2904), 'unittest.SkipTest', 'unittest.SkipTest', (['"""Storage-based snapshots functionality is not supported for NFS/Local primary storage"""'], {}), "(\n 'Storage-based snapshots functionality is not supported for NFS/Local primary storage'\n )\n", (2806, 2904), False, 'import unittest\n'), ((2999, 3162), 'unittest.SkipTest', 'unittest.SkipTest', (['"""The standard `qemu-kvm` which is the default for CentOS does not support the new functionality. It has to be installed `qemu-kvm-ev`"""'], {}), "(\n 'The standard `qemu-kvm` which is the default for CentOS does not support the new functionality. It has to be installed `qemu-kvm-ev`'\n )\n", (3016, 3162), False, 'import unittest\n')] |
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2018-07-17 23:36:37
# @Last modified by: <NAME>
# @Last Modified time: 2018-07-19 15:44:42
from __future__ import print_function, division, absolute_import
from collections import defaultdict
from marvin.utils.datamodel.drp import datamodel
from marvin.contrib.vacs.base import VACMixIn
from .base import VACList, VACDataModel
subvacs = VACMixIn.__subclasses__()
vacdms = []
# create a dictionary of VACs by release
vacdict = defaultdict(list)
for sv in subvacs:
# skip hidden VACs
if sv._hidden:
continue
# add versions to dictionary
for k in sv.version.keys():
vacdict[k].append(sv)
# create VAC datamodels
for release, vacs in vacdict.items():
vc = VACList(vacs)
dm = datamodel[release] if release in datamodel else None
aliases = dm.aliases if dm else None
vacdm = VACDataModel(release, vacs=vc, aliases=aliases)
vacdms.append(vacdm)
| [
"marvin.contrib.vacs.base.VACMixIn.__subclasses__"
] | [((463, 488), 'marvin.contrib.vacs.base.VACMixIn.__subclasses__', 'VACMixIn.__subclasses__', ([], {}), '()\n', (486, 488), False, 'from marvin.contrib.vacs.base import VACMixIn\n'), ((553, 570), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (564, 570), False, 'from collections import defaultdict\n')] |
#!/usr/bin/env python
# encoding: utf-8
#
# Licensed under a 3-clause BSD license.
#
#
# map.py
#
# Created by <NAME> on 28 Apr 2017.
#
# Includes code from mangadap.plot.maps.py licensed under the following 3-clause
# BSD license.
#
# Copyright (c) 2015, SDSS-IV/MaNGA Pipeline Group
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
# HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import division, print_function, absolute_import
import copy
from astropy import units
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from marvin import config
from marvin.core.exceptions import MarvinError
import marvin.utils.plot.colorbar as colorbar
from marvin.utils.general import get_plot_params
from marvin.utils.general.maskbit import Maskbit
def _mask_nocov(dapmap, mask, ivar=None):
"""Mask spaxels that are not covered by the IFU.
Parameters:
dapmap (marvin.tools.map.Map):
Marvin Map object.
mask (array):
Mask for image.
ivar (array):
Inverse variance for image. Default is None.
Returns:
array: Boolean array for mask (i.e., True corresponds to value to be
masked out).
"""
assert (dapmap is not None) or (mask is not None) or (ivar is not None), \
'Must provide ``dapmap``, ``mask`` or ``ivar``.'
if dapmap is None:
pixmask = Maskbit('MANGA_DAPPIXMASK')
pixmask.mask = mask
else:
pixmask = dapmap.pixmask
try:
return pixmask.get_mask('NOCOV')
except (MarvinError, AttributeError, IndexError, TypeError):
return ivar == 0
def mask_low_snr(value, ivar, snr_min):
"""Mask spaxels with a signal-to-noise ratio below some threshold.
Parameters:
value (array):
Value for image.
ivar (array):
Inverse variance of value.
snr_min (float):
Minimum signal-to-noise for keeping a valid measurement.
Returns:
array: Boolean array for mask (i.e., True corresponds to value to be
masked out).
"""
low_snr = np.zeros(value.shape, dtype=bool)
if (ivar is not None) and (not np.all(np.isnan(ivar))):
low_snr = (ivar == 0.)
if snr_min is not None:
low_snr[np.abs(value * np.sqrt(ivar)) < snr_min] = True
return low_snr
def mask_neg_values(value):
"""Mask spaxels with negative values.
This method is primarily for using a logarithmic colorbar.
Parameters:
value (array):
Value for image.
Returns:
array: Boolean array for mask (i.e., True corresponds to value to be
masked out).
"""
mask = np.zeros(value.shape, dtype=bool)
mask[value <= 0.] = True
return mask
def _format_use_masks(use_masks, mask, dapmap, default_masks):
"""Convert input format of ``use_masks`` into list of strings.
Parameters:
use_masks (bool, list):
If ``True``, use the ``default_masks``. If ``False``, do
not use any masks. Otherwise, use a list of bitnames.
mask (array):
Mask values.
dapmap (marvin.tools.quantities.Map):
Marvin Map object.
default_masks:
Default bitmasks to use if ``use_mask == True``.
Returns:
list:
Names of bitmasks to apply.
"""
if (mask is None) or (use_masks is False):
return []
elif isinstance(use_masks, bool):
return default_masks if dapmap is not None else []
else:
return use_masks
def _get_prop(title):
"""Get property name from plot title.
Parameters:
title (str):
Plot title.
Returns:
str
"""
if 'vel' in title:
return 'vel'
elif 'sigma' in title:
return 'sigma'
else:
return 'default'
def _set_extent(cube_size, sky_coords):
"""Set extent of map.
Parameters:
cube_size (tuple):
Size of the cube in spaxels.
sky_coords (bool):
If True, use sky coordinates, otherwise use spaxel coordinates.
Returns:
array
"""
if sky_coords:
spaxel_size = 0.5 # arcsec
extent = np.array([-(cube_size[0] * spaxel_size), (cube_size[0] * spaxel_size),
-(cube_size[1] * spaxel_size), (cube_size[1] * spaxel_size)])
else:
extent = np.array([0, cube_size[0] - 1, 0, cube_size[1] - 1])
return extent
def _set_patch_style(patch_kws, extent):
"""Set default parameters for a patch.
Parameters:
patch_kws (dict):
Keyword args to pass to `matplotlib.patches.Rectangle
<https://matplotlib.org/api/_as_gen/matplotlib.patches.Rectangle.html>`_.
extent (tuple):
Extent of image (xmin, xmax, ymin, ymax).
Returns:
dict
"""
patch_kws_default = dict(xy=(extent[0] + 0.01, extent[2] + 0.01),
width=extent[1] - extent[0] - 0.02,
height=extent[3] - extent[2] - 0.02, hatch='xxxx', linewidth=0,
fill=True, facecolor='#A8A8A8', edgecolor='w', zorder=0)
for k, v in patch_kws_default.items():
if k not in patch_kws:
patch_kws[k] = v
return patch_kws
def ax_setup(sky_coords, fig=None, ax=None, facecolor='#A8A8A8'):
"""Do basic axis setup for maps.
Parameters:
sky_coords (bool):
If True, show plot in sky coordinates (i.e., arcsec), otherwise
show in spaxel coordinates.
fig (plt.figure object):
Matplotlib plt.figure object. Use if creating subplot of a
multi-panel plot. Default is None.
ax (plt.figure axis object):
Matplotlib plt.figure axis object. Use if creating subplot of a
multi-panel plot. Default is None.
facecolor (str):
Axis facecolor. Default is '#A8A8A8'.
Returns:
tuple: (plt.figure object, plt.figure axis object)
"""
xlabel = 'arcsec' if sky_coords else 'spaxel'
ylabel = 'arcsec' if sky_coords else 'spaxel'
if ax is None:
fig, ax = plt.subplots()
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if int(mpl.__version__.split('.')[0]) <= 1:
ax.set_axis_bgcolor(facecolor)
else:
ax.set_facecolor(facecolor)
ax.grid(False, which='both', axis='both')
return fig, ax
def set_title(title=None, property_name=None, channel=None):
"""Set title for map.
Parameters:
title (str):
If ``None``, try to set automatically from property (and channel)
name(s). For no title, set to ''. Default is ``None``.
property_str (str):
Map property name. Default is ``None``.
channel (str):
Map channel name. Default is ``None``.
Returns:
str
"""
if title is None:
property_name = property_name if property_name is not None else ''
channel = channel if channel is not None else ''
title = ' '.join((property_name, channel))
title = ' '.join(title.split('_')).strip()
return title
def plot(*args, **kwargs):
"""Make single panel map or one panel of multi-panel map plot.
Please see the `Plotting Tutorial
<http://sdss-marvin.readthedocs.io/en/latest/tutorials/plotting-tutorial.html>`_
for examples.
Parameters:
dapmap (marvin.tools.quantities.Map):
Marvin Map object. Default is ``None``.
value (array):
Data array. Default is ``None``.
ivar (array):
Inverse variance array. Default is ``None``.
mask (array):
Mask array. Default is ``None``.
cmap (str):
Colormap (see :ref:`marvin-utils-plot-map-default-params` for
defaults).
percentile_clip (tuple-like):
Percentile clip (see :ref:`marvin-utils-plot-map-default-params`
for defaults).
sigma_clip (float):
Sigma clip. Default is ``False``.
cbrange (tuple-like):
If ``None``, set automatically. Default is ``None``.
symmetric (bool):
Draw a colorbar that is symmetric around zero (see
:ref:`marvin-utils-plot-map-default-params` for default).
snr_min (float):
Minimum signal-to-noise for keeping a valid measurement (see
:ref:`marvin-utils-plot-map-default-params` for default).
log_cb (bool):
Draw a log normalized colorbar. Default is ``False``.
title (str):
If ``None``, set automatically from property (and channel) name(s).
For no title, set to ''. Default is ``None``.
title_mode (str):
The mode to generate a title automatically, if ``title`` is not
set. Usually ``'string'`` or ``'latex'``. Default is ``'string'``.
See :func:`~marvin.utils.datamodel.dap.base.Property.to_string`
for details.
cblabel (str):
If ``None``, set automatically from unit. For no colorbar label,
set to ''. Default is ``None``.
sky_coords (bool):
If ``True``, show plot in sky coordinates (i.e., arcsec), otherwise
show in spaxel coordinates. Default is ``False``.
use_masks (bool, str, list):
Use DAP bitmasks. If ``True``, use the recommended DAP masks.
Otherwise provide a mask name as a string or multiple mask names as
a list of strings. Default is ``True``.
plt_style (str):
Matplotlib style sheet to use. Default is 'seaborn-darkgrid'.
fig (matplotlib Figure object):
Use if creating subplot of a multi-panel plot. Default is ``None``.
ax (matplotlib Axis object):
Use if creating subplot of a multi-panel plot. Default is ``None``.
patch_kws (dict):
Keyword args to pass to `matplotlib.patches.Rectangle
<https://matplotlib.org/api/_as_gen/matplotlib.patches.Rectangle.html>`_.
Default is ``None``.
imshow_kws (dict):
Keyword args to pass to `ax.imshow
<http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.imshow.html#matplotlib.axes.Axes.imshow>`_.
Default is ``None``.
cb_kws (dict):
Keyword args to set and draw colorbar. Default is ``None``.
return_cb (bool):
Return colorbar axis. Default is ``False``.
return_cbrange (bool):
Return colorbar range without drawing plot. Default is ``False``.
Returns:
fig, ax (tuple):
`matplotlib.figure <http://matplotlib.org/api/figure_api.html>`_,
`matplotlib.axes <http://matplotlib.org/api/axes_api.html>`_
Example:
>>> import marvin.utils.plot.map as mapplot
>>> maps = Maps(plateifu='8485-1901')
>>> ha = maps['emline_gflux_ha_6564']
>>> fig, ax = mapplot.plot(dapmap=ha)
"""
valid_kwargs = ['dapmap', 'value', 'ivar', 'mask', 'cmap', 'percentile_clip', 'sigma_clip',
'cbrange', 'symmetric', 'snr_min', 'log_cb', 'title', 'title_mode', 'cblabel',
'sky_coords', 'use_masks', 'plt_style', 'fig', 'ax', 'patch_kws', 'imshow_kws',
'cb_kws', 'return_cb', 'return_cbrange']
assert len(args) == 0, 'Map.plot() does not accept arguments, only keywords.'
for kw in kwargs:
assert kw in valid_kwargs, 'keyword {0} is not valid'.format(kw)
assert ((kwargs.get('percentile_clip', None) is not None) +
(kwargs.get('sigma_clip', None) is not None) +
(kwargs.get('cbrange', None) is not None) <= 1), \
'Only set one of percentile_clip, sigma_clip, or cbrange!'
dapmap = kwargs.get('dapmap', None)
value = kwargs.get('value', None)
ivar = kwargs.get('ivar', None)
mask = kwargs.get('mask', None)
sigma_clip = kwargs.get('sigma_clip', False)
cbrange = kwargs.get('cbrange', None)
log_cb = kwargs.get('log_cb', False)
title = kwargs.get('title', None)
title_mode = kwargs.get('title_mode', 'string')
cblabel = kwargs.get('cblabel', None)
sky_coords = kwargs.get('sky_coords', False)
use_masks = kwargs.get('use_masks', True)
plt_style = kwargs.get('plt_style', 'seaborn-darkgrid')
fig = kwargs.get('fig', None)
ax = kwargs.get('ax', None)
patch_kws = kwargs.get('patch_kws', {})
imshow_kws = kwargs.get('imshow_kws', {})
cb_kws = kwargs.get('cb_kws', {})
return_cb = kwargs.get('return_cb', False)
return_cbrange = kwargs.get('return_cbrange', False)
assert (value is not None) or (dapmap is not None), \
'Map.plot() requires specifying ``value`` or ``dapmap``.'
# user-defined value, ivar, or mask overrides dapmap attributes
value = value if value is not None else getattr(dapmap, 'value', None)
ivar = ivar if ivar is not None else getattr(dapmap, 'ivar', None)
all_true = np.zeros(value.shape, dtype=bool)
mask = mask if mask is not None else getattr(dapmap, 'mask', all_true)
if title is None:
if getattr(dapmap, 'datamodel', None) is not None:
title = dapmap.datamodel.to_string(title_mode)
else:
title = ''
try:
prop = dapmap.datamodel.full()
except (AttributeError, TypeError):
prop = ''
# get plotparams from datamodel
dapver = dapmap._datamodel.parent.release if dapmap is not None else config.lookUpVersions()[1]
params = get_plot_params(dapver, prop)
cmap = kwargs.get('cmap', params['cmap'])
percentile_clip = kwargs.get('percentile_clip', params['percentile_clip'])
symmetric = kwargs.get('symmetric', params['symmetric'])
snr_min = kwargs.get('snr_min', params['snr_min'])
if sigma_clip:
percentile_clip = False
assert (not symmetric) or (not log_cb), 'Colorbar cannot be both symmetric and logarithmic.'
use_masks = _format_use_masks(use_masks, mask, dapmap, default_masks=params['bitmasks'])
# Create no coverage, bad data, low SNR, and negative value masks.
nocov_conditions = (('NOCOV' in use_masks) or (ivar is not None))
bad_data_conditions = (use_masks and (dapmap is not None) and (mask is not None))
nocov = _mask_nocov(dapmap, mask, ivar) if nocov_conditions else all_true
bad_data = dapmap.pixmask.get_mask(use_masks, mask=mask) if bad_data_conditions else all_true
low_snr = mask_low_snr(value, ivar, snr_min) if use_masks else all_true
neg_val = mask_neg_values(value) if log_cb else all_true
# Final masked array to show.
good_spax = np.ma.array(value, mask=np.logical_or.reduce((nocov, bad_data, low_snr, neg_val)))
# setup colorbar
cb_kws['cmap'] = cmap
cb_kws['percentile_clip'] = percentile_clip
cb_kws['sigma_clip'] = sigma_clip
cb_kws['cbrange'] = cbrange
cb_kws['symmetric'] = symmetric
cblabel = cblabel if cblabel is not None else getattr(dapmap, 'unit', '')
if isinstance(cblabel, units.UnitBase):
cb_kws['label'] = cblabel.to_string('latex_inline')
else:
cb_kws['label'] = cblabel
cb_kws['log_cb'] = log_cb
cb_kws = colorbar._set_cb_kws(cb_kws)
cb_kws = colorbar._set_cbrange(good_spax, cb_kws)
if return_cbrange:
return cb_kws['cbrange']
# setup unmasked spaxels
extent = _set_extent(value.shape, sky_coords)
imshow_kws.setdefault('extent', extent)
imshow_kws.setdefault('interpolation', 'nearest')
imshow_kws.setdefault('origin', 'lower')
imshow_kws['norm'] = LogNorm() if log_cb else None
# setup background
nocov_kws = copy.deepcopy(imshow_kws)
nocov_image = np.ma.array(np.ones(value.shape), mask=~nocov.astype(bool))
A8A8A8 = colorbar._one_color_cmap(color='#A8A8A8')
# setup masked spaxels
patch_kws = _set_patch_style(patch_kws, extent=imshow_kws['extent'])
# finish setup of unmasked spaxels and colorbar range
imshow_kws = colorbar._set_vmin_vmax(imshow_kws, cb_kws['cbrange'])
# set hatch color and linewidths (in matplotlib 2.0+)
try:
mpl_rc = {it: mpl.rcParams[it] for it in ['hatch.color', 'hatch.linewidth']}
mpl.rc_context({'hatch.color': 'w', 'hatch.linewidth': '0.5'})
except KeyError as ee:
mpl_rc = {}
with plt.style.context(plt_style):
fig, ax = ax_setup(sky_coords=sky_coords, fig=fig, ax=ax)
# plot hatched regions by putting one large patch as lowest layer
# hatched regions are bad data, low SNR, or negative values if the colorbar is logarithmic
ax.add_patch(mpl.patches.Rectangle(**patch_kws))
# plot regions without IFU coverage as a solid color (gray #A8A8A8)
ax.imshow(nocov_image, cmap=A8A8A8, zorder=1, **nocov_kws)
# plot unmasked spaxels
p = ax.imshow(good_spax, cmap=cb_kws['cmap'], zorder=10, **imshow_kws)
fig, cb = colorbar._draw_colorbar(fig, mappable=p, ax=ax, **cb_kws)
if title is not '':
ax.set_title(label=title)
# restore previous matplotlib rc parameters (as of matplotlib 2.0.2 this
# redraws the hatches with the original rcParam settings)
# mpl.rc_context(mpl_rc)
# turn on to preserve zorder when saving to pdf (or other vector based graphics format)
mpl.rcParams['image.composite_image'] = False
output = (fig, ax) if not return_cb else (fig, ax, cb)
return output
| [
"marvin.utils.plot.colorbar._one_color_cmap",
"marvin.utils.plot.colorbar._draw_colorbar",
"marvin.config.lookUpVersions",
"marvin.utils.general.maskbit.Maskbit",
"marvin.utils.plot.colorbar._set_vmin_vmax",
"marvin.utils.plot.colorbar._set_cbrange",
"marvin.utils.general.get_plot_params",
"marvin.uti... | [((3544, 3577), 'numpy.zeros', 'np.zeros', (['value.shape'], {'dtype': 'bool'}), '(value.shape, dtype=bool)\n', (3552, 3577), True, 'import numpy as np\n'), ((4127, 4160), 'numpy.zeros', 'np.zeros', (['value.shape'], {'dtype': 'bool'}), '(value.shape, dtype=bool)\n', (4135, 4160), True, 'import numpy as np\n'), ((14502, 14535), 'numpy.zeros', 'np.zeros', (['value.shape'], {'dtype': 'bool'}), '(value.shape, dtype=bool)\n', (14510, 14535), True, 'import numpy as np\n'), ((15046, 15075), 'marvin.utils.general.get_plot_params', 'get_plot_params', (['dapver', 'prop'], {}), '(dapver, prop)\n', (15061, 15075), False, 'from marvin.utils.general import get_plot_params\n'), ((16710, 16738), 'marvin.utils.plot.colorbar._set_cb_kws', 'colorbar._set_cb_kws', (['cb_kws'], {}), '(cb_kws)\n', (16730, 16738), True, 'import marvin.utils.plot.colorbar as colorbar\n'), ((16752, 16792), 'marvin.utils.plot.colorbar._set_cbrange', 'colorbar._set_cbrange', (['good_spax', 'cb_kws'], {}), '(good_spax, cb_kws)\n', (16773, 16792), True, 'import marvin.utils.plot.colorbar as colorbar\n'), ((17168, 17193), 'copy.deepcopy', 'copy.deepcopy', (['imshow_kws'], {}), '(imshow_kws)\n', (17181, 17193), False, 'import copy\n'), ((17285, 17326), 'marvin.utils.plot.colorbar._one_color_cmap', 'colorbar._one_color_cmap', ([], {'color': '"""#A8A8A8"""'}), "(color='#A8A8A8')\n", (17309, 17326), True, 'import marvin.utils.plot.colorbar as colorbar\n'), ((17504, 17558), 'marvin.utils.plot.colorbar._set_vmin_vmax', 'colorbar._set_vmin_vmax', (['imshow_kws', "cb_kws['cbrange']"], {}), "(imshow_kws, cb_kws['cbrange'])\n", (17527, 17558), True, 'import marvin.utils.plot.colorbar as colorbar\n'), ((2833, 2860), 'marvin.utils.general.maskbit.Maskbit', 'Maskbit', (['"""MANGA_DAPPIXMASK"""'], {}), "('MANGA_DAPPIXMASK')\n", (2840, 2860), False, 'from marvin.utils.general.maskbit import Maskbit\n'), ((5658, 5791), 'numpy.array', 'np.array', (['[-(cube_size[0] * spaxel_size), cube_size[0] * spaxel_size, -(cube_size[1] *\n spaxel_size), cube_size[1] * spaxel_size]'], {}), '([-(cube_size[0] * spaxel_size), cube_size[0] * spaxel_size, -(\n cube_size[1] * spaxel_size), cube_size[1] * spaxel_size])\n', (5666, 5791), True, 'import numpy as np\n'), ((5845, 5897), 'numpy.array', 'np.array', (['[0, cube_size[0] - 1, 0, cube_size[1] - 1]'], {}), '([0, cube_size[0] - 1, 0, cube_size[1] - 1])\n', (5853, 5897), True, 'import numpy as np\n'), ((7621, 7635), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (7633, 7635), True, 'import matplotlib.pyplot as plt\n'), ((17098, 17107), 'matplotlib.colors.LogNorm', 'LogNorm', ([], {}), '()\n', (17105, 17107), False, 'from matplotlib.colors import LogNorm\n'), ((17224, 17244), 'numpy.ones', 'np.ones', (['value.shape'], {}), '(value.shape)\n', (17231, 17244), True, 'import numpy as np\n'), ((17720, 17782), 'matplotlib.rc_context', 'mpl.rc_context', (["{'hatch.color': 'w', 'hatch.linewidth': '0.5'}"], {}), "({'hatch.color': 'w', 'hatch.linewidth': '0.5'})\n", (17734, 17782), True, 'import matplotlib as mpl\n'), ((17840, 17868), 'matplotlib.pyplot.style.context', 'plt.style.context', (['plt_style'], {}), '(plt_style)\n', (17857, 17868), True, 'import matplotlib.pyplot as plt\n'), ((18443, 18500), 'marvin.utils.plot.colorbar._draw_colorbar', 'colorbar._draw_colorbar', (['fig'], {'mappable': 'p', 'ax': 'ax'}), '(fig, mappable=p, ax=ax, **cb_kws)\n', (18466, 18500), True, 'import marvin.utils.plot.colorbar as colorbar\n'), ((15006, 15029), 'marvin.config.lookUpVersions', 'config.lookUpVersions', ([], {}), '()\n', (15027, 15029), False, 'from marvin import config\n'), ((16178, 16235), 'numpy.logical_or.reduce', 'np.logical_or.reduce', (['(nocov, bad_data, low_snr, neg_val)'], {}), '((nocov, bad_data, low_snr, neg_val))\n', (16198, 16235), True, 'import numpy as np\n'), ((18132, 18166), 'matplotlib.patches.Rectangle', 'mpl.patches.Rectangle', ([], {}), '(**patch_kws)\n', (18153, 18166), True, 'import matplotlib as mpl\n'), ((3621, 3635), 'numpy.isnan', 'np.isnan', (['ivar'], {}), '(ivar)\n', (3629, 3635), True, 'import numpy as np\n'), ((7701, 7727), 'matplotlib.__version__.split', 'mpl.__version__.split', (['"""."""'], {}), "('.')\n", (7722, 7727), True, 'import matplotlib as mpl\n'), ((3738, 3751), 'numpy.sqrt', 'np.sqrt', (['ivar'], {}), '(ivar)\n', (3745, 3751), True, 'import numpy as np\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for praimary storage - Maximum Limits
Test Plan: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Limit+Resources+to+domain+or+accounts
Issue Link: https://issues.apache.org/jira/browse/CLOUDSTACK-1466
Feature Specifications: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Limit+Resources+to+domains+and+accounts
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.lib.base import (Account,
ServiceOffering,
VirtualMachine,
Resources,
Domain,
Project,
Volume,
DiskOffering)
from marvin.lib.common import (get_domain,
get_zone,
get_template)
from marvin.lib.utils import (cleanup_resources,
validateList)
from marvin.codes import PASS, FAIL
class TestMaxPrimaryStorageLimits(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cloudstackTestClient = super(TestMaxPrimaryStorageLimits,
cls).getClsTestClient()
cls.api_client = cloudstackTestClient.getApiClient()
# Fill services from the external config file
cls.services = cloudstackTestClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cloudstackTestClient.getZoneForTests())
cls.services["mode"] = cls.zone.networktype
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.services["volume"]["zoneid"] = cls.zone.id
cls._cleanup = []
try:
cls.service_offering = ServiceOffering.create(cls.api_client, cls.services["service_offering"])
cls._cleanup.append(cls.service_offering)
except Exception as e:
cls.tearDownClass()
raise unittest.SkipTest("Exception in setUpClass: %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
try:
response = self.setupAccounts()
if response[0] == FAIL:
self.skipTest("Failure while setting up accounts: %s" % response[1])
self.services["disk_offering"]["disksize"] = 2
self.disk_offering = DiskOffering.create(self.apiclient, self.services["disk_offering"])
self.cleanup.append(self.disk_offering)
except Exception as e:
self.tearDown()
self.skipTest("Failure in setup: %s" % e)
return
def tearDown(self):
try:
# Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setupAccounts(self):
try:
self.child_domain = Domain.create(self.apiclient,services=self.services["domain"],
parentdomainid=self.domain.id)
self.child_do_admin = Account.create(self.apiclient, self.services["account"], admin=True,
domainid=self.child_domain.id)
# Create project as a domain admin
self.project = Project.create(self.apiclient, self.services["project"],
account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid)
# Cleanup created project at end of test
self.cleanup.append(self.project)
# Cleanup accounts created
self.cleanup.append(self.child_do_admin)
self.cleanup.append(self.child_domain)
except Exception as e:
return [FAIL, e]
return [PASS, None]
def updatePrimaryStorageLimits(self, accountLimit=None, domainLimit=None,
projectLimit=None):
try:
# Update resource limits for account
if accountLimit:
Resources.updateLimit(self.apiclient, resourcetype=10,
max=accountLimit, account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid)
if projectLimit:
Resources.updateLimit(self.apiclient, resourcetype=10,
max=projectLimit, projectid=self.project.id)
if domainLimit:
Resources.updateLimit(self.apiclient, resourcetype=10,
max=domainLimit, domainid=self.child_domain.id)
except Exception as e:
return [FAIL, e]
return [PASS, None]
@attr(tags=["advanced","selfservice"])
def test_01_deploy_vm_domain_limit_reached(self):
"""Test Try to deploy VM with admin account where account has not used
the resources but @ domain they are not available
# Validate the following
# 1. Try to deploy VM with admin account where account has not used the
# resources but @ domain they are not available
# 2. Deploy VM should error out saying ResourceAllocationException
# with "resource limit exceeds"""
self.virtualMachine = VirtualMachine.create(self.api_client, self.services["virtual_machine"],
accountid=self.child_do_admin.name, domainid=self.child_do_admin.domainid,
serviceofferingid=self.service_offering.id)
accounts = Account.list(self.apiclient, id=self.child_do_admin.id)
self.assertEqual(validateList(accounts)[0], PASS,
"accounts list validation failed")
self.initialResourceCount = int(accounts[0].primarystoragetotal)
domainLimit = self.initialResourceCount + 3
self.debug("Setting up account and domain hierarchy")
response = self.updatePrimaryStorageLimits(domainLimit=domainLimit)
self.assertEqual(response[0], PASS, response[1])
self.services["volume"]["size"] = self.services["disk_offering"]["disksize"] = 2
try:
disk_offering = DiskOffering.create(self.apiclient,
services=self.services["disk_offering"])
self.cleanup.append(disk_offering)
Volume.create(self.apiclient,
self.services["volume"],
zoneid=self.zone.id,
account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid,
diskofferingid=disk_offering.id)
except Exception as e:
self.fail("Exception occurred: %s" % e)
with self.assertRaises(Exception):
Volume.create(self.apiclient,
self.services["volume"],
zoneid=self.zone.id,
account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid,
diskofferingid=disk_offering.id)
return
@attr(tags=["advanced","selfservice"])
def test_02_deploy_vm_account_limit_reached(self):
"""Test Try to deploy VM with admin account where account has used
the resources but @ domain they are available"""
self.virtualMachine = VirtualMachine.create(self.api_client, self.services["virtual_machine"],
accountid=self.child_do_admin.name, domainid=self.child_do_admin.domainid,
serviceofferingid=self.service_offering.id)
accounts = Account.list(self.apiclient, id=self.child_do_admin.id)
self.assertEqual(validateList(accounts)[0], PASS,
"accounts list validation failed")
self.initialResourceCount = int(accounts[0].primarystoragetotal)
accountLimit = self.initialResourceCount + 3
self.debug("Setting up account and domain hierarchy")
response = self.updatePrimaryStorageLimits(accountLimit=accountLimit)
self.assertEqual(response[0], PASS, response[1])
self.services["volume"]["size"] = self.services["disk_offering"]["disksize"] = 2
try:
disk_offering = DiskOffering.create(self.apiclient,
services=self.services["disk_offering"])
self.cleanup.append(disk_offering)
Volume.create(self.apiclient,
self.services["volume"],
zoneid=self.zone.id,
account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid,
diskofferingid=disk_offering.id)
except Exception as e:
self.fail("failed to create volume: %s" % e)
with self.assertRaises(Exception):
Volume.create(self.apiclient,
self.services["volume"],
zoneid=self.zone.id,
account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid,
diskofferingid=disk_offering.id)
return
@attr(tags=["advanced","selfservice"])
def test_03_deploy_vm_project_limit_reached(self):
"""Test TTry to deploy VM with admin account where account has not used
the resources but @ project they are not available
# Validate the following
# 1. Try to deploy VM with admin account where account has not used the
# resources but @ project they are not available
# 2. Deploy VM should error out saying ResourceAllocationException
# with "resource limit exceeds"""
self.virtualMachine = VirtualMachine.create(self.api_client, self.services["virtual_machine"],
projectid=self.project.id,
serviceofferingid=self.service_offering.id)
try:
projects = Project.list(self.apiclient, id=self.project.id, listall=True)
except Exception as e:
self.fail("failed to get projects list: %s" % e)
self.assertEqual(validateList(projects)[0], PASS,
"projects list validation failed")
self.initialResourceCount = int(projects[0].primarystoragetotal)
projectLimit = self.initialResourceCount + 3
self.debug("Setting up account and domain hierarchy")
response = self.updatePrimaryStorageLimits(projectLimit=projectLimit)
self.assertEqual(response[0], PASS, response[1])
self.services["volume"]["size"] = self.services["disk_offering"]["disksize"] = 2
try:
disk_offering = DiskOffering.create(self.apiclient,
services=self.services["disk_offering"])
self.cleanup.append(disk_offering)
Volume.create(self.apiclient,
self.services["volume"],
zoneid=self.zone.id,
projectid=self.project.id,
diskofferingid=disk_offering.id)
except Exception as e:
self.fail("Exception occurred: %s" % e)
with self.assertRaises(Exception):
Volume.create(self.apiclient,
self.services["volume"],
zoneid=self.zone.id,
projectid=self.project.id,
diskofferingid=disk_offering.id)
return
| [
"marvin.lib.common.get_domain",
"marvin.lib.base.Project.list",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.utils.validateList",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.Volume.create",
"marvin.lib.base.Account.list",
"marvin.lib.base.Project.create",
"marvin.lib.base.Virtual... | [((6420, 6458), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'selfservice']"}), "(tags=['advanced', 'selfservice'])\n", (6424, 6458), False, 'from nose.plugins.attrib import attr\n'), ((8907, 8945), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'selfservice']"}), "(tags=['advanced', 'selfservice'])\n", (8911, 8945), False, 'from nose.plugins.attrib import attr\n'), ((11104, 11142), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'selfservice']"}), "(tags=['advanced', 'selfservice'])\n", (11108, 11142), False, 'from nose.plugins.attrib import attr\n'), ((2324, 2350), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2334, 2350), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((2511, 2576), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (2523, 2576), False, 'from marvin.lib.common import get_domain, get_zone, get_template\n'), ((6978, 7178), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'accountid': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n accountid=self.child_do_admin.name, domainid=self.child_do_admin.\n domainid, serviceofferingid=self.service_offering.id)\n", (6999, 7178), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((7246, 7301), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'id': 'self.child_do_admin.id'}), '(self.apiclient, id=self.child_do_admin.id)\n', (7258, 7301), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((9167, 9367), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'accountid': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n accountid=self.child_do_admin.name, domainid=self.child_do_admin.\n domainid, serviceofferingid=self.service_offering.id)\n", (9188, 9367), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((9435, 9490), 'marvin.lib.base.Account.list', 'Account.list', (['self.apiclient'], {'id': 'self.child_do_admin.id'}), '(self.apiclient, id=self.child_do_admin.id)\n', (9447, 9490), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((11662, 11809), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['self.api_client', "self.services['virtual_machine']"], {'projectid': 'self.project.id', 'serviceofferingid': 'self.service_offering.id'}), "(self.api_client, self.services['virtual_machine'],\n projectid=self.project.id, serviceofferingid=self.service_offering.id)\n", (11683, 11809), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((2955, 3027), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (2977, 3027), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((3339, 3386), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (3356, 3386), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((3939, 4006), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['self.apiclient', "self.services['disk_offering']"], {}), "(self.apiclient, self.services['disk_offering'])\n", (3958, 4006), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((4315, 4362), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (4332, 4362), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((4559, 4657), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.apiclient'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.apiclient, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (4572, 4657), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((4730, 4833), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.child_domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.child_domain.id)\n", (4744, 4833), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((4950, 5084), 'marvin.lib.base.Project.create', 'Project.create', (['self.apiclient', "self.services['project']"], {'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid'}), "(self.apiclient, self.services['project'], account=self.\n child_do_admin.name, domainid=self.child_do_admin.domainid)\n", (4964, 5084), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((7861, 7937), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['self.apiclient'], {'services': "self.services['disk_offering']"}), "(self.apiclient, services=self.services['disk_offering'])\n", (7880, 7937), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((8033, 8222), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid', 'diskofferingid': 'disk_offering.id'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n account=self.child_do_admin.name, domainid=self.child_do_admin.domainid,\n diskofferingid=disk_offering.id)\n", (8046, 8222), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((8529, 8718), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid', 'diskofferingid': 'disk_offering.id'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n account=self.child_do_admin.name, domainid=self.child_do_admin.domainid,\n diskofferingid=disk_offering.id)\n", (8542, 8718), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((10053, 10129), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['self.apiclient'], {'services': "self.services['disk_offering']"}), "(self.apiclient, services=self.services['disk_offering'])\n", (10072, 10129), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((10225, 10414), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid', 'diskofferingid': 'disk_offering.id'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n account=self.child_do_admin.name, domainid=self.child_do_admin.domainid,\n diskofferingid=disk_offering.id)\n", (10238, 10414), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((10726, 10915), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid', 'diskofferingid': 'disk_offering.id'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n account=self.child_do_admin.name, domainid=self.child_do_admin.domainid,\n diskofferingid=disk_offering.id)\n", (10739, 10915), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((11899, 11961), 'marvin.lib.base.Project.list', 'Project.list', (['self.apiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.apiclient, id=self.project.id, listall=True)\n', (11911, 11961), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((12617, 12693), 'marvin.lib.base.DiskOffering.create', 'DiskOffering.create', (['self.apiclient'], {'services': "self.services['disk_offering']"}), "(self.apiclient, services=self.services['disk_offering'])\n", (12636, 12693), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((12789, 12928), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'projectid': 'self.project.id', 'diskofferingid': 'disk_offering.id'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n projectid=self.project.id, diskofferingid=disk_offering.id)\n", (12802, 12928), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((13204, 13343), 'marvin.lib.base.Volume.create', 'Volume.create', (['self.apiclient', "self.services['volume']"], {'zoneid': 'self.zone.id', 'projectid': 'self.project.id', 'diskofferingid': 'disk_offering.id'}), "(self.apiclient, self.services['volume'], zoneid=self.zone.id,\n projectid=self.project.id, diskofferingid=disk_offering.id)\n", (13217, 13343), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((3163, 3215), 'unittest.SkipTest', 'unittest.SkipTest', (["('Exception in setUpClass: %s' % e)"], {}), "('Exception in setUpClass: %s' % e)\n", (3180, 3215), False, 'import unittest\n'), ((5730, 5879), 'marvin.lib.base.Resources.updateLimit', 'Resources.updateLimit', (['self.apiclient'], {'resourcetype': '(10)', 'max': 'accountLimit', 'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid'}), '(self.apiclient, resourcetype=10, max=accountLimit,\n account=self.child_do_admin.name, domainid=self.child_do_admin.domainid)\n', (5751, 5879), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((5986, 6089), 'marvin.lib.base.Resources.updateLimit', 'Resources.updateLimit', (['self.apiclient'], {'resourcetype': '(10)', 'max': 'projectLimit', 'projectid': 'self.project.id'}), '(self.apiclient, resourcetype=10, max=projectLimit,\n projectid=self.project.id)\n', (6007, 6089), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((6177, 6283), 'marvin.lib.base.Resources.updateLimit', 'Resources.updateLimit', (['self.apiclient'], {'resourcetype': '(10)', 'max': 'domainLimit', 'domainid': 'self.child_domain.id'}), '(self.apiclient, resourcetype=10, max=domainLimit,\n domainid=self.child_domain.id)\n', (6198, 6283), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, Resources, Domain, Project, Volume, DiskOffering\n'), ((7327, 7349), 'marvin.lib.utils.validateList', 'validateList', (['accounts'], {}), '(accounts)\n', (7339, 7349), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((9516, 9538), 'marvin.lib.utils.validateList', 'validateList', (['accounts'], {}), '(accounts)\n', (9528, 9538), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((12080, 12102), 'marvin.lib.utils.validateList', 'validateList', (['projects'], {}), '(projects)\n', (12092, 12102), False, 'from marvin.lib.utils import cleanup_resources, validateList\n')] |
#!/usr/bin/env python
# encoding: utf-8
'''
Created by <NAME> on 2016-05-02 16:16:27
Licensed under a 3-clause BSD license.
Revision History:
Initial Version: 2016-05-02 16:16:27 by <NAME>
Last Modified On: 2016-05-02 16:16:27 by Brian
'''
from __future__ import print_function
from __future__ import division
from flask import session as current_session, render_template, request, g, jsonify
from marvin import config
from marvin.utils.db import get_traceback
from collections import defaultdict
import re
import traceback
def configFeatures(app, mode):
''' Configure Flask Feature Flags '''
app.config['FEATURE_FLAGS']['collab'] = False if mode == 'dr13' else True
app.config['FEATURE_FLAGS']['new'] = False if mode == 'dr13' else True
app.config['FEATURE_FLAGS']['dev'] = True if config.db == 'local' else False
def updateGlobalSession():
''' updates the Marvin config with the global Flask session '''
# check if mpl versions in session
if 'versions' not in current_session:
setGlobalSession()
elif 'drpver' not in current_session or \
'dapver' not in current_session:
drpver, dapver = config.lookUpVersions(release=config.release)
current_session['drpver'] = drpver
current_session['dapver'] = dapver
elif 'release' not in current_session:
current_session['release'] = config.release
def setGlobalSession():
''' Sets the global session for Flask '''
mpls = list(config._mpldict.keys())
versions = [{'name': mpl, 'subtext': str(config.lookUpVersions(release=mpl))} for mpl in mpls]
current_session['versions'] = versions
if 'release' not in current_session:
current_session['release'] = config.release
drpver, dapver = config.lookUpVersions(release=config.release)
current_session['drpver'] = drpver
current_session['dapver'] = dapver
def parseSession():
''' parse the current session for MPL versions '''
drpver = current_session['drpver']
dapver = current_session['dapver']
release = current_session['release']
return drpver, dapver, release
# def make_error_json(error, name, code):
# ''' creates the error json dictionary for API errors '''
# shortname = name.lower().replace(' ', '_')
# messages = {'error': shortname,
# 'message': error.description if hasattr(error, 'description') else None,
# 'status_code': code,
# 'traceback': get_traceback(asstring=True)}
# return jsonify({'api_error': messages}), code
# def make_error_page(app, name, code, sentry=None, data=None):
# ''' creates the error page dictionary for web errors '''
# shortname = name.lower().replace(' ', '_')
# error = {}
# error['title'] = 'Marvin | {0}'.format(name)
# error['page'] = request.url
# error['event_id'] = g.get('sentry_event_id', None)
# error['data'] = data
# if sentry:
# error['public_dsn'] = sentry.client.get_public_dsn('https')
# app.logger.error('{0} Exception {1}'.format(name, error))
# return render_template('errors/{0}.html'.format(shortname), **error), code
def send_request():
''' sends the request info to the history db '''
if request.blueprint is not None:
print(request.cookies)
print(request.headers)
print(request.blueprint)
print(request.endpoint)
print(request.url)
print(request.remote_addr)
print(request.environ)
print(request.environ['REMOTE_ADDR'])
# def setGlobalSession_old():
# ''' Set default global session variables '''
# if 'currentver' not in current_session:
# setGlobalVersion()
# if 'searchmode' not in current_session:
# current_session['searchmode'] = 'plateid'
# if 'marvinmode' not in current_session:
# current_session['marvinmode'] = 'mangawork'
# configFeatures(current_app, current_session['marvinmode'])
# # current_session['searchoptions'] = getDblist(current_session['searchmode'])
# # get code versions
# #if 'codeversions' not in current_session:
# # buildCodeVersions()
# # user authentication
# if 'http_authorization' not in current_session:
# try:
# current_session['http_authorization'] = request.environ['HTTP_AUTHORIZATION']
# except:
# pass
# def getDRPVersion():
# ''' Get DRP version to use during MaNGA SAS '''
# # DRP versions
# vers = marvindb.session.query(marvindb.datadb.PipelineVersion).\
# filter(marvindb.datadb.PipelineVersion.version.like('%v%')).\
# order_by(marvindb.datadb.PipelineVersion.version.desc()).all()
# versions = [v.version for v in vers]
# return versions
# def getDAPVersion():
# ''' Get DAP version to use during MaNGA SAS '''
# # DAP versions
# vers = marvindb.session.query(marvindb.datadb.PipelineVersion).\
# join(marvindb.datadb.PipelineInfo, marvindb.datadb.PipelineName).\
# filter(marvindb.datadb.PipelineName.label == 'DAP',
# ~marvindb.datadb.PipelineVersion.version.like('%trunk%')).\
# order_by(marvindb.datadb.PipelineVersion.version.desc()).all()
# versions = [v.version for v in vers]
# return versions+['NA']
# def setGlobalVersion():
# ''' set the global version '''
# # set MPL version
# try:
# mplver = current_session['currentmpl']
# except:
# mplver = None
# if not mplver:
# current_session['currentmpl'] = 'MPL-4'
# # set version mode
# try:
# vermode = current_session['vermode']
# except:
# vermode = None
# if not vermode:
# current_session['vermode'] = 'MPL'
# # initialize
# if 'MPL' in current_session['vermode']:
# setMPLVersion(current_session['currentmpl'])
# # set global DRP version
# try:
# versions = current_session['versions']
# except:
# versions = getDRPVersion()
# current_session['versions'] = versions
# try:
# drpver = current_session['currentver']
# except:
# drpver = None
# if not drpver:
# realvers = [ver for ver in versions if os.path.isdir(os.path.join(os.getenv('MANGA_SPECTRO_REDUX'), ver))]
# current_session['currentver'] = realvers[0]
# # set global DAP version
# try:
# dapversions = current_session['dapversions']
# except:
# dapversions = getDAPVersion()
# current_session['dapversions'] = dapversions
# try:
# ver = current_session['currentdapver']
# except:
# ver = None
# if not ver:
# realvers = [ver for ver in versions if os.path.isdir(os.path.join(os.getenv('MANGA_SPECTRO_ANALYSIS'),
# current_session['currentver'], ver))]
# current_session['currentdapver'] = realvers[0] if realvers else 'NA'
def buildImageDict(imagelist, test=None, num=16):
''' Builds a list of dictionaries from a sdss_access return list of images '''
# get thumbnails and plateifus
if imagelist:
thumbs = [imagelist.pop(imagelist.index(t)) if 'thumb' in t else t for t in imagelist]
plateifu = ['-'.join(re.findall('\d{3,5}', im)) for im in imagelist]
# build list of dictionaries
images = []
if imagelist:
for i, image in enumerate(imagelist):
imdict = defaultdict(str)
imdict['name'] = plateifu[i]
imdict['image'] = image
imdict['thumb'] = thumbs[i] if thumbs else None
images.append(imdict)
elif test and not imagelist:
for i in xrange(num):
imdict = defaultdict(str)
imdict['name'] = '4444-0000'
imdict['image'] = 'http://placehold.it/470x480&text={0}'.format(i)
imdict['thumb'] = 'http://placehold.it/150x150&text={0}'.format(i)
images.append(imdict)
return images
| [
"marvin.config._mpldict.keys",
"marvin.config.lookUpVersions"
] | [((1480, 1502), 'marvin.config._mpldict.keys', 'config._mpldict.keys', ([], {}), '()\n', (1500, 1502), False, 'from marvin import config\n'), ((1765, 1810), 'marvin.config.lookUpVersions', 'config.lookUpVersions', ([], {'release': 'config.release'}), '(release=config.release)\n', (1786, 1810), False, 'from marvin import config\n'), ((1164, 1209), 'marvin.config.lookUpVersions', 'config.lookUpVersions', ([], {'release': 'config.release'}), '(release=config.release)\n', (1185, 1209), False, 'from marvin import config\n'), ((7408, 7424), 'collections.defaultdict', 'defaultdict', (['str'], {}), '(str)\n', (7419, 7424), False, 'from collections import defaultdict\n'), ((1549, 1583), 'marvin.config.lookUpVersions', 'config.lookUpVersions', ([], {'release': 'mpl'}), '(release=mpl)\n', (1570, 1583), False, 'from marvin import config\n'), ((7225, 7251), 're.findall', 're.findall', (['"""\\\\d{3,5}"""', 'im'], {}), "('\\\\d{3,5}', im)\n", (7235, 7251), False, 'import re\n'), ((7680, 7696), 'collections.defaultdict', 'defaultdict', (['str'], {}), '(str)\n', (7691, 7696), False, 'from collections import defaultdict\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Network migration test
"""
# Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.lib.base import (
Account,
ServiceOffering,
VirtualMachine,
NetworkOffering,
Network,
VpcOffering,
VPC
)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
list_virtual_machines)
from marvin.lib.utils import (get_hypervisor_type,
cleanup_resources)
# Import System Modules
from nose.plugins.attrib import attr
from marvin.lib.decoratorGenerators import skipTestIf
class Services:
"""Test network services
"""
def __init__(self):
self.services = {
"vpc": {
"name": "TestVPC",
"displaytext": "TestVPC",
"cidr": '10.0.0.1/24'
},
"network": {
"name": "Test Network",
"displaytext": "Test Network",
"netmask": '255.255.255.0'
},
"virtual_machine": {
"displayname": "Test VM",
"username": "root",
"password": "password",
"ssh_port": 22,
"privateport": 22,
"publicport": 22,
"protocol": 'TCP',
},
}
class TestNetworkMigration(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestNetworkMigration, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.test_data = cls.testClient.getParsedTestDataConfig()
cls.services = Services().services
cls.hypervisorNotSupported = False
hypervisor = get_hypervisor_type(cls.api_client)
if hypervisor.lower() not in ["vmware", "kvm"]:
cls.hypervisorNotSupported = True
cls._cleanup = []
if not cls.hypervisorNotSupported:
# Get Domain, Zone, Template
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(
cls.api_client,
cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.test_data["ostype"]
)
cls.services["virtual_machine"]["template"] = cls.template.id
if cls.zone.localstorageenabled:
cls.storagetype = 'local'
cls.test_data["service_offerings"][
"tiny"]["storagetype"] = 'local'
else:
cls.storagetype = 'shared'
cls.test_data["service_offerings"][
"tiny"]["storagetype"] = 'shared'
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.test_data["service_offerings"]["tiny"]
)
# Create Network offering without userdata
cls.network_offering_nouserdata = NetworkOffering.create(
cls.api_client,
cls.test_data["network_offering"]
)
# Enable Network offering
cls.network_offering_nouserdata.update(cls.api_client,
state='Enabled')
# Create Network Offering with all the serices
cls.network_offering_all = NetworkOffering.create(
cls.api_client,
cls.test_data["isolated_network_offering"]
)
# Enable Network offering
cls.network_offering_all.update(cls.api_client, state='Enabled')
cls.native_vpc_network_offering = NetworkOffering.create(
cls.api_client,
cls.test_data["nw_offering_isolated_vpc"],
conservemode=False)
cls.native_vpc_network_offering.update(cls.api_client,
state='Enabled')
cls._cleanup = [
cls.service_offering,
cls.network_offering_nouserdata,
cls.network_offering_all,
cls.native_vpc_network_offering
]
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.hypervisor = self.testClient.getHypervisorInfo()
self.dbclient = self.testClient.getDbConnection()
if not self.hypervisorNotSupported:
self.account = Account.create(
self.apiclient,
self.test_data["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = []
return
def tearDown(self):
try:
if not self.hypervisorNotSupported:
self.account.delete(self.apiclient)
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
# Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def migrate_network(self, nw_off, network, resume=False):
return network.migrate(self.api_client, nw_off.id, resume)
def migrate_vpc(self, vpc, vpc_offering,
network_offering_map, resume=False):
return vpc.migrate(self.api_client,
vpc_offering.id,
network_offering_map, resume)
@skipTestIf("hypervisorNotSupported")
@attr(tags=["advanced", "smoke", "nativeisoonly"],
required_hardware="false")
def test_01_native_to_native_network_migration(self):
"""
Verify Migration for an isolated network nativeOnly
1. create native non-persistent isolated network
2. migrate to other non-persistent isolated network
3. migrate back to first native non-persistent network
4. deploy VM in non-persistent isolated network
5. migrate to native persistent isolated network
6. migrate back to native non-persistent network
"""
isolated_network = Network.create(
self.apiclient,
self.test_data["isolated_network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering_all.id,
zoneid=self.zone.id
)
self.migrate_network(
self.network_offering_nouserdata,
isolated_network, resume=False)
self.migrate_network(
self.network_offering_all,
isolated_network, resume=False)
deployVmResponse = VirtualMachine.create(
self.apiclient,
services=self.test_data["virtual_machine_userdata"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(isolated_network.id)],
templateid=self.template.id,
zoneid=self.zone.id
)
vms = list_virtual_machines(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
id=deployVmResponse.id
)
self.assert_(len(vms) > 0, "There are no Vms deployed in the account"
" %s" % self.account.name)
vm = vms[0]
self.assert_(vm.id == str(deployVmResponse.id),
"Vm deployed is different from the test")
self.assert_(vm.state == "Running", "VM is not in Running state")
self.migrate_network(
self.network_offering_nouserdata,
isolated_network, resume=False)
self.migrate_network(
self.network_offering_all,
isolated_network, resume=False)
@skipTestIf("hypervisorNotSupported")
@attr(tags=["advanced", "smoke", "nativevpconly"],
required_hardware="false")
def test_02_native_to_native_vpc_migration(self):
"""
Verify Migration for a vpc network nativeOnly
1. create native vpc with 2 tier networks
2. migrate to native vpc, check VR state
3. deploy VM in vpc tier network
4. acquire ip and enable staticnat
5. migrate to native vpc network
"""
self.debug("Creating Native VSP VPC offering with Static NAT service "
"provider as VPCVR...")
native_vpc_off = VpcOffering.create(
self.apiclient,
self.test_data["vpc_offering_reduced"])
self.debug("Enabling the VPC offering created")
native_vpc_off.update(self.apiclient, state='Enabled')
self.debug("Creating a VPC with Static NAT service provider as "
"VpcVirtualRouter")
self.services["vpc"]["cidr"] = '10.1.1.1/16'
vpc = VPC.create(
self.apiclient,
self.services["vpc"],
vpcofferingid=native_vpc_off.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.debug("Creating native VPC Network Tier offering "
"with Static NAT service provider as VPCVR")
native_tiernet_off = \
NetworkOffering.create(self.apiclient,
self.test_data
["nw_offering_reduced_vpc"],
conservemode=False)
native_tiernet_off.update(self.apiclient, state='Enabled')
self.debug("Creating a VPC tier network with Static NAT service")
vpc_tier = Network.create(self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=native_tiernet_off.id,
zoneid=self.zone.id,
gateway='10.1.1.1',
vpcid=vpc.id if vpc else self.vpc.id
)
self.debug("Created network with ID: %s" % vpc_tier.id)
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.native_vpc_network_offering.id}]
self.migrate_vpc(vpc, native_vpc_off,
network_offering_map, resume=False)
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": native_tiernet_off.id}]
self.migrate_vpc(vpc, native_vpc_off,
network_offering_map, resume=False)
self.debug('Creating VM in network=%s' % native_tiernet_off.name)
vm = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(vpc_tier.id)],
templateid=self.template.id,
zoneid=self.zone.id
)
self.debug('Created VM=%s in network=%s' %
(vm.id, native_tiernet_off.name))
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": self.native_vpc_network_offering.id}]
self.migrate_vpc(vpc, native_vpc_off,
network_offering_map, resume=False)
network_offering_map = \
[{"networkid": vpc_tier.id,
"networkofferingid": native_tiernet_off.id}]
self.migrate_vpc(vpc, native_vpc_off,
network_offering_map, resume=False)
| [
"marvin.lib.common.get_domain",
"marvin.lib.base.VpcOffering.create",
"marvin.lib.decoratorGenerators.skipTestIf",
"marvin.lib.base.NetworkOffering.create",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.VPC.create",
"marvin.lib.base.Network.create",
... | [((6581, 6617), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (6591, 6617), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((6623, 6699), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke', 'nativeisoonly']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'smoke', 'nativeisoonly'], required_hardware='false')\n", (6627, 6699), False, 'from nose.plugins.attrib import attr\n'), ((9054, 9090), 'marvin.lib.decoratorGenerators.skipTestIf', 'skipTestIf', (['"""hypervisorNotSupported"""'], {}), "('hypervisorNotSupported')\n", (9064, 9090), False, 'from marvin.lib.decoratorGenerators import skipTestIf\n'), ((9096, 9172), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke', 'nativevpconly']", 'required_hardware': '"""false"""'}), "(tags=['advanced', 'smoke', 'nativevpconly'], required_hardware='false')\n", (9100, 9172), False, 'from nose.plugins.attrib import attr\n'), ((2588, 2623), 'marvin.lib.utils.get_hypervisor_type', 'get_hypervisor_type', (['cls.api_client'], {}), '(cls.api_client)\n', (2607, 2623), False, 'from marvin.lib.utils import get_hypervisor_type, cleanup_resources\n'), ((7230, 7434), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.test_data['isolated_network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering_all.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.test_data['isolated_network'],\n accountid=self.account.name, domainid=self.account.domainid,\n networkofferingid=self.network_offering_all.id, zoneid=self.zone.id)\n", (7244, 7434), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((8249, 8374), 'marvin.lib.common.list_virtual_machines', 'list_virtual_machines', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'id': 'deployVmResponse.id'}), '(self.apiclient, account=self.account.name, domainid=\n self.account.domainid, id=deployVmResponse.id)\n', (8270, 8374), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_virtual_machines\n'), ((9687, 9761), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.test_data['vpc_offering_reduced']"], {}), "(self.apiclient, self.test_data['vpc_offering_reduced'])\n", (9705, 9761), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((10095, 10265), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'native_vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=\n native_vpc_off.id, zoneid=self.zone.id, account=self.account.name,\n domainid=self.account.domainid)\n", (10105, 10265), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((10534, 10640), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', "self.test_data['nw_offering_reduced_vpc']"], {'conservemode': '(False)'}), "(self.apiclient, self.test_data[\n 'nw_offering_reduced_vpc'], conservemode=False)\n", (10556, 10640), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((10903, 11155), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'native_tiernet_off.id', 'zoneid': 'self.zone.id', 'gateway': '"""10.1.1.1"""', 'vpcid': '(vpc.id if vpc else self.vpc.id)'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=\n native_tiernet_off.id, zoneid=self.zone.id, gateway='10.1.1.1', vpcid=\n vpc.id if vpc else self.vpc.id)\n", (10917, 11155), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((2862, 2888), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2872, 2888), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_virtual_machines\n'), ((3039, 3105), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.test_data['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.test_data['ostype'])\n", (3051, 3105), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_virtual_machines\n'), ((3649, 3736), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.test_data['service_offerings']['tiny']"], {}), "(cls.api_client, cls.test_data['service_offerings'][\n 'tiny'])\n", (3671, 3736), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((3888, 3961), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.test_data['network_offering']"], {}), "(cls.api_client, cls.test_data['network_offering'])\n", (3910, 3961), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((4288, 4375), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.test_data['isolated_network_offering']"], {}), "(cls.api_client, cls.test_data[\n 'isolated_network_offering'])\n", (4310, 4375), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((4587, 4693), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.test_data['nw_offering_isolated_vpc']"], {'conservemode': '(False)'}), "(cls.api_client, cls.test_data[\n 'nw_offering_isolated_vpc'], conservemode=False)\n", (4609, 4693), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((5387, 5485), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.test_data['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.test_data['account'], admin=True,\n domainid=self.domain.id)\n", (5401, 5485), False, 'from marvin.lib.base import Account, ServiceOffering, VirtualMachine, NetworkOffering, Network, VpcOffering, VPC\n'), ((5767, 5814), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (5784, 5814), False, 'from marvin.lib.utils import get_hypervisor_type, cleanup_resources\n'), ((6043, 6090), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (6060, 6090), False, 'from marvin.lib.utils import get_hypervisor_type, cleanup_resources\n')] |
#!/usr/bin/env python
# encoding: utf-8
#
# modelcube.py
#
# Licensed under a 3-clause BSD license.
#
# Revision history:
# 25 Sep 2016 <NAME>
# Initial version
from __future__ import division, print_function
import json
import os
from flask import Response, jsonify
from flask_classful import route
from marvin import config
from marvin.api.base import BaseView
from marvin.api.base import arg_validate as av
from marvin.core.exceptions import MarvinError
from marvin.tools.modelcube import ModelCube
from marvin.utils.general import mangaid2plateifu, parseIdentifier
try:
from sdss_access.path import Path
except ImportError:
Path = None
def _get_model_cube(name, use_file=False, release=None, **kwargs):
"""Retrieves a Marvin ModelCube object."""
model_cube = None
results = {}
drpver, dapver = config.lookUpVersions(release)
# parse name into either mangaid or plateifu
try:
idtype = parseIdentifier(name)
except Exception as err:
results['error'] = 'Failed to parse input name {0}: {1}'.format(name, str(err))
return model_cube, results
filename = None
plateifu = None
mangaid = None
bintype = kwargs.pop('bintype')
template = kwargs.pop('template')
try:
if use_file:
if idtype == 'mangaid':
plate, ifu = mangaid2plateifu(name, drpver=drpver)
elif idtype == 'plateifu':
plate, ifu = name.split('-')
if Path is not None:
daptype = '{0}-{1}'.format(bintype, template)
filename = Path().full('mangadap5', ifu=ifu,
drpver=drpver,
dapver=dapver,
plate=plate, mode='LOGCUBE',
daptype=daptype)
assert os.path.exists(filename), 'file not found.'
else:
raise MarvinError('cannot create path for MaNGA cube.')
else:
if idtype == 'plateifu':
plateifu = name
elif idtype == 'mangaid':
mangaid = name
else:
raise MarvinError('invalid plateifu or mangaid: {0}'.format(idtype))
model_cube = ModelCube(filename=filename, mangaid=mangaid, plateifu=plateifu,
release=release, template=template, bintype=bintype, **kwargs)
results['status'] = 1
except Exception as err:
results['error'] = 'Failed to retrieve ModelCube {0}: {1}'.format(name, str(err))
return model_cube, results
class ModelCubeView(BaseView):
"""Class describing API calls related to ModelCubes."""
route_base = '/modelcubes/'
@route('/<name>/', defaults={'bintype': None, 'template': None},
methods=['GET', 'POST'], endpoint='getModelCube')
@route('/<name>/<bintype>/', defaults={'template': None},
methods=['GET', 'POST'], endpoint='getModelCube')
@route('/<name>/<bintype>/<template>/', methods=['GET', 'POST'], endpoint='getModelCube')
@av.check_args()
def get(self, args, name, bintype, template):
"""Retrieves a ModelCube.
.. :quickref: ModelCube; Get a modelcube given a name, bintype, and template
:param name: The name of the modelcube as plate-ifu or mangaid
:param bintype: The bintype associated with this modelcube.
If not defined, the default is used
:param template: The template associated with this modelcube.
If not defined, the default is used
:form release: the release of MaNGA data
:resjson int status: status of response. 1 if good, -1 if bad.
:resjson string error: error message, null if None
:resjson json inconfig: json of incoming configuration
:resjson json utahconfig: json of outcoming configuration
:resjson string traceback: traceback of an error, null if None
:resjson json data: dictionary of returned data
:json string header: the modelcube header as a string
:json list shape: the modelcube shape [x, y]
:json list wavelength: the modelcube wavelength array
:json list redcorr: the modelcube redcorr array
:json string wcs_header: the modelcube wcs_header as a string
:json string bintype: the bintype of the modelcube
:json string template: the template library of the modelcube
:resheader Content-Type: application/json
:statuscode 200: no error
:statuscode 422: invalid input parameters
**Example request**:
.. sourcecode:: http
GET /marvin/api/modelcubes/8485-1901/SPX/GAU-MILESHC/ HTTP/1.1
Host: api.sdss.org
Accept: application/json, */*
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"status": 1,
"error": null,
"inconfig": {"release": "MPL-5"},
"utahconfig": {"release": "MPL-5", "mode": "local"},
"traceback": null,
"data": {"plateifu": 8485-1901,
"mangaid": '1-209232',
"header": "XTENSION= 'IMAGE', NAXIS=3, .... END",
"wcs_header": "WCSAXES = 3 / Number of coordindate axes .... END",
"shape": [34, 34],
"wavelength": [3621.6, 3622.43, 3623.26, ...],
"redcorr": [1.06588, 1.065866, 1.06585, ...],
"bintype": "SPX",
"template": "GAU-MILESHC"
}
}
"""
# Pop any args we don't want going into ModelCube
args = self._pop_args(args, arglist='name')
model_cube, results = _get_model_cube(name, **args)
self.update_results(results)
if model_cube is not None:
self.results['data'] = {
'plateifu': model_cube.plateifu,
'mangaid': model_cube.mangaid,
'header': model_cube.header.tostring(),
'shape': model_cube._shape,
'wavelength': model_cube._wavelength.tolist(),
'redcorr': model_cube._redcorr.tolist(),
'wcs_header': model_cube.wcs.to_header_string(),
'bintype': model_cube.bintype.name,
'template': model_cube.template.name}
return jsonify(self.results)
@route('/<name>/extensions/<modelcube_extension>/',
defaults={'bintype': None, 'template': None},
methods=['GET', 'POST'], endpoint='getModelCubeExtension')
@route('/<name>/<bintype>/extensions/<modelcube_extension>/',
defaults={'template': None},
methods=['GET', 'POST'], endpoint='getModelCubeExtension')
@route('/<name>/<bintype>/<template>/extensions/<modelcube_extension>/',
methods=['GET', 'POST'], endpoint='getModelCubeExtension')
@av.check_args()
def getModelCubeExtension(self, args, name, bintype, template, modelcube_extension):
"""Returns the extension for a modelcube given a plateifu/mangaid.
.. :quickref: ModelCube; Gets the extension given a plate-ifu or mangaid
:param name: The name of the cube as plate-ifu or mangaid
:param bintype: The bintype associated with this modelcube.
:param template: The template associated with this modelcube.
:param modelcube_extension: The name of the cube extension. Either flux, ivar, or mask.
:form release: the release of MaNGA
:resjson int status: status of response. 1 if good, -1 if bad.
:resjson string error: error message, null if None
:resjson json inconfig: json of incoming configuration
:resjson json utahconfig: json of outcoming configuration
:resjson string traceback: traceback of an error, null if None
:resjson json data: dictionary of returned data
:json string modelcube_extension: the data for the specified extension
:resheader Content-Type: application/json
:statuscode 200: no error
:statuscode 422: invalid input parameters
**Example request**:
.. sourcecode:: http
GET /marvin/api/modelcubes/8485-1901/extensions/flux/ HTTP/1.1
Host: api.sdss.org
Accept: application/json, */*
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"status": 1,
"error": null,
"inconfig": {"release": "MPL-5"},
"utahconfig": {"release": "MPL-5", "mode": "local"},
"traceback": null,
"data": {"extension_data": [[0,0,..0], [], ... [0, 0, 0,... 0]]
}
}
"""
# Pass the args in and get the cube
args = self._pop_args(args, arglist=['name', 'modelcube_extension'])
modelcube, res = _get_model_cube(name, use_file=True, **args)
self.update_results(res)
if modelcube:
extension_data = modelcube.data[modelcube_extension.upper()].data
if extension_data is None:
self.results['data'] = {'extension_data': None}
else:
self.results['data'] = {'extension_data': extension_data.tolist()}
return Response(json.dumps(self.results), mimetype='application/json')
@route('/<name>/binids/<modelcube_extension>/',
defaults={'bintype': None, 'template': None},
methods=['GET', 'POST'], endpoint='getModelCubeBinid')
@route('/<name>/<bintype>/binids/<modelcube_extension>/',
defaults={'template': None},
methods=['GET', 'POST'], endpoint='getModelCubeBinid')
@route('/<name>/<bintype>/<template>/binids/<modelcube_extension>/',
methods=['GET', 'POST'], endpoint='getModelCubeBinid')
@av.check_args()
def getModelCubeBinid(self, args, name, bintype, template, modelcube_extension):
"""Returns the binid array for a modelcube given a plateifu/mangaid.
.. :quickref: ModelCube; Gets the binid array given a plate-ifu or mangaid
:param name: The name of the modelcube as plate-ifu or mangaid
:param bintype: The bintype associated with this modelcube.
:param template: The template associated with this modelcube.
:param modelcube_extension: The name of the cube extension.
:form release: the release of MaNGA
:resjson int status: status of response. 1 if good, -1 if bad.
:resjson string error: error message, null if None
:resjson json inconfig: json of incoming configuration
:resjson json utahconfig: json of outcoming configuration
:resjson string traceback: traceback of an error, null if None
:resjson json data: dictionary of returned data
:json string binid: the binid data
:resheader Content-Type: application/json
:statuscode 200: no error
:statuscode 422: invalid input parameters
**Example request**:
.. sourcecode:: http
GET /marvin/api/modelcubes/8485-1901/binids/flux/ HTTP/1.1
Host: api.sdss.org
Accept: application/json, */*
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"status": 1,
"error": null,
"inconfig": {"release": "MPL-5"},
"utahconfig": {"release": "MPL-5", "mode": "local"},
"traceback": null,
"data": {"binid": [[0,0,..0], [], ... [0, 0, 0,... 0]]
}
}
"""
# Pass the args in and get the cube
args = self._pop_args(args, arglist=['name', 'modelcube_extension'])
modelcube, res = _get_model_cube(name, use_file=False, **args)
self.update_results(res)
if modelcube:
try:
model = modelcube.datamodel.from_fits_extension(modelcube_extension)
binid_data = modelcube.get_binid(model)
self.results['data'] = {'binid': binid_data.value.tolist()}
except Exception as ee:
self.results['error'] = str(ee)
return Response(json.dumps(self.results), mimetype='application/json')
@route('/<name>/<bintype>/<template>/quantities/<x>/<y>/',
methods=['GET', 'POST'], endpoint='getModelCubeQuantitiesSpaxel')
@av.check_args()
def getModelCubeQuantitiesSpaxel(self, args, name, bintype, template, x, y):
"""Returns a dictionary with all the quantities.
.. :quickref: ModelCube; Returns a dictionary with all the quantities
:param name: The name of the cube as plate-ifu or mangaid
:param bintype: The bintype associated with this modelcube.
:param template: The template associated with this modelcube.
:param x: The x coordinate of the spaxel (origin is ``lower``)
:param y: The y coordinate of the spaxel (origin is ``lower``)
:form release: the release of MaNGA
:resjson int status: status of response. 1 if good, -1 if bad.
:resjson string error: error message, null if None
:resjson json inconfig: json of incoming configuration
:resjson json utahconfig: json of outcoming configuration
:resjson string traceback: traceback of an error, null if None
:resjson json data: dictionary of returned data
:resheader Content-Type: application/json
:statuscode 200: no error
:statuscode 422: invalid input parameters
**Example request**:
.. sourcecode:: http
GET /marvin/api/modelcubes/8485-1901/SPX/GAU_MILESHC/quantities/10/12/ HTTP/1.1
Host: api.sdss.org
Accept: application/json, */*
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"status": 1,
"error": null,
"inconfig": {"release": "MPL-5"},
"utahconfig": {"release": "MPL-5", "mode": "local"},
"traceback": null,
"data": {"binned_flux": {"value": [0,0,..0], "ivar": ...},
"emline_fit": ...}
}
}
"""
# Pass the args in and get the cube
args = self._pop_args(args, arglist=['name', 'x', 'y'])
modelcube, res = _get_model_cube(name, **args)
self.update_results(res)
if modelcube:
self.results['data'] = {}
spaxel_quantities = modelcube._get_spaxel_quantities(x, y)
for quant in spaxel_quantities:
spectrum = spaxel_quantities[quant]
if spectrum is None:
self.data[quant] = {'value': None}
continue
value = spectrum.value.tolist()
ivar = spectrum.ivar.tolist() if spectrum.ivar is not None else None
mask = spectrum.mask.tolist() if spectrum.mask is not None else None
self.results['data'][quant] = {'value': value,
'ivar': ivar,
'mask': mask}
self.results['data']['wavelength'] = modelcube._wavelength.tolist()
return Response(json.dumps(self.results), mimetype='application/json')
| [
"marvin.utils.general.mangaid2plateifu",
"marvin.config.lookUpVersions",
"marvin.tools.modelcube.ModelCube",
"marvin.api.base.arg_validate.check_args",
"marvin.utils.general.parseIdentifier",
"marvin.core.exceptions.MarvinError"
] | [((843, 873), 'marvin.config.lookUpVersions', 'config.lookUpVersions', (['release'], {}), '(release)\n', (864, 873), False, 'from marvin import config\n'), ((2780, 2898), 'flask_classful.route', 'route', (['"""/<name>/"""'], {'defaults': "{'bintype': None, 'template': None}", 'methods': "['GET', 'POST']", 'endpoint': '"""getModelCube"""'}), "('/<name>/', defaults={'bintype': None, 'template': None}, methods=[\n 'GET', 'POST'], endpoint='getModelCube')\n", (2785, 2898), False, 'from flask_classful import route\n'), ((2910, 3020), 'flask_classful.route', 'route', (['"""/<name>/<bintype>/"""'], {'defaults': "{'template': None}", 'methods': "['GET', 'POST']", 'endpoint': '"""getModelCube"""'}), "('/<name>/<bintype>/', defaults={'template': None}, methods=['GET',\n 'POST'], endpoint='getModelCube')\n", (2915, 3020), False, 'from flask_classful import route\n'), ((3033, 3126), 'flask_classful.route', 'route', (['"""/<name>/<bintype>/<template>/"""'], {'methods': "['GET', 'POST']", 'endpoint': '"""getModelCube"""'}), "('/<name>/<bintype>/<template>/', methods=['GET', 'POST'], endpoint=\n 'getModelCube')\n", (3038, 3126), False, 'from flask_classful import route\n'), ((3127, 3142), 'marvin.api.base.arg_validate.check_args', 'av.check_args', ([], {}), '()\n', (3140, 3142), True, 'from marvin.api.base import arg_validate as av\n'), ((6588, 6752), 'flask_classful.route', 'route', (['"""/<name>/extensions/<modelcube_extension>/"""'], {'defaults': "{'bintype': None, 'template': None}", 'methods': "['GET', 'POST']", 'endpoint': '"""getModelCubeExtension"""'}), "('/<name>/extensions/<modelcube_extension>/', defaults={'bintype':\n None, 'template': None}, methods=['GET', 'POST'], endpoint=\n 'getModelCubeExtension')\n", (6593, 6752), False, 'from flask_classful import route\n'), ((6771, 6929), 'flask_classful.route', 'route', (['"""/<name>/<bintype>/extensions/<modelcube_extension>/"""'], {'defaults': "{'template': None}", 'methods': "['GET', 'POST']", 'endpoint': '"""getModelCubeExtension"""'}), "('/<name>/<bintype>/extensions/<modelcube_extension>/', defaults={\n 'template': None}, methods=['GET', 'POST'], endpoint=\n 'getModelCubeExtension')\n", (6776, 6929), False, 'from flask_classful import route\n'), ((6947, 7081), 'flask_classful.route', 'route', (['"""/<name>/<bintype>/<template>/extensions/<modelcube_extension>/"""'], {'methods': "['GET', 'POST']", 'endpoint': '"""getModelCubeExtension"""'}), "('/<name>/<bintype>/<template>/extensions/<modelcube_extension>/',\n methods=['GET', 'POST'], endpoint='getModelCubeExtension')\n", (6952, 7081), False, 'from flask_classful import route\n'), ((7094, 7109), 'marvin.api.base.arg_validate.check_args', 'av.check_args', ([], {}), '()\n', (7107, 7109), True, 'from marvin.api.base import arg_validate as av\n'), ((9592, 9743), 'flask_classful.route', 'route', (['"""/<name>/binids/<modelcube_extension>/"""'], {'defaults': "{'bintype': None, 'template': None}", 'methods': "['GET', 'POST']", 'endpoint': '"""getModelCubeBinid"""'}), "('/<name>/binids/<modelcube_extension>/', defaults={'bintype': None,\n 'template': None}, methods=['GET', 'POST'], endpoint='getModelCubeBinid')\n", (9597, 9743), False, 'from flask_classful import route\n'), ((9767, 9912), 'flask_classful.route', 'route', (['"""/<name>/<bintype>/binids/<modelcube_extension>/"""'], {'defaults': "{'template': None}", 'methods': "['GET', 'POST']", 'endpoint': '"""getModelCubeBinid"""'}), "('/<name>/<bintype>/binids/<modelcube_extension>/', defaults={\n 'template': None}, methods=['GET', 'POST'], endpoint='getModelCubeBinid')\n", (9772, 9912), False, 'from flask_classful import route\n'), ((9935, 10062), 'flask_classful.route', 'route', (['"""/<name>/<bintype>/<template>/binids/<modelcube_extension>/"""'], {'methods': "['GET', 'POST']", 'endpoint': '"""getModelCubeBinid"""'}), "('/<name>/<bintype>/<template>/binids/<modelcube_extension>/', methods\n =['GET', 'POST'], endpoint='getModelCubeBinid')\n", (9940, 10062), False, 'from flask_classful import route\n'), ((10074, 10089), 'marvin.api.base.arg_validate.check_args', 'av.check_args', ([], {}), '()\n', (10087, 10089), True, 'from marvin.api.base import arg_validate as av\n'), ((12534, 12661), 'flask_classful.route', 'route', (['"""/<name>/<bintype>/<template>/quantities/<x>/<y>/"""'], {'methods': "['GET', 'POST']", 'endpoint': '"""getModelCubeQuantitiesSpaxel"""'}), "('/<name>/<bintype>/<template>/quantities/<x>/<y>/', methods=['GET',\n 'POST'], endpoint='getModelCubeQuantitiesSpaxel')\n", (12539, 12661), False, 'from flask_classful import route\n'), ((12674, 12689), 'marvin.api.base.arg_validate.check_args', 'av.check_args', ([], {}), '()\n', (12687, 12689), True, 'from marvin.api.base import arg_validate as av\n'), ((950, 971), 'marvin.utils.general.parseIdentifier', 'parseIdentifier', (['name'], {}), '(name)\n', (965, 971), False, 'from marvin.utils.general import mangaid2plateifu, parseIdentifier\n'), ((2305, 2437), 'marvin.tools.modelcube.ModelCube', 'ModelCube', ([], {'filename': 'filename', 'mangaid': 'mangaid', 'plateifu': 'plateifu', 'release': 'release', 'template': 'template', 'bintype': 'bintype'}), '(filename=filename, mangaid=mangaid, plateifu=plateifu, release=\n release, template=template, bintype=bintype, **kwargs)\n', (2314, 2437), False, 'from marvin.tools.modelcube import ModelCube\n'), ((6560, 6581), 'flask.jsonify', 'jsonify', (['self.results'], {}), '(self.results)\n', (6567, 6581), False, 'from flask import Response, jsonify\n'), ((9531, 9555), 'json.dumps', 'json.dumps', (['self.results'], {}), '(self.results)\n', (9541, 9555), False, 'import json\n'), ((12473, 12497), 'json.dumps', 'json.dumps', (['self.results'], {}), '(self.results)\n', (12483, 12497), False, 'import json\n'), ((15607, 15631), 'json.dumps', 'json.dumps', (['self.results'], {}), '(self.results)\n', (15617, 15631), False, 'import json\n'), ((1356, 1393), 'marvin.utils.general.mangaid2plateifu', 'mangaid2plateifu', (['name'], {'drpver': 'drpver'}), '(name, drpver=drpver)\n', (1372, 1393), False, 'from marvin.utils.general import mangaid2plateifu, parseIdentifier\n'), ((1892, 1916), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (1906, 1916), False, 'import os\n'), ((1976, 2025), 'marvin.core.exceptions.MarvinError', 'MarvinError', (['"""cannot create path for MaNGA cube."""'], {}), "('cannot create path for MaNGA cube.')\n", (1987, 2025), False, 'from marvin.core.exceptions import MarvinError\n'), ((1603, 1609), 'sdss_access.path.Path', 'Path', ([], {}), '()\n', (1607, 1609), False, 'from sdss_access.path import Path\n')] |
import glob
from google.colab import drive
import time
import colab_env
from colab_env import envvar_handler
import os
from marvin import config
def mount_drive():
drive.mount("/content/gdrive", force_remount = True)
def check_mount_status():
files = []
start_time = time.time()
while len(files) == 0:
print("Checking for mount completion...")
files = glob.glob("/content/gdrive/My Drive/sas/mangawork/manga/sandbox/galaxyzoo3d/v3_0_0/*.fits.gz")
time.sleep(30.)
end_time = time.time()
print(f"Mount complete! after {(end_time-start_time):.1f} seconds")
def add_sas_path():
envvar_handler.add_env("SAS_BASE_DIR", "/content/gdrive/My Drive/sas", overwrite=True)
colab_env.RELOAD()
print("Current SAS_BASE_DIR set to:")
os.system("echo $SAS_BASE_DIR")
def make_netrc():
pw = input("Enter SDSS Login Password: ")
os.system("echo 'machine api.sdss.org' >> $HOME/.netrc")
os.system("echo ' login sdss' >> $HOME/.netrc")
os.system(f"echo ' password {pw}' >> $HOME/.netrc")
os.system("echo 'machine data.sdss.org' >> $HOME/.netrc")
os.system("echo ' login sdss' >> $HOME/.netrc")
os.system(f"echo ' password {pw}' >> $HOME/.netrc")
os.system("chmod 600 $HOME/.netrc")
def prepare_marvin():
from marvin import config
config.access = "collab"
config.mode = "auto"
config.setRelease("MPL-10")
config.login()
def setup(public = True):
print("Mounting Google Drive")
mount_drive()
print("Checking Google Drive mount status (this can take ~5 minutes)")
check_mount_status()
print("Setting up SAS_BASE_DIR")
add_sas_path()
if not public:
print("Setting up SDSS login")
print("Note: you will need the SDSS login password for data access")
make_netrc()
print("Setting up Marvin for MPL-10")
prepare_marvin()
print("Ready to use!")
| [
"marvin.config.setRelease",
"marvin.config.login"
] | [((170, 220), 'google.colab.drive.mount', 'drive.mount', (['"""/content/gdrive"""'], {'force_remount': '(True)'}), "('/content/gdrive', force_remount=True)\n", (181, 220), False, 'from google.colab import drive\n'), ((283, 294), 'time.time', 'time.time', ([], {}), '()\n', (292, 294), False, 'import time\n'), ((522, 533), 'time.time', 'time.time', ([], {}), '()\n', (531, 533), False, 'import time\n'), ((631, 721), 'colab_env.envvar_handler.add_env', 'envvar_handler.add_env', (['"""SAS_BASE_DIR"""', '"""/content/gdrive/My Drive/sas"""'], {'overwrite': '(True)'}), "('SAS_BASE_DIR', '/content/gdrive/My Drive/sas',\n overwrite=True)\n", (653, 721), False, 'from colab_env import envvar_handler\n'), ((722, 740), 'colab_env.RELOAD', 'colab_env.RELOAD', ([], {}), '()\n', (738, 740), False, 'import colab_env\n'), ((787, 818), 'os.system', 'os.system', (['"""echo $SAS_BASE_DIR"""'], {}), "('echo $SAS_BASE_DIR')\n", (796, 818), False, 'import os\n'), ((889, 945), 'os.system', 'os.system', (['"""echo \'machine api.sdss.org\' >> $HOME/.netrc"""'], {}), '("echo \'machine api.sdss.org\' >> $HOME/.netrc")\n', (898, 945), False, 'import os\n'), ((950, 999), 'os.system', 'os.system', (['"""echo \' login sdss\' >> $HOME/.netrc"""'], {}), '("echo \' login sdss\' >> $HOME/.netrc")\n', (959, 999), False, 'import os\n'), ((1004, 1057), 'os.system', 'os.system', (['f"""echo \' password {pw}\' >> $HOME/.netrc"""'], {}), '(f"echo \' password {pw}\' >> $HOME/.netrc")\n', (1013, 1057), False, 'import os\n'), ((1063, 1120), 'os.system', 'os.system', (['"""echo \'machine data.sdss.org\' >> $HOME/.netrc"""'], {}), '("echo \'machine data.sdss.org\' >> $HOME/.netrc")\n', (1072, 1120), False, 'import os\n'), ((1125, 1174), 'os.system', 'os.system', (['"""echo \' login sdss\' >> $HOME/.netrc"""'], {}), '("echo \' login sdss\' >> $HOME/.netrc")\n', (1134, 1174), False, 'import os\n'), ((1179, 1232), 'os.system', 'os.system', (['f"""echo \' password {pw}\' >> $HOME/.netrc"""'], {}), '(f"echo \' password {pw}\' >> $HOME/.netrc")\n', (1188, 1232), False, 'import os\n'), ((1238, 1273), 'os.system', 'os.system', (['"""chmod 600 $HOME/.netrc"""'], {}), "('chmod 600 $HOME/.netrc')\n", (1247, 1273), False, 'import os\n'), ((1385, 1412), 'marvin.config.setRelease', 'config.setRelease', (['"""MPL-10"""'], {}), "('MPL-10')\n", (1402, 1412), False, 'from marvin import config\n'), ((1417, 1431), 'marvin.config.login', 'config.login', ([], {}), '()\n', (1429, 1431), False, 'from marvin import config\n'), ((388, 492), 'glob.glob', 'glob.glob', (['"""/content/gdrive/My Drive/sas/mangawork/manga/sandbox/galaxyzoo3d/v3_0_0/*.fits.gz"""'], {}), "(\n '/content/gdrive/My Drive/sas/mangawork/manga/sandbox/galaxyzoo3d/v3_0_0/*.fits.gz'\n )\n", (397, 492), False, 'import glob\n'), ((491, 507), 'time.sleep', 'time.sleep', (['(30.0)'], {}), '(30.0)\n', (501, 507), False, 'import time\n')] |
import unittest
from marvin.utils.MarvinLog import MarvinLog
class TestMarvinLog(unittest.TestCase):
def test_create_marvin_log_with_name(self):
name = 'test-log'
marvin_log = MarvinLog(name)
self.assertIsNotNone(marvin_log)
self.assertEquals(name, marvin_log.get_logger().name)
def test_create_marvin_log_with_default_name(self):
marvin_log = MarvinLog()
self.assertIsNotNone(marvin_log)
self.assertEquals('marvin.utils.MarvinLog', marvin_log.get_logger().name)
if __name__ == '__main__':
unittest.main()
| [
"marvin.utils.MarvinLog.MarvinLog"
] | [((566, 581), 'unittest.main', 'unittest.main', ([], {}), '()\n', (579, 581), False, 'import unittest\n'), ((199, 214), 'marvin.utils.MarvinLog.MarvinLog', 'MarvinLog', (['name'], {}), '(name)\n', (208, 214), False, 'from marvin.utils.MarvinLog import MarvinLog\n'), ((397, 408), 'marvin.utils.MarvinLog.MarvinLog', 'MarvinLog', ([], {}), '()\n', (406, 408), False, 'from marvin.utils.MarvinLog import MarvinLog\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" Tests for secondary storage - Maximum Limits
Test Plan: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Limit+Resources+to+domain+or+accounts
Issue Link: https://issues.apache.org/jira/browse/CLOUDSTACK-1466
Feature Specifications: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Limit+Resources+to+domains+and+accounts
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import (Account,
ServiceOffering,
Resources,
Domain,
Project,
Template)
from marvin.lib.common import (get_domain,
get_zone,
get_template,
get_builtin_template_info,
matchResourceCount)
from marvin.lib.utils import (cleanup_resources,
validateList)
from marvin.codes import PASS, FAIL, RESOURCE_SECONDARY_STORAGE
class TestMaxSecondaryStorageLimits(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cloudstackTestClient = super(TestMaxSecondaryStorageLimits,
cls).getClsTestClient()
cls.api_client = cloudstackTestClient.getApiClient()
# Fill services from the external config file
cls.services = cloudstackTestClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cloudstackTestClient.getZoneForTests())
cls.services["mode"] = cls.zone.networktype
cls._cleanup = []
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["virtual_machine"]["template"] = cls.template.id
cls.services["volume"]["zoneid"] = cls.zone.id
cls.service_offering = ServiceOffering.create(cls.api_client, cls.services["service_offering"])
cls._cleanup.append(cls.service_offering)
return
@classmethod
def tearDownClass(cls):
super(TestMaxSecondaryStorageLimits, cls).tearDownClass()
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
super(TestMaxSecondaryStorageLimits, self).tearDown()
def registerTemplate(self, inProject=False):
"""Register and download template by default in the account/domain,
in project if stated so"""
try:
builtin_info = get_builtin_template_info(self.apiclient, self.zone.id)
self.services["template_2"]["url"] = builtin_info[0]
self.services["template_2"]["hypervisor"] = builtin_info[1]
self.services["template_2"]["format"] = builtin_info[2]
template = Template.register(self.userapiclient,
self.services["template_2"],
zoneid=self.zone.id,
account=self.child_do_admin.name if not inProject else None,
domainid=self.child_do_admin.domainid if not inProject else None,
projectid=self.project.id if inProject else None)
self.cleanup.append(template)
template.download(self.apiclient)
templates = Template.list(self.userapiclient,
templatefilter=\
self.services["template_2"]["templatefilter"],
id=template.id)
self.assertEqual(validateList(templates)[0], PASS,\
"templates list validation failed")
self.templateSize = (templates[0].size / (1024**3))
except Exception as e:
return [FAIL, e]
return [PASS, None]
def setupAccounts(self):
try:
self.child_domain = Domain.create(self.apiclient,services=self.services["domain"],
parentdomainid=self.domain.id)
self.cleanup.append(self.child_domain)
self.child_do_admin = Account.create(self.apiclient, self.services["account"], admin=True,
domainid=self.child_domain.id)
self.cleanup.append(self.child_do_admin)
self.userapiclient = self.testClient.getUserApiClient(
UserName=self.child_do_admin.name,
DomainName=self.child_do_admin.domain)
# Create project as a domain admin
self.project = Project.create(self.apiclient, self.services["project"],
account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid)
self.cleanup.append(self.project)
except Exception as e:
return [FAIL, e]
return [PASS, None]
def updateSecondaryStorageLimits(self, accountLimit=None, domainLimit=None, projectLimit=None):
try:
# Update resource limits for account
if accountLimit is not None:
Resources.updateLimit(self.apiclient, resourcetype=11,
max=int(accountLimit), account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid)
if projectLimit is not None:
Resources.updateLimit(self.apiclient, resourcetype=11,
max=int(projectLimit), projectid=self.project.id)
if domainLimit is not None:
Resources.updateLimit(self.apiclient, resourcetype=11,
max=int(domainLimit), domainid=self.child_domain.id)
except Exception as e:
return [FAIL, e]
return [PASS, None]
@attr(tags=["advanced"], required_hardware="true")
def test_01_deploy_vm_domain_limit_reached(self):
"""Test Try to deploy VM with admin account where account has not used
the resources but @ domain they are not available
# Validate the following
# 1. Try to register template with admin account where account has not used the
# resources but @ domain they are not available
# 2. Template registration should fail"""
response = self.setupAccounts()
self.assertEqual(response[0], PASS, response[1])
response = self.registerTemplate()
self.assertEqual(response[0], PASS, response[1])
expectedCount = self.templateSize
response = matchResourceCount(
self.apiclient, expectedCount,
RESOURCE_SECONDARY_STORAGE,
accountid=self.child_do_admin.id)
self.assertEqual(response[0], PASS, response[1])
domainLimit = self.templateSize
response = self.updateSecondaryStorageLimits(domainLimit=domainLimit)
self.assertEqual(response[0], PASS, response[1])
with self.assertRaises(Exception):
template = Template.register(self.userapiclient,
self.services["template_2"],
zoneid=self.zone.id,
account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid)
template.delete(self.userapiclient)
return
@attr(tags=["advanced"], required_hardware="true")
def test_02_deploy_vm_account_limit_reached(self):
"""Test Try to deploy VM with admin account where account has used
the resources but @ domain they are available
# Validate the following
# 1. Try to register template with admin account where account has used the
# resources but @ domain they are available
# 2. Template registration should fail"""
response = self.setupAccounts()
self.assertEqual(response[0], PASS, response[1])
response = self.registerTemplate()
self.assertEqual(response[0], PASS, response[1])
expectedCount = self.templateSize
response = matchResourceCount(
self.apiclient, expectedCount,
RESOURCE_SECONDARY_STORAGE,
accountid=self.child_do_admin.id)
self.assertEqual(response[0], PASS, response[1])
accountLimit = self.templateSize
response = self.updateSecondaryStorageLimits(accountLimit=accountLimit)
self.assertEqual(response[0], PASS, response[1])
with self.assertRaises(Exception):
template = Template.register(self.userapiclient,
self.services["template_2"],
zoneid=self.zone.id,
account=self.child_do_admin.name,
domainid=self.child_do_admin.domainid)
template.delete(self.userapiclient)
return
@attr(tags=["advanced"], required_hardware="true")
def test_03_deploy_vm_project_limit_reached(self):
"""Test TTry to deploy VM with admin account where account has not used
the resources but @ project they are not available
# Validate the following
# 1. Try to register template with admin account where account has not used the
# resources but @ project they are not available
# 2. Template registration should error out saying ResourceAllocationException
# with "resource limit exceeds"""
response = self.setupAccounts()
self.assertEqual(response[0], PASS, response[1])
response = self.registerTemplate(inProject=True)
self.assertEqual(response[0], PASS, response[1])
try:
projects = Project.list(self.userapiclient, id=self.project.id, listall=True)
except Exception as e:
self.fail("failed to get projects list: %s" % e)
self.assertEqual(validateList(projects)[0], PASS,
"projects list validation failed")
self.assertEqual(self.templateSize, projects[0].secondarystoragetotal, "Resource count %s\
not matching with the expcted count: %s" %
(projects[0].secondarystoragetotal, self.templateSize))
projectLimit = self.templateSize
response = self.updateSecondaryStorageLimits(projectLimit=projectLimit)
self.assertEqual(response[0], PASS, response[1])
with self.assertRaises(Exception):
template = Template.register(self.userapiclient,
self.services["template_2"],
zoneid=self.zone.id,
projectid=self.project.id)
template.delete(self.userapiclient)
return
| [
"marvin.lib.common.get_domain",
"marvin.lib.common.get_builtin_template_info",
"marvin.lib.base.Project.list",
"marvin.lib.utils.validateList",
"marvin.lib.base.ServiceOffering.create",
"marvin.lib.base.Template.register",
"marvin.lib.common.matchResourceCount",
"marvin.lib.base.Project.create",
"ma... | [((7129, 7178), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (7133, 7178), False, 'from nose.plugins.attrib import attr\n'), ((8730, 8779), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (8734, 8779), False, 'from nose.plugins.attrib import attr\n'), ((10319, 10368), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced']", 'required_hardware': '"""true"""'}), "(tags=['advanced'], required_hardware='true')\n", (10323, 10368), False, 'from nose.plugins.attrib import attr\n'), ((2364, 2390), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2374, 2390), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, matchResourceCount\n'), ((2577, 2642), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (2589, 2642), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, matchResourceCount\n'), ((2978, 3050), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (3000, 3050), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((7866, 7981), 'marvin.lib.common.matchResourceCount', 'matchResourceCount', (['self.apiclient', 'expectedCount', 'RESOURCE_SECONDARY_STORAGE'], {'accountid': 'self.child_do_admin.id'}), '(self.apiclient, expectedCount,\n RESOURCE_SECONDARY_STORAGE, accountid=self.child_do_admin.id)\n', (7884, 7981), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, matchResourceCount\n'), ((9452, 9567), 'marvin.lib.common.matchResourceCount', 'matchResourceCount', (['self.apiclient', 'expectedCount', 'RESOURCE_SECONDARY_STORAGE'], {'accountid': 'self.child_do_admin.id'}), '(self.apiclient, expectedCount,\n RESOURCE_SECONDARY_STORAGE, accountid=self.child_do_admin.id)\n', (9470, 9567), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, matchResourceCount\n'), ((3694, 3749), 'marvin.lib.common.get_builtin_template_info', 'get_builtin_template_info', (['self.apiclient', 'self.zone.id'], {}), '(self.apiclient, self.zone.id)\n', (3719, 3749), False, 'from marvin.lib.common import get_domain, get_zone, get_template, get_builtin_template_info, matchResourceCount\n'), ((3979, 4256), 'marvin.lib.base.Template.register', 'Template.register', (['self.userapiclient', "self.services['template_2']"], {'zoneid': 'self.zone.id', 'account': '(self.child_do_admin.name if not inProject else None)', 'domainid': '(self.child_do_admin.domainid if not inProject else None)', 'projectid': '(self.project.id if inProject else None)'}), "(self.userapiclient, self.services['template_2'], zoneid=\n self.zone.id, account=self.child_do_admin.name if not inProject else\n None, domainid=self.child_do_admin.domainid if not inProject else None,\n projectid=self.project.id if inProject else None)\n", (3996, 4256), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((4543, 4659), 'marvin.lib.base.Template.list', 'Template.list', (['self.userapiclient'], {'templatefilter': "self.services['template_2']['templatefilter']", 'id': 'template.id'}), "(self.userapiclient, templatefilter=self.services['template_2'\n ]['templatefilter'], id=template.id)\n", (4556, 4659), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((5129, 5227), 'marvin.lib.base.Domain.create', 'Domain.create', (['self.apiclient'], {'services': "self.services['domain']", 'parentdomainid': 'self.domain.id'}), "(self.apiclient, services=self.services['domain'],\n parentdomainid=self.domain.id)\n", (5142, 5227), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((5351, 5454), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.child_domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.child_domain.id)\n", (5365, 5454), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((5838, 5972), 'marvin.lib.base.Project.create', 'Project.create', (['self.apiclient', "self.services['project']"], {'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid'}), "(self.apiclient, self.services['project'], account=self.\n child_do_admin.name, domainid=self.child_do_admin.domainid)\n", (5852, 5972), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((8352, 8522), 'marvin.lib.base.Template.register', 'Template.register', (['self.userapiclient', "self.services['template_2']"], {'zoneid': 'self.zone.id', 'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid'}), "(self.userapiclient, self.services['template_2'], zoneid=\n self.zone.id, account=self.child_do_admin.name, domainid=self.\n child_do_admin.domainid)\n", (8369, 8522), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((9941, 10111), 'marvin.lib.base.Template.register', 'Template.register', (['self.userapiclient', "self.services['template_2']"], {'zoneid': 'self.zone.id', 'account': 'self.child_do_admin.name', 'domainid': 'self.child_do_admin.domainid'}), "(self.userapiclient, self.services['template_2'], zoneid=\n self.zone.id, account=self.child_do_admin.name, domainid=self.\n child_do_admin.domainid)\n", (9958, 10111), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((11128, 11194), 'marvin.lib.base.Project.list', 'Project.list', (['self.userapiclient'], {'id': 'self.project.id', 'listall': '(True)'}), '(self.userapiclient, id=self.project.id, listall=True)\n', (11140, 11194), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((11872, 11991), 'marvin.lib.base.Template.register', 'Template.register', (['self.userapiclient', "self.services['template_2']"], {'zoneid': 'self.zone.id', 'projectid': 'self.project.id'}), "(self.userapiclient, self.services['template_2'], zoneid=\n self.zone.id, projectid=self.project.id)\n", (11889, 11991), False, 'from marvin.lib.base import Account, ServiceOffering, Resources, Domain, Project, Template\n'), ((11313, 11335), 'marvin.lib.utils.validateList', 'validateList', (['projects'], {}), '(projects)\n', (11325, 11335), False, 'from marvin.lib.utils import cleanup_resources, validateList\n'), ((4800, 4823), 'marvin.lib.utils.validateList', 'validateList', (['templates'], {}), '(templates)\n', (4812, 4823), False, 'from marvin.lib.utils import cleanup_resources, validateList\n')] |
#!/usr/bin/env python
# encoding: utf-8
'''
Created by <NAME> on 2016-04-29 01:15:33
Licensed under a 3-clause BSD license.
Revision History:
Initial Version: 2016-04-29 01:15:33 by <NAME>
Last Modified On: 2016-04-29 01:15:33 by Brian
'''
from __future__ import print_function
from __future__ import division
from flask import Blueprint, render_template, request
from flask_classful import FlaskView, route
from brain.api.base import processRequest
from marvin.core.exceptions import MarvinError
from marvin.utils.general import getRandomImages
from marvin.web.web_utils import buildImageDict, parseSession
from marvin.web.controllers import BaseWebView
images = Blueprint("images_page", __name__)
class Random(BaseWebView):
route_base = '/random/'
def __init__(self):
''' Initialize the route '''
super(Random, self).__init__('marvin-random')
self.random = self.base.copy()
def before_request(self, *args, **kwargs):
''' Do these things before a request to any route '''
super(Random, self).before_request(*args, **kwargs)
self.reset_dict(self.random)
@route('/', methods=['GET', 'POST'])
def index(self):
# Attempt to retrieve search parameters
form = processRequest(request=request)
self.random['imnumber'] = 16
images = []
# Get random images ; parse out thumbnails ; construct plate-IFUs
imfiles = None
try:
imfiles = getRandomImages(as_url=True, num=self.random['imnumber'], mode='local', release=self._release)
except MarvinError as e:
self.random['error'] = 'Error: could not get images: {0}'.format(e)
else:
images = buildImageDict(imfiles)
# if image grab failed, make placeholders
if not imfiles:
images = buildImageDict(imfiles, test=True, num=self.random['imnumber'])
# Add images to dict
self.random['images'] = images
return render_template('random.html', **self.random)
Random.register(images)
| [
"marvin.utils.general.getRandomImages",
"marvin.web.web_utils.buildImageDict"
] | [((676, 710), 'flask.Blueprint', 'Blueprint', (['"""images_page"""', '__name__'], {}), "('images_page', __name__)\n", (685, 710), False, 'from flask import Blueprint, render_template, request\n'), ((1136, 1171), 'flask_classful.route', 'route', (['"""/"""'], {'methods': "['GET', 'POST']"}), "('/', methods=['GET', 'POST'])\n", (1141, 1171), False, 'from flask_classful import FlaskView, route\n'), ((1257, 1288), 'brain.api.base.processRequest', 'processRequest', ([], {'request': 'request'}), '(request=request)\n', (1271, 1288), False, 'from brain.api.base import processRequest\n'), ((1991, 2036), 'flask.render_template', 'render_template', (['"""random.html"""'], {}), "('random.html', **self.random)\n", (2006, 2036), False, 'from flask import Blueprint, render_template, request\n'), ((1479, 1577), 'marvin.utils.general.getRandomImages', 'getRandomImages', ([], {'as_url': '(True)', 'num': "self.random['imnumber']", 'mode': '"""local"""', 'release': 'self._release'}), "(as_url=True, num=self.random['imnumber'], mode='local',\n release=self._release)\n", (1494, 1577), False, 'from marvin.utils.general import getRandomImages\n'), ((1722, 1745), 'marvin.web.web_utils.buildImageDict', 'buildImageDict', (['imfiles'], {}), '(imfiles)\n', (1736, 1745), False, 'from marvin.web.web_utils import buildImageDict, parseSession\n'), ((1842, 1905), 'marvin.web.web_utils.buildImageDict', 'buildImageDict', (['imfiles'], {'test': '(True)', 'num': "self.random['imnumber']"}), "(imfiles, test=True, num=self.random['imnumber'])\n", (1856, 1905), False, 'from marvin.web.web_utils import buildImageDict, parseSession\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import (stopVirtualMachine,
stopRouter,
startRouter)
from marvin.lib.utils import (cleanup_resources,
get_process_status)
from marvin.lib.base import (ServiceOffering,
VirtualMachine,
Account,
ServiceOffering,
NATRule,
NetworkACL,
FireWallRule,
PublicIPAddress,
NetworkOffering,
Network,
Router)
from marvin.lib.common import (get_zone,
get_template,
get_domain,
list_virtual_machines,
list_networks,
list_configurations,
list_routers,
list_nat_rules,
list_publicIP,
list_firewall_rules,
list_hosts)
# Import System modules
import time
import logging
class TestRedundantIsolateNetworks(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestRedundantIsolateNetworks, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
# Create an account, network, VM and IP addresses
cls.account = Account.create(
cls.api_client,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.services["nw_off_persistent_RVR"]["egress_policy"] = "true"
cls.network_offering = NetworkOffering.create(
cls.api_client,
cls.services["nw_off_persistent_RVR"],
conservemode=True
)
cls.network_offering.update(cls.api_client, state='Enabled')
cls._cleanup = [
cls.service_offering,
cls.network_offering,
]
cls.logger = logging.getLogger('TestRedundantIsolateNetworks')
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.account = Account.create(
self.apiclient,
self.services["account"],
admin=True,
domainid=self.domain.id
)
self.cleanup = []
self.cleanup.insert(0, self.account)
return
def tearDown(self):
try:
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags=["advanced", "advancedns", "ssh"], required_hardware="true")
def test_RVR_Network_FW_PF_SSH_default_routes(self):
""" Test redundant router internals """
self.logger.debug("Starting test_RVR_Network_FW_PF_SSH_default_routes...")
self.logger.debug("Creating network with network offering: %s" % self.network_offering.id)
network = Network.create(
self.apiclient,
self.services["network"],
accountid=self.account.name,
domainid=self.account.domainid,
networkofferingid=self.network_offering.id,
zoneid=self.zone.id
)
self.logger.debug("Created network with ID: %s" % network.id)
networks = Network.list(
self.apiclient,
id=network.id,
listall=True
)
self.assertEqual(
isinstance(networks, list),
True,
"List networks should return a valid response for created network"
)
nw_response = networks[0]
self.logger.debug("Deploying VM in account: %s" % self.account.name)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
networkids=[str(network.id)]
)
self.logger.debug("Deployed VM in network: %s" % network.id)
vms = VirtualMachine.list(
self.apiclient,
id=virtual_machine.id,
listall=True
)
self.assertEqual(
isinstance(vms, list),
True,
"List Vms should return a valid list"
)
vm = vms[0]
self.assertEqual(
vm.state,
"Running",
"VM should be in running state after deployment"
)
self.logger.debug("Listing routers for network: %s" % network.name)
routers = Router.list(
self.apiclient,
networkid=network.id,
listall=True
)
self.assertEqual(
isinstance(routers, list),
True,
"list router should return Master and backup routers"
)
self.assertEqual(
len(routers),
2,
"Length of the list router should be 2 (Backup & master)"
)
self.logger.debug("Associating public IP for network: %s" % network.name)
public_ip = PublicIPAddress.create(
self.apiclient,
accountid=self.account.name,
zoneid=self.zone.id,
domainid=self.account.domainid,
networkid=network.id
)
self.logger.debug("Associated %s with network %s" % (
public_ip.ipaddress.ipaddress,
network.id
))
public_ips = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(public_ips, list),
True,
"Check for list public IPs response return valid data"
)
public_ip_1 = public_ips[0]
self.logger.debug("Creating Firewall rule for VM ID: %s" % virtual_machine.id)
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip_1.id,
protocol=self.services["natrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["natrule"]["publicport"],
endport=self.services["natrule"]["publicport"]
)
self.logger.debug("Creating NAT rule for VM ID: %s" % virtual_machine.id)
nat_rule = NATRule.create(
self.apiclient,
virtual_machine,
self.services["natrule"],
public_ip_1.id
)
self.cleanup.insert(0, network)
self.cleanup.insert(0, virtual_machine)
result = 'failed'
try:
ssh_command = "ping -c 3 8.8.8.8"
ssh = virtual_machine.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress, retries=5)
self.logger.debug("Ping to google.com from VM")
result = str(ssh.execute(ssh_command))
self.logger.debug("SSH result: %s; COUNT is ==> %s" % (result, result.count("3 packets received")))
except:
self.fail("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress))
self.assertEqual(
result.count("3 packets received"),
1,
"Ping to outside world from VM should be successful"
)
return
class TestIsolatedNetworks(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestIsolatedNetworks, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.services['mode'] = cls.zone.networktype
template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
# Create an account, network, VM and IP addresses
cls.account = Account.create(
cls.api_client,
cls.services["account"],
admin=True,
domainid=cls.domain.id
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.services["network_offering"]["egress_policy"] = "true"
cls.network_offering = NetworkOffering.create(cls.api_client,
cls.services["network_offering"],
conservemode=True)
cls.network_offering.update(cls.api_client, state='Enabled')
cls.network = Network.create(cls.api_client,
cls.services["network"],
accountid=cls.account.name,
domainid=cls.account.domainid,
networkofferingid=cls.network_offering.id,
zoneid=cls.zone.id)
cls.vm_1 = VirtualMachine.create(cls.api_client,
cls.services["virtual_machine"],
templateid=template.id,
accountid=cls.account.name,
domainid=cls.domain.id,
serviceofferingid=cls.service_offering.id,
networkids=[str(cls.network.id)])
cls._cleanup = [
cls.vm_1,
cls.network,
cls.network_offering,
cls.service_offering,
cls.account
]
cls.logger = logging.getLogger('TestIsolatedNetworks')
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
return
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
return
@attr(tags=["advanced", "advancedns", "ssh"], required_hardware="true")
def test_isolate_network_FW_PF_default_routes(self):
"""Stop existing router, add a PF rule and check we can access the VM """
self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
routers = list_routers(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
router = routers[0]
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
public_ips = list_publicIP(
self.apiclient,
account=self.account.name,
domainid=self.account.domainid,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(public_ips, list),
True,
"Check for list public IPs response return valid data"
)
public_ip = public_ips[0]
self.logger.debug("Creating Firewall rule for VM ID: %s" % self.vm_1.id)
FireWallRule.create(
self.apiclient,
ipaddressid=public_ip.id,
protocol=self.services["natrule"]["protocol"],
cidrlist=['0.0.0.0/0'],
startport=self.services["natrule"]["publicport"],
endport=self.services["natrule"]["publicport"]
)
self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_1.id)
# Create NAT rule
nat_rule = NATRule.create(
self.apiclient,
self.vm_1,
self.services["natrule"],
public_ip.id
)
nat_rules = list_nat_rules(
self.apiclient,
id=nat_rule.id
)
self.assertEqual(
isinstance(nat_rules, list),
True,
"Check for list NAT rules response return valid data"
)
self.assertEqual(
nat_rules[0].state,
'Active',
"Check list port forwarding rules"
)
result = 'failed'
try:
ssh_command = "ping -c 3 8.8.8.8"
self.logger.debug("SSH into VM with IP: %s" % nat_rule.ipaddress)
ssh = self.vm_1.get_ssh_client(ipaddress=nat_rule.ipaddress, port=self.services["natrule"]["publicport"], retries=5)
result = str(ssh.execute(ssh_command))
self.logger.debug("SSH result: %s; COUNT is ==> %s" % (result, result.count("3 packets received")))
except:
self.fail("Failed to SSH into VM - %s" % (nat_rule.ipaddress))
self.assertEqual(
result.count("3 packets received"),
1,
"Ping to outside world from VM should be successful"
)
return
| [
"marvin.lib.base.Network.list",
"marvin.lib.base.NATRule.create",
"marvin.lib.common.list_nat_rules",
"marvin.lib.base.Router.list",
"marvin.lib.base.VirtualMachine.list",
"marvin.lib.base.PublicIPAddress.create",
"marvin.lib.utils.cleanup_resources",
"marvin.lib.base.FireWallRule.create",
"marvin.l... | [((5031, 5101), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'ssh']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'ssh'], required_hardware='true')\n", (5035, 5101), False, 'from nose.plugins.attrib import attr\n'), ((13913, 13983), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'advancedns', 'ssh']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'advancedns', 'ssh'], required_hardware='true')\n", (13917, 13983), False, 'from nose.plugins.attrib import attr\n'), ((2547, 2573), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (2557, 2573), False, 'from marvin.lib.common import get_zone, get_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((2727, 2792), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (2739, 2792), False, 'from marvin.lib.common import get_zone, get_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((2984, 3079), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], admin=True,\n domainid=cls.domain.id)\n", (2998, 3079), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((3165, 3237), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (3187, 3237), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((3377, 3478), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['nw_off_persistent_RVR']"], {'conservemode': '(True)'}), "(cls.api_client, cls.services['nw_off_persistent_RVR'\n ], conservemode=True)\n", (3399, 3478), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((3887, 3936), 'logging.getLogger', 'logging.getLogger', (['"""TestRedundantIsolateNetworks"""'], {}), "('TestRedundantIsolateNetworks')\n", (3904, 3936), False, 'import logging\n'), ((3966, 3989), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (3987, 3989), False, 'import logging\n'), ((4439, 4536), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (4453, 4536), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((5408, 5600), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'self.network_offering.id', 'zoneid': 'self.zone.id'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=self.\n network_offering.id, zoneid=self.zone.id)\n", (5422, 5600), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((5907, 5964), 'marvin.lib.base.Network.list', 'Network.list', (['self.apiclient'], {'id': 'network.id', 'listall': '(True)'}), '(self.apiclient, id=network.id, listall=True)\n', (5919, 5964), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((7006, 7078), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'virtual_machine.id', 'listall': '(True)'}), '(self.apiclient, id=virtual_machine.id, listall=True)\n', (7025, 7078), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((7725, 7788), 'marvin.lib.base.Router.list', 'Router.list', (['self.apiclient'], {'networkid': 'network.id', 'listall': '(True)'}), '(self.apiclient, networkid=network.id, listall=True)\n', (7736, 7788), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((8392, 8539), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=network.id)\n', (8414, 8539), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((8978, 9092), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, zoneid=self.zone.id)\n', (8991, 9092), False, 'from marvin.lib.common import get_zone, get_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((9443, 9690), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip_1.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=public_ip_1.id, protocol=\n self.services['natrule']['protocol'], cidrlist=['0.0.0.0/0'], startport\n =self.services['natrule']['publicport'], endport=self.services[\n 'natrule']['publicport'])\n", (9462, 9690), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((9860, 9953), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'virtual_machine', "self.services['natrule']", 'public_ip_1.id'], {}), "(self.apiclient, virtual_machine, self.services['natrule'],\n public_ip_1.id)\n", (9874, 9953), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((11200, 11226), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (11210, 11226), False, 'from marvin.lib.common import get_zone, get_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((11376, 11441), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (11388, 11441), False, 'from marvin.lib.common import get_zone, get_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((11633, 11728), 'marvin.lib.base.Account.create', 'Account.create', (['cls.api_client', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.api_client, cls.services['account'], admin=True,\n domainid=cls.domain.id)\n", (11647, 11728), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((11814, 11886), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (11836, 11886), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((12021, 12116), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['cls.api_client', "cls.services['network_offering']"], {'conservemode': '(True)'}), "(cls.api_client, cls.services['network_offering'],\n conservemode=True)\n", (12043, 12116), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((12316, 12503), 'marvin.lib.base.Network.create', 'Network.create', (['cls.api_client', "cls.services['network']"], {'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'networkofferingid': 'cls.network_offering.id', 'zoneid': 'cls.zone.id'}), "(cls.api_client, cls.services['network'], accountid=cls.\n account.name, domainid=cls.account.domainid, networkofferingid=cls.\n network_offering.id, zoneid=cls.zone.id)\n", (12330, 12503), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((13371, 13412), 'logging.getLogger', 'logging.getLogger', (['"""TestIsolatedNetworks"""'], {}), "('TestIsolatedNetworks')\n", (13388, 13412), False, 'import logging\n'), ((13442, 13465), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (13463, 13465), False, 'import logging\n'), ((14225, 14317), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (14237, 14317), False, 'from marvin.lib.common import get_zone, get_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((14834, 14948), 'marvin.lib.common.list_publicIP', 'list_publicIP', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid', 'zoneid': 'self.zone.id'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid, zoneid=self.zone.id)\n', (14847, 14948), False, 'from marvin.lib.common import get_zone, get_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((15291, 15536), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'public_ip.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=public_ip.id, protocol=self\n .services['natrule']['protocol'], cidrlist=['0.0.0.0/0'], startport=\n self.services['natrule']['publicport'], endport=self.services['natrule'\n ]['publicport'])\n", (15310, 15536), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((15726, 15811), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.vm_1', "self.services['natrule']", 'public_ip.id'], {}), "(self.apiclient, self.vm_1, self.services['natrule'],\n public_ip.id)\n", (15740, 15811), False, 'from marvin.lib.base import ServiceOffering, VirtualMachine, Account, ServiceOffering, NATRule, NetworkACL, FireWallRule, PublicIPAddress, NetworkOffering, Network, Router\n'), ((15887, 15933), 'marvin.lib.common.list_nat_rules', 'list_nat_rules', (['self.apiclient'], {'id': 'nat_rule.id'}), '(self.apiclient, id=nat_rule.id)\n', (15901, 15933), False, 'from marvin.lib.common import get_zone, get_template, get_domain, list_virtual_machines, list_networks, list_configurations, list_routers, list_nat_rules, list_publicIP, list_firewall_rules, list_hosts\n'), ((4170, 4217), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (4187, 4217), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((4856, 4904), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.api_client', 'self.cleanup'], {}), '(self.api_client, self.cleanup)\n', (4873, 4904), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((13646, 13693), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (13663, 13693), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.