code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
from rest_framework import serializers
class AttachmentSerializer(serializers.Serializer):
pass
"""
//*
// As of 2017-06-13, up to 38 attachments can be worn per agent
// max of 328 bytes per attach point (if name and description are maxed out).
// x38 = 12464 bytes
// without descriptions: 188 * 38 = 7144 bytes top
// I measured a real outfit with 38 attachments; it's json encoding was 6877 bytes
string avatarAttachmentsJson(key id) {
list ans = [];
list attachments = llGetAttachedList(id);
debug((string)llGetListLength(attachments) + " attachments");
integer i;
for (i = llGetListLength(attachments) - 1; i >= 0; i--) {
key attachment = llList2Key(attachments, i);
list details = llGetObjectDetails(attachment, [OBJECT_NAME, OBJECT_DESC, OBJECT_CREATOR, OBJECT_ATTACHED_POINT]);
ans = [llList2Json(JSON_OBJECT, [
"id", attachment, // 6+2+36 = 44 bytes
"name", llList2String(details, 0), // 6+4+64 = 74 bytes
"desc", llList2String(details, 1), // 6+4+128 = 140 bytes
"creator", llList2String(details, 2), // 6+7+36 = 49 bytes
"attachPoint", llList2String(details, 3) // 6+11+2 = 19 bytes
])] + ans;
}
return llList2Json(JSON_ARRAY, ans);
}
"""
| tapple/nsize-web | nsize/body_detector/serializers.py | Python | agpl-3.0 | 1,173 |
from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
self.table = table
self.queries = []
self.debug = debug
def commit(self):
if len(self.queries) == 0:
return
stmts = "\n".join(self.queries)
query = "BEGIN;\n"
query += stmts
query += "COMMIT;\n"
if self.debug:
print query
resp = self.cl.sql(query)
if self.debug:
print resp
def _craft_insert(self, the_geom, event_type, happened_at, message):
if happened_at is None:
happened_at = ''
if message is None:
message = ''
def quote(s):
return "'" + s + "'"
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
the_geom = "ST_SetSRID(ST_Point(%s,%s), 4326)" %(point.longitude, point.latitude)
insert = self._craft_insert(the_geom, "checkin", point.dateTime, point.message)
self.queries.append(insert)
def update_line(self, trip_id, coords):
geojson = json.dumps({ "type" : "MultiLineString", "coordinates": [coords] })
the_geom = "ST_SetSRID(ST_GeomFromGeoJSON('%s'), 4326)" % (geojson)
insert = self._craft_insert(the_geom, "track", str(datetime.datetime.now()), None)
self.queries.append(insert)
| Ramblurr/wander | wander/cartodbutils/__init__.py | Python | agpl-3.0 | 1,661 |
# Copyright 2009 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Import module for legacy KDE .po files.
This is an extension of standard gettext PO files.
You can read more about this file format from:
* http://l10n.kde.org/docs/translation-howto/gui-peculiarities.html
* http://docs.kde.org/development/en/kdesdk/kbabel/kbabel-pluralforms.html
* http://websvn.kde.org/branches/KDE/3.5/kdelibs/kdecore/klocale.cpp
"""
__metaclass__ = type
__all__ = [
'KdePOImporter'
]
from zope.interface import implements
from lp.translations.interfaces.translationfileformat import (
TranslationFileFormat,
)
from lp.translations.interfaces.translationimporter import (
ITranslationFormatImporter,
)
from lp.translations.utilities.gettext_po_importer import GettextPOImporter
class KdePOImporter(GettextPOImporter):
"""Support class for importing KDE .po files."""
implements(ITranslationFormatImporter)
def getFormat(self, file_contents):
"""See `ITranslationFormatImporter`."""
# XXX DaniloSegan 20070904: I first tried using POParser()
# to check if the file is a legacy KDE PO file or not, but
# that is too slow in some cases like tarball uploads (processing
# of all PO files in a tarball is done in the same transaction,
# and with extremely big PO files, this will be too slow). Thus,
# a heuristic verified to be correct on all PO files from
# Ubuntu language packs.
if ('msgid "_n: ' in file_contents or
'msgid ""\n"_n: ' in file_contents or
'msgid "_: ' in file_contents or
'msgid ""\n"_: ' in file_contents):
return TranslationFileFormat.KDEPO
else:
return TranslationFileFormat.PO
priority = 10
content_type = 'application/x-po'
def parse(self, translation_import_queue_entry):
"""See `ITranslationFormatImporter`."""
translation_file = GettextPOImporter.parse(
self, translation_import_queue_entry)
plural_prefix = u'_n: '
context_prefix = u'_: '
for message in translation_file.messages:
msgid = message.msgid_singular
if msgid.startswith(plural_prefix) and '\n' in msgid:
# This is a KDE plural form
singular, plural = msgid[len(plural_prefix):].split('\n')
message.msgid_singular = singular
message.msgid_plural = plural
msgstrs = message._translations
if len(msgstrs) > 0:
message._translations = msgstrs[0].split('\n')
self.internal_format = TranslationFileFormat.KDEPO
elif msgid.startswith(context_prefix) and '\n' in msgid:
# This is a KDE context message
message.context, message.msgid_singular = (
msgid[len(context_prefix):].split('\n', 1))
self.internal_format = TranslationFileFormat.KDEPO
else:
# Other messages are left as they are parsed by
# GettextPOImporter
pass
return translation_file
| abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/translations/utilities/kde_po_importer.py | Python | agpl-3.0 | 3,250 |
import pickle
from content_stats import Compare_regions
from content_stats import Title_stats
# load saved dictionaries
nz_titles = pickle.load(open('nz/all_movies_dict.p', 'rb'))
us_titles = pickle.load(open('nz/all_movies_dict.p', 'rb'))
| NZRS/content-analysis | example_usage.py | Python | agpl-3.0 | 246 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
# And itemgroup is like a item, but it's a group of items :)
from item import Item, Items
from shinken.brok import Brok
from shinken.property import StringProp, ListProp, ToGuessProp
from shinken.log import logger
# TODO: subclass Item & Items for Itemgroup & Itemgroups?
class Itemgroup(Item):
id = 0
properties = Item.properties.copy()
properties.update({
'members': ListProp(fill_brok=['full_status'], default=None, split_on_coma=True),
# Shinken specific
'unknown_members': ListProp(default=None),
})
def __init__(self, params={}):
self.id = self.__class__.id
self.__class__.id += 1
cls = self.__class__
self.init_running_properties()
for key in params:
if key in self.properties:
val = self.properties[key].pythonize(params[key])
elif key in self.running_properties:
warning = "using a the running property %s in a config file" % key
self.configuration_warnings.append(warning)
val = self.running_properties[key].pythonize(params[key])
else:
warning = "Guessing the property %s type because it is not in %s object properties" % \
(key, cls.__name__)
self.configuration_warnings.append(warning)
val = ToGuessProp.pythonize(params[key])
setattr(self, key, val)
# Copy the groups properties EXCEPT the members
# members need to be fill after manually
def copy_shell(self):
cls = self.__class__
old_id = cls.id
new_i = cls() # create a new group
new_i.id = self.id # with the same id
cls.id = old_id # Reset the Class counter
# Copy all properties
for prop in cls.properties:
if prop is not 'members':
if self.has(prop):
val = getattr(self, prop)
setattr(new_i, prop, val)
# but no members
new_i.members = []
return new_i
def replace_members(self, members):
self.members = members
# If a prop is absent and is not required, put the default value
def fill_default(self):
cls = self.__class__
for prop, entry in cls.properties.items():
if not hasattr(self, prop) and not entry.required:
value = entry.default
setattr(self, prop, value)
def add_string_member(self, member):
add_fun = list.extend if isinstance(member, list) else list.append
if not hasattr(self, "members"):
self.members = []
add_fun(self.members, member)
def add_string_unknown_member(self, member):
add_fun = list.extend if isinstance(member, list) else list.append
if not self.unknown_members:
self.unknown_members = []
add_fun(self.unknown_members, member)
def __str__(self):
return str(self.__dict__) + '\n'
def __iter__(self):
return self.members.__iter__()
def __delitem__(self, i):
try:
self.members.remove(i)
except ValueError:
pass
# a item group is correct if all members actually exists,
# so if unknown_members is still []
def is_correct(self):
res = True
if self.unknown_members:
for m in self.unknown_members:
logger.error("[itemgroup::%s] as %s, got unknown member %s", self.get_name(), self.__class__.my_type, m)
res = False
if self.configuration_errors != []:
for err in self.configuration_errors:
logger.error("[itemgroup] %s", err)
res = False
return res
def has(self, prop):
return hasattr(self, prop)
# Get a brok with hostgroup info (like id, name)
# members is special: list of (id, host_name) for database info
def get_initial_status_brok(self):
cls = self.__class__
data = {}
# Now config properties
for prop, entry in cls.properties.items():
if entry.fill_brok != []:
if self.has(prop):
data[prop] = getattr(self, prop)
# Here members is just a bunch of host, I need name in place
data['members'] = []
for i in self.members:
# it look like lisp! ((( ..))), sorry....
data['members'].append((i.id, i.get_name()))
b = Brok('initial_' + cls.my_type + '_status', data)
return b
class Itemgroups(Items):
# If a prop is absent and is not required, put the default value
def fill_default(self):
for i in self:
i.fill_default()
def add(self, ig):
self.add_item(ig)
def get_members_by_name(self, gname):
g = self.find_by_name(gname)
if g is None:
return []
return getattr(g, 'members', [])
| kaji-project/shinken | shinken/objects/itemgroup.py | Python | agpl-3.0 | 5,862 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012-2013 Elanz (<http://www.openelanz.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
class sale_order(osv.osv):
_inherit = 'sale.order'
def action_button_confirm(self, cr, uid, ids, context=None):
# fetch the partner's id and subscribe the partner to the sale order
assert len(ids) == 1
order = self.browse(cr, uid, ids[0], context=context)
add_delivery_method = True
only_service = True
delivery_method = self.pool.get('delivery.carrier').search(cr, uid, [('default_in_sales', '=', True)])
if delivery_method:
delivery_method = self.pool.get('delivery.carrier').browse(cr, uid, delivery_method[0])
if order.amount_untaxed < delivery_method.min_amount and not order.carrier_id:
if order.partner_id.without_delivery:
add_delivery_method = False
else:
for order_line in order.order_line:
if order_line.product_id:
if order_line.product_id.without_delivery:
add_delivery_method = False
break
elif order_line.product_id.type != 'service':
only_service = False
if only_service:
add_delivery_method = False
if add_delivery_method:
delivery_method = delivery_method.id
self.write(cr, uid, ids[0], {'carrier_id': delivery_method})
return super(sale_order, self).action_button_confirm(cr, uid, ids, context=context) | noemis-fr/old-custom | e3z_add_delivery_method/sale_order.py | Python | agpl-3.0 | 2,622 |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class FieldLevelExplanation(Document):
pass
| gangadharkadam/office_erp | erpnext/projects/doctype/field_level_explanation/field_level_explanation.py | Python | agpl-3.0 | 283 |
'''
This module is part of ngs_backbone. This module provide mapping related
analyses
Created on 15/03/2010
@author: peio
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of franklin.
# franklin is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# franklin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with franklin. If not, see <http://www.gnu.org/licenses/>.
import os, shutil
from gzip import GzipFile
from tempfile import NamedTemporaryFile
from franklin.backbone.analysis import (Analyzer, scrape_info_from_fname,
_LastAnalysisAnalyzer)
from franklin.mapping import map_reads
from franklin.utils.cmd_utils import call
from franklin.utils.misc_utils import (NamedTemporaryDir, VersionedPath,
rel_symlink)
from franklin.backbone.specifications import (BACKBONE_BASENAMES,
PLOT_FILE_FORMAT,
BACKBONE_DIRECTORIES)
from franklin.sam import (bam2sam, add_header_and_tags_to_sam, merge_sam,
sam2bam, sort_bam_sam, standardize_sam, realign_bam,
bam_distribs, create_bam_index, bam_general_stats)
class SetAssemblyAsReferenceAnalyzer(Analyzer):
'It sets the reference assembly as mapping reference'
def run(self):
'''It runs the analysis.'''
contigs_path = self._get_input_fpaths()['contigs']
contigs_ext = contigs_path.extension
reference_dir = self._create_output_dirs()['result']
reference_fpath = os.path.join(reference_dir,
BACKBONE_BASENAMES['mapping_reference'] + '.' + \
contigs_ext)
if os.path.exists(reference_fpath):
os.remove(reference_fpath)
rel_symlink(contigs_path.last_version, reference_fpath)
def _get_basename(fpath):
'It returns the base name without path and extension'
return os.path.splitext(os.path.basename(fpath))[0]
class MappingAnalyzer(Analyzer):
'It performs the mapping of the sequences to the reference'
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
project_settings = self._project_settings
settings = project_settings['Mappers']
tmp_dir = project_settings['General_settings']['tmpdir']
project_path = project_settings['General_settings']['project_path']
unmapped_fhand = None
if 'keep_unmapped_reads_in_bam' in settings:
if settings['keep_unmapped_reads_in_bam'] == False:
unmapped_fpath = os.path.join(project_path,
BACKBONE_DIRECTORIES['mappings'][0],
BACKBONE_BASENAMES['unmapped_list'])
unmapped_fhand = GzipFile(unmapped_fpath, 'w')
inputs = self._get_input_fpaths()
reads_fpaths = inputs['reads']
output_dir = self._create_output_dirs(timestamped=True)['result']
# define color and sequence references
reference_path = inputs['reference']
mapping_index_dir = inputs['mapping_index']
#print reference_path, mapping_index_dir
#memory for the java programs
java_mem = self._project_settings['Other_settings']['java_memory']
picard_path = self._project_settings['Other_settings']['picard_path']
for read_fpath in reads_fpaths:
mapping_parameters = {}
read_info = scrape_info_from_fname(read_fpath)
platform = read_info['pl']
#which maper are we using for this platform
mapper = settings['mapper_for_%s' % platform]
(reference_fpath,
color_space) = self._prepare_mapper_index(mapping_index_dir,
reference_path,
platform, mapper)
mapping_parameters['unmapped_fhand'] = unmapped_fhand
mapping_parameters['colorspace'] = color_space
out_bam_fpath = os.path.join(output_dir,
read_fpath.basename + '.bam')
if platform in ('454', 'sanger'):
mapping_parameters['reads_length'] = 'long'
else:
mapping_parameters['reads_length'] = 'short'
if not os.path.exists(out_bam_fpath):
mapping_parameters['threads'] = self.threads
mapping_parameters['java_conf'] = {'java_memory':java_mem,
'picard_path':picard_path}
mapping_parameters['tmp_dir'] = tmp_dir
map_reads(mapper,
reads_fpath=read_fpath.last_version,
reference_fpath=reference_fpath,
out_bam_fpath=out_bam_fpath,
parameters=mapping_parameters)
# Now we run the select _last mapping
self._spawn_analysis(DEFINITIONS['_select_last_mapping'],
silent=self._silent)
self._log({'analysis_finished':True})
def _prepare_mapper_index(self, mapping_index_dir, reference_path, platform,
mapper):
'It creates reference_fpath depending on the mapper and the platform'
kind = 'color' if platform == 'solid' else 'sequence'
color_space = True if kind == 'color' else False
mapping_index_dir = mapping_index_dir[0].original_path
index_dir = mapping_index_dir % (mapper, kind)
if not os.path.exists(index_dir):
os.mkdir(index_dir)
reference_fpath = reference_path.last_version
reference_fname = os.path.basename(reference_fpath)
index_fpath = os.path.join(index_dir, reference_fname)
if not os.path.exists(index_fpath):
rel_symlink(reference_fpath, index_fpath)
return index_fpath, color_space
class MergeBamAnalyzer(Analyzer):
'It performs the merge of various bams into only one'
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
settings = self._project_settings
project_path = settings['General_settings']['project_path']
tmp_dir = settings['General_settings']['tmpdir']
inputs = self._get_input_fpaths()
bam_paths = inputs['bams']
reference_path = inputs['reference']
output_dir = self._create_output_dirs()['result']
merged_bam_path = VersionedPath(os.path.join(output_dir,
BACKBONE_BASENAMES['merged_bam']))
merged_bam_fpath = merged_bam_path.next_version
#Do we have to add the default qualities to the sam file?
#do we have characters different from ACTGN?
add_qualities = settings['Sam_processing']['add_default_qualities']
#memory for the java programs
java_mem = settings['Other_settings']['java_memory']
picard_path = settings['Other_settings']['picard_path']
if add_qualities:
default_sanger_quality = settings['Other_settings']['default_sanger_quality']
default_sanger_quality = int(default_sanger_quality)
else:
default_sanger_quality = None
temp_dir = NamedTemporaryDir()
for bam_path in bam_paths:
bam_basename = bam_path.basename
temp_sam = NamedTemporaryFile(prefix='%s.' % bam_basename,
suffix='.sam')
sam_fpath = os.path.join(temp_dir.name, bam_basename + '.sam')
bam2sam(bam_path.last_version, temp_sam.name)
sam_fhand = open(sam_fpath, 'w')
# First we need to create the sam with added tags and headers
add_header_and_tags_to_sam(temp_sam, sam_fhand)
temp_sam.close()
sam_fhand.close()
#the standardization
temp_sam2 = NamedTemporaryFile(prefix='%s.' % bam_basename,
suffix='.sam', delete=False)
standardize_sam(open(sam_fhand.name), temp_sam2,
default_sanger_quality,
add_def_qual=add_qualities,
only_std_char=True)
temp_sam2.flush()
shutil.move(temp_sam2.name, sam_fhand.name)
temp_sam2.close()
get_sam_fpaths = lambda dir_: [os.path.join(dir_, fname) for fname in os.listdir(dir_) if fname.endswith('.sam')]
# Once the headers are ready we are going to merge
sams = get_sam_fpaths(temp_dir.name)
sams = [open(sam) for sam in sams]
temp_sam = NamedTemporaryFile(suffix='.sam')
reference_fhand = open(reference_path.last_version)
try:
merge_sam(sams, temp_sam, reference_fhand)
except Exception:
if os.path.exists(merged_bam_fpath):
os.remove(merged_bam_fpath)
raise
reference_fhand.close()
# close files
for sam in sams:
sam.close()
# Convert sam into a bam,(Temporary)
temp_bam = NamedTemporaryFile(suffix='.bam')
sam2bam(temp_sam.name, temp_bam.name)
# finally we need to order the bam
#print 'unsorted.bam', temp_bam.name
#raw_input()
sort_bam_sam(temp_bam.name, merged_bam_fpath,
java_conf={'java_memory':java_mem,
'picard_path':picard_path}, tmp_dir=tmp_dir )
temp_bam.close()
temp_sam.close()
create_bam_index(merged_bam_fpath)
self._log({'analysis_finished':True})
class CalmdBamAnalyzer(Analyzer):
'It runs samtools calmd '
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
inputs = self._get_input_fpaths()
bam_path = inputs['bam']
bam_fpath = bam_path.last_version
reference_fpath = inputs['reference'].last_version
out_fhand = open(bam_path.next_version, 'w')
cmd = ['samtools', 'calmd', '-Abr', bam_fpath, reference_fpath]
call(cmd, raise_on_error=True, stdout=out_fhand)
create_bam_index(out_fhand.name)
out_fhand.close()
self._log({'analysis_finished':True})
class RealignBamAnalyzer(Analyzer):
'It realigns the bam using GATK'
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
settings = self._project_settings
project_path = settings['General_settings']['project_path']
tmp_dir = settings['General_settings']['tmpdir']
inputs = self._get_input_fpaths()
bam_path = inputs['bam']
bam_fpath = bam_path.last_version
reference_path = inputs['reference']
#memory for the java programs
osettings = settings['Other_settings']
java_mem = osettings['java_memory']
picard_path = osettings['picard_path']
gatk_path = osettings['gatk_path']
#we need a temporary path
temp_bam = NamedTemporaryFile(suffix='.bam')
temp_bam_fpath = temp_bam.name
temp_bam.close()
#do the realigment
realign_bam(bam_fpath=bam_fpath,
reference_fpath=reference_path.last_version,
out_bam_fpath=temp_bam_fpath,
java_conf={'java_memory':java_mem,
'picard_path':picard_path,
'gatk_path':gatk_path},
threads=self.threads,
tmp_dir=tmp_dir)
#a new version for the original bam
out_bam_fpath = bam_path.next_version
shutil.move(temp_bam_fpath, out_bam_fpath)
self._log({'analysis_finished':True})
class BamStatsAnalyzer(Analyzer):
'It makes the stats of the mapping'
def run(self):
'''It runs the analysis.'''
self._log({'analysis_started':True})
settings = self._project_settings
self._create_output_dirs()['result']
project_name = settings['General_settings']['project_name']
sample_size = settings['Sam_stats']['sampling_size']
project_path = settings['General_settings']['project_path']
inputs = self._get_input_fpaths()
bam_path = inputs['bam']
bam_fpath = bam_path.last_version
bam_fhand = open(bam_fpath)
out_dir = os.path.abspath(self._get_output_dirs()['result'])
summary_fname = os.path.join(out_dir,
BACKBONE_BASENAMES['statistics_file'])
summary_fhand = open(summary_fname, 'w')
# non mapped_reads_fhand
unmapped_fpath = os.path.join(project_path,
BACKBONE_DIRECTORIES['mappings'][0],
BACKBONE_BASENAMES['unmapped_list'])
if os.path.exists(unmapped_fpath):
unmapped_fhand = GzipFile(unmapped_fpath)
else:
unmapped_fhand = None
#The general statistics
bam_general_stats(bam_fhand, summary_fhand, unmapped_fhand)
for kind in ('coverage', 'mapq'):
basename = os.path.join(out_dir, "%s" % (project_name))
bam_fhand.seek(0)
bam_distribs(bam_fhand, kind, basename=basename,
sample_size=sample_size, summary_fhand=summary_fhand,
plot_file_format=PLOT_FILE_FORMAT)
bam_fhand.close()
if unmapped_fhand is not None:
unmapped_fhand.close()
DEFINITIONS = {
'set_assembly_as_reference':
{'inputs':{
'contigs':
{'directory': 'assembly_result',
'file': 'contigs'},
},
'outputs':{'result':{'directory': 'mapping_reference'}},
'analyzer': SetAssemblyAsReferenceAnalyzer,
},
'mapping':
{'inputs':{
'reads':
{'directory': 'cleaned_reads',
'file_kinds': 'sequence_files'},
'reference':
{'directory': 'mapping_reference',
'file': 'mapping_reference'},
'mapping_index':
{'directory': 'mapping_index'},
},
'outputs':{'result':{'directory': 'mappings_by_readgroup'}},
'analyzer': MappingAnalyzer,
},
'_select_last_mapping':
{'inputs':{'analyses_dir':{'directory': 'mappings'}},
'outputs':{'result':{'directory': 'mapping_result',
'create':False}},
'analyzer': _LastAnalysisAnalyzer,
},
'merge_bams':
{'inputs':{
'bams':
{'directory': 'mappings_by_readgroup',
'file_kinds': 'bam'},
'reference':
{'directory': 'mapping_reference',
'file': 'mapping_reference'},
},
'outputs':{'result':{'directory': 'mapping_result'}},
'analyzer': MergeBamAnalyzer,
},
'realign_bam':
{'inputs':{
'bam':
{'directory': 'mapping_result',
'file': 'merged_bam'},
'reference':
{'directory': 'mapping_reference',
'file': 'mapping_reference'},
},
'outputs':{'result':{'directory': 'mapping_result'}},
'analyzer': RealignBamAnalyzer,
},
'calmd_bam':
{'inputs':{
'bam':
{'directory': 'mapping_result',
'file': 'merged_bam'},
'reference':
{'directory': 'mapping_reference',
'file': 'mapping_reference'},
},
'outputs':{'result':{'directory': 'mapping_result'}},
'analyzer': CalmdBamAnalyzer,
},
'mapping_stats':
{'inputs':{
'bam':
{'directory': 'mapping_result',
'file': 'merged_bam'},
},
'outputs':{'result':{'directory': 'mapping_stats'}},
'analyzer': BamStatsAnalyzer,
},
}
| JoseBlanca/franklin | franklin/backbone/mapping.py | Python | agpl-3.0 | 16,787 |
from odoo import models, fields, api, _
# import odoo.tools as tools
try:
from pyafipws.iibb import IIBB
except ImportError:
IIBB = None
# from pyafipws.padron import PadronAFIP
from odoo.exceptions import UserError
import logging
import json
import requests
# from dateutil.relativedelta import relativedelta
_logger = logging.getLogger(__name__)
class ResCompany(models.Model):
_inherit = "res.company"
regimenes_ganancias_ids = fields.Many2many(
'afip.tabla_ganancias.alicuotasymontos',
'res_company_tabla_ganancias_rel',
'company_id', 'regimen_id',
'Regimenes Ganancia',
)
agip_padron_type = fields.Selection([
('regimenes_generales', 'Regímenes Generales')],
string='Padron AGIP',
default='regimenes_generales',
)
agip_alicuota_no_sincripto_retencion = fields.Float(
'Agip: Alicuota no inscripto retención',
)
agip_alicuota_no_sincripto_percepcion = fields.Float(
'Agip: Alicuota no inscripto percepción',
)
arba_alicuota_no_sincripto_retencion = fields.Float(
'Arba: Alicuota no inscripto retención',
)
arba_alicuota_no_sincripto_percepcion = fields.Float(
'Arba: Alicuota no inscripto percepción',
)
cdba_alicuota_no_sincripto_retencion = fields.Float(
'Rentas Córdoba: Alícuota no inscripto retención'
)
cdba_alicuota_no_sincripto_percepcion = fields.Float(
'Rentas Córdoba: Alícuota no inscripto percepción'
)
def _localization_use_withholdings(self):
""" Argentinian localization use documents """
self.ensure_one()
return True if self.country_id == self.env.ref('base.ar') else super()._localization_use_withholdings()
@api.model
def _get_arba_environment_type(self):
"""
Function to define homologation/production environment
First it search for a paramter "arba.ws.env.type" if exists and:
* is production --> production
* is homologation --> homologation
Else
Search for 'server_mode' parameter on conf file. If that parameter is:
* 'test' or 'develop' --> homologation
* other or no parameter --> production
"""
# como no se dispone de claves de homologacion usamos produccion
# siempre
environment_type = 'production'
# parameter_env_type = self.env[
# 'ir.config_parameter'].sudo().get_param('arba.ws.env.type')
# if parameter_env_type == 'production':
# environment_type = 'production'
# elif parameter_env_type == 'homologation':
# environment_type = 'homologation'
# else:
# server_mode = tools.config.get('server_mode')
# if not server_mode or server_mode == 'production':
# environment_type = 'production'
# else:
# environment_type = 'homologation'
# _logger.info(
# 'Running arba WS on %s mode' % environment_type)
return environment_type
@api.model
def get_arba_login_url(self, environment_type):
if environment_type == 'production':
arba_login_url = (
'https://dfe.arba.gov.ar/DomicilioElectronico/'
'SeguridadCliente/dfeServicioConsulta.do')
else:
arba_login_url = (
'https://dfe.test.arba.gov.ar/DomicilioElectronico'
'/SeguridadCliente/dfeServicioConsulta.do')
return arba_login_url
def arba_connect(self):
"""
Method to be called
"""
self.ensure_one()
cuit = self.partner_id.cuit_required()
if not self.arba_cit:
raise UserError(_(
'You must configure ARBA CIT on company %s') % (
self.name))
ws = IIBB()
environment_type = self._get_arba_environment_type()
_logger.info(
'Getting connection to ARBA on %s mode' % environment_type)
# argumentos de conectar: self, url=None, proxy="",
# wrapper=None, cacert=None, trace=False, testing=""
arba_url = self.get_arba_login_url(environment_type)
ws.Usuario = cuit
ws.Password = self.arba_cit
ws.Conectar(url=arba_url)
_logger.info(
'Connection getted to ARBA with url "%s" and CUIT %s' % (
arba_url, cuit))
return ws
def get_agip_data(self, partner, date):
raise UserError(_(
'Falta configuración de credenciales de ADHOC para consulta de '
'Alícuotas de AGIP'))
def get_arba_data(self, partner, from_date, to_date):
self.ensure_one()
# from_date = date + relativedelta(day=1).strftime('%Y%m%d')
# to_date = date + relativedelta(
# day=1, days=-1, months=+1).strftime('%Y%m%d')
cuit = partner.cuit_required()
_logger.info(
'Getting ARBA data for cuit %s from date %s to date %s' % (
from_date, to_date, cuit))
ws = self.arba_connect()
ws.ConsultarContribuyentes(
from_date,
to_date,
cuit)
if ws.Excepcion:
raise UserError("%s\nExcepcion: %s" % (
ws.Traceback, ws.Excepcion))
# ' Hubo error general de ARBA?
if ws.CodigoError:
if ws.CodigoError == '11':
# we still create the record so we don need to check it again
# on same period
_logger.info('CUIT %s not present on padron ARBA' % cuit)
else:
raise UserError("%s\nError %s: %s" % (
ws.MensajeError, ws.TipoError, ws.CodigoError))
# no ponemos esto, si no viene alicuota es porque es cero entonces
# if not ws.AlicuotaRetencion or not ws.AlicuotaPercepcion:
# raise UserError('No pudimos obtener la AlicuotaRetencion')
# ' Datos generales de la respuesta:'
data = {
'numero_comprobante': ws.NumeroComprobante,
'codigo_hash': ws.CodigoHash,
# 'CuitContribuyente': ws.CuitContribuyente,
'alicuota_percepcion': ws.AlicuotaPercepcion and float(
ws.AlicuotaPercepcion.replace(',', '.')),
'alicuota_retencion': ws.AlicuotaRetencion and float(
ws.AlicuotaRetencion.replace(',', '.')),
'grupo_percepcion': ws.GrupoPercepcion,
'grupo_retencion': ws.GrupoRetencion,
'from_date': from_date,
'to_date': to_date,
}
_logger.info('We get the following data: \n%s' % data)
return data
def get_cordoba_data(self, partner, date):
""" Obtener alícuotas desde app.rentascordoba.gob.ar
:param partner: El partner sobre el cual trabajamos
:param date: La fecha del comprobante
:param from_date: Fecha de inicio de validez de alícuota por defecto
:param to_date: Fecha de fin de validez de alícuota por defecto
Devuelve diccionario de datos
"""
_logger.info('Getting withholding data from rentascordoba.gob.ar')
date_date = fields.Date.from_string(date)
# Establecer parámetros de solicitud
url = "https://app.rentascordoba.gob.ar/rentas/rest/svcGetAlicuotas"
payload = {'body': partner.main_id_number}
headers = {'content-type': 'application/json'}
# Realizar solicitud
r = requests.post(url, data=json.dumps(payload), headers=headers)
json_body = r.json()
if r.status_code != 200:
raise UserError('Error al contactar rentascordoba.gob.ar. '
'El servidor respondió: \n\n%s' % json_body)
code = json_body.get("errorCod")
# Capturar Códigos de Error.
# 3 => No Inscripto, 2 => No pasible, 1 => CUIT incorrecta, 0 => OK
if code == 3:
alicuota_percepcion = self.cdba_alicuota_no_sincripto_percepcion
alicuota_retencion = self.cdba_alicuota_no_sincripto_retencion
elif code == 2:
alicuota_percepcion = 0.0
alicuota_retencion = 0.0
elif code != 0:
raise UserError(json_body.get("message"))
else:
dict_alic = json_body.get("sdtConsultaAlicuotas")
alicuota_percepcion = float(dict_alic.get("CRD_ALICUOTA_PER"))
alicuota_retencion = float(dict_alic.get("CRD_ALICUOTA_RET"))
# Verificar que el comprobante tenga fecha dentro de la vigencia
from_date_date = fields.Date.from_string(dict_alic.get("CRD_FECHA_INICIO"))
to_date_date = fields.Date.from_string(dict_alic.get("CRD_FECHA_FIN"))
if not (from_date_date <= date_date < to_date_date):
raise UserError(
'No se puede obtener automáticamente la alicuota para la '
'fecha %s. Por favor, ingrese la misma manualmente '
'en el partner.' % date)
data = {
'alicuota_percepcion': alicuota_percepcion,
'alicuota_retencion': alicuota_retencion,
}
_logger.info("We've got the following data: \n%s" % data)
return data
| adhoc-dev/odoo-argentina | l10n_ar_account_withholding/models/res_company.py | Python | agpl-3.0 | 9,290 |
"""
Tests for the recently enrolled messaging within the Dashboard.
"""
import datetime
import unittest
import ddt
from django.conf import settings
from django.urls import reverse
from django.utils.timezone import now
from opaque_keys.edx import locator
from pytz import UTC
from six.moves import range, zip
from common.test.utils import XssTestMixin
from course_modes.tests.factories import CourseModeFactory
from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration_context
from student.models import CourseEnrollment, DashboardConfiguration
from student.tests.factories import UserFactory
from student.views import get_course_enrollments
from student.views.dashboard import _get_recently_enrolled_courses
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
@ddt.ddt
class TestRecentEnrollments(ModuleStoreTestCase, XssTestMixin):
"""
Unit tests for getting the list of courses for a logged in user
"""
PASSWORD = 'test'
def setUp(self):
"""
Add a student
"""
super(TestRecentEnrollments, self).setUp()
self.student = UserFactory()
self.student.set_password(self.PASSWORD)
self.student.save()
# Old Course
old_course_location = locator.CourseLocator('Org0', 'Course0', 'Run0')
__, enrollment = self._create_course_and_enrollment(old_course_location)
enrollment.created = datetime.datetime(1900, 12, 31, 0, 0, 0, 0, tzinfo=UTC)
enrollment.save()
# New Course
course_location = locator.CourseLocator('Org1', 'Course1', 'Run1')
self.course, self.enrollment = self._create_course_and_enrollment(course_location)
def _create_course_and_enrollment(self, course_location):
""" Creates a course and associated enrollment. """
course = CourseFactory.create(
org=course_location.org,
number=course_location.course,
run=course_location.run
)
enrollment = CourseEnrollment.enroll(self.student, course.id)
return course, enrollment
def _configure_message_timeout(self, timeout):
"""Configure the amount of time the enrollment message will be displayed. """
config = DashboardConfiguration(recent_enrollment_time_delta=timeout)
config.save()
def test_recently_enrolled_courses(self):
"""
Test if the function for filtering recent enrollments works appropriately.
"""
self._configure_message_timeout(60)
# get courses through iterating all courses
courses_list = list(get_course_enrollments(self.student, None, []))
self.assertEqual(len(courses_list), 2)
recent_course_list = _get_recently_enrolled_courses(courses_list)
self.assertEqual(len(recent_course_list), 1)
def test_zero_second_delta(self):
"""
Tests that the recent enrollment list is empty if configured to zero seconds.
"""
self._configure_message_timeout(0)
courses_list = list(get_course_enrollments(self.student, None, []))
self.assertEqual(len(courses_list), 2)
recent_course_list = _get_recently_enrolled_courses(courses_list)
self.assertEqual(len(recent_course_list), 0)
def test_enrollments_sorted_most_recent(self):
"""
Test that the list of newly created courses are properly sorted to show the most
recent enrollments first.
Also test recent enrollment message rendered appropriately for more than two courses.
"""
self._configure_message_timeout(600)
# Create a number of new enrollments and courses, and force their creation behind
# the first enrollment
courses = []
for idx, seconds_past in zip(list(range(2, 6)), [5, 10, 15, 20]):
course_location = locator.CourseLocator(
'Org{num}'.format(num=idx),
'Course{num}'.format(num=idx),
'Run{num}'.format(num=idx)
)
course, enrollment = self._create_course_and_enrollment(course_location)
enrollment.created = now() - datetime.timedelta(seconds=seconds_past)
enrollment.save()
courses.append(course)
courses_list = list(get_course_enrollments(self.student, None, []))
self.assertEqual(len(courses_list), 6)
recent_course_list = _get_recently_enrolled_courses(courses_list)
self.assertEqual(len(recent_course_list), 5)
self.assertEqual(recent_course_list[1].course.id, courses[0].id)
self.assertEqual(recent_course_list[2].course.id, courses[1].id)
self.assertEqual(recent_course_list[3].course.id, courses[2].id)
self.assertEqual(recent_course_list[4].course.id, courses[3].id)
self.client.login(username=self.student.username, password=self.PASSWORD)
response = self.client.get(reverse("dashboard"))
# verify recent enrollment message
self.assertContains(
response,
'Thank you for enrolling in:'.format(course_name=self.course.display_name)
)
self.assertContains(
response,
', '.join(enrollment.course.display_name for enrollment in recent_course_list)
)
def test_dashboard_rendering_with_single_course(self):
"""
Tests that the dashboard renders the recent enrollment message appropriately for single course.
"""
self._configure_message_timeout(600)
self.client.login(username=self.student.username, password=self.PASSWORD)
response = self.client.get(reverse("dashboard"))
self.assertContains(
response,
"Thank you for enrolling in {course_name}".format(course_name=self.course.display_name)
)
def test_dashboard_rendering_with_two_courses(self):
"""
Tests that the dashboard renders the recent enrollment message appropriately for two courses.
"""
self._configure_message_timeout(600)
course_location = locator.CourseLocator(
'Org2',
'Course2',
'Run2'
)
course, _ = self._create_course_and_enrollment(course_location)
self.client.login(username=self.student.username, password=self.PASSWORD)
response = self.client.get(reverse("dashboard"))
courses_enrollments = list(get_course_enrollments(self.student, None, []))
courses_enrollments.sort(key=lambda x: x.created, reverse=True)
self.assertEqual(len(courses_enrollments), 3)
recent_course_enrollments = _get_recently_enrolled_courses(courses_enrollments)
self.assertEqual(len(recent_course_enrollments), 2)
self.assertContains(
response,
"Thank you for enrolling in:".format(course_name=self.course.display_name)
)
self.assertContains(
response,
' and '.join(enrollment.course.display_name for enrollment in recent_course_enrollments)
)
def test_dashboard_escaped_rendering(self):
"""
Tests that the dashboard renders the escaped recent enrollment messages appropriately.
"""
self._configure_message_timeout(600)
self.client.login(username=self.student.username, password=self.PASSWORD)
# New Course
course_location = locator.CourseLocator('TestOrg', 'TestCourse', 'TestRun')
xss_content = "<script>alert('XSS')</script>"
course = CourseFactory.create(
org=course_location.org,
number=course_location.course,
run=course_location.run,
display_name=xss_content
)
CourseEnrollment.enroll(self.student, course.id)
response = self.client.get(reverse("dashboard"))
self.assertContains(response, "Thank you for enrolling in")
# Check if response is escaped
self.assert_no_xss(response, xss_content)
| msegado/edx-platform | common/djangoapps/student/tests/test_recent_enrollments.py | Python | agpl-3.0 | 8,149 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('commerce', '0008_auto_20150110_2000'),
]
operations = [
migrations.AlterField(
model_name='order',
name='invoicing_address',
field=models.ForeignKey(related_name='order_invoicing_address', verbose_name=b'Adresse de facturation', to='commerce.Address'),
preserve_default=True,
),
migrations.AlterField(
model_name='order',
name='shipping_address',
field=models.ForeignKey(related_name='order_shipping_address', verbose_name=b'Adresse de livraison', to='commerce.Address'),
preserve_default=True,
),
migrations.AlterField(
model_name='orderdetail',
name='order',
field=models.ForeignKey(verbose_name=b'Commande associ\xc3\xa9e', to='commerce.Order'),
preserve_default=True,
),
migrations.AlterField(
model_name='products',
name='category',
field=models.ForeignKey(verbose_name=b'Cat\xc3\xa9gorie du produit', to='commerce.Category'),
preserve_default=True,
),
migrations.AlterField(
model_name='products',
name='vat',
field=models.ForeignKey(verbose_name=b'Taux de TVA', to='commerce.VAT'),
preserve_default=True,
),
]
| jtraulle/django-ecommerce | commerce/migrations/0009_auto_20150110_2012.py | Python | agpl-3.0 | 1,529 |
# -*- coding: utf-8 -*-
# Copyright 2017 Ainara Galdona - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Account Invoice Merge Stock Picking",
"version": "8.0.1.0.0",
"license": "AGPL-3",
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"contributors": [
"Ainara Galdona <ainaragaldona@avanzosc.es>",
],
"category": "Accounting & Finance",
"depends": [
"account_invoice_merge",
"stock_picking_invoice_link"
],
"data": [
],
"installable": True,
"autoinstall": True,
}
| Daniel-CA/odoo-addons | account_invoice_merge_stock_picking/__openerp__.py | Python | agpl-3.0 | 596 |
"""
Various caching help functions and classes.
"""
from django.core.cache import cache
DEFAULT_CACHE_DELAY = 60 * 60 # Default cache delay is 1hour. It's quite long.
USERACCOUNT_CACHE_DELAY = 60 * 3 # 3 minutes here. This is used to know if a user is online or not.
class _AbstractCache(object):
"""
Abstract cache management class.
A cache class manages data about a whole population.
It is instanciated with a specific instance of this cache object.
"""
delay = DEFAULT_CACHE_DELAY
def __init__(self, key_prefix):
"""
We store the key prefix for easy values retrieval
"""
# Save key profile AND save an empty cache value to use as an optional global timeout
self.key_prefix = key_prefix
def _get(self, attr, default = None):
"""
Return attr from the cache or default value
"""
return cache.get("%s#%s" % (self.key_prefix, attr), default)
def _set(self, attr, value):
cache.set("%s#%s" % (self.key_prefix, attr), value, self.delay)
class UserAccountCache(_AbstractCache):
delay = USERACCOUNT_CACHE_DELAY
def __init__(self, useraccount_or_id):
"""
Instanciate a cache from given user (or userid)
"""
# Instanciate cache
from twistranet.twistapp import Twistable
if isinstance(useraccount_or_id, Twistable):
useraccount_or_id = useraccount_or_id.id
super(UserAccountCache, self).__init__("UA%d" % useraccount_or_id)
# Online information
def get_online(self): return self._get("online", False)
def set_online(self, v): return self._set("online", v)
online = property(get_online, set_online)
| numericube/twistranet | twistranet/core/caches.py | Python | agpl-3.0 | 1,772 |
import pytest
from django.urls import reverse
from adhocracy4.modules.models import Module
from adhocracy4.test.helpers import redirect_target
@pytest.mark.django_db
def test_module_delete_perms(client, phase, user, user2):
module = phase.module
module_delete_url = reverse('a4dashboard:module-delete', kwargs={
'slug': module.slug})
response = client.post(module_delete_url)
assert redirect_target(response) == 'account_login'
client.login(username=user, password='password')
response = client.post(module_delete_url)
assert response.status_code == 403
organisation = module.project.organisation
organisation.initiators.add(user2)
client.login(username=user2, password='password')
response = client.post(module_delete_url)
assert redirect_target(response) == 'project-edit'
@pytest.mark.django_db
def test_module_delete(client, phase, user2):
module = phase.module
module.is_draft = False
module.save()
organisation = module.project.organisation
organisation.initiators.add(user2)
assert Module.objects.all().count() == 1
module_delete_url = reverse('a4dashboard:module-delete', kwargs={
'slug': module.slug})
# deleting published modules has no effect
client.login(username=user2, password='password')
response = client.post(module_delete_url)
assert response.status_code == 302
assert Module.objects.all().count() == 1
# unpublish module
module.is_draft = True
module.save()
client.login(username=user2, password='password')
response = client.post(module_delete_url)
assert redirect_target(response) == 'project-edit'
assert Module.objects.all().count() == 0
@pytest.mark.django_db
def test_module_delete_redirect(client, module_factory, user2):
module = module_factory(is_draft=True)
organisation = module.project.organisation
organisation.initiators.add(user2)
module_2 = module_factory(project=module.project, is_draft=True)
module_3 = module_factory(project=module.project, is_draft=True)
module_delete_url = reverse('a4dashboard:module-delete', kwargs={
'slug': module.slug})
module_delete_url_2 = reverse('a4dashboard:module-delete', kwargs={
'slug': module_2.slug})
module_delete_url_3 = reverse('a4dashboard:module-delete', kwargs={
'slug': module_3.slug})
client.login(username=user2, password='password')
referrer = reverse('a4dashboard:dashboard-information-edit', kwargs={
'project_slug': module.project.slug})
response = client.post(module_delete_url, {'referrer': referrer})
assert response.status_code == 302
assert response['location'] == referrer
response = client.post(module_delete_url_2, {}, HTTP_REFERER=referrer)
assert response.status_code == 302
assert response['location'] == referrer
response = client.post(module_delete_url_3, {})
assert redirect_target(response) == 'project-edit'
@pytest.mark.django_db
def test_module_unsuccessful_delete_redirect(client, module_factory, user2):
module = module_factory(is_draft=False)
organisation = module.project.organisation
organisation.initiators.add(user2)
module_delete_url = reverse('a4dashboard:module-delete', kwargs={
'slug': module.slug})
client.login(username=user2, password='password')
referrer = reverse('a4dashboard:dashboard-information-edit', kwargs={
'project_slug': module.project.slug})
response = client.post(module_delete_url, {'referrer': referrer})
assert response.status_code == 302
assert response['location'] == referrer
response = client.post(module_delete_url, {}, HTTP_REFERER=referrer)
assert response.status_code == 302
assert response['location'] == referrer
response = client.post(module_delete_url, {})
assert redirect_target(response) == 'project-edit'
| liqd/a4-meinberlin | tests/dashboard/test_dashboard_views_module_delete.py | Python | agpl-3.0 | 3,903 |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class RAffyio(RPackage):
"""Routines for parsing Affymetrix data files based upon file format
information. Primary focus is on accessing the CEL and CDF file
formats."""
homepage = "https://bioconductor.org/packages/affyio/"
url = "https://bioconductor.org/packages/3.5/bioc/src/contrib/affyio_1.46.0.tar.gz"
version('1.46.0', 'e1f7a89ae16940aa29b998a4dbdc0ef9')
depends_on('r-zlibbioc', type=('build', 'run'))
depends_on('r@3.4.0:3.4.9', when='@1.46.0')
| lgarren/spack | var/spack/repos/builtin/packages/r-affyio/package.py | Python | lgpl-2.1 | 1,756 |
#!/usr/bin/python
from distutils.core import setup, Extension, extension_keywords
#print extension_keywords
module1 = Extension('krui',
sources = ['snns/krui.c'],
include_dirs = ['../kernel/sources'],
library_dirs = ['../kernel/sources'],
libraries = ['kernel','func','fl'])
setup (name = 'snns-kernel',
ext_package='snns',
version = '0.1',
author='Patrick Kursawe',
author_email='Patrick.Kursawe@web.de',
description = 'SNNS kernel functions',
packages = ['snns'],
ext_modules = [module1],
py_modules = ['snns.util'])
| mwri/snns | python/setup.py | Python | lgpl-2.1 | 618 |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import os
import re
import llnl.util.tty as tty
from llnl.util.lang import pretty_date
from llnl.util.filesystem import working_dir
from llnl.util.tty.colify import colify_table
import spack
from spack.util.executable import which
from spack.cmd import spack_is_git_repo
description = "show contributors to packages"
section = "developer"
level = "long"
def setup_parser(subparser):
view_group = subparser.add_mutually_exclusive_group()
view_group.add_argument(
'-t', '--time', dest='view', action='store_const', const='time',
default='time', help='sort by last modification date (default)')
view_group.add_argument(
'-p', '--percent', dest='view', action='store_const', const='percent',
help='sort by percent of code')
view_group.add_argument(
'-g', '--git', dest='view', action='store_const', const='git',
help='show git blame output instead of summary')
subparser.add_argument(
'package_name', help='name of package to show contributions for, '
'or path to a file in the spack repo')
def blame(parser, args):
# make sure this is a git repo
if not spack_is_git_repo():
tty.die("This spack is not a git clone. Can't use 'spack blame'")
git = which('git', required=True)
# Get name of file to blame
blame_file = None
if os.path.isfile(args.package_name):
path = os.path.realpath(args.package_name)
if path.startswith(spack.prefix):
blame_file = path
if not blame_file:
pkg = spack.repo.get(args.package_name)
blame_file = pkg.module.__file__.rstrip('c') # .pyc -> .py
# get git blame for the package
with working_dir(spack.prefix):
if args.view == 'git':
git('blame', blame_file)
return
else:
output = git('blame', '--line-porcelain', blame_file, output=str)
lines = output.split('\n')
# Histogram authors
counts = {}
emails = {}
last_mod = {}
total_lines = 0
for line in lines:
match = re.match(r'^author (.*)', line)
if match:
author = match.group(1)
match = re.match(r'^author-mail (.*)', line)
if match:
email = match.group(1)
match = re.match(r'^author-time (.*)', line)
if match:
mod = int(match.group(1))
last_mod[author] = max(last_mod.setdefault(author, 0), mod)
# ignore comments
if re.match(r'^\t[^#]', line):
counts[author] = counts.setdefault(author, 0) + 1
emails.setdefault(author, email)
total_lines += 1
if args.view == 'time':
rows = sorted(
counts.items(), key=lambda t: last_mod[t[0]], reverse=True)
else: # args.view == 'percent'
rows = sorted(counts.items(), key=lambda t: t[1], reverse=True)
# Print a nice table with authors and emails
table = [['LAST_COMMIT', 'LINES', '%', 'AUTHOR', 'EMAIL']]
for author, nlines in rows:
table += [[
pretty_date(last_mod[author]),
nlines,
round(nlines / float(total_lines) * 100, 1),
author,
emails[author]]]
table += [[''] * 5]
table += [[pretty_date(max(last_mod.values())), total_lines, '100.0'] +
[''] * 3]
colify_table(table)
| skosukhin/spack | lib/spack/spack/cmd/blame.py | Python | lgpl-2.1 | 4,597 |
import re
import sjconfparts.exceptions
class Error(sjconfparts.exceptions.Error):
pass
class ConversionError(Error):
pass
class ConversionList:
"""Custom list implementation, linked to the related Conf.
Each modification of the list will auto-update the string representation
of the list directly in the Conf object, via a call to
self.conversion_method().
Nowadays this is considered ugly (maybe it wasn't back in 2008 with Python 2.5?),
but no one wants nor has time to redevelop a big part of SJConf to get rid of this.
(aka don't blame the current dev who just wants to port this mess to Python3 :-p)
Starting from Python3/new style classes, all used special methods must be
explicitly redefined:
https://docs.python.org/3/reference/datamodel.html#special-lookup
"""
def __add__(self, other):
self.innerList.__add__(other)
self.conversion_method()
def __init__(self, conversion_method, list_object=None):
self.conversion_method = conversion_method
if list_object == None:
list_object = []
self.innerList = list_object
def __contains__(self, item):
return self.innerList.__contains__(item)
def __delitem__(self, key):
self.innerList.__delitem__(key)
self.conversion_method()
def __getitem__(self, key):
self.innerList.__getitem__(key)
def __iadd__(self, other):
self.innerList.__iadd__(other)
self.conversion_method()
def __imul__(self, other):
self.innerList.__imul__(other)
self.conversion_method()
def __iter__(self):
return self.innerList.__iter__()
def __len__(self):
return self.innerList.__len__()
def __mul__(self, other):
self.innerList.__mul__(other)
self.conversion_method()
def __reversed__(self, other):
self.innerList.__reversed__(other)
self.conversion_method()
def __rmul__(self, other):
self.innerList.__rmul__(other)
self.conversion_method()
def __setitem__(self, key, value):
self.innerList.__setitem__(key, value)
self.conversion_method()
def __str__(self):
return self.innerList.__str__()
def __getattr__(self, name):
list_method = getattr(self.innerList, name)
def method(*args, **kw):
result = list_method(*args, **kw)
if name in (
"append",
"extend",
"insert",
"pop",
"remove",
"reverse",
"sort",
):
self.conversion_method()
return result
return method
class Type:
class ConversionBadTypeError(ConversionError):
def __init__(self, type_source, type_dest):
self.msg = "Invalid conversion from type %s to type %s, can only convert from str or to str"
@classmethod
def convert(cls, type_source, type_dest, dict_source, dict_dest, key):
if type_source == "str":
type_class_name = type_dest.capitalize()
elif type_dest == "str":
type_class_name = type_source.capitalize()
else:
raise Type.ConversionBadTypeError(type_source, type_dest)
type_class = getattr(cls, type_class_name)
return getattr(type_class, type_source + "_to_" + type_dest)(
dict_source, dict_dest, key
)
@classmethod
def convert_safe(cls, type_source, type_dest, dict_source, dict_dest, key):
if type_source == "str":
type_class_name = type_dest.capitalize()
elif type_dest == "str":
type_class_name = type_source.capitalize()
else:
raise Type.ConversionBadTypeError(type_source, type_dest)
type_class = getattr(cls, type_class_name)
if hasattr(type_class, type_source + "_to_" + type_dest + "_safe"):
return getattr(type_class, type_source + "_to_" + type_dest + "_safe")(
dict_source, dict_dest, key
)
else:
return getattr(type_class, type_source + "_to_" + type_dest)(
dict_source, dict_dest, key
)
@classmethod
def convert_key(cls, key, type):
return cls._convert_method("key", key, type)
@classmethod
def convert_value(cls, value, type, dict_str, dict_type, key):
return cls._convert_method("value", value, type, dict_str, dict_type, key)
@classmethod
def convert_key_for_search(cls, key, type):
return cls._convert_method("key_for_search", key, type)
@classmethod
def _convert_method(cls, method, value, type, *args):
type_class = getattr(cls, type.capitalize())
if not hasattr(type_class, method):
converted_value = value
else:
converted_value = getattr(type_class, method)(value, *args)
return converted_value
class List:
@classmethod
def value(cls, value, dict_str, dict_type, key):
def conversion_method():
Type.List.list_to_str(dict_type, dict_str, key)
return ConversionList(conversion_method, value)
@classmethod
def str_to_list(cls, dict_source, dict_dest, key):
def conversion_method():
Type.List.list_to_str(dict_dest, dict_source, key)
str_object = dict_source[key]
li = list(map(str.strip, str_object.split(",")))
try:
li.remove("")
except ValueError:
pass
dict_dest[key] = ConversionList(conversion_method, li)
return dict_dest
@classmethod
def str_to_list_safe(cls, dict_source, dict_dest, key):
str_object = dict_source[key]
list_object = list(map(str.strip, str_object.split(",")))
try:
list_object.remove("")
except ValueError:
pass
dict_dest[key] = list_object
return dict_dest
@classmethod
def list_to_str(cls, dict_source, dict_dest, key):
list_object = dict_source[key]
str_object = ", ".join(list_object)
dict_dest[key] = str_object
return dict_dest
class Bool:
TRUE_VALUES = ("yes", "on", "true", "enabled", "enable")
FALSE_VALUES = ("no", "off", "false", "disabled", "disable")
class StrToBoolError(ConversionError):
def __init__(self, str_object):
self.msg = (
'Bad value "%s" for str to bool conversion, expected a value in %s'
% (str_object, str(Type.Bool.TRUE_VALUES + Type.Bool.FALSE_VALUES))
)
class BoolToStrError(ConversionError):
def __init__(self, bool_object):
self.msg = (
'Bad value "%s" for bool to str conversion, expected a boolean'
% (bool_object)
)
@classmethod
def str_to_bool(cls, dict_source, dict_dest, key):
str_object = dict_source[key]
if str_object.lower() in Type.Bool.TRUE_VALUES:
bool_object = True
elif str_object.lower() in Type.Bool.FALSE_VALUES:
bool_object = False
else:
raise Type.Bool.StrToBoolError(str_object)
dict_dest[key] = bool_object
return dict_dest
@classmethod
def bool_to_str(cls, dict_source, dict_dest, key):
bool_object = dict_source[key]
if bool_object == True:
str_object = "yes"
elif bool_object == False:
str_object = "no"
else:
raise Type.Bool.BoolToStrError(bool_object)
dict_dest[key] = str_object
return dict_dest
class Size:
class StrToSizeError(ConversionError):
def __init__(self, str_object):
self.msg = (
'Bad value "%s" for str to size conversion, expected a value like, e.g. 10M'
% (str_object)
)
class SizeToStrError(ConversionError):
def __init__(self, size_object):
self.msg = (
'Bad value "%s" for size to str conversion, expected an integer'
% (size_object)
)
@classmethod
def str_to_size(cls, dict_source, dict_dest, key):
str_object = dict_source[key]
suffixes = ["T", "G", "M", "k"]
match_result = re.compile("^(\d+)([%s])?$" % ("".join(suffixes))).match(
str_object
)
if match_result == None:
raise Type.Size.StrToSizeError(str_object)
size, suffix = match_result.groups("")
size_object = int(size)
while len(suffixes) > 0:
if suffix in suffixes:
size_object *= 1024
suffixes.pop()
dict_dest[key] = size_object
return dict_dest
@classmethod
def size_to_str(cls, dict_source, dict_dest, key):
try:
size_object = int(dict_source[key])
except ValueError:
raise Type.Size.SizeToStrError(size_object)
for suffix_to_test in ("k", "M", "G", "T"):
if size_object > 1024:
suffix = suffix_to_test
size_object /= 1024
str_object = str(size_object) + suffix
dict_dest[key] = str_object
return dict_dest
class Sequence:
@classmethod
def key(cls, key):
match_results = re.compile("^(.*)-\d+$").match(key)
if match_results:
key = match_results.group(1)
return key
@classmethod
def key_for_search(cls, key):
if not hasattr(key, "search"):
key = cls.key(key)
key = re.compile("^%s(-\d+)?$" % (key))
return key
@classmethod
def value(cls, value, dict_str, dict_type, key):
def conversion_method():
Type.Sequence.sequence_to_str(dict_type, dict_str, key)
return ConversionList(conversion_method, value)
@classmethod
def key_to_index(cls, key, key_to_convert):
index = key_to_convert[len(key) + 1 :]
if index == "":
index = -1
else:
index = int(index)
return index
@classmethod
def str_to_sequence(cls, dict_source, dict_dest, key):
def conversion_method():
Type.Sequence.sequence_to_str(dict_dest, dict_source, key)
str_object = []
key = cls.key(key)
regexp = re.compile("^%s-\d+$" % (key))
for (key_to_test, value) in dict_source.items():
if key_to_test == key or regexp.match(key_to_test):
str_object.append((key_to_test, value))
str_object.sort(key=lambda str_object: cls.key_to_index(key, str_object[0]))
sequence_object = ConversionList(
conversion_method, [value for (str_key, value) in str_object]
)
dict_dest[key] = sequence_object
return dict_dest
@classmethod
def str_to_sequence_safe(cls, dict_source, dict_dest, key):
str_object = []
key = cls.key(key)
regexp = re.compile("^%s-\d+$" % (key))
for (key_to_test, value) in dict_source.items():
if key_to_test == key or regexp.match(key_to_test):
str_object.append((key_to_test, value))
str_object.sort(key=lambda str_object: cls.key_to_index(key, str_object[0]))
dict_dest[key] = [value for (str_key, value) in str_object]
return dict_dest
@classmethod
def assign_elts(cls, elts, assignments_old, indices_unassigned):
def _assign_unassigned(
indices, elts_unassigned, indices_unassigned, index_prev, index
):
indices_available = [
index_unassigned
for index_unassigned in indices_unassigned
if index_unassigned > index_prev
and (index_unassigned < index or index < -1)
]
for index_available in indices_available:
indices_unassigned.remove(index_available)
while len(indices_available) > len(elts_unassigned) - (
index >= -1 and 1 or 0
):
indices_available.pop()
indices_available.append(index)
indices_to_assign = []
for index_available in indices_available:
while len(indices_to_assign) < len(elts_unassigned) - (
index_available >= -1 and 1 or 0
):
if index_prev < index_available - 1 or index_available < -1:
index_prev += 1
indices_to_assign.append(index_prev)
if index_available >= -1:
indices_to_assign.append(index_available)
index_prev = index_available
while len(elts_unassigned) > 0:
elts_unassigned.pop(0)
index_prev = indices_to_assign.pop(0)
indices.append(index_prev)
return index_prev
elts_unassigned = []
indices = []
index_prev = 0
for elt in elts:
elts_unassigned.append(elt)
if elt in assignments_old:
index = assignments_old[elt]
if index > index_prev and (
len(elts_unassigned) == 1
or len(elts_unassigned) <= index - index_prev
):
index_prev = _assign_unassigned(
indices,
elts_unassigned,
indices_unassigned,
index_prev,
index,
)
index_prev = _assign_unassigned(
indices, elts_unassigned, indices_unassigned, index_prev, -2
)
return indices
@classmethod
def sequence_to_str(cls, dict_source, dict_dest, key):
key = cls.key(key)
sequence_object = [elt for elt in list(dict_source[key]) if elt != ""]
regexp = re.compile("^%s-\d+$" % (key))
str_keys = [
key_to_test for key_to_test in dict_dest if regexp.match(key_to_test)
]
keys_unassigned = [
str_key for str_key in str_keys if dict_dest[str_key] == ""
]
str_keys = [
str_key for str_key in str_keys if str_key not in keys_unassigned
]
assignments_old = dict(
[
(dict_dest[str_key], cls.key_to_index(key, str_key))
for str_key in sorted(
str_keys,
key=lambda key_to_convert: cls.key_to_index(
key, key_to_convert
),
)
]
)
indices = cls.assign_elts(
sequence_object,
assignments_old,
[
cls.key_to_index(key, key_to_convert)
for key_to_convert in keys_unassigned
],
)
for str_key in str_keys:
del dict_dest[str_key]
while len(sequence_object) > 0:
elt = sequence_object.pop(0)
index = indices.pop(0)
dict_dest[key + "-" + str(index)] = elt
return dict_dest
| SmartJog/sjconf | sjconfparts/type.py | Python | lgpl-2.1 | 16,215 |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Scalasca(AutotoolsPackage):
"""Scalasca is a software tool that supports the performance optimization
of parallel programs by measuring and analyzing their runtime
behavior. The analysis identifies potential performance
bottlenecks - in particular those concerning communication and
synchronization - and offers guidance in exploring their causes.
"""
homepage = "http://www.scalasca.org"
url = "http://apps.fz-juelich.de/scalasca/releases/scalasca/2.1/dist/scalasca-2.1.tar.gz"
version('2.3.1', 'a83ced912b9d2330004cb6b9cefa7585')
version('2.2.2', '2bafce988b0522d18072f7771e491ab9')
version('2.1', 'bab9c2b021e51e2ba187feec442b96e6')
depends_on("mpi")
# version 2.3
depends_on('cube@4.3:', when='@2.3:')
depends_on('otf2@2:', when='@2.3:')
# version 2.1+
depends_on('cube@4.2', when='@2.1:2.2.999')
depends_on('otf2@1.4', when='@2.1:2.2.999')
def url_for_version(self, version):
return 'http://apps.fz-juelich.de/scalasca/releases/scalasca/{0}/dist/scalasca-{1}.tar.gz'.format(version.up_to(2), version)
def configure_args(self):
spec = self.spec
config_args = ["--enable-shared"]
config_args.append("--with-cube=%s" % spec['cube'].prefix.bin)
config_args.append("--with-otf2=%s" % spec['otf2'].prefix.bin)
if self.spec['mpi'].name == 'openmpi':
config_args.append("--with-mpi=openmpi")
elif self.spec.satisfies('^mpich@3:'):
config_args.append("--with-mpi=mpich3")
return config_args
| skosukhin/spack | var/spack/repos/builtin/packages/scalasca/package.py | Python | lgpl-2.1 | 2,845 |
##cobra.solvers.glpk_solver
#This script provides wrappers for libglpk-java 1.0.22 and pyglpk 0.3
from warnings import warn
from copy import deepcopy
###solver specific parameters
from .parameters import status_dict, variable_kind_dict, \
sense_dict, parameter_mappings, parameter_defaults, \
objective_senses, default_objective_sense
from ..core.Solution import Solution
from time import time
solver_name = 'glpk'
sense_dict = eval(sense_dict[solver_name])
#Functions that are different for java implementation of a solver
from os import name
if name != "java":
raise Exception("jython only")
warn("cobra.solvers.glpk_solver isn't mature. consider using gurobi or cplex")
from org.gnu.glpk import GLPK, GLPKConstants, glp_smcp, glp_iocp
variable_kind_dict = eval(variable_kind_dict['%s_%s'%(solver_name,
__name)])
status_dict = eval(status_dict['%s_%s'%(solver_name,
__name)])
objective_senses = objective_senses['%s_%s'%(solver_name,
__name)]
parameter_mappings = parameter_mappings['%s_%s'%(solver_name,
__name)]
parameter_defaults = parameter_defaults['%s_%s'%(solver_name,
__name)]
class Problem():
"""Create a more pythonesqe class to wrap the key
features of the libglpk-java functions.
"""
def __init__(self):
"""the attributes g, lp, mip should be made private
"""
self._g = GLPK
self._lp= GLPK.glp_create_prob()
self._simplex_parameters = glp_smcp()
self._mip_parameters = None
self._g.glp_init_smcp(self._simplex_parameters)
self.status = self.objective_value = None
self._mip = False
def set_name(self, name=''):
self._g.glp_set_prob_name(self._lp, name)
def solve(self):
try:
self._g.glp_simplex(self._lp,
self._simplex_parameters)
if self._mip:
#perform the MIP
setattr(self._mip_parameters, 'msg_lev',
self._simplex_parameters.msg_lev)
self._g.glp_intopt(self._lp, self._mip_parameters)
self.status = self.get_status()
self.objective_value = self.get_objective_value()
except:
self.status = 'failed'
return self.status
def get_status(self):
if self._mip:
status = self._g.glp_mip_status(self._lp)
else:
status = self._g.glp_get_status(self._lp)
return status_dict[status]
def set_objective_sense(self, parameter_value='maximize'):
self._g.glp_set_obj_dir(self._lp,
eval(objective_senses[parameter_value]))
def set_parameter(self, parameter_name, parameter_value, warning=False):
if parameter_name == 'objective_sense':
self.set_objective_sense(parameter_value)
else:
if parameter_name == 'meth' and parameter_value not in [1,2,3]:
parameter_value = 1
try:
setattr(self._simplex_parameters, parameter_name,
parameter_value)
except Exception, e1:
try:
setattr(self._mip_parameters, parameter_name,
parameter_value)
except Exception, e2:
if warning:
print "Could not set simplex parameter " +\
"%s: %s"%(parameter_name, repr(e1))
if self._mip_parameters is not None:
print "Could not set mip parameter " +\
"%s: %s"%(parameter_name, repr(e2))
def get_objective_value(self):
if self._mip:
tmp_value = self._g.glp_mip_obj_val(self._lp)
else:
tmp_value = self._g.glp_get_obj_val(self._lp)
return tmp_value
def create_problem(self, cobra_model):
g = self._g
lp = self._lp
number_of_reactions = len(cobra_model.reactions)
number_of_metabolites = len(cobra_model.metabolites)
g.glp_add_cols(lp, number_of_reactions)
reaction_to_index = {}
objective_dict = {}
#Add in the variables
tmp_kinds = []
for i, the_reaction in enumerate(cobra_model.reactions):
i_offset = i + 1
reaction_to_index[the_reaction] = i_offset
if the_reaction.objective_coefficient != 0:
objective_dict[i_offset] = the_reaction.objective_coefficient
g.glp_set_col_name(lp, i_offset, the_reaction.id)
tmp_kinds.append(the_reaction.variable_kind)
the_kind = variable_kind_dict[the_reaction.variable_kind]
lower_bound = the_reaction.lower_bound
upper_bound = the_reaction.upper_bound
#Note. It is possible to have unbounded or one-bound variables
if lower_bound == upper_bound:
bound_kind = GLPKConstants.GLP_FX
else:
bound_kind = GLPKConstants.GLP_DB
g.glp_set_col_kind(lp, i_offset, the_kind)
g.glp_set_col_bnds(lp, i_offset,
bound_kind, the_reaction.lower_bound,
the_reaction.upper_bound)
tmp_kinds = set(tmp_kinds)
if 'integer' in tmp_kinds or 'binary' in tmp_kinds:
self._mip = True
self._mip_parameters = glp_iocp()
g.glp_init_iocp(self._mip_parameters)
#create constraints
g.glp_add_rows(lp, number_of_metabolites)
row_indices = []
column_indices = []
constraint_values = []
for i, the_metabolite in enumerate(cobra_model.metabolites):
i_offset = i + 1
g.glp_set_row_name(lp, i_offset, the_metabolite.id)
lower_bound = upper_bound = the_metabolite._bound
constraint_sense = sense_dict[the_metabolite._constraint_sense]
if constraint_sense == 'E':
bound_type = GLPKConstants.GLP_FX
elif constraint_sense == 'L':
bound_type = GLPKConstants.GLP_UP
elif constraint_sense == 'G':
bound_type = GLPKConstants.GLP_LO
elif constraint_sense == 'U':
bound_type = GLPKConstants.GLP_FR
elif hasattr(lower_bound, '__iter__'):
lower_bound, upper_bound = lower_bound[:2]
bound_type = GLPKConstants.GLP_DB
g.glp_set_row_bnds(lp, i_offset, bound_type,
lower_bound, upper_bound)
[(row_indices.append(i_offset),
column_indices.append(reaction_to_index[k]),
constraint_values.append(k._metabolites[the_metabolite]))
for k in the_metabolite._reaction]
#Load the constraints into the lp. Need to use
#typed arrays.
number_of_constraints = len(row_indices)
i_array = g.new_intArray(number_of_constraints)
j_array = g.new_intArray(number_of_constraints)
v_array = g.new_doubleArray(number_of_constraints)
for a, (i, j, v) in enumerate(zip(row_indices,
column_indices,
constraint_values)):
g.intArray_setitem(i_array, a+1, i)
g.intArray_setitem(j_array, a+1, j)
g.doubleArray_setitem(v_array, a+1, v)
g.glp_load_matrix(lp, number_of_constraints, i_array,
j_array, v_array)
# the following lines often cause memory crashes
g.delete_intArray(i_array)
g.delete_intArray(j_array)
g.delete_doubleArray(v_array)
g.glp_set_obj_name(lp, "z")
[g.glp_set_obj_coef(lp, k, v)
for k, v in objective_dict.iteritems()]
__solver_class = Problem
def set_parameter(lp, parameter_name, parameter_value):
lp.set_parameter(parameter_name, parameter_value)
def get_status(lp):
return lp.get_status()
def format_solution(lp, cobra_model, **kwargs):
"""
"""
status = get_status(lp)
if not lp._mip:
try:
x = [lp._g.glp_get_col_prim(lp._lp, i + 1)
for i in range(len(cobra_model.reactions))]
x_dict = dict(zip(cobra_model.reactions, x))
y = [lp._g.glp_get_row_dual(lp._lp, i + 1)
for i in range(len(cobra_model.metabolites))]
y_dict = dict(zip(cobra_model.metabolites, y))
objective_value = lp.objective_value
except Exception, e:
print repr(e)
y = y_dict = x = x_dict = objective_value = None
#print status
else:
try:
x = [lp._g.glp_mip_col_val(lp._lp, i + 1)
for i in range(len(cobra_model.reactions))]
x_dict = dict(zip(cobra_model.reactions, x))
y = y_dict = None
objective_value = lp.objective_value
except:
y = y_dict = x = x_dict = objective_value = None
return(Solution(objective_value, x=x, x_dict=x_dict, y=y,
y_dict=y_dict, status=status))
def create_problem(cobra_model, **kwargs):
"""Solver-specific method for constructing a solver problem from
a cobra.Model. This can be tuned for performance using kwargs
"""
the_parameters = parameter_defaults
if kwargs:
the_parameters = deepcopy(parameter_defaults)
the_parameters.update(kwargs)
quadratic_component = the_parameters['quadratic_component']
new_objective = the_parameters['new_objective']
if quadratic_component is not None:
raise Exception('%s cannot solve QPs, try a different solver'%solver_name)
lp = Problem() # Create empty problem instance
lp.create_problem(cobra_model)
[set_parameter(lp, parameter_mappings[k], v)
for k, v in the_parameters.iteritems() if k in parameter_mappings]
return(lp)
def update_problem(lp, cobra_model, **kwargs):
"""
Assumes that neither Metabolites nor Reaction have been
added or removed.
Currently only deals with reaction bounds and objective
coefficients.
"""
g = lp._g
l = lp._lp
for i, the_reaction in enumerate(cobra_model.reactions):
lower_bound = float(the_reaction.lower_bound)
upper_bound = float(the_reaction.upper_bound)
objective_coefficient = float(the_reaction.objective_coefficient)
if lower_bound == upper_bound:
bound_type = GLPKConstants.GLP_FX
else:
bound_type = GLPKConstants.GLP_DB
g.glp_set_col_bnds(l, i + 1, bound_type, lower_bound, upper_bound)
g.glp_set_obj_coef(l, i + 1, objective_coefficient)
def solve_problem(lp, **kwargs):
"""A performance tunable method for updating a model problem file
"""
#Update parameter settings if provided
if kwargs:
[set_parameter(lp, parameter_mappings[k], v)
for k, v in kwargs.iteritems() if k in parameter_mappings]
try:
print_solver_time = kwargs['print_solver_time']
start_time = time()
except:
print_solver_time = False
lp_method = lp._simplex_parameters.meth
lp.solve()
status = get_status(lp)
if print_solver_time:
print 'optimize time: %f'%(time() - start_time)
return status
def solve(cobra_model, **kwargs):
"""Smart interface to optimization solver functions that will convert
the cobra_model to a solver object, set the parameters, and try multiple
methods to get an optimal solution before returning the solver object and
a cobra.Solution (which is attached to cobra_model.solution)
cobra_model: a cobra.Model
returns a dict: {'the_problem': solver specific object, 'the_solution':
cobra.Solution for the optimization problem'}
"""
#Start out with default parameters and then modify if
#new onese are provided
the_parameters = deepcopy(parameter_defaults)
if kwargs:
the_parameters.update(kwargs)
#Update objectives if they are new.
error_reporting = the_parameters['error_reporting']
if 'new_objective' in the_parameters and \
the_parameters['new_objective'] not in ['update problem', None]:
from ..flux_analysis.objective import update_objective
update_objective(cobra_model, the_parameters['new_objective'])
if 'the_problem' in the_parameters:
the_problem = the_parameters['the_problem']
else:
the_problem = None
if isinstance(the_problem, __solver_class):
#Update the problem with the current cobra_model
lp = the_problem
update_problem(lp, cobra_model, **the_parameters)
else:
#Create a new problem
lp = create_problem(cobra_model, **the_parameters)
#Deprecated way for returning a solver problem created from a cobra_model
#without performing optimization
if the_problem == 'setup':
return lp
###Try to solve the problem using other methods if the first method doesn't work
lp_method = the_parameters['lp_method']
the_methods = [1, 2, 3]
if lp_method in the_methods:
the_methods.remove(lp_method)
#Start with the user specified method
the_methods.insert(0, lp_method)
for the_method in the_methods:
the_parameters['lp_method'] = the_method
try:
status = solve_problem(lp, **the_parameters)
except:
status = 'failed'
if status == 'optimal':
break
the_solution = format_solution(lp, cobra_model)
if status != 'optimal' and error_reporting:
print '%s failed: %s'%(solver_name, status)
cobra_model.solution = the_solution
solution = {'the_problem': lp, 'the_solution': the_solution}
return solution
| jerkos/cobrapy | cobra/solvers/glpk_solver_java.py | Python | lgpl-2.1 | 14,112 |
# This file is part of the GOsa framework.
#
# http://gosa-project.org
#
# Copyright:
# (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de
#
# See the LICENSE file in the project's top-level directory for details.
import logging
import os
from zipfile import ZipFile
from gosa.backend.routes.sse.main import SseHandler
from gosa.common.event import EventMaker
from lxml import objectify, etree
from pkg_resources import resource_filename
from gosa.backend.plugins.upload.main import IUploadFileHandler
from gosa.backend.components.workflowregistry import WorkflowRegistry
from gosa.common import Environment
class WorkflowUploadHandler(IUploadFileHandler):
def __init__(self):
self.env = Environment.getInstance()
self.log = logging.getLogger(__name__)
self.log.info("initializing workflow upload handler")
def handle_upload(self, file, request):
filename = request.headers.get('X-File-Name')
self.log.debug("uploaded workflow file received %s" % filename)
self.extract(file.f_out.name, filename)
def extract(self, fn, real_name):
try:
with ZipFile(fn) as workflow_zip:
if workflow_zip.testzip():
self.log.error("bad workflow zip uploaded")
return
env = Environment.getInstance()
schema = etree.XMLSchema(file=resource_filename("gosa.backend", "data/workflow.xsd"))
parser = objectify.makeparser(schema=schema)
try:
with workflow_zip.open('workflow.xml') as dsc:
root = objectify.fromstring(dsc.read(), parser)
id = objectify.ObjectPath("Workflow.Id")(root)[0].text
target = os.path.join(env.config.get("core.workflow-path", "/var/lib/gosa/workflows"), id)
workflow_zip.extractall(target)
WorkflowRegistry.get_instance().refreshWorkflows()
# send the event to the clients
e = EventMaker()
ev = e.Event(e.WorkflowUpdate(
e.Id(id),
e.ChangeType("create")
))
event_object = objectify.fromstring(etree.tostring(ev, pretty_print=True).decode('utf-8'))
SseHandler.notify(event_object, channel="broadcast")
except KeyError:
self.log.error("bad workflow zip uploaded - no workflow.xml present")
except Exception as e:
print(e)
raise e | gonicus/gosa | backend/src/gosa/backend/plugins/upload/handler/workflow.py | Python | lgpl-2.1 | 2,661 |
from tendrl.commons import flows
class CephIntegrationBaseFlow(flows.BaseFlow):
def __init__(self, *args, **kwargs):
super(CephIntegrationBaseFlow, self).__init__(*args, **kwargs)
| r0h4n/ceph-integration | tendrl/ceph_integration/flows/__init__.py | Python | lgpl-2.1 | 194 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import traceback
from typing import Any, Optional, List
from hotness.exceptions import BaseHotnessException
from hotness.requests import Request
from hotness.responses import Response
class ResponseFailure(Response):
"""
Class that represents failure response returned from use case.
It is send when some exception happen during the use case.
Defines constants for error types.
Attributes:
type: Type of the failure.
message: Error message.
traceback: Exception traceback as string.
use_case_value: Partial use case output from Exception, if provided.
"""
VALIDATOR_ERROR = "ValidatorError"
BUILDER_ERROR = "BuilderError"
DATABASE_ERROR = "DatabaseError"
NOTIFIER_ERROR = "NotifierError"
PATCHER_ERROR = "PatcherError"
INVALID_REQUEST_ERROR = "InvalidRequestError"
def __init__(self, type: str, message: Any) -> None:
"""
Class constructor.
"""
self.type = type
self.message = self._format_message(message)
self.traceback = self._get_stack_trace(message)
self.use_case_value = self._get_value(message)
def _get_value(self, message: Any) -> Optional[dict]:
"""
Retrieves the use case value information from Exception,
otherwise just returns empty dict.
Params:
message: Input to retrieve use case value from
Returns:
Value if message is Exception, otherwise None
"""
value = None
if isinstance(message, BaseHotnessException):
value = message.value
return value
def _get_stack_trace(self, message: Any) -> List[str]:
"""
Retrieves the stack trace information from Exception,
otherwise just returns empty list.
Params:
message: Input to retrieve stack trace from
Returns:
Stack trace if message is Exception, otherwise empty string
"""
stack_trace = []
if isinstance(message, Exception):
stack_trace = traceback.format_tb(message.__traceback__)
return stack_trace
def _format_message(self, message: Any) -> Any:
"""
Formats the input message if the message inherits from Exception,
otherwise just return it back.
Params:
message: Input message to format
Returns:
String if exception, otherwise return the same object we received.
"""
if isinstance(message, Exception):
return "{}: {}".format(message.__class__.__name__, "{}".format(message))
return message
@property
def value(self):
"""
Returns the dict representation of the failure response.
"""
return {
"type": self.type,
"message": self.message,
"use_case_value": self.use_case_value,
}
def __bool__(self) -> bool:
"""
Boolean representation of response.
"""
return False
@classmethod
def validator_error(cls, message: Any) -> "ResponseFailure":
"""
Creates response for validator failure.
Params:
message: Message to add to this error
Returns:
ResponseFailure object
"""
response = ResponseFailure(
type=ResponseFailure.VALIDATOR_ERROR, message=message
)
return response
@classmethod
def builder_error(cls, message: Any) -> "ResponseFailure":
"""
Creates response for builder failure.
Params:
message: Message to add to this error
Returns:
ResponseFailure object
"""
response = ResponseFailure(type=ResponseFailure.BUILDER_ERROR, message=message)
return response
@classmethod
def database_error(cls, message: Any) -> "ResponseFailure":
"""
Creates response for database failure.
Params:
message: Message to add to this error
Returns:
ResponseFailure object
"""
response = ResponseFailure(type=ResponseFailure.DATABASE_ERROR, message=message)
return response
@classmethod
def notifier_error(cls, message: Any) -> "ResponseFailure":
"""
Creates response for notifier failure.
Params:
message: Message to add to this error
Returns:
ResponseFailure object
"""
response = ResponseFailure(type=ResponseFailure.NOTIFIER_ERROR, message=message)
return response
@classmethod
def patcher_error(cls, message: Any) -> "ResponseFailure":
"""
Creates response for patcher failure.
Params:
message: Message to add to this error
Returns:
ResponseFailure object
"""
response = ResponseFailure(type=ResponseFailure.PATCHER_ERROR, message=message)
return response
@classmethod
def invalid_request_error(cls, request: Request) -> "ResponseFailure":
"""
Creates response for invalid request failure.
Params:
request: Invalid request to add to this error
Returns:
ResponseFailure object
"""
response = ResponseFailure(
type=ResponseFailure.INVALID_REQUEST_ERROR, message=str(request.errors)
)
return response
| fedora-infra/the-new-hotness | hotness/responses/response_failure.py | Python | lgpl-2.1 | 6,212 |
# This file is part of cclib (http://cclib.github.io), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006, the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You should have
# received a copy of the license along with cclib. You can also access
# the full license online at http://www.gnu.org/copyleft/lgpl.html.
"""Bridge for using cclib data in openbabel (http://openbabel.org)."""
import openbabel as ob
def makeopenbabel(atomcoords, atomnos, charge=0, mult=1):
"""Create an Open Babel molecule.
>>> import numpy, openbabel
>>> atomnos = numpy.array([1,8,1],"i")
>>> coords = numpy.array([[-1.,1.,0.],[0.,0.,0.],[1.,1.,0.]])
>>> obmol = makeopenbabel(coords, atomnos)
>>> obconversion = openbabel.OBConversion()
>>> formatok = obconversion.SetOutFormat("inchi")
>>> print obconversion.WriteString(obmol).strip()
InChI=1/H2O/h1H2
"""
obmol = ob.OBMol()
for i in range(len(atomnos)):
# Note that list(atomcoords[i]) is not equivalent!!!
coords = atomcoords[i].tolist()
atomno = int(atomnos[i])
obatom = ob.OBAtom()
obatom.SetAtomicNum(atomno)
obatom.SetVector(*coords)
obmol.AddAtom(obatom)
obmol.ConnectTheDots()
obmol.PerceiveBondOrders()
obmol.SetTotalSpinMultiplicity(mult)
obmol.SetTotalCharge(charge)
return obmol
if __name__ == "__main__":
import doctest
doctest.testmod()
| Clyde-fare/cclib | src/cclib/bridge/cclib2openbabel.py | Python | lgpl-2.1 | 1,577 |
#!/usr/bin/env python
# Build a bunch of SRPMs
import argparse
import getopt
import sys
import os
import glob
import subprocess
import shutil
import rpm
import hashlib
import time
from planex.globals import (BUILD_ROOT_DIR, SRPMS_DIR, RPMS_DIR, BUILD_DIR,
SPECS_GLOB)
from planex.util import (bcolours, print_col, run, dump_cmds)
TMP_RPM_PATH = "/tmp/RPMS"
RPM_TOP_DIR = os.path.join(os.getcwd(), BUILD_ROOT_DIR)
CACHE_DIR = "rpmcache"
DEFAULT_ARCH = "x86_64"
def doexec(args, inputtext=None, check=True):
"""Execute a subprocess, then return its return code, stdout and stderr"""
myenv = os.environ.copy()
myenv['HOME'] = RPM_TOP_DIR
return run(args, check=check, env=myenv, inputtext=inputtext)
def get_srpm_info(srpm):
for spec_path in glob.glob(SPECS_GLOB):
os.unlink(spec_path)
doexec(["rpm", "-i", srpm])
myspecfile = glob.glob(SPECS_GLOB)[0]
spec = rpm.ts().parseSpec(myspecfile)
info = {}
info['deps'] = spec.sourceHeader["requires"]
info['arch'] = DEFAULT_ARCH
info['packages'] = [{'name':p.header['name']} for p in spec.packages]
info['srcrpm'] = srpm
content_file = open(myspecfile,'r')
info['spec'] = content_file.read()
content_file.close()
return info
def extract_target(srpm_infos, srpm_filename):
"""
Given a list of srpm_info and an srpm filename, return the target arch
"""
for srpm_info in srpm_infos:
if srpm_info["srcrpm"] == srpm_filename:
return srpm_info["arch"]
def get_package_to_srpm_map(srpm_info):
pkg_map = {}
for srpm in srpm_info:
for package in srpm['packages']:
pkg_map[package['name']] = srpm['srcrpm']
return pkg_map
def get_deps(srpm_infos):
p_to_s_map = get_package_to_srpm_map(srpm_infos)
deps = {}
for srpm_info in srpm_infos:
deps[srpm_info['srcrpm']] = set()
for dep in srpm_info['deps']:
if dep in p_to_s_map:
deps[srpm_info['srcrpm']].add(p_to_s_map[dep])
return deps
def toposort2(data):
# Ignore self dependencies.
for key, val in data.items():
val.discard(key)
# Find all items that don't depend on anything.
extra_items_in_deps = reduce(set.union,
data.itervalues()) - set(data.iterkeys())
# Add empty dependences where needed
extra = {}
for item in extra_items_in_deps:
extra[item] = set()
data.update(extra)
result = []
while True:
ordered = set(item for item, dep in data.iteritems() if not dep)
if not ordered:
break
result.append(ordered)
newdata = {}
for item, dep in data.iteritems():
if item not in ordered:
newdata[item] = (dep - ordered)
data = newdata
assert not data, ("Cyclic dependencies exist among these items:\n%s" %
'\n'.join(repr(x) for x in data.iteritems()))
return result
def write_rpmmacros():
rpmmacros = open(os.path.join(RPM_TOP_DIR, '.rpmmacros'), 'w')
rpmmacros.write('%%_topdir %s\n' % RPM_TOP_DIR)
rpmmacros.write('%%_rpmdir %s\n' % TMP_RPM_PATH)
rpmmacros.close()
def find_pkg(srpm_infos, srpm):
for srpm_info in srpm_infos:
if srpm_info["srcrpm"] == srpm:
return srpm_info
def get_pkg_ddeps(deps, srpm):
if srpm in deps:
ddeps = []
for dep in deps[srpm]:
ddeps.append(dep)
for ddep in get_pkg_ddeps(deps, dep):
ddeps.append(ddep)
return ddeps
else:
return []
def get_srpm_hash(srpm_infos, external, deps, srpm):
allpkgs = get_pkg_ddeps(deps, srpm)
allpkgs.append(srpm)
allpkgs.sort()
srpm_hash = hashlib.md5()
for mypkg in allpkgs:
srpm_info = find_pkg(srpm_infos, mypkg)
srpm_hash.update(srpm_info['spec'])
srpm_hash.update(external)
return srpm_hash.hexdigest()
def get_external_hash(external_deps):
external_deps.sort()
external_hash = hashlib.md5()
for dep in external_deps:
with open(dep, "rb") as f:
for block in iter(lambda: f.read(1024), ""):
external_hash.update(block)
return external_hash.hexdigest()
def get_cache_dir(srpm_infos, external, deps, srpm):
if not os.path.exists(CACHE_DIR):
return None
myhash = get_srpm_hash(srpm_infos, external, deps, srpm)
dst_dir = os.path.join(CACHE_DIR, myhash)
return dst_dir
def need_to_build(srpm_infos, external, deps, srpm):
dst_dir = get_cache_dir(srpm_infos, external, deps, srpm)
if not dst_dir:
return True
return (not os.path.exists(dst_dir))
def get_new_number(srpm, cache_dir):
if cache_dir == None:
return 1
latest_path = os.path.join(CACHE_DIR, srpm, "latest")
if os.path.exists(latest_path):
latest = int(os.readlink(latest_path))
os.remove(latest_path)
build_number = latest+1
else:
try:
os.makedirs(os.path.join(CACHE_DIR, srpm))
except os.error:
pass
build_number = 1
os.symlink("%d" % build_number, latest_path)
num_file_path = os.path.join(CACHE_DIR, srpm, "%d" % build_number)
num_file = open(num_file_path, 'w')
num_file.write(cache_dir)
num_file.close()
return build_number
def createrepo():
doexec(["createrepo", "--update", RPMS_DIR])
def do_build(srpm, target, build_number, use_mock, xs_build_sys):
if xs_build_sys:
mock = "/usr/bin/mock"
else:
mock = "mock"
if use_mock:
cmd = [mock, "--configdir=mock",
"--resultdir=%s" % TMP_RPM_PATH, "--rebuild",
"--target", target,
# "--enable-plugin=tmpfs",
"--define", "extrarelease .%d" % build_number,
"-v", srpm]
if not xs_build_sys:
cmd = ["sudo"] + cmd + ["--disable-plugin=package_state"]
else:
cmd = ["rpmbuild", "--rebuild", "-v", "%s" % srpm,
"--target", target, "--define",
"_build_name_fmt %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm"]
doexec(cmd)
srpms = glob.glob(os.path.join(TMP_RPM_PATH, "*.src.rpm"))
for srpm in srpms:
print_col(bcolours.WARNING,"Removing SRPM %s" % srpm)
os.unlink(srpm)
return glob.glob(os.path.join(TMP_RPM_PATH, "*.rpm"))
def build_srpm(srpm, srpm_infos, external, deps, use_mock, xs_build_sys):
cache_dir = get_cache_dir(srpm_infos, external, deps, srpm)
if(need_to_build(srpm_infos, external, deps, srpm)):
target = extract_target(srpm_infos, srpm)
build_number = get_new_number(srpm, cache_dir)
print_col(bcolours.OKGREEN, "CACHE MISS: Building %s (%d)" % (srpm, build_number))
createrepo()
pkgs = do_build(srpm, target, build_number, use_mock, xs_build_sys)
if cache_dir:
try:
os.makedirs(cache_dir+".tmp")
print "Archiving result in cache"
for pkg in pkgs:
shutil.copy(pkg, cache_dir+".tmp")
os.rename(cache_dir+".tmp",cache_dir)
except:
print bgcolors.WARNING + "FAILED TO PUT BUILD RESULTS INTO CACHE"
else:
print_col(bcolours.OKGREEN,"CACHE HIT: Not building %s" % srpm)
pkgs = glob.glob(os.path.join(cache_dir, "*.rpm"))
for pkg in pkgs:
shutil.copy(pkg, TMP_RPM_PATH)
mytime=time.time()
os.utime(cache_dir,(mytime,mytime))
pkgs = glob.glob(os.path.join(TMP_RPM_PATH, "*.rpm"))
if not use_mock:
result = doexec(["rpm", "-U", "--force", "--nodeps"] + pkgs, check=False)
if result['rc'] != 0:
print "Ignoring failure installing rpm batch: %s" % pkgs
print result['stderr']
for pkg in pkgs:
shutil.move(pkg, RPMS_DIR)
def parse_cmdline(argv=None):
"""
Parse command line options
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--no-mock', help="Don't use mock", action='store_true')
parser.add_argument(
'--xs-build-sys', help='Assume XenServer build system',
action='store_true')
parser.add_argument('--i686', help='Build for i686',
action='store_true')
parser.add_argument('--external-dependencies',
help='External dependencies to include in the package hash',
metavar="file", nargs="+", default=[])
parser.add_argument('--cache-dir',
help='Root directory of the RPM cache',
metavar="directory", default=None)
return parser.parse_args(argv)
def main():
global DEFAULT_ARCH
args = parse_cmdline()
use_mock = not args.no_mock
xs_build_sys = args.xs_build_sys
if args.i686:
DEFAULT_ARCH = "i686"
if args.cache_dir:
CACHE_DIR = args.cache_dir
if not os.path.isdir(SRPMS_DIR) or not os.listdir(SRPMS_DIR):
print ("Error: No srpms found in %s; First run configure.py." %
SRPMS_DIR)
sys.exit(1)
packages = glob.glob(os.path.join(SRPMS_DIR, '*.src.rpm'))
write_rpmmacros()
srpm_infos = [get_srpm_info(pkg) for pkg in packages]
deps = get_deps(srpm_infos)
order = toposort2(deps)
external = get_external_hash(args.external_dependencies)
for path in (TMP_RPM_PATH, BUILD_DIR, RPMS_DIR):
if os.path.exists(path):
print "Cleaning out directory: %s" % path
shutil.rmtree(path)
os.makedirs(path)
os.chmod(path, 0777)
createrepo()
for batch in order:
for srpm in batch:
build_srpm(srpm, srpm_infos, external, deps, use_mock, xs_build_sys)
createrepo()
if __name__ == '__main__':
main()
| jonludlam/planex | planex/build.py | Python | lgpl-2.1 | 9,798 |
"""Social content items: messages aka status updates, private messages, etc."""
from __future__ import annotations
import re
from sqlalchemy.orm import relationship
from sqlalchemy.orm.query import Query
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, UnicodeText
from abilian.core.entities import SEARCHABLE, Entity
from abilian.core.extensions import db
from abilian.core.models.subjects import Group, User
__all__ = ["Message", "PrivateMessage"]
class MessageQuery(Query):
def by_creator(self, user):
return self.filter(Message.creator_id == user.id)
class Message(Entity):
"""Message aka Status update aka Note.
See: http://activitystrea.ms/head/activity-schema.html#note
"""
__tablename__ = "message"
__indexable__ = False
__editable__ = ["content"]
__exportable__ = __editable__ + [
"id",
"created_at",
"updated_at",
"creator_id",
"owner_id",
]
#: The content for this message.
content = Column(UnicodeText(), info=SEARCHABLE | {"index_to": ("text",)})
#: Nullable: if null, then message is public.
group_id = Column(Integer, ForeignKey(Group.id))
#: The group this message has been posted to.
group = relationship("Group", primaryjoin=(group_id == Group.id), lazy="joined")
query = db.session.query_property(MessageQuery)
@property
def tags(self) -> list[str]:
return re.findall(r"(?u)#([^\W]+)", self.content)
# TODO: inheriting from Entity is overkill here
class TagApplication(Entity):
__tablename__ = "tag_application"
tag = Column(UnicodeText, index=True)
message_id = Column(Integer, ForeignKey("message.id"))
class PrivateMessage(Entity):
"""Private messages are like messages, except they are private."""
__tablename__ = "private_message"
__indexable__ = False
__editable__ = ["content", "recipient_id"]
__exportable__ = __editable__ + [
"id",
"created_at",
"updated_at",
"creator_id",
"owner_id",
]
content = Column(UnicodeText, info=SEARCHABLE | {"index_to": ("text",)})
recipient_id = Column(Integer, ForeignKey(User.id), nullable=False)
class Like(Entity):
__tablename__ = "like"
__indexable__ = False
__editable__ = ["content", "message_id"]
__exportable__ = __editable__ + [
"id",
"created_at",
"updated_at",
"creator_id",
"owner_id",
]
content = Column(UnicodeText, info=SEARCHABLE | {"index_to": ("text",)})
message_id = Column(Integer, ForeignKey(Message.id), nullable=False)
| abilian/abilian-sbe | src/abilian/sbe/apps/social/models.py | Python | lgpl-2.1 | 2,645 |
#
# images driver for migration (without FS transfer)
#
import os
import tempfile
import rpyc
import tarfile
import time
import shutil
import time
img_path = "/var/local/p.haul-fs/"
img_tarfile = "images.tar"
xfer_size = 64 * 1024
def copy_file(s, d):
while True:
chunk = s.read(xfer_size)
if not chunk:
break
d.write(chunk)
class phaul_images:
def __init__(self):
self.current_iter = 0
self.current_dir = None
prefix = time.strftime("%y.%m.%d-%H.%M-", time.localtime())
self.wdir = tempfile.mkdtemp("", prefix, img_path)
self.img_path = os.path.join(self.wdir, "img")
os.mkdir(self.img_path)
self.sync_time = 0.0
def close(self, keep_images):
if not keep_images:
print "Removing images"
shutil.rmtree(self.wdir)
else:
print "Images are kept in %s" % self.wdir
pass
def img_sync_time(self):
return self.sync_time
def new_image_dir(self):
self.current_iter += 1
img_dir = "%s/%d" % (self.img_path, self.current_iter)
print "\tMaking directory %s" % img_dir
self.current_dir = img_dir
os.mkdir(img_dir)
def image_dir_fd(self):
return os.open(self.current_dir, os.O_DIRECTORY)
def work_dir_fd(self):
return os.open(self.wdir, os.O_DIRECTORY)
def image_dir(self):
return self.current_dir
def work_dir(self):
return self.wdir
def prev_image_dir(self):
if self.current_iter == 1:
return None
else:
return "../%d" % (self.current_iter - 1)
# Images transfer
# Are there better ways for doing this?
def sync_imgs_to_target(self, th, htype):
# Pre-dump doesn't generate any images (yet?)
# so copy only those from the top dir
print "Sending images to target"
start = time.time()
print "\tPack"
tf_name = os.path.join(self.current_dir, img_tarfile)
tf = tarfile.open(tf_name, "w")
for img in os.listdir(self.current_dir):
if img.endswith(".img"):
tf.add(os.path.join(self.current_dir, img), img)
print "\tAdd htype images"
for himg in htype.get_meta_images(self.current_dir):
tf.add(himg[0], himg[1])
tf.close()
print "\tCopy"
lfh = open(tf_name, "rb")
os.unlink(tf_name)
rfh = th.open_image_tar()
copy_file(lfh, rfh)
print "\tUnpack"
rfh.unpack_and_close()
self.sync_time = time.time() - start
# This one is created by target
class exposed_images_tar():
def __init__(self, dir):
self.dir = dir
self.fname = os.path.join(dir, img_tarfile)
self.fh = open(self.fname, "wb")
def exposed_write(self, chunk):
return self.fh.write(chunk)
def exposed_unpack_and_close(self):
self.fh.close()
tf = tarfile.open(self.fname, "r")
os.unlink(self.fname)
tf.extractall(self.dir)
tf.close()
| avagin/p.haul | p_haul_img.py | Python | lgpl-2.1 | 2,640 |
# -*- coding: utf-8 -*-
from blocFissure.gmu.fissureCoude import fissureCoude
class fissureCoude_4(fissureCoude):
"""
problème de fissure du Coude : ASCOU09A
adaptation maillage
"""
# ---------------------------------------------------------------------------
def setParamGeometrieSaine(self):
"""
Paramètres géométriques du tuyau coudé sain:
angleCoude
r_cintr
l_tube_p1
l_tube_p2
epais
de
"""
self.geomParams = dict(angleCoude = 40,
r_cintr = 654,
l_tube_p1 = 1700,
l_tube_p2 = 1700,
epais = 62.5,
de = 912.4)
# ---------------------------------------------------------------------------
def setParamMaillageSain(self):
self.meshParams = dict(n_long_p1 = 16,
n_ep = 5,
n_long_coude = 30,
n_circ_g = 50,
n_circ_d = 20,
n_long_p2 = 12)
# ---------------------------------------------------------------------------
def setParamShapeFissure(self):
"""
paramètres de la fissure pour le tuyau coude
profondeur : 0 < profondeur <= épaisseur
rayonPipe : rayon du pipe correspondant au maillage rayonnant
lenSegPipe : longueur des mailles rayonnantes le long du fond de fissure (= rayonPipe par défaut)
azimut : entre 0 et 360°
alpha : 0 < alpha < angleCoude
longueur : <=2*profondeur ==> force une fissure elliptique (longueur/profondeur = grand axe/petit axe).
orientation : 0° : longitudinale, 90° : circonférentielle, autre : uniquement fissures elliptiques
lgInfluence : distance autour de la shape de fissure a remailler (si 0, pris égal à profondeur. A ajuster selon le maillage)
elliptique : True : fissure elliptique (longueur/profondeur = grand axe/petit axe); False : fissure longue (fond de fissure de profondeur constante, demi-cercles aux extrémites)
pointIn_x : optionnel coordonnées x d'un point dans le solide, pas trop loin du centre du fond de fissure (idem y,z)
externe : True : fissure face externe, False : fissure face interne
"""
print "setParamShapeFissure", self.nomCas
self.shapeFissureParams = dict(profondeur = 10,
rayonPipe = 2.5,
lenSegPipe =2.5,
azimut = 90,
alpha = 20,
longueur = 240,
orientation = 90,
lgInfluence = 30,
elliptique = False,
externe = True)
# ---------------------------------------------------------------------------
def setParamMaillageFissure(self):
"""
Paramètres du maillage de la fissure pour le tuyau coudé
Voir également setParamShapeFissure, paramètres rayonPipe et lenSegPipe.
nbSegRad = nombre de couronnes
nbSegCercle = nombre de secteurs
areteFaceFissure = taille cible de l'arête des triangles en face de fissure.
"""
self.maillageFissureParams = dict(nomRep = '.',
nomFicSain = self.nomCas,
nomFicFissure = 'fissure_' + self.nomCas,
nbsegRad = 5,
nbsegCercle = 6,
areteFaceFissure = 5)
# ---------------------------------------------------------------------------
def setReferencesMaillageFissure(self):
self.referencesMaillageFissure = dict(Entity_Node = 133832,
Entity_Quad_Edge = 1133,
Entity_Quad_Triangle = 1498,
Entity_Quad_Quadrangle = 11892,
Entity_Quad_Tetra = 18401,
Entity_Quad_Hexa = 22412,
Entity_Quad_Penta = 600,
Entity_Quad_Pyramid = 816)
| FedoraScientific/salome-smesh | src/Tools/blocFissure/CasTests/fissureCoude_4.py | Python | lgpl-2.1 | 4,424 |
# -*- coding: utf-8 -*-
import socket
from paramiko import SSHClient, AutoAddPolicy, AuthenticationException
from bssh.utils import env
from bssh.auth import get_pkey
from bssh.logger import logger
def connect(
hostname=None,
port=22,
username=None,
password=None,
pkey=None,
pkey_pwd=None,
sock=None,
timeout=env.timeout,
**kwargs
):
"""Connect the remote ssh server"""
passauth = True if password else False
pkey = pkey if passauth else get_pkey(pkey, pkey_pwd)
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
try:
client.connect(hostname=hostname,
port=int(port),
username=username,
password=password,
pkey=pkey,
sock=sock,
timeout=timeout)
logger.login.debug('%s connect successfully.' % hostname)
return client
except AuthenticationException:
logger.login.error('%s Validation failed.' % hostname)
except socket.error:
logger.login.error('%s Network Error' % hostname)
except Exception as e:
logger.login.error('%s %s' % (hostname, str(e)))
| liwanggui/bssh | bssh/network.py | Python | lgpl-2.1 | 1,271 |
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of REDHAWK core.
#
# REDHAWK core is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# REDHAWK core is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
from redhawk.codegen.lang import java
from redhawk.codegen.jinja.mapping import PortMapper
class JavaPortMapper(PortMapper):
def _mapPort(self, port, generator):
javaport = {}
javaport['javaname'] = java.identifier('port_'+port.name())
javaport['javatype'] = generator.className()
javaport['constructor'] = generator.constructor(port.name())
javaport['start'] = generator.start()
javaport['stop'] = generator.stop()
javaport['multiout'] = generator.supportsMultiOut()
return javaport
| RedhawkSDR/framework-codegen | redhawk/codegen/jinja/java/ports/mapping.py | Python | lgpl-3.0 | 1,372 |
#!/usr/bin/python
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-sizefield',
version='0.10.ceda',
author='Mathieu Leplatre',
author_email='contact@mathieu-leplatre.info',
url='https://github.com/leplatrem/django-sizefield',
download_url="http://pypi.python.org/pypi/django-sizefield/",
description="A model field to store a file size, whose edition and display shows units.",
long_description=open(os.path.join(here, 'README.rst')).read() + '\n\n' +
open(os.path.join(here, 'CHANGES')).read(),
license='LPGL, see LICENSE file.',
install_requires=[
'Django',
],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
classifiers=['Topic :: Utilities',
'Natural Language :: English',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Environment :: Web Environment',
'Framework :: Django',
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.7'],
)
| cedadev/django-sizefield | setup.py | Python | lgpl-3.0 | 1,205 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from entropyfw import System
from s_pico_tc08.module import EntropyPicoTc08
from s_tti_cpx.module import EntropyTTiCPX
from s_laird_optotec_ot15.module import EntropyLairdOT15ConstantQc
from .s_controller.module import EntropyController as GFAEntropyController
from s_eventlogger.module import EntropyEventLogger
from . import config
from . import system_names
__author__ = 'otger'
class SystemMonitorGFAThermal(System):
def __init__(self, flask_app):
System.__init__(self, flask_app)
self.pico = EntropyPicoTc08(name=system_names.TC08_MOD, channels=[])
self.add_module(self.pico)
# self.tticpx = EntropyTTiCPX(name=system_names.TTiCPX_MOD)
# self.add_module(self.tticpx)
self.elogger = EntropyEventLogger(name=system_names.LOGGER_MOD, backup_path='/tmp')
self.add_module(self.elogger)
def enable_tc08_channel(self, channel, tc_type, units):
self.pico.enable(channel=channel, tc_type=tc_type, units=units)
| otger/gfa_thermal_entropySys | gfa_thermal/monitor_system.py | Python | lgpl-3.0 | 1,028 |
#!/usr/bin/env python
# encoding: utf-8
"""
Show how to use `dur` and `delay` parameters of play() and out()
methods to sequence events over time.
"""
from pyo import *
import random
s = Server(duplex=0).boot()
num = 70
freqs = [random.uniform(100, 1000) for i in range(num)]
start1 = [i * 0.5 for i in range(num)]
fade1 = Fader([1] * num, 1, 5, mul=0.03).play(dur=5, delay=start1)
a = SineLoop(freqs, feedback=0.05, mul=fade1).out(dur=5, delay=start1)
start2 = 30
dur2 = 40
snds = [
"../snds/alum1.wav",
"../snds/alum2.wav",
"../snds/alum3.wav",
"../snds/alum4.wav",
]
tabs = SndTable(snds)
fade2 = Fader(0.05, 10, dur2, mul=0.7).play(dur=dur2, delay=start2)
b = Beat(time=0.125, w1=[90, 30, 30, 20], w2=[30, 90, 50, 40], w3=[0, 30, 30, 40], poly=1).play(dur=dur2, delay=start2)
out = TrigEnv(b, tabs, b["dur"], mul=b["amp"] * fade2).out(dur=dur2, delay=start2)
start3 = 45
dur3 = 30
fade3 = Fader(15, 15, dur3, mul=0.02).play(dur=dur3, delay=start3)
fm = FM(carrier=[149, 100, 151, 50] * 3, ratio=[0.2499, 0.501, 0.75003], index=10, mul=fade3).out(
dur=dur3, delay=start3
)
s.gui(locals())
| belangeo/pyo | pyo/examples/sequencing/01_starttime_duration.py | Python | lgpl-3.0 | 1,118 |
# (C) British Crown Copyright 2020, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cartopy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with cartopy. If not, see <https://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
def pytest_configure(config):
# Register additional markers.
config.addinivalue_line('markers',
'natural_earth: mark tests that use Natural Earth '
'data, and the network, if not cached.')
config.addinivalue_line('markers',
'network: mark tests that use the network.')
| ocefpaf/cartopy | lib/cartopy/tests/conftest.py | Python | lgpl-3.0 | 1,159 |
#import printStatWithName
from AZutilities import dataUtilities
from AZutilities import paramOptUtilities
from trainingMethods import AZorngRF
from trainingMethods import AZorngCvSVM
import Orange
import orange
import math
import copy
import string
"""
Module for calculation of non conformity scores and the corresponding p-values and
conformal predictions for binary classifiers.
getPvalue
|
|
getScore
|
|
{Methods to calculate the non-conf score}
"""
def meanStd(data):
""" Calculate mean and standard deviation of data data[]: """
length, mean, std = len(data), 0, 0
for elem in data:
mean = mean + elem
mean = mean / float(length)
for elem in data:
std = std + (elem - mean) ** 2
std = math.sqrt(std / float(length))
mean = round(mean, 3)
std = round(std, 3)
return mean, std
def getScore(idx, extTrain, SVMparam, method = "minNN", maxDistRatio = None, measure = None):
"""
Calculates non-conformity score for the example with index idx in the data set extTrain
method:
1) minNN - Get relative (all ex with diff labels) min distance in feature space from ex with idx in extTrain to the rest of extTrain with the same label as idx
2) avgNN - average distance to 10 NN of the two diff classes
"""
if method == "minNN":
alpha = minNN(idx, extTrain, measure)
elif method == "avgNN":
alpha = avgNN(idx, extTrain, measure)
elif method == "scaledMinNN":
print "There is some problem with the scaling"
alpha = minNN(idx, extTrain, maxDistRatio, measure)
elif method == "kNNratio":
alpha = kNNratio(idx, extTrain, measure)
elif method == "kNNratioStruct":
alpha = kNNratioStruct(idx, extTrain, measure)
elif method == "probPred":
alpha, SVMparam = probPred(idx, extTrain, SVMparam)
elif method == "LLOO":
alpha = LLOO(idx, extTrain, measure)
elif method == "LLOOprob":
alpha = LLOOprob(idx, extTrain, measure)
elif method == "LLOOprob_b":
alpha = LLOOprob_b(idx, extTrain, measure)
else:
alpha = None
print "Method not implemented"
return alpha, SVMparam
def descRange(idx, extTrain):
"""
Use the fraction of descriptors in the train set range.
Not possible to use. Alpha must reflect the non-conformity with the rest of the train set with a given lable.
Inside our outside the range is not predictive for which class the example belongs to.
"""
# Deselect example idx in extTrain
idxList = range(0,idx)
idxList.extend(range(idx+1,len(extTrain)))
train = extTrain.get_items(idxList)
# Get the idx example
idxEx = extTrain.get_items([idx])
# Loop over att attributes to see if the idxEx values are within the range of train
outRangeCount = 0
stat = Orange.statistics.basic.Domain(train)
#print "%20s %5s %5s %5s" % ("feature", "min", "max", "avg")
for a in stat:
if a:
#print "%20s %5.3f %5.3f %5.3f" % (a.variable.name, a.min, a.max, a.avg)
#print idxEx[0][a.variable.name]
idxValue = idxEx[0][a.variable.name]
trainMin = a.min
trainMax = a.max
try:
if idxValue < trainMin:
outRangeCount = outRangeCount + 1
elif idxValue > trainMax:
outRangeCount = outRangeCount + 1
except: pass
alpha = float(outRangeCount)/len(extTrain.domain.attributes)
return alpha
def trainSVMOptParam(train, SVMparam):
# Optimize parameters
#SVMparam = [1.0, 0.05]
if not SVMparam:
trainDataFile = "/scratch/trainDataTmp.tab"
train.save(trainDataFile)
learner = AZorngCvSVM.CvSVMLearner()
param = paramOptUtilities.getOptParam(learner, trainDataFile, paramList = None, useGrid = False, verbose = 1, queueType = "NoSGE", runPath = None, nExtFolds = None, nFolds = 10, logFile = "", getTunedPars = True, fixedParams = {})
optC = float(param[1]["C"])
optGamma = float(param[1]["gamma"])
SVMparam = [optC, optGamma]
else:
optC = SVMparam[0]
optGamma = SVMparam[1]
#print "Optimal SVM parameters ", optC, optGamma
model = AZorngCvSVM.CvSVMLearner(train, C = optC, gamma = optGamma)
return model, SVMparam
def probPred(idx, extTrain, SVMparam):
"""
Use the RF prediction probability to set the non-conf score
"""
attrList = ["SMILES_1"]
extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList)
# Deselect example idx in extTrain
idxList = range(0,idx)
idxList.extend(range(idx+1,len(extTrain)))
train = extTrain.get_items(idxList)
# Train a model
model = AZorngRF.RFLearner(train)
#model, SVMparam = trainSVMOptParam(train, SVMparam)
# Predict example idx
predList = model(extTrain[idx], returnDFV = True)
pred = predList[0].value
prob = predList[1]
actual = extTrain[idx].get_class().value
#print pred, actual, prob
# More non conforming if prediction is different from actual label
if pred != actual:
alpha = 1.0 + abs(prob)
else:
alpha = 1.0 - abs(prob)
#print alpha
return alpha, SVMparam
def minNN(idx, extTrain, maxDistRatio = None, measure = None):
"""
Use the ratio between the distance to the nearest neighbor of the same and of the other class
Two versions exist, with and without scaling with the max distance ratio within the train set.
"""
attrList = ["SMILES_1"]
extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList)
distListSame = []
distListDiff = []
#measure = Orange.distance.Euclidean(extTrain)
if not measure:
measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain)
for runIdx in range(len(extTrain)):
if runIdx != idx:
dist = measure(extTrain[idx], extTrain[runIdx])
if extTrain[idx].get_class().value == extTrain[runIdx].get_class().value:
distListSame.append(dist)
else:
distListDiff.append(dist)
minDistSame = min(distListSame)
minDistDiff = min(distListDiff)
if minDistDiff == 0:
if maxDistRatio:
alpha = 1.0
else:
alpha = max(distListDiff)
else:
if maxDistRatio:
alpha = minDistSame/(float(minDistDiff)*maxDistRatio)
else:
alpha = minDistSame/float(minDistDiff)
#fid = open("tempFile.txt", "a")
#fid.write(str(minDistSame)+"\t"+str(minDistDiff)+"\t"+str(maxDistRatio)+"\t"+str(alpha)+"\n")
#fid.close()
return alpha
def avgNN(idx, extTrain, measure = None):
"""
Use the ratio between the distance to the kNN of the same and of the other class
"""
attrList = ["SMILES_1"]
extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList)
distListSame = []
distListDiff = []
#measure = Orange.distance.Euclidean(extTrain)
if not measure:
measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain)
for runIdx in range(len(extTrain)):
if runIdx != idx:
dist = measure(extTrain[idx], extTrain[runIdx])
if extTrain[idx].get_class().value == extTrain[runIdx].get_class().value:
distListSame.append(dist)
else:
distListDiff.append(dist)
distListSame.sort()
avgSame = sum(distListSame[0:10])/10.0
distListDiff.sort()
avgDiff = sum(distListDiff[0:10])/10.0
if avgDiff == 0:
alpha = max(distListDiff)
else:
alpha = avgSame/float(avgDiff)
return alpha
def kNNratio(idx, extTrain, measure = None):
"""
Use the fraction of kNN with the same response.
"""
attrList = ["SMILES_1"]
extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList)
distList = []
if not measure:
#measure = instances.MahalanobisConstructor(extTrain)
measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain)
for runIdx in range(len(extTrain)):
if runIdx != idx:
dist = measure(extTrain[idx], extTrain[runIdx])
distList.append(dist)
# Get the distance of the 10th NN
distList.sort()
thresDist = distList[9]
# Find the labels of the 10 NN
sameCount = 0
for runIdx in range(len(extTrain)):
if runIdx != idx:
dist = measure(extTrain[idx], extTrain[runIdx])
if dist <= thresDist:
if extTrain[idx].get_class().value == extTrain[runIdx].get_class().value:
sameCount = sameCount + 1
alpha = 1.00 - float(sameCount)/10.0
return alpha
def kNNratioInd(train, calSet, measure = None):
"""
Use the fraction of kNN with the same response.
"""
if not measure:
#measure = instances.MahalanobisConstructor(extTrain)
measure = orange.ExamplesDistanceConstructor_Euclidean(train)
alphaList = []
for predEx in calSet:
distList = []
for runIdx in range(len(train)):
dist = measure(predEx, train[runIdx])
distList.append(dist)
# Get the distance of the 10th NN
distList.sort()
thresDist = distList[9]
# Find the labels of the 10 NN
sameCount = 0
for runIdx in range(len(train)):
dist = measure(predEx, train[runIdx])
if dist <= thresDist:
if predEx.get_class().value == train[runIdx].get_class().value:
sameCount = sameCount + 1
alpha = 1.00 - float(sameCount)/10.0
alphaList.append(alpha)
return alphaList, train
def kNNratioStruct(idx, extTrain, measure = None):
"""
Use the fraction of kNN with the same response.
"""
from rdkit import Chem
from rdkit.Chem.Fingerprints import FingerprintMols
from rdkit import DataStructs
# Daylight like fp
smiles = extTrain[idx]["SMILES_1"].value
mol = Chem.MolFromSmiles(smiles)
fp = FingerprintMols.FingerprintMol(mol)
simList = []
for runIdx in range(len(extTrain)):
if runIdx != idx:
smiles0 = extTrain[runIdx]["SMILES_1"].value
mol0 = Chem.MolFromSmiles(smiles0)
fp0 = FingerprintMols.FingerprintMol(mol0)
tanSim = DataStructs.FingerprintSimilarity(fp,fp0)
simList.append(tanSim)
# Get the distance of the 10th NN
simList.sort(reverse = True)
thresDist = simList[9]
# Find the labels of the 10 NN
sameCount = 0
for runIdx in range(len(extTrain)):
if runIdx != idx:
smiles0 = extTrain[runIdx]["SMILES_1"].value
mol0 = Chem.MolFromSmiles(smiles0)
fp0 = FingerprintMols.FingerprintMol(mol0)
tanSim = DataStructs.FingerprintSimilarity(fp,fp0)
if tanSim >= thresDist:
if extTrain[idx].get_class().value == extTrain[runIdx].get_class().value:
sameCount = sameCount + 1
alpha = 1.00 - float(sameCount)/10.0
return alpha
def LLOO(idx, extTrain, measure = None):
"""
Use the fraction of kNN correctly predicted by a local model
Hard coded to 20 NN.
Modeling method. RF of Tree?
"""
attrList = ["SMILES_1"]
extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList)
distList = []
if not measure:
measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain)
for runIdx in range(len(extTrain)):
if runIdx != idx:
dist = measure(extTrain[idx], extTrain[runIdx])
distList.append(dist)
# Get the distance of the 20th NN
distList.sort()
thresDist = distList[19]
# Find the labels of the 20 NN
kNN = []
for runIdx in range(len(extTrain)):
dist = measure(extTrain[idx], extTrain[runIdx])
if dist <= thresDist:
kNN.append(extTrain[runIdx])
kNNtrain = dataUtilities.DataTable(kNN)
# Find the fraction of correctly predicted ex in a LOO over kNN
corrPred = 0
for idx in range(len(kNNtrain)):
# Deselect example idx in extTrain
idxList = range(0,idx)
idxList.extend(range(idx+1,len(kNNtrain)))
train = kNNtrain.get_items(idxList)
# Train a model
model = AZorngRF.RFLearner(train)
#model = Orange.classification.tree.TreeLearner(train)
pred = model(kNNtrain[idx]).value
actual = kNNtrain[idx].get_class().value
if pred == actual:
corrPred = corrPred + 1
alpha = 1.0 - float(corrPred)/len(kNNtrain)
return alpha
def LLOOprob(idx, extTrain, measure = None):
"""
Use the fraction of kNN correctly predicted by a local model
Hard coded to 20 NN.
Modeling method. RF of Tree?
"""
distList = []
if not measure:
measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain)
for runIdx in range(len(extTrain)):
if runIdx != idx:
dist = measure(extTrain[idx], extTrain[runIdx])
distList.append(dist)
# Get the distance of the 20th NN
distList.sort()
thresDist = distList[50] # Smaller number of NN does not work with returnDFV
# Find the predEx and the 20 NN
kNN = []
for runIdx in range(len(extTrain)):
dist = measure(extTrain[idx], extTrain[runIdx])
if dist <= thresDist:
kNN.append(extTrain[runIdx])
kNNtrain = dataUtilities.DataTable(kNN)
# Find the fraction of correctly predicted ex in a LOO over kNN
alphaList = []
for iidx in range(len(kNNtrain)):
# Deselect example idx in extTrain
idxList = range(0,iidx)
idxList.extend(range(iidx+1,len(kNNtrain)))
train = kNNtrain.get_items(idxList)
# Get prediction and pred probability
model = AZorngRF.RFLearner(train)
predList = model(kNNtrain[iidx], returnDFV = True)
pred = predList[0].value
prob = predList[1]
actual = kNNtrain[iidx].get_class().value
# alpha should be greater the less certain the model
try:
if pred != actual:
alpha = 1.0 + abs(prob)
else:
alpha = 1.0 - abs(prob)
alphaList.append(alpha)
except: pass
alpha = sum(alphaList)/float(len(alphaList))
return alpha
def LLOOprob_b(idx, extTrain, measure = None):
"""
Use the fraction of kNN correctly predicted by a local model
Hard coded to 50 NN.
Modeling method. RF of Tree?
"""
distList = []
if not measure:
measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain)
for runIdx in range(len(extTrain)):
if runIdx != idx:
dist = measure(extTrain[idx], extTrain[runIdx])
distList.append(dist)
# Get the distance of the 50th NN
distList.sort()
thresDist = distList[50] # Smaller number of NN does not work with returnDFV
# Find the predEx and the 20 NN
kNN = []
for runIdx in range(len(extTrain)):
dist = measure(extTrain[idx], extTrain[runIdx])
if dist <= thresDist:
kNN.append(extTrain[runIdx])
kNNtrain = dataUtilities.DataTable(kNN)
# Find the fraction of correctly predicted ex in a LOO over kNN
alphaList = []
alphaEx = 0
for iidx in range(len(kNNtrain)):
# Deselect example idx in extTrain
idxList = range(0,iidx)
idxList.extend(range(iidx+1,len(kNNtrain)))
train = kNNtrain.get_items(idxList)
# Get prediction and pred probability
model = AZorngRF.RFLearner(train)
predList = model(kNNtrain[iidx], returnDFV = True)
pred = predList[0].value
prob = predList[1]
actual = kNNtrain[iidx].get_class().value
# The prob of the predEx is more important
dist = measure(extTrain[idx], kNNtrain[iidx])
# alpha should be greater the less certain the model
try:
if pred != actual:
alpha = 1.0 + abs(prob)
if dist < 0.001:
alphaEx = alpha
else:
alpha = 1.0 - abs(prob)
if dist < 0.001:
alphaEx = alpha
alphaList.append(alpha)
except: pass
alpha = alphaEx + sum(alphaList)/float(len(alphaList))
return alpha
def getMeanStd(extTrain):
# Get the min dist for all ex in the data set
minSame = []
minDiff = []
measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain)
for idx in range(len(extTrain)):
distListSame = []
distListDiff = []
for iidx in range(len(extTrain)):
if idx != iidx:
dist = measure(extTrain[idx], extTrain[iidx])
if extTrain[idx].get_class().value == extTrain[iidx].get_class().value:
distListSame.append(dist)
else:
distListDiff.append(dist)
minSame.append(min(distListSame))
minDiff.append(min(distListDiff))
# Calculate mean and std of all the min distances
meanSame, stdSame = meanStd(minSame)
meanDiff, stdDiff = meanStd(minDiff)
return meanSame, stdSame, meanDiff, stdDiff
def getMinDistRatio(train):
"""
Calculate the minDistSame and minDistDiff ratio for all ex in the data set and select the greatest quotient.
Used to scale the minDist ratios in the non-conf score.
"""
# Get the min dist for all ex in the data set
minSame = []
minDiff = []
minRatio = []
measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain)
for idx in range(len(train)):
distListSame = []
distListDiff = []
for iidx in range(len(train)):
if idx != iidx:
dist = measure(train[idx], train[iidx])
if train[idx].get_class().value == train[iidx].get_class().value:
distListSame.append(dist)
else:
distListDiff.append(dist)
minSame.append(min(distListSame))
minDiff.append(min(distListDiff))
if min(distListDiff) == 0:
alpha = max(distListDiff)
else:
minRatio.append(min(distListSame)/float(min(distListDiff)))
# Calculate min, mean and std of all the min distances
meanSame, stdSame = meanStd(minSame)
meanDiff, stdDiff = meanStd(minDiff)
maxDistRatio = max(minRatio)
return maxDistRatio
def getPvalueFromList(nonConfList):
trainList = nonConfList[0:len(nonConfList)-1]
alphaPredEx = nonConfList[len(nonConfList)-1]
moreNonConfList = []
for score in trainList:
if score > alphaPredEx:
moreNonConfList.append(score)
pvalue = len(moreNonConfList)/float(len(trainList))
return pvalue
def getPvalue(train, predEx, label, SVMparam, method = "avgNN", measure = None):
"""
method; avgNN, scaledMinNN, minNN, kNNratio
"""
# Set label to class of predEx
newPredEx = Orange.data.Table(predEx.domain, [predEx])
newPredEx[0][newPredEx.domain.classVar] = label
# Add predEx to train
extTrain = dataUtilities.concatenate([train, newPredEx], True)
extTrain = extTrain[0]
# Calculate a non-conf score for each ex in train + predEx with given label
if method == "scaledMinNN":
# Calculate average and std of min distanses in train set
maxDistRatio = getMinDistRatio(train)
nonConfList = []
nonConfListMondrian = []
for idx in range(len(extTrain)):
if method == "scaledMinNN":
alpha = getScore(idx, extTrain, method, maxDistRatio)
else:
alpha, SVMparam = getScore(idx, extTrain, SVMparam, method, None, measure)
nonConfList.append(alpha)
if extTrain[idx].get_class().value == label:
nonConfListMondrian.append(alpha)
#nonConfListSorted = copy.deepcopy(nonConfList)
#nonConfListSorted.sort()
#nonConfListMondrianSorted = copy.deepcopy(nonConfListMondrian)
#nonConfListMondrianSorted.sort()
#fid = open("NonConf.txt", "w")
#for ex in nonConfListSorted:
# fid.write(str(ex)+"\n")
#fid.close()
# The last non-conf score is that of predEx
# The p-value is the fraction of ex with alpha gt that of predEx
pvalue = getPvalueFromList(nonConfList)
pvalueMondrian = getPvalueFromList(nonConfListMondrian)
return pvalue, pvalueMondrian, SVMparam
def printResults(pvalues, labels, actualLabel, method, resultsFile, name):
confLevel = 0.95
#print "OBS! Assuming two labels!!!"
#print "Confidence level in predicting label ", labels[0]
conf1 = round(1-pvalues[1], 3)
#print "Confidence level in predicting label ", labels[1]
conf2 = round(1-pvalues[0], 3)
#print "Requiering 95% confidence gives "
if conf1 > confLevel and conf2 < confLevel:
# print "Label ", labels[0], "is predicted with at least 95% conf"
prediction = labels[0]
elif conf1 < confLevel and conf2 > confLevel:
# print "Label ", labels[1], "is predicted with at least 95% conf"
prediction = labels[1]
elif conf1 <= confLevel and conf2 <= confLevel:
# print "No prediction can be given at 95% confidence. Both?"
prediction = "Both"
else: # if conf1 > confLevel and conf2 > confLevel:
# print "Predicting both labels. Empty?"
prediction = "Empty"
fid = open(resultsFile, "a")
fid.write(str(name)+"\t"+actualLabel+"\t"+labels[0]+"\t"+labels[1]+"\t"+str(pvalues[0])+"\t"+str(pvalues[1])+"\t"+str(conf1)+"\t"+str(conf2)+"\t"+prediction+"\n")
fid.close()
return prediction
def printStat(resDict, labels):
# Print statistics
T0 = 0
T1 = 0
F0 = 0
F1 = 0
Both = 0
Empty = 0
for key, values in resDict.iteritems():
if values["actualLabel"] == labels[0]:
if values["actualLabel"] == values["prediction"]:
T0 = T0 + 1
elif values["prediction"] == "Both":
Both = Both + 1
elif values["prediction"] == "Empty":
Empty = Empty + 1
elif values["prediction"] == labels[1]:
F1 = F1 + 1
if values["actualLabel"] == labels[1]:
if values["actualLabel"] == values["prediction"]:
T1 = T1 + 1
elif values["prediction"] == "Both":
Both = Both + 1
elif values["prediction"] == "Empty":
Empty = Empty + 1
elif values["prediction"] == labels[0]:
F0 = F0 + 1
print "True ", labels[0], ": ", T0
print "True ", labels[1], ": ", T1
print "False ", labels[0], ": ", F0
print "False ", labels[1], ": ", F1
print "Both: ", Both
print "Empty: ", Empty
def getRFAcc(train, work):
model = AZorngRF.RFLearner(train)
TP = 0
TN = 0
FP = 0
FN = 0
for ex in work:
pred = model(ex).value
actual = ex.get_class().value
if actual == "POS":
if pred == "POS":
TP = TP + 1
else:
FN = FN + 1
elif actual == "NEG":
if pred == "NEG":
TN = TN + 1
else:
FP = FP + 1
print "TP\tTN\tFP\tFN\n"
print str(TP)+"\t"+str(TN)+"\t"+str(FP)+"\t"+str(FN)+"\n"
fid = open("RFresults.txt", "a")
fid.write(str(TP)+"\t"+str(TN)+"\t"+str(FP)+"\t"+str(FN)+"\n")
fid.close()
def getRFprobAcc(train, work, probThres):
model = AZorngRF.RFLearner(train)
TP = 0
TN = 0
FP = 0
FN = 0
noPred = 0
for ex in work:
actual = ex.get_class().value
predList = model(ex, returnDFV = True)
pred = predList[0].value
prob = predList[1]
if abs(prob) > probThres:
if actual == "POS":
if pred == "POS":
TP = TP + 1
else:
FN = FN + 1
elif actual == "NEG":
if pred == "NEG":
TN = TN + 1
else:
FP = FP + 1
else:
noPred = noPred + 1
print "TP\tTN\tFP\tFN\tnoPred\n"
print str(TP)+"\t"+str(TN)+"\t"+str(FP)+"\t"+str(FN)+"\t"+str(noPred)+"\n"
fid = open("RFprob"+str(probThres)+"Results.txt", "a")
fid.write(str(TP)+"\t"+str(TN)+"\t"+str(FP)+"\t"+str(FN)+"\t"+str(noPred)+"\n")
fid.close()
def getProbPredAlpha(model, ex):
predList = model(ex, returnDFV = True)
pred = predList[0].value
prob = predList[1]
actual = ex.get_class().value
# More non conforming if prediction is different from actual label
if pred != actual:
alpha = 1.0 + abs(prob)
else:
alpha = 1.0 - abs(prob)
return alpha
def probPredInd(trainSet, calSet):
"""
Use the RF prediction probability to set the non-conf score
"""
attrList = ["SMILES_1"]
trainSet = dataUtilities.attributeDeselectionData(trainSet, attrList)
# Train a model
model = AZorngRF.RFLearner(trainSet)
# Get the list of NC for all ex in calSet
alphaList = []
for ex in calSet:
alpha = getProbPredAlpha(model, ex)
alphaList.append(alpha)
return alphaList, model
def getScores(trainSet, calSet, method):
#if method == "minNN":
# alpha = minNN(idx, extTrain, measure)
#elif method == "avgNN":
# alpha = avgNN(idx, extTrain, measure)
#elif method == "scaledMinNN":
# print "There is some problem with the scaling"
# alpha = minNN(idx, extTrain, maxDistRatio, measure)
if method == "kNNratio":
alphaList, model = kNNratioInd(trainSet, calSet)
#elif method == "kNNratioStruct":
# alpha = kNNratioStruct(idx, extTrain, measure)
elif method == "probPred":
alphaList, model = probPredInd(trainSet, calSet)
#elif method == "LLOO":
# alpha = LLOO(idx, extTrain, measure)
#elif method == "LLOOprob":
# alpha = LLOOprob(idx, extTrain, measure)
#elif method == "LLOOprob_b":
# alpha = LLOOprob_b(idx, extTrain, measure)
#else:
# alpha = None
# print "Method not implemented"
return alphaList, model
def getIndPvalue(model, NClist, predEx, label, method = "avgNN", measure = None):
"""
method; avgNN, scaledMinNN, minNN, kNNratio
"""
# Set label to class of predEx
newPredEx = Orange.data.Table(predEx.domain, [predEx])
newPredEx[0][newPredEx.domain.classVar] = label
# Calculate the NC score of predEx
if method == "probPred":
alpha = getProbPredAlpha(model, newPredEx[0])
elif method == "kNNratio":
alphaList, model = kNNratioInd(model, newPredEx) # model is the train set for NN methods
alpha = alphaList[0]
# The p-value is the fraction of ex with alpha gt that of predEx
moreNonConfList = []
for score in NClist:
if score > alpha:
moreNonConfList.append(score)
pvalue = len(moreNonConfList)/float(len(NClist))
return pvalue
def getConfPred(train, work, method, SVMparam, measure = None, resultsFile = "CPresults.txt", verbose = False):
"""
method - non-conformity score method
"""
# Get conformal predictions
resDict = {}
idx = 0
for predEx in work:
labels = train.domain.classVar.values
pvalues = []
pvaluesMondrian = []
for label in labels:
if method == "combo":
pvalue1 = getPvalue(train, predEx, label, "kNNratio", measure)
pvalue2 = getPvalue(train, predEx, label, "probPred")
pvalue = (pvalue1 + pvalue2)/2.0
else:
pvalue, pvalueMondrian, SVMparam = getPvalue(train, predEx, label, SVMparam, method, measure)
pvalues.append(pvalue)
pvaluesMondrian.append(pvalueMondrian)
actualLabel = predEx.get_class().value
name = None
prediction = printResults(pvalues, labels, actualLabel, method, resultsFile, name)
MondrianFile = resultsFile+"_Mondrian.txt"
predictionMondrian = printResults(pvaluesMondrian, labels, actualLabel, method, MondrianFile, name)
idx = idx + 1
resDict[idx] = {"actualLabel": actualLabel, "prediction": predictionMondrian}
if verbose:
printStat(resDict, labels)
return SVMparam, resDict
def getIndConfPred(train, work, method, measure = None, resultsFile = "CPresults.txt", verbose = False):
"""
Partition train into a training and a calibration set (10%). Use the non-conf scores of the cal set to predict
all examples in work.
method - non-conformity score method
"""
# Randomily select 10% of train as a cal set
indices2 = Orange.data.sample.SubsetIndices2(p0=0.10)
ind = indices2(train)
calSet = train.select(ind, 0)
trainSet = train.select(ind, 1)
# Calculate NC for the calibration set
NClist, model = getScores(trainSet, calSet, method)
# Calculate p-values for all ex in work
resDict = {}
idx = 0
for predEx in work:
labels = predEx.domain.classVar.values
pvalues = []
for label in labels:
if method == "combo":
pvalue1 = getIndPvalue(model, NClist, predEx, label, "kNNratio", measure)
pvalue2 = getIndPvalue(model, NClist, predEx, label, "probPred")
pvalue = (pvalue1 + pvalue2)/2.0
else:
pvalue = getIndPvalue(model, NClist, predEx, label, method, measure)
pvalues.append(pvalue)
actualLabel = predEx.get_class().value
prediction = printResults(pvalues, labels, actualLabel, method, resultsFile)
idx = idx + 1
resDict[idx] = {"actualLabel": actualLabel, "prediction": prediction}
#print "Break after the first example"
#if idx == 1: break
if __name__ == "__main__":
"""
Assumptions;
Binary classification
This main will test the implemented CP methods in a 10 fold CV
"""
data = dataUtilities.DataTable("HLMSeries2_rdkPhysChemPrepClass.txt")
attrList = ['"Medivir;HLM (XEN025);CLint (uL/min/mg);(Num)"', 'Structure', '"MV Number"', "rdk.MolecularFormula"]
data = dataUtilities.attributeDeselectionData(data, attrList)
print "Select all attributes"
descListList = [[]]
for attr in data.domain.attributes:
descListList[0].append(attr.name)
#methods = ["kNNratio", "minNN", "avgNN", "probPred", "combo", "LLOO", "LLOOprob"] # Non-conformity score method
methods = ["probPred"]
cpMethod = "transductive" # inductive or transductive
#print "Temp position to save comp time!!"
# Append to python path /home/kgvf414/dev/AZOrange0.5.5/orangeDependencies/src/orange/orange/Orange/distance/
#import instances
#measure = instances.MahalanobisConstructor(data)
measure = None
methodIdx = 1
method = methods[0]
idx = 0
descResultsFile = "CPresults.txt"
fid = open(descResultsFile, "w")
fid.close()
for descList in descListList:
SVMparam = []
idx = idx + 1
resultsFile = "CPresults.txt"
fid = open(resultsFile, "w")
fid.write("Name\tActualLabel\tLabel1\tLabel2\tPvalue1\tPvalue2\tConf1\tConf2\tPrediction\n")
fid.close()
MondrianFile = resultsFile+"_Mondrian"
fid = open(MondrianFile, "w")
fid.write("Name\tActualLabel\tLabel1\tLabel2\tPvalue1\tPvalue2\tConf1\tConf2\tPrediction\n")
fid.close()
# Run a 10 fold CV
nFolds = 10
ind = Orange.data.sample.SubsetIndicesCV(data, nFolds)
for idx in range(nFolds):
work = data.select(ind, idx)
train = None
for iidx in range(nFolds):
if iidx != idx:
if not train:
train = data.select(ind, iidx)
else:
train.extend(data.select(ind, iidx))
print "Length of train ", len(train)
print "Length of work ", len(work)
# Create results file and get the conformal predictions
if cpMethod == "transductive":
#SVMparam = getConfPred(train, work, method, descList, SVMparam, measure, resultsFile, True)
SVMparam, resDict = getConfPred(train, work, method, SVMparam, measure, resultsFile, True)
elif cpMethod == "inductive":
print "Please note, only kNNratio and probPred implemented for ICP!"
getIndConfPred(train, work, method, measure, resultsFile, verbose = True)
else:
print "Valid cpMethod values are 'transductive' and 'inductive'"
print descList
fid = open(descResultsFile, "a")
fid.write(str(descList)+"\n")
fid.close()
print "OBS copy printstatwithname"
#printStatWithName.readAndPrint(resultsFile, descResultsFile)
| JonnaStalring/AZOrange | azorange/AZutilities/TCPMondrian.py | Python | lgpl-3.0 | 33,237 |
# Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> or <pmartin@yaco.es>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this programe. If not, see <http://www.gnu.org/licenses/>.
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
INPLACEEDIT_EDIT_EMPTY_VALUE = (getattr(settings, 'INPLACEEDIT_EDIT_EMPTY_VALUE', None) and
_(settings.INPLACEEDIT_EDIT_EMPTY_VALUE) or _('Doubleclick to edit'))
INPLACEEDIT_AUTO_SAVE = getattr(settings, 'INPLACEEDIT_AUTO_SAVE', False)
INPLACEEDIT_EVENT = getattr(settings, 'INPLACEEDIT_EVENT', 'dblclick')
INPLACEEDIT_DISABLE_CLICK = getattr(settings, 'INPLACEEDIT_DISABLE_CLICK', True)
INPLACEEDIT_EDIT_MESSAGE_TRANSLATION = (getattr(settings, 'INPLACEEDIT_EDIT_MESSAGE_TRANSLATION', None) and
_(settings.INPLACEEDIT_EDIT_MESSAGE_TRANSLATION) or _('Write a translation'))
INPLACEEDIT_SUCCESS_TEXT = (getattr(settings, 'INPLACEEDIT_SUCCESS_TEXT', None) and
_(settings.INPLACEEDIT_SUCCESS_TEXT) or _('Successfully saved'))
INPLACEEDIT_UNSAVED_TEXT = (getattr(settings, 'INPLACEEDIT_UNSAVED_TEXT', None) and
_(settings.INPLACEEDIT_UNSAVED_TEXT) or _('You have unsaved changes!'))
INPLACE_ENABLE_CLASS = getattr(settings, 'ADAPTOR_INPLACEEDIT_EDIT', 'enable')
DEFAULT_INPLACE_EDIT_OPTIONS = getattr(settings, "DEFAULT_INPLACE_EDIT_OPTIONS", {})
DEFAULT_INPLACE_EDIT_OPTIONS_ONE_BY_ONE = getattr(settings, 'DEFAULT_INPLACE_EDIT_OPTIONS_ONE_BY_ONE', False)
ADAPTOR_INPLACEEDIT_EDIT = getattr(settings, 'ADAPTOR_INPLACEEDIT_EDIT', None)
ADAPTOR_INPLACEEDIT = getattr(settings, 'ADAPTOR_INPLACEEDIT', {})
INPLACE_GET_FIELD_URL = getattr(settings, 'INPLACE_GET_FIELD_URL', None)
INPLACE_SAVE_URL = getattr(settings, 'INPLACE_SAVE_URL', None)
INPLACE_FIELD_TYPES = getattr(settings, 'INPLACE_FIELD_TYPES', 'input, select, textarea')
INPLACE_FOCUS_WHEN_EDITING = getattr(settings, 'INPLACE_FOCUS_WHEN_EDITING', True)
| shadow-identity/django-inplaceedit | inplaceeditform/settings.py | Python | lgpl-3.0 | 2,572 |
"""Driver module for Newport's Spectra-Physics Quanta-Ray INDI, PRO, and LAB
Series Nd:YAG lasers.
NOTE: the watchdog parameter is important! The laser will turn off if it does
not receive a command within the watchdog time period. Therefore, it is
advised to use a command like QRstatus().get_status() at regular intervals to
query the status of the laser during operation.
@author: Jami L Johnson
September 5, 2014
"""
import serial
class QuantaRay:
"""QuantaRay class"""
def __init__(self, portINDI='/dev/ttyUSB0', baudINDI=9600):
"""Define serial port for INDI"""
self.indi = serial.Serial(
port=portINDI,
baudrate=baudINDI,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.EIGHTBITS
)
def open_connection(self):
""" Open serial connection to INDI"""
self.indi.close()
self.indi.open()
indi_open = self.indi.isOpen()
if indi_open is False:
raise RuntimeError('unable to connect to INDI')
def close_connection(self):
"""Close connection to INDI"""
self.indi.close()
def get_id(self):
"""Get ID"""
self.indi.write('*IDN?\r'.encode())
return self.indi.readline().decode()
def help(self):
"""Prints serial command options (operational commands)"""
self.indi.write('HELP\r'.encode())
for _ in range(1, 6):
print(self.indi.readline().decode())
def turn_on(self):
"""Turns Quanta-Ray INDI on"""
self.indi.write('ON\r'.encode())
def turn_off(self):
"""Turns Quanta-Ray INDI off"""
self.indi.write('OFF\r'.encode())
def set_lamp(self, lamp_set='FIX', lamp_pulse=''):
"""Select lamp trigger source
lamp_set:
FIX = set lamp trigger to Fixed
EXT = set lamp trigger to External Source
VAR = set lamp trigger to Variable
INH = inhibit lamp trigger
lamp_pulse = set rate of lamp (pulses/second)
"""
if lamp_pulse != '':
self.indi.write(('LAMP '+ str(lamp_set) + ' ' + str(lamp_pulse) + '\r').encode())
else:
self.indi.write(('LAMP '+ str(lamp_set) + '\r').encode())
def get_lamp(self):
""" Returns the lamp Variable Rate trigger setting """
self.indi.write('LAMP VAR?\r'.encode())
return self.indi.readline().decode()
def set(self, cmd='NORM'):
"""Set mode, type, or timing of Q-switch
cmd:
LONG = long pulse mode
EXT = external mode
NORM = normal mode
SING = single shot
FIR = fire Q-switch once
REP = repetitive shots
"""
self.indi.write(('QSW ' + str(cmd) + '\r').encode())
def single_shot(self):
"""Set single shot"""
self.set('SING')
def normal_mode(self):
"""Set normal mode"""
self.set('NORM')
def repeat_mode(self, watchdog_timeout):
"""Set repetitive shots and ensures watchdog is turned on (not disabled)
:param watchdog_timeout: seconds before laser safety shutoff
:type watchdog_timeout: int
#:raises ValueError: if watchdog is requested to be 0 (disabled)
"""
if watchdog_timeout == 0:
dummy = input('QuantaRay INDI Laser watchdog is 0 s. This will ' +
'disable watchdog and the laser will continue to run ' +
'after the experiment has finished. Continue? [ y / n ]:')
if dummy == 'n':
raise ValueError('Disabling watchdog when using repeat mode is not advised')
self.set_watchdog(watchdog_timeout)
self.set('REP')
def get(self):
"""Queries and returns the Q-switch settings."""
self.indi.write('QSW?\r'.encode())
return self.indi.readline().decode()
def set_adv(self, delay):
"""Set advanced sync delay"""
self.indi.write(('ADV ' + str(delay) + '\r').encode())
def get_adv(self):
"""Queries and returns the Q-switch Advanced Sync settings"""
self.indi.write('QSW ADV? \r'.encode())
return self.indi.readline().decode()
def set_delay(self, delay):
"""Sets delay for Q-switch delay"""
self.indi.write(('QSW DEL ' + str(delay) + '\r').encode())
def get_delay(self):
"""Queries and returns the Q-switch delay setting"""
self.indi.write('QSW DEL? \r'.encode())
return self.indi.readline().decode()
def set_echo(self, mode=0):
"""Set echo mode of INDI.
mode:
0 = show prompts
1 = laser echoes characters as received
2 = shows error messages
3 = output line feed for every command (even those that don't normally generate a response)
4 = terminate responses with <cr><lf>, rather than just <lf>
5 = use XON/XOFF handshaking for data sent to laser (not for data sent from the laser)
"""
self.indi.write(('ECH ' + str(mode) + '\r').encode())
def set_watchdog(self, time=10):
"""Set range of watchdog. If the laser does not receive communication
from the control computer within the specifiedc time, it turns off. If
disabled, the default time is zero. Time must be between 0 and 110
seconds.
"""
if time < 0 or time > 110:
raise ValueError('Invalid watchdog time. Choose value between 0 and 110 seconds.')
self.indi.write(('WATC ' + str(time) + '\r').encode())
def set_baud(self, baud_indi=9600):
"""Sets baudrate of laser. At power-up, baudrate is always 9600."""
self.indi.write(('BAUD ' + str(baud_indi) + '\r').encode())
def get_amp_setting(self):
"""Queries amplifier PFN command setting in percent"""
self.indi.write('READ:APFN?\r'.encode())
return self.indi.readline().decode()
def get_amp_power(self):
"""Queries amplifier PFN monitor in percent (what PFN power supply is actually doing)"""
self.indi.write('READ:AMON?\r'.encode())
return self.indi.readline().decode()
def get_osc_setting(self):
"""Queries oscillator PFN command setting in percent"""
self.indi.write('READ:OPFN?\r'.encode())
return self.indi.readline().decode()
def get_osc_power(self):
"""Queries oscillator PFN monitor in percent (what PFN power supply is actually doing)"""
self.indi.write('READ:OMON?\r'.encode())
return self.indi.readline().decode()
def get_qsw_adv(self):
"""Queries and returns the current Q-Switch Advanced Sync setting"""
self.indi.write('READ:QSWADV?\r'.encode())
return self.indi.readline().decode()
def get_shots(self):
"""Queries and returns the number of shots"""
self.indi.write('SHOT?\r'.encode())
return self.indi.readline().decode()
def get_trig_rate(self):
"""Queries and returns the lamp trigger rate (unless lamp trigger source is external"""
self.indi.write('READ:VAR?\r'.encode())
return self.indi.readline().decode()
def set_osc_power(self, percent=0):
"""set the Oscillator PFN voltage as a percentage of factory full scale"""
self.indi.write(('OPFN ' + str(percent) + '\r').encode())
def set_amp_power(self, percent=0):
"""set the PFN Amplifier voltage as a percentage of factory full scale"""
self.indi.write(('APFN ' + str(percent) + '\r').encode())
def get_status(self):
"""Returns the laser status.
Result is a list with entries of the form: [bit, error], where "bit" is
the bit of the status byte, and "error" is a text description of the
error.
"""
self.indi.write('*STB?\r'.encode())
stb_value = bin(int(self.indi.readline().decode()))
stb_value = stb_value[2:] # remove 0b at beginning
#print 'stb_value: ', stb_value # prints binary status byte value
error_list = list()
if stb_value[len(stb_value)-1] == '1':
bit = '0'
error = 'Laser emission can occur'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-2] == '1':
bit = '1'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-3] == '1':
bit = '2'
error = ('Data is in the error log.\n'
+ '(use QRstatus().getHist() for details on the error.)')
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-4] == '1':
bit = '3'
error = 'Check QRstatus().getQuest() for error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-5] == '1':
bit = '4'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-6] == '1': #5 **********
bit = '5'
error = 'Check *ESR bits for error.'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-7] == '1':
bit = '6'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-8] == '1': #7 ****
bit = '7'
error = 'Check STR:OPER bits'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-9] == '1':
bit = '8'
error = 'Main contactor is energized'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-10] == '1':
bit = '9'
error = 'Oscillator simmer is on'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-11] == '1':
bit = '10'
error = 'Amplifier simmer is on'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-12] == '1':
bit = '11'
error = 'Oscillator PFN is at target'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-13] == '1':
bit = '12'
error = 'The laser has recently fired'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-14] == '1':
bit = '13'
error = '15 Vdc power supply failure'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-15] == '1':
bit = '14'
error = 'Laser cover interlock open'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-16] == '1':
bit = '15'
error = ('Interlock open: CDRH plug, power supply cover, laser '
+ 'head cover, laser head temperature, water pressure, '
+ 'or water flow')
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-17] == '1':
bit = '16'
error = 'Remote panel disconnected'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-18] == '1':
bit = '17'
error = 'Internal 208 Vac failure'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-19] == '1':
bit = '18'
error = 'CDRH enable failure'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-20] == '1':
bit = '19'
error = 'Laser ID fault'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-21] == '1':
bit = '20'
error = 'Low water fault'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-22] == '1':
bit = '21'
error = 'Interlock fault'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-23] == '1':
bit = '22'
error = 'Remote panel connected'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-24] == '1':
bit = '23'
error = 'Remote panel indicates that the computer is in control.'
stat = [bit, error]
error_list.append(stat)
if len(stb_value) > 24:
if stb_value[len(stb_value)-25] == '1':
bit = '24'
error = 'Main contactor should be on.'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-26] == '1':
bit = '25'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-27] == '1':
bit = '26'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-28] == '1':
bit = '27'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-29] == '1':
bit = '28'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-30] == '1':
bit = '29'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-31] == '1':
bit = '30'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
if stb_value[len(stb_value)-31] == '1':
bit = '32'
error = 'Reserved error'
stat = [bit, error]
error_list.append(stat)
return error_list
def get_quest(self):
"""Returns questionable condition register.
Result is a list with entries of the form: [bit, error], where "bit" is
the bit of the status byte, and "error" is a text description of the
error.
"""
self.indi.write('STAT:QUES?\r'.encode())
qb_value = bin(int(self.indi.readline().decode()))
qb_value = qb_value[3:]
error_list = list()
#print 'qb_value: ', qb_value # prints binary STAT:QUES? value
if qb_value[len(qb_value)-1] == '1':
bit = '0'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-2] == '1':
bit = '1'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-3] == '1':
bit = '2'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-4] == '1':
bit = '3'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-5] == '1':
bit = '4'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-6] == '1':
bit = '5'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-7] == '1':
bit = '6'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-8] == '1':
bit = '7'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-9] == '1':
bit = '8'
error = '-Reserved error'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-10] == '1':
bit = '9'
error = '-Oscillator HV failure'
stat = [bit, error]
error_list.append(stat)
QuantaRay().turn_off()
exit()
if qb_value[len(qb_value)-11] == '1':
bit = '10'
error = '-Amplifier HV failure'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-12] == '1':
bit = '11'
error = '-External trigger rate out of range.'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-13] == '1':
bit = '12'
error = '-De-ionized water low'
stat = [bit, error]
error_list.append(stat)
if len(qb_value) > 15:
# bits 13-15 undefined
if qb_value[len(qb_value)-17] == '1':
bit = '16'
error = '-OSC HVPS # 1 EndOfCharge'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-18] == '1':
bit = '17'
error = '-OverLoad'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-19] == '1':
bit = '18'
error = '-OverTemp'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-20] == '1':
bit = '19'
error = '-OverVolt'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-21] == '1':
bit = '20'
error = '-OSC HVPS #2 EndOfCharge'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-22] == '1':
bit = '21'
error = '-OverLoad'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-23] == '1':
bit = '22'
error = '-OverTemp'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-24] == '1':
bit = '23'
error = '-OverVolt'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-25] == '1':
bit = '24'
error = '-AMP HVPS # 1 EndOfCharge'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-26] == '1':
bit = '25'
error = '-OverLoad'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-27] == '1':
bit = '26'
error = '-OverTemp'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-28] == '1':
bit = '27'
error = '-OverVolt'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-29] == '1':
bit = '28'
error = '-AMP HVPS # 2 EndOfCharge'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-30] == '1':
bit = '29'
error = '-OverLoad'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-31] == '1':
bit = '30'
error = '-OverTemp'
stat = [bit, error]
error_list.append(stat)
if qb_value[len(qb_value)-32] == '1':
bit = '31'
error = '-OverVolt'
stat = [bit, error]
error_list.append(stat)
return error_list
def reset(self):
""" Resets the laser head PC board"""
self.indi.write('*RST?\r'.encode())
print('Laser PC board reset')
def get_hist(self):
"""Returns up to 16 status/error codes from the system history buffer.
Use if the laser has shut off or the system is behaving erratically.
The first element is the most recent.
Example output:
1 827 # 1 error has occured, current time is 827 sec
301 801 # Error code 301 occured at 810 seconds
0 0 # End of history buffer
"""
self.indi.write('READ:HIST?\r'.encode())
reply = '1'
reply_list = list()
while reply[0] != '0': #end of history buffer
reply = self.indi.readline().decode().rstrip()
reply_list.append(reply)
return reply_list
| PALab/PLACE | place/plugins/quanta_ray/qray_driver.py | Python | lgpl-3.0 | 21,278 |
#!/usr/bin/python
import sys
import urllib2
RAINX_STAT_KEYS = [
("rainx.reqpersec", "total_reqpersec"),
("rainx.reqputpersec", "put_reqpersec"),
("rainx.reqgetpersec", "get_reqpersec"),
("rainx.avreqtime", "total_avreqtime"),
("rainx.avputreqtime", "put_avreqtime"),
("rainx.avgetreqtime", "get_avreqtime"),
]
def parse_info(stream):
data = {}
for line in stream.readlines():
parts = line.split()
if len(parts) > 1:
# try to cast value to int or float
try:
value = int(parts[1])
except ValueError:
try:
value = float(parts[1])
except ValueError:
value = parts[1]
data[parts[0]] = value
else:
data[parts[0]] = None
return data
def get_stat_lines(url, stat_keys):
stream = urllib2.urlopen(url)
data = parse_info(stream)
stream.close()
stats = [("stat.%s = %s" % (k[1], str(data[k[0]])))
for k in stat_keys if k[0] in data]
return stats
def main(args):
ip_port = args[1].split("|")[2]
stats_url = "http://%s/stat" % ip_port
for stat in get_stat_lines(stats_url, RAINX_STAT_KEYS):
print stat
if __name__ == "__main__":
main(sys.argv)
| redcurrant/redcurrant | svc-monitor/contrib/rainx-monitor.py | Python | lgpl-3.0 | 1,285 |
# -*- coding: utf-8 -*-
import unittest
from nose.tools import ok_, eq_, assert_equal, assert_false, assert_true, assert_raises
# noinspection PyUnresolvedReferences
from .._tins import EthernetII, HWAddress, PDU, IP, TCP, RAW, PDUNotFound, UDP, ICMP, OptionNotFound, DNS, DHCP, IPv4Address
import platform
IS_MACOSX = platform.system().lower().strip() == "darwin"
def _f(packet):
return "".join(chr(i) for i in packet)
dhcp_chaddr = "16:ab:54:12:fa:ca:56:7f:1b:65:11:fa:da:ab:19:18"
sname = "\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xbb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xcb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xeb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xfb\x19\x18"
dhcp_file = "\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xbb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xcb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xeb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xfb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xbb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xcb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xeb\x19\x18" \
"\x16\xab\x54\x12\xfa\xca\x56\x7f\x1b\x65\x11\xfa\xda\xfb\x19\x18"
addr = "192.168.8.1"
expected_packet = _f([
1, 1, 6, 31, 63, 171, 35, 222, 159, 26, 0, 0, 192, 168, 0, 102, 243,
22, 34, 98, 167, 32, 11, 154, 123, 43, 55, 254, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 99, 130, 83, 99,
54, 4, 192, 168, 4, 2, 1, 4, 255, 255, 32, 11, 53, 1, 4, 3, 8, 192,
168, 0, 1, 127, 0, 0, 1, 6, 8, 192, 168, 0, 2, 127, 0, 0, 1
])
class DHCPTest(unittest.TestCase):
def check_equals(self, dhcp1, dhcp2):
eq_(dhcp1.opcode, dhcp2.opcode)
eq_(dhcp1.htype, dhcp2.htype)
eq_(dhcp1.hlen, dhcp2.hlen)
eq_(dhcp1.hops, dhcp2.hops)
eq_(dhcp1.xid, dhcp2.xid)
eq_(dhcp1.padding, dhcp2.padding)
eq_(dhcp1.ciaddr, dhcp2.ciaddr)
eq_(dhcp1.yiaddr, dhcp2.yiaddr)
eq_(dhcp1.siaddr, dhcp2.siaddr)
eq_(dhcp1.giaddr, dhcp2.giaddr)
eq_(dhcp1.chaddr, dhcp2.chaddr)
eq_(dhcp1.sname, dhcp2.sname)
eq_(dhcp1.file, dhcp2.file)
eq_(set(dhcp1.options()), set(dhcp1.options()))
def test_constr(self):
dhcp = DHCP()
assert_equal(dhcp.htype, 1)
assert_equal(dhcp.hlen, 6)
def test_copy(self):
dhcp1 = DHCP.from_buffer(expected_packet)
dhcp2 = dhcp1.copy()
self.check_equals(dhcp1, dhcp2)
def test_opcode(self):
dhcp = DHCP()
dhcp.opcode = 0x71
eq_(dhcp.opcode, 0x71)
def test_htype(self):
dhcp = DHCP()
dhcp.htype = 0x71
eq_(dhcp.htype, 0x71)
def test_hlen(self):
dhcp = DHCP()
dhcp.hlen = 0x71
eq_(dhcp.hlen, 0x71)
def test_hops(self):
dhcp = DHCP()
dhcp.hops = 0x71
eq_(dhcp.hops, 0x71)
def test_xid(self):
dhcp = DHCP()
dhcp.xid = 0x71bd167c
eq_(dhcp.xid, 0x71bd167c)
def test_srcs(self):
dhcp = DHCP()
dhcp.secs = 0x71
eq_(dhcp.secs, 0x71)
def test_padding(self):
dhcp = DHCP()
dhcp.padding = 0x71bd
eq_(dhcp.padding, 0x71bd)
def test_ciaddr(self):
dhcp = DHCP()
dhcp.ciaddr = addr
eq_(dhcp.ciaddr, addr)
def test_yiaddr(self):
dhcp = DHCP()
dhcp.yiaddr = addr
eq_(dhcp.yiaddr, addr)
def test_siaddr(self):
dhcp = DHCP()
dhcp.siaddr = addr
eq_(dhcp.siaddr, addr)
def test_giaddr(self):
dhcp = DHCP()
dhcp.giaddr = addr
eq_(dhcp.giaddr, addr)
def test_chaddr(self):
dhcp = DHCP()
dhcp.chaddr = dhcp_chaddr
eq_(dhcp.chaddr, dhcp_chaddr)
dhcp.chaddr = "31:33:70:00"
eq_("31:33:70:00", dhcp.chaddr[:11])
def test_sname(self):
dhcp = DHCP()
dhcp.sname = sname
eq_(dhcp.sname, sname)
def test_file(self):
dhcp = DHCP()
dhcp.file = dhcp_file
eq_(dhcp.file, dhcp_file)
def test_type_opt(self):
dhcp = DHCP()
dhcp.type = DHCP.Flags.REQUEST
eq_(dhcp.type, DHCP.Flags.REQUEST)
def test_server_id_opt(self):
dhcp = DHCP()
dhcp.server_identifier = "192.168.0.1"
eq_(dhcp.server_identifier, "192.168.0.1")
def test_lease(self):
dhcp = DHCP()
dhcp.lease_time = 0x34f1
eq_(dhcp.lease_time, 0x34f1)
def test_subnet_mask(self):
dhcp = DHCP()
dhcp.subnet_mask = "192.168.0.1"
eq_(dhcp.subnet_mask, "192.168.0.1")
def test_routers_option(self):
dhcp = DHCP()
routers = [IPv4Address("192.168.0.253"), IPv4Address("10.123.45.67")]
dhcp.routers = routers
eq_(dhcp.routers, routers)
def test_dns_option(self):
dhcp = DHCP()
dns = [IPv4Address("192.168.0.253"), IPv4Address("10.123.45.67")]
dhcp.domain_name_servers = dns
eq_(dhcp.domain_name_servers, dns)
def test_domain_name_opt(self):
dhcp = DHCP()
domain = "libtins.test.domain"
dhcp.domain_name = domain
eq_(dhcp.domain_name, domain)
def test_hostname_opt(self):
dhcp = DHCP()
hostname = "libtins-hostname"
dhcp.hostname = hostname
eq_(dhcp.hostname, hostname)
def test_broadcast_opt(self):
dhcp = DHCP()
dhcp.broadcast = "192.168.0.1"
eq_(dhcp.broadcast, "192.168.0.1")
def test_constr_buffer(self):
dhcp1 = DHCP.from_buffer(expected_packet)
expected_routers = [IPv4Address("192.168.0.1"), IPv4Address("127.0.0.1")]
eq_(dhcp1.opcode, DHCP.Flags.DISCOVER)
eq_(dhcp1.htype, 1)
eq_(dhcp1.hlen, 6)
eq_(dhcp1.hops, 0x1f)
eq_(dhcp1.xid, 0x3fab23de)
eq_(dhcp1.secs, 0x9f1a)
eq_(dhcp1.padding, 0)
eq_(dhcp1.ciaddr, "192.168.0.102")
eq_(dhcp1.yiaddr, "243.22.34.98")
eq_(dhcp1.giaddr, "123.43.55.254")
eq_(dhcp1.siaddr, "167.32.11.154")
eq_(dhcp1.server_identifier, "192.168.4.2")
eq_(dhcp1.routers, expected_routers)
def test_serialize(self):
dhcp1 = DHCP.from_buffer(expected_packet)
buf = dhcp1.serialize()
eq_(expected_packet, buf)
dhcp2 = DHCP.from_buffer(buf)
self.check_equals(dhcp1, dhcp2)
| stephane-martin/cycapture | cycapture/libtins/tests/test_dhcp.py | Python | lgpl-3.0 | 7,257 |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from datetime import datetime, timedelta
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
try:
from oauthlib import common as oauthlib_common
except:
pass
import uuid
class OauthApplication(models.Model):
CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
_name = 'oauth.application'
_rec_name = 'client_id'
def generate_client_id(self):
return str(uuid.uuid1())
client_id = fields.Char('Client ID', index=True, required=True, default=generate_client_id)
token_ids = fields.One2many('oauth.access_token', 'application_id', 'Tokens')
_sql_constraints = [
('client_id_uniq', 'unique (client_id)', 'client_id should be unique!'),
]
@api.multi
def _get_access_token(self, user_id=None, create=False):
self.ensure_one()
if not user_id:
user_id = self.env.user.id
access_token = self.env['oauth.access_token'].sudo().search([('application_id', '=', self.id), ('user_id', '=', user_id)], order='id DESC', limit=1)
if access_token:
access_token = access_token[0]
if access_token.is_expired():
access_token = None
if not access_token and create:
expires = datetime.now() + timedelta(seconds=60 * 60)
vals = {
'user_id': user_id,
'scope': 'userinfo',
'expires': expires.strftime(DEFAULT_SERVER_DATETIME_FORMAT),
'token': oauthlib_common.generate_token(),
'application_id': self.id,
}
access_token = self.env['oauth.access_token'].create(vals)
# we have to commit now, because /oauth2/tokeninfo could
# be called before we finish current transaction.
self._cr.commit()
if not access_token:
return None
return access_token.token
class OauthAccessToken(models.Model):
_name = 'oauth.access_token'
application_id = fields.Many2one('oauth.application', string='Application')
token = fields.Char('Access Token', required=True)
user_id = fields.Many2one('res.users', string='User', required=True)
expires = fields.Datetime('Expires', required=True)
scope = fields.Char('Scope')
@api.multi
def is_valid(self, scopes=None):
"""
Checks if the access token is valid.
:param scopes: An iterable containing the scopes to check or None
"""
self.ensure_one()
return not self.is_expired() and self._allow_scopes(scopes)
@api.multi
def is_expired(self):
self.ensure_one()
return datetime.now() > datetime.strptime(self.expires, DEFAULT_SERVER_DATETIME_FORMAT)
@api.multi
def _allow_scopes(self, scopes):
self.ensure_one()
if not scopes:
return True
provided_scopes = set(self.scope.split())
resource_scopes = set(scopes)
return resource_scopes.issubset(provided_scopes)
| thinkopensolutions/odoo-saas-tools | oauth_provider/models/oauth_provider.py | Python | lgpl-3.0 | 3,090 |
# Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
from rbnics.utils.io import NumpyIO
def function_load(fun, directory, filename, suffix=None):
if suffix is not None:
filename = filename + "." + str(suffix)
file_exists = NumpyIO.exists_file(directory, filename)
if file_exists:
vec = NumpyIO.load_file(directory, filename)
fun.vector()[:] = vec
return file_exists
| mathLab/RBniCS | rbnics/backends/online/numpy/wrapping/function_load.py | Python | lgpl-3.0 | 485 |
# Copyright (C) 2016 VIB/BEG/UGent - Tim Diels <tim@diels.me>
#
# This file is part of pytil.
#
# pytil is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pytil is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pytil. If not, see <http://www.gnu.org/licenses/>.
from contextlib import contextmanager
from pathlib import Path
from pytil import path as path_ # yay, 'resolving' circular dependencies
import pytest
import os
# Used by cedalion
@pytest.fixture
def temp_dir_cwd(tmpdir):
'''
pytest fixture which sets current working directory to a temporary
directory.
'''
original_cwd = Path.cwd()
os.chdir(str(tmpdir))
yield tmpdir
# ensure the user has full permissions on temp dir (so that pytest can remove it later)
path_.chmod(Path(str(tmpdir)), 0o700, '+', recursive=True)
os.chdir(str(original_cwd))
# Used by cedalion
@contextmanager
def assert_dir_unchanged(path, ignore=()):
'''
Assert dir unchanged after code block.
Parameters
----------
path : ~pathlib.Path
Dir to assert for changes.
ignore : ~typing.Collection[~pathlib.Path]
Paths to ignore in comparison.
Examples
--------
>>> with assert_dir_unchanged(Path('input')):
... Path('input/child').mkdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: ...
'''
def contents():
children = set(path.iterdir())
ignored_children = {
child
for child in children
for path in ignore
if path_.is_descendant_or_self(child, path)
}
return set(map(str, children - ignored_children))
expected = contents()
yield
actual = contents()
assert actual == expected, f'\nActual: {actual}\nExpected: {expected}'
| timdiels/chicken_turtle_util | pytil/test.py | Python | lgpl-3.0 | 2,286 |
# -*- coding: utf-8 -*-
import pytest
from greek_stemmer.tools.text_tools import *
class TestParseText:
def test_parse_word_receives_no_string(self):
assert parse_word(None) == ''
# check accents removal and uppercase letters
parse_word_testdata = [
(' $', '$'),
(' foo ', 'FOO'),
('(25%)', '(25%)'),
(u'\u2167 ί', 'Ⅷ Ι'),
("Greek's", "GREEK'S"),
('κ', 'Κ'),
('ιστορικός', 'ΙΣΤΟΡΙΚΟΣ'),
('Ιστορικός ', 'ΙΣΤΟΡΙΚΟΣ'),
('ΙΣΤΟΡΙΚΌΣ', 'ΙΣΤΟΡΙΚΟΣ'),
('Λαϊκός', 'ΛΑΙΚΟΣ'),
(' ΛΑΪΚΌΣ', 'ΛΑΙΚΟΣ')
]
@pytest.mark.parametrize('word, output', parse_word_testdata)
def test_parse_word_with_various_inputs(self, word, output):
assert parse_word(word) == output
class TestParsePos:
def test_parse_pos_receives_no_string(self):
with pytest.raises(TypeError):
parse_pos(None)
# check accents removal and uppercase letters
parse_pos_testdata = [
(' $', '$'),
(' foo ', 'FOO'),
('(25%)', '(25%)'),
(u'\u2167 ι', 'Ⅷ Ι'),
("Greek's", "GREEK'S"),
('κ', 'Κ'),
('nnsf', 'NNSF'),
('vbfs ', 'VBFS'),
(' prp', 'PRP'),
('Inp', 'INP'),
(' date ', 'DATE')
]
@pytest.mark.parametrize('word, output', parse_pos_testdata)
def test_parse_pos_with_various_inputs(self, word, output):
assert parse_pos(word) == output
class TestIsGreek:
def test_is_greek_receives_no_string(self):
assert is_greek(None) is False
# check accents removal and uppercase letters
parse_is_greek_testdata = [
(' $', False),
('0.5', False),
('foo', False),
('(25%)', False),
(u'\u2167 ί', False),
("Greek's", False),
('κ', True),
('eλληνικά', False),
('EΛΛΗΝΙΚΆ', False),
('ΕΛΛΗΝΙΚΑ', True),
(' ελληνικά', True),
('NOT', False),
('ΝΟΤ', True),
(' Λαϊκός ', True),
('ΛΑΪΚΌΣ', True)
]
@pytest.mark.parametrize('word, output', parse_is_greek_testdata)
def test_is_greek_with_various_inputs(self, word, output):
assert is_greek(word) == output
| kpech21/Greek-Stemmer | tests/tools/test_text_tools.py | Python | lgpl-3.0 | 2,368 |
'''
PyPlato is set of batching utilies useful in HPC scheduling context
and shell (bash-like) automation in python.
Copyright (C) 2013 Yauhen Yakimovich
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
'''
import logging
def getBasicLogger(name, level):
logging.basicConfig(level=level,
format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')
console = logging.StreamHandler()
console.setLevel(level)
logger = logging.getLogger(name)
return logger
| ewiger/plato | src/plato/__init__.py | Python | lgpl-3.0 | 1,105 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
INSTR_PER_LINE = 8
class Output(object):
def __init__(self):
pass
def output_text(self, tokens, outfile):
fd = open(outfile, 'w')
instr_counter = 0
for t in tokens:
instr = "%02X%02X%02X%02X" % tuple(reversed(t))
instr_counter = instr_counter + 1
if (instr_counter >= INSTR_PER_LINE):
instr_counter = 0
instr += "\n"
else:
instr += " "
fd.write(instr)
fd.close()
| m-wichmann/pyArch | asm/src/output.py | Python | lgpl-3.0 | 572 |
#!/usr/bin/env python
"""
Deprecated since the solenoid was not strong enough.
Was using: https://www.sparkfun.com/products/11015
5v, 4.5mm throw
"""
# Import required libraries
import time
import RPi.GPIO as GPIO
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Base class for a solenoid motor controller using a stepper ULN2003 controller
class SolenoidMotor(object):
# # Define GPIO signals to use
# Pin 13, GPIO27
pin = 27
wait_time = .01
wait_time = .1
def __init__(self, **kwargs):
for key in kwargs:
if hasattr(self.__class__, key):
setattr(self, key, kwargs[key])
# Set pin as output
print "Setup pin"
GPIO.setup(self.pin, GPIO.OUT)
GPIO.output(self.pin, False)
def tap(self):
GPIO.output(self.pin, True)
time.sleep(self.wait_time)
GPIO.output(self.pin, False)
def reset(self):
GPIO.output(self.pin, False)
if __name__ == "__main__":
pen = SolenoidMotor()
start_time = time.time()
for i in range(8):
pen.tap()
time.sleep(.09)
print time.time() - start_time
pen.reset()
| krimkus/stipplebot | solenoid.py | Python | unlicense | 1,215 |
## Cubieboard@Armbian plugin for temperature measurment
from libraries import utility
def plugin_main(json_arguments=None):
data="Undefned"
with open ("/sys/class/hwmon/hwmon0/device/temp1_input", "r") as temperature:
data=temperature.read()
return "{0} C".format(int(data)/1000)
| znoxx/tbng | engine/plugins/cputemp_cubie1.py | Python | unlicense | 292 |
# Taken from here: https://stackoverflow.com/questions/50566934/why-is-this-singleton-implementation-not-thread-safe
import functools
import threading
lock = threading.Lock()
def synchronized(lock):
""" Synchronization decorator """
def wrapper(f):
@functools.wraps(f)
def inner_wrapper(*args, **kw):
with lock:
return f(*args, **kw)
return inner_wrapper
return wrapper
class SingletonOptimized(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._locked_call(*args, **kwargs)
return cls._instances[cls]
@synchronized(lock)
def _locked_call(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(SingletonOptimized, cls).__call__(*args, **kwargs)
| cinepost/Copperfield_FX | copper/core/utils/singleton.py | Python | unlicense | 849 |
# Copyright (C) 2016 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
import functools
import os
from ycmd.tests.test_utils import BuildRequest, ClearCompletionsCache, SetUpApp
shared_app = None
def PathToTestFile( *args ):
dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) )
return os.path.join( dir_of_current_script, 'testdata', *args )
def StopGoCodeServer( app ):
app.post_json( '/run_completer_command',
BuildRequest( completer_target = 'filetype_default',
command_arguments = [ 'StopServer' ],
filetype = 'go' ) )
def setUpPackage():
"""Initializes the ycmd server as a WebTest application that will be shared
by all tests using the SharedYcmd decorator in this package. Additional
configuration that is common to these tests, like starting a semantic
subserver, should be done here."""
global shared_app
shared_app = SetUpApp()
def tearDownPackage():
global shared_app
StopGoCodeServer( shared_app )
def SharedYcmd( test ):
"""Defines a decorator to be attached to tests of this package. This decorator
passes the shared ycmd application as a parameter.
Do NOT attach it to test generators but directly to the yielded tests."""
global shared_app
@functools.wraps( test )
def Wrapper( *args, **kwargs ):
ClearCompletionsCache()
return test( shared_app, *args, **kwargs )
return Wrapper
| netsamir/dotfiles | files/vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/tests/go/__init__.py | Python | unlicense | 2,316 |
import requests
from bs4 import BeautifulSoup
import unittest
import numpy.testing as npt
import unicodedata
from selenium import webdriver
# from selenium.webdriver.support.ui import WebDriverWait
import os
import time
from tabulate import tabulate
import linkcheck_helper
phantomjs_path = "C://Python27//Lib//site-packages//selenium//webdriver//phantomjs//phantomjs-2.1.1-windows//bin//phantomjs.exe"
# this testing routine tests input and QAQC functionality of models;
# the input tests include login authentication, submittal of default inputs,
# and invocation of the QAQC
# Note: the login/input/output tests included here net the same results as those
# included in 'test_host_qed.py'; the difference is that "selenium/webdriver" is used here to
# navigate html whereas "mechanize" was used in test_host_qed.py; mechanize is for forms
# only and cannot handle button pushing (which is needed for the QAQC test)
# this routine accepts a list of url's where a group of models and pages (i.e.,tabs)
# are presented as web pages. two url's represent the backend servers where the models
# reside; these servers are accessible directly or indirectly (via the two front end url's)
test = {}
# local server = ["http://127.0.0.1:8000/"]
servers = ["http://qed.epa.gov/ubertool/", "http://qedinternal.epa.gov/ubertool/",
"http://134.67.114.3/ubertool/", "http://134.67.114.1/ubertool/"]
#models = ["sip/", "stir/", "rice/", "terrplant/", "iec/",
# "agdrift/", "agdrift_trex/", "agdrift_therps/", "earthworm/",
# "kabam/", "pfam/", "sam/", "therps/", "trex2/"]
models = ["sip/", "stir/", "pfam/", "earthworm/"] # this short list is used for debugging
# The following list represents the model output page titles to be checked (order of models
# needs to be the same as "models" list above
#models_io = ["SIP", "STIR", "RICE", "TerrPlant", "IEC",
# "AgDrift", "AgDrift & T-REX", "AgDrift & T-HERPS", "Earthworm",
# "KABAM", "PFAM", "SAM", "T-Herps", "T-REX 1.5.2"]
models_io = ["SIP", "STIR", "PFAM", "Earthworm"] # this short list is used for debugging
# these two servers require login/authentication for inputs
redirect_servers = ["http://qed.epa.gov/ubertool/", "http://134.67.114.3/ubertool/"]
redirect_pages = ["input"] # user is redirected to login page for inputs
redirect_model_pages = [s + m + p for s in redirect_servers for m in models
for p in redirect_pages]
redirect_models = models_io * len(redirect_servers)
qaqc_pages = ["qaqc"]
qaqc_model_pages = [s + m + p for s in servers for m in models for p in qaqc_pages]
qaqc_models = models_io * len(servers) * len(qaqc_pages)
class WaitForPageLoad(object):
"""
This class provides functionality to ensure that a web page has
fully loaded upon a click/submit
"""
def __init__(self, browser):
self.browser = browser
def __enter__(self):
self.old_page = self.browser.find_element_by_tag_name('html')
def page_has_loaded(self):
new_page = self.browser.find_element_by_tag_name('html')
return new_page.id != self.old_page.id
def wait_for(self, condition_function):
start_time = time.time()
while time.time() < start_time + 3:
if condition_function():
return True
else:
time.sleep(0.1)
raise Exception(
'Timeout waiting for {}'.format(condition_function.__name__))
def __exit__(self, *_):
self.wait_for(self.page_has_loaded)
class TestQAQC(unittest.TestCase, WaitForPageLoad):
"""
This set of methods represent unit tests for the Ubertool frontend (i.e., what the
user sees as the web interface). The tests include:
1. Login verficcation for model input pages
2. Verification that Login results in the input data form page loads
3. Verification that defaults input data form is successfully submitted and
that the output data is generated and displayed
4. Automated QAQC run submittal and presentation of results
Note: the first three tests here are also included in the "test_host_qed.py"
code; the difference being that the selenium package is used here and
the mechanize package is used in test_host_qed.py code
"""
def setup(self):
pass
@staticmethod
def test_qed_authenticate_input():
try: # verify successful login and that we land on input page url
test_name = "Login Authentication "
current_page = [""] * len(redirect_model_pages)
expected_page = [""] * len(redirect_model_pages)
assert_error = False
for idx, m in enumerate(redirect_model_pages):
browser = webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull)
browser.get(m)
# login and authenticate
username = browser.find_element_by_name("username")
username.send_keys("betatester")
password = browser.find_element_by_name("password")
password.send_keys("ubertool")
with WaitForPageLoad(browser):
login = browser.find_element_by_xpath("//form[@name='auth']")
login.submit() # use .click() for individual buttons and .submit() for form submittal
#next two lines is alternative technique
#LoginButton = browser.find_element_by_class_name("input_button")
#LoginButton.click()
# Verify we have successfully logged in and are now at input page url
current_page[idx] = str(browser.current_url)
expected_page[idx] = m
try:
npt.assert_array_equal(expected_page, current_page, 'Login Test Failed', True)
except AssertionError:
assert_error = True
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
finally:
linkcheck_helper.write_report(test_name, assert_error, expected_page, current_page)
browser.quit()
return
@staticmethod
def test_qed_input_form():
# verify input page contains expected content (we chk page title, e.g., 'SIP Inputs')
# need to repeat login
try:
test_name = "Input Form URL "
current_title = [""] * len(redirect_model_pages)
expected_title = [""] * len(redirect_model_pages)
assert_error = False
for idx, m in enumerate(redirect_model_pages):
expected_title[idx] = m + " : " + redirect_models[idx] + " Inputs"
browser = webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull)
browser.get(m)
# login and authenticate
username = browser.find_element_by_name("username")
username.send_keys("betatester")
password = browser.find_element_by_name("password")
password.send_keys("ubertool")
with WaitForPageLoad(browser):
login = browser.find_element_by_xpath("//form[@name='auth']")
login.submit() # use .click() for individual buttons and .submit() for form submittal
# verify that login was successful by checking that inputs page title is rendered
if browser.page_source.__contains__(redirect_models[idx] + " Inputs"):
current_title[idx] = m + " : " + redirect_models[idx] + " Inputs"
else:
current_title[idx] = m + " : " + redirect_models[idx] + " Input Submit Error"
# build array for reporting table
try:
npt.assert_array_equal(expected_title, current_title, 'Input Form Submittal Failed', True)
except AssertionError:
assert_error = True
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
finally:
linkcheck_helper.write_report(test_name, assert_error, expected_title, current_title)
browser.quit()
return
@staticmethod
def test_qed_output_form():
try: # verify proper output page content, i.e., page title
# need to repeat login, submit default inputs
test_name = "Input Form Submittal and Output Generation "
current_title = [""] * len(redirect_model_pages)
expected_title = [""] * len(redirect_model_pages)
assert_error = False
for idx, m in enumerate(redirect_model_pages):
expected_title[idx] = m.replace("input", "") + " : " + redirect_models[idx] + " Output"
browser = webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull)
browser.get(m)
# login and authenticate
username = browser.find_element_by_name("username")
username.send_keys("betatester")
password = browser.find_element_by_name("password")
password.send_keys("ubertool")
with WaitForPageLoad(browser):
login = browser.find_element_by_xpath("//form[@name='auth']")
login.submit() # use .click() for individual buttons and .submit() for form submittal
# Locate and submit input form (using the default data for now)
with WaitForPageLoad(browser):
locate_submit = browser.find_element_by_xpath("//div[@class='input_right']")
try:
form_submit = browser.find_element_by_xpath("//button[@class='input_button']")
except:
form_submit = browser.find_element_by_xpath("//button[@class='submit input_button']")
form_submit.submit() # use .click() for individual buttons and .submit() for form submittal
if browser.page_source.__contains__("User Inputs"):
current_title[idx] = browser.current_url.replace("output", "") + " : " + redirect_models[
idx] + " Output"
elif browser.page_source.__contains__('File Not Found'):
current_title[idx] = browser.current_url.replace("output", "") + " : File Not Found Page Error"
else:
current_title[idx] = browser.current_url.replace("output", "") + " : Unknown Output Page Error"
try:
npt.assert_array_equal(expected_title, current_title, 'Submittal of Input Failed', True)
except AssertionError:
assert_error = True
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
finally:
linkcheck_helper.write_report(test_name, assert_error, expected_title, current_title)
browser.quit()
return
@staticmethod
def test_qed_qaqc_form():
try:
test_name = "QAQC Execution and Results Generation "
current_page_id = [""] * len(qaqc_model_pages) # pageID = url + <h2 class='model header' string>
expected_page_id = [""] * len(qaqc_model_pages)
assert_error = False
browser = webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull)
# added the argument service_log_path=os.path.devnull to the function webdriver.PhantomJS()
# to prevent PhantomJS from creating a ghostdriver.log in the directory of the python file
# being executed.
for idx, m in enumerate(qaqc_model_pages):
expected_page_id[idx] = m + "/run : " + qaqc_models[idx] + " QAQC"
browser.get(m)
try:
with WaitForPageLoad(browser):
qaqc_run_button = browser.find_element_by_id('runQAQC')
qaqc_run_button.click()
if browser.current_url.__str__() != m + "/run":
current_page_id[idx] = str(
browser.current_url) + " : Run QAQC failed" # we did not arrive at expected url
elif browser.page_source.__contains__('File Not Found'):
current_page_id[idx] = str(browser.current_url) + " : File Not Found Page Error"
elif browser.page_source.__contains__("User Inputs"):
# check to see of string User Inputs appears on page
current_page_id[idx] = m + "/run : " + qaqc_models[idx] + " QAQC"
else:
current_page_id[idx] = str(browser.current_url) + " Unknown QAQC run error"
except:
current_page_id[idx] = m + " Unknown exception thrown"
# build array for reporting table
try:
npt.assert_array_equal(expected_page_id, current_page_id, 'QAQC Failed', True)
except AssertionError:
assert_error = True
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
except Exception as e:
# handle any other exception
print "Error '{0}' occured. Arguments {1}.".format(e.message, e.args)
finally:
linkcheck_helper.write_report(test_name, assert_error, expected_page_id, current_page_id)
browser.quit()
return
def teardown(self):
pass
if __name__ == '__main__':
unittest.main()
| puruckertom/qed_tests | tests/testing_ground.py | Python | unlicense | 14,478 |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
parse_age_limit,
parse_iso8601,
)
class Go90IE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?go90\.com/videos/(?P<id>[0-9a-zA-Z]+)'
_TEST = {
'url': 'https://www.go90.com/videos/84BUqjLpf9D',
'md5': 'efa7670dbbbf21a7b07b360652b24a32',
'info_dict': {
'id': '84BUqjLpf9D',
'ext': 'mp4',
'title': 'Daily VICE - Inside The Utah Coalition Against Pornography Convention',
'description': 'VICE\'s Karley Sciortino meets with activists who discuss the state\'s strong anti-porn stance. Then, VICE Sports explains NFL contracts.',
'timestamp': 1491868800,
'upload_date': '20170411',
'age_limit': 14,
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
video_data = self._download_json(
'https://www.go90.com/api/view/items/' + video_id,
video_id, headers={
'Content-Type': 'application/json; charset=utf-8',
}, data=b'{"client":"web","device_type":"pc"}')
if video_data.get('requires_drm'):
raise ExtractorError('This video is DRM protected.', expected=True)
main_video_asset = video_data['main_video_asset']
episode_number = int_or_none(video_data.get('episode_number'))
series = None
season = None
season_id = None
season_number = None
for metadata in video_data.get('__children', {}).get('Item', {}).values():
if metadata.get('type') == 'show':
series = metadata.get('title')
elif metadata.get('type') == 'season':
season = metadata.get('title')
season_id = metadata.get('id')
season_number = int_or_none(metadata.get('season_number'))
title = episode = video_data.get('title') or series
if series and series != title:
title = '%s - %s' % (series, title)
thumbnails = []
formats = []
subtitles = {}
for asset in video_data.get('assets'):
if asset.get('id') == main_video_asset:
for source in asset.get('sources', []):
source_location = source.get('location')
if not source_location:
continue
source_type = source.get('type')
if source_type == 'hls':
m3u8_formats = self._extract_m3u8_formats(
source_location, video_id, 'mp4',
'm3u8_native', m3u8_id='hls', fatal=False)
for f in m3u8_formats:
mobj = re.search(r'/hls-(\d+)-(\d+)K', f['url'])
if mobj:
height, tbr = mobj.groups()
height = int_or_none(height)
f.update({
'height': f.get('height') or height,
'width': f.get('width') or int_or_none(height / 9.0 * 16.0 if height else None),
'tbr': f.get('tbr') or int_or_none(tbr),
})
formats.extend(m3u8_formats)
elif source_type == 'dash':
formats.extend(self._extract_mpd_formats(
source_location, video_id, mpd_id='dash', fatal=False))
else:
formats.append({
'format_id': source.get('name'),
'url': source_location,
'width': int_or_none(source.get('width')),
'height': int_or_none(source.get('height')),
'tbr': int_or_none(source.get('bitrate')),
})
for caption in asset.get('caption_metadata', []):
caption_url = caption.get('source_url')
if not caption_url:
continue
subtitles.setdefault(caption.get('language', 'en'), []).append({
'url': caption_url,
'ext': determine_ext(caption_url, 'vtt'),
})
elif asset.get('type') == 'image':
asset_location = asset.get('location')
if not asset_location:
continue
thumbnails.append({
'url': asset_location,
'width': int_or_none(asset.get('width')),
'height': int_or_none(asset.get('height')),
})
self._sort_formats(formats)
return {
'id': video_id,
'title': title,
'formats': formats,
'thumbnails': thumbnails,
'description': video_data.get('short_description'),
'like_count': int_or_none(video_data.get('like_count')),
'timestamp': parse_iso8601(video_data.get('released_at')),
'series': series,
'episode': episode,
'season': season,
'season_id': season_id,
'season_number': season_number,
'episode_number': episode_number,
'subtitles': subtitles,
'age_limit': parse_age_limit(video_data.get('rating')),
}
| epitron/youtube-dl | youtube_dl/extractor/go90.py | Python | unlicense | 5,640 |
#!/usr/bin/env python
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for google.cloud.security.enforcer.enforcer."""
import copy
import json
import httplib2
import mock
import testing_constants as constants
from tests.unittest_utils import ForsetiTestCase
from google.protobuf import text_format
from tests.unittest_utils import get_datafile_path
from google.cloud.security.enforcer import enforcer_log_pb2
from google.cloud.security.enforcer import enforcer
# Used anywhere a real timestamp could be generated to ensure consistent
# comparisons in tests
MOCK_TIMESTAMP = 1234567890
class EnforcerTest(ForsetiTestCase):
"""Extended unit tests for BatchFirewallEnforcer class."""
def setUp(self):
"""Set up."""
self.mock_compute = mock.patch.object(enforcer.batch_enforcer.compute,
'ComputeClient').start()
self.gce_service = self.mock_compute().service
self.gce_service.networks().list().execute.return_value = (
constants.SAMPLE_TEST_NETWORK_SELFLINK)
self.project = constants.TEST_PROJECT
self.mock_time = mock.patch.object(enforcer.batch_enforcer.datelib,
'Timestamp').start()
self.mock_time.now().AsMicroTimestamp.return_value = MOCK_TIMESTAMP
self.mock_time.now().AsSecondsSinceEpoch.return_value = MOCK_TIMESTAMP
self.enforcer = enforcer.initialize_batch_enforcer(
{},
concurrent_threads=1,
max_write_threads=1,
max_running_operations=0,
dry_run=True)
self.expected_summary = (
enforcer_log_pb2.BatchResult(
batch_id=MOCK_TIMESTAMP,
timestamp_start_msec=MOCK_TIMESTAMP,
timestamp_end_msec=MOCK_TIMESTAMP))
self.addCleanup(mock.patch.stopall)
def test_enforce_single_project(self):
"""Verifies enforce_single_project returns the correct results.
Setup:
* Set API calls to return the different firewall rules from the new
policy on the first call, and the expected new firewall rules on the
second call.
* Load a mock policy file.
* Create a temporary directory for writing the dremel recordio table out
to.
* Send the policy and project to EnforceSingleProject.
Expected Results:
* The results proto returned matches the expected results.
"""
self.gce_service.firewalls().list().execute.side_effect = [
constants.DEFAULT_FIREWALL_API_RESPONSE,
constants.EXPECTED_FIREWALL_API_RESPONSE]
policy_filename = get_datafile_path(__file__, 'sample_policy.json')
results = enforcer.enforce_single_project(self.enforcer, self.project,
policy_filename)
self.expected_summary.projects_total = 1
self.expected_summary.projects_success = 1
self.expected_summary.projects_changed = 1
self.expected_summary.projects_unchanged = 0
self.assertEqual(self.expected_summary, results.summary)
expected_results = enforcer_log_pb2.ProjectResult()
text_format.Merge(constants.SAMPLE_ENFORCER_PROJECTRESULTS_ASCIIPB,
expected_results)
expected_results.run_context = enforcer_log_pb2.ENFORCER_ONE_PROJECT
expected_results.gce_firewall_enforcement.policy_path = policy_filename
project_result = results.results[0]
self.assertEqual(expected_results, project_result)
def test_enforcer_raises_exception_with_invalid_json_policy(self):
"""Verifies json parsed correct as a list of dictionaries.
Setup:
* Load an invalid json file (no list).
* Give it to enforcer to parse and load
Expected Results:
* Enforcer should raise InvalidParsedPolicyFileError
"""
policy_filename = get_datafile_path(__file__, 'invalid_sample_policy.json')
with self.assertRaises(enforcer.InvalidParsedPolicyFileError) as r:
enforcer.enforce_single_project(
self.enforcer, self.project, policy_filename)
if __name__ == '__main__':
unittest.main()
| cschnei3/forseti-security | tests/enforcer/enforcer_test.py | Python | apache-2.0 | 4,766 |
# coding: utf-8
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from pprint import pformat
from six import iteritems
class ComputerSystem100SystemType(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
ComputerSystem100SystemType - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
}
self.attribute_map = {
}
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| jlongever/redfish-client-python | on_http_redfish_1_0/models/computer_system_1_0_0_system_type.py | Python | apache-2.0 | 2,513 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Metrics."""
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_gan as tfgan
import tensorflow_hub as hub
i3d_model = None
lpips_model = None
def flatten_video(video):
return np.reshape(video, (-1,) + video.shape[2:])
def psnr(video_1, video_2):
video_1 = flatten_video(video_1)
video_2 = flatten_video(video_2)
dist = tf.image.psnr(video_1, video_2, max_val=1.0)
return np.mean(dist.numpy())
def ssim(video_1, video_2):
video_1 = flatten_video(video_1)
video_2 = flatten_video(video_2)
dist = tf.image.ssim(video_1, video_2, max_val=1.0)
return np.mean(dist.numpy())
def psnr_image(target_image, out_image):
dist = tf.image.psnr(target_image, out_image, max_val=1.0)
return np.mean(dist.numpy())
def psnr_per_frame(target_video, out_video):
max_val = 1.0
mse = np.mean(np.square(out_video - target_video), axis=(2, 3, 4))
return 20 * np.log10(max_val) - 10.0 * np.log10(mse)
def lpips_image(generated_image, real_image):
global lpips_model
result = tf.convert_to_tensor(0.0)
return result
def lpips(video_1, video_2):
video_1 = flatten_video(video_1)
video_2 = flatten_video(video_2)
dist = lpips_image(video_1, video_2)
return np.mean(dist.numpy())
def fvd_preprocess(videos, target_resolution):
videos = tf.convert_to_tensor(videos * 255.0, dtype=tf.float32)
videos_shape = videos.shape.as_list()
all_frames = tf.reshape(videos, [-1] + videos_shape[-3:])
resized_videos = tf.image.resize(all_frames, size=target_resolution)
target_shape = [videos_shape[0], -1] + list(target_resolution) + [3]
output_videos = tf.reshape(resized_videos, target_shape)
scaled_videos = 2. * tf.cast(output_videos, tf.float32) / 255. - 1
return scaled_videos
def create_id3_embedding(videos):
"""Get id3 embeddings."""
global i3d_model
module_spec = 'https://tfhub.dev/deepmind/i3d-kinetics-400/1'
if not i3d_model:
base_model = hub.load(module_spec)
input_tensor = base_model.graph.get_tensor_by_name('input_frames:0')
i3d_model = base_model.prune(input_tensor, 'RGB/inception_i3d/Mean:0')
output = i3d_model(videos)
return output
def calculate_fvd(real_activations, generated_activations):
return tfgan.eval.frechet_classifier_distance_from_activations(
real_activations, generated_activations)
def fvd(video_1, video_2):
video_1 = fvd_preprocess(video_1, (224, 224))
video_2 = fvd_preprocess(video_2, (224, 224))
x = create_id3_embedding(video_1)
y = create_id3_embedding(video_2)
result = calculate_fvd(x, y)
return result.numpy()
def inception_score(images):
return tfgan.eval.inception_score(images)
| google-research/fitvid | metrics.py | Python | apache-2.0 | 3,220 |
from collections import namedtuple
import io
import re
from six.moves.urllib.parse import urlparse
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.deployment_manager import dm_base
from ruamel.yaml import YAML
DM_OUTPUT_QUERY_REGEX = re.compile(
r'!DMOutput\s+(?P<url>\bdm://[-/a-zA-Z0-9]+\b)|'
r'\$\(out\.(?P<token>[-.a-zA-Z0-9]+)\)'
)
DMOutputQueryAttributes = namedtuple(
'DMOutputQueryAttributes',
['project',
'deployment',
'resource',
'name']
)
@dm_base.UseDmApi(dm_base.DmApiVersion.V2)
class DM_API(dm_base.DmCommand):
""" Class representing the DM API
This a proxy class only, so other modules in this project
only import this local class instead of gcloud's. Here's the source:
https://github.com/google-cloud-sdk/google-cloud-sdk/blob/master/lib/googlecloudsdk/api_lib/deployment_manager/dm_base.py
"""
API = DM_API()
def get_deployment(project, deployment):
try:
return API.client.deployments.Get(
API.messages.DeploymentmanagerDeploymentsGetRequest(
project=project,
deployment=deployment
)
)
except apitools_exceptions.HttpNotFoundError as _:
return None
def get_manifest(project, deployment):
deployment_rsp = get_deployment(project, deployment)
return API.client.manifests.Get(
API.messages.DeploymentmanagerManifestsGetRequest(
project=project,
deployment=deployment,
manifest=deployment_rsp.manifest.split('/')[-1]
)
)
def parse_dm_output_url(url, project=''):
error_msg = (
'The url must look like '
'"dm://${project}/${deployment}/${resource}/${name}" or'
'"dm://${deployment}/${resource}/${name}"'
)
parsed_url = urlparse(url)
if parsed_url.scheme != 'dm':
raise ValueError(error_msg)
path = parsed_url.path.split('/')[1:]
# path == 2 if project isn't specified in the URL
# path == 3 if project is specified in the URL
if len(path) == 2:
args = [project] + [parsed_url.netloc] + path
elif len(path) == 3:
args = [parsed_url.netloc] + path
else:
raise ValueError(error_msg)
return DMOutputQueryAttributes(*args)
def parse_dm_output_token(token, project=''):
error_msg = (
'The url must look like '
'$(out.${project}.${deployment}.${resource}.${name}" or '
'$(out.${deployment}.${resource}.${name}"'
)
parts = token.split('.')
# parts == 3 if project isn't specified in the token
# parts == 4 if project is specified in the token
if len(parts) == 3:
return DMOutputQueryAttributes(project, *parts)
elif len(parts) == 4:
return DMOutputQueryAttributes(*parts)
else:
raise ValueError(error_msg)
def get_deployment_output(project, deployment, resource, name):
manifest = get_manifest(project, deployment)
layout = YAML().load(manifest.layout)
for r in layout.get('resources', []):
if r['name'] != resource:
continue
for output in r.get('outputs', []):
if output['name'] == name:
return output['finalValue']
| aljim/deploymentmanager-samples | community/cloud-foundation/src/cloud_foundation_toolkit/dm_utils.py | Python | apache-2.0 | 3,240 |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Amazon EC2, Eucalyptus, Nimbus and Outscale drivers.
"""
import re
import sys
import base64
import copy
import warnings
try:
from lxml import etree as ET
except ImportError:
from xml.etree import ElementTree as ET
from libcloud.utils.py3 import b, basestring, ensure_string
from libcloud.utils.xml import fixxpath, findtext, findattr, findall
from libcloud.utils.publickey import get_pubkey_ssh2_fingerprint
from libcloud.utils.publickey import get_pubkey_comment
from libcloud.utils.iso8601 import parse_date
from libcloud.common.aws import AWSBaseResponse, SignedAWSConnection
from libcloud.common.types import (InvalidCredsError, MalformedResponseError,
LibcloudError)
from libcloud.compute.providers import Provider
from libcloud.compute.base import Node, NodeDriver, NodeLocation, NodeSize
from libcloud.compute.base import NodeImage, StorageVolume, VolumeSnapshot
from libcloud.compute.base import KeyPair
from libcloud.compute.types import NodeState, KeyPairDoesNotExistError
__all__ = [
'API_VERSION',
'NAMESPACE',
'INSTANCE_TYPES',
'OUTSCALE_INSTANCE_TYPES',
'OUTSCALE_SAS_REGION_DETAILS',
'OUTSCALE_INC_REGION_DETAILS',
'DEFAULT_EUCA_API_VERSION',
'EUCA_NAMESPACE',
'EC2NodeDriver',
'BaseEC2NodeDriver',
'NimbusNodeDriver',
'EucNodeDriver',
'OutscaleSASNodeDriver',
'OutscaleINCNodeDriver',
'EC2NodeLocation',
'EC2ReservedNode',
'EC2SecurityGroup',
'EC2PlacementGroup',
'EC2Network',
'EC2NetworkSubnet',
'EC2NetworkInterface',
'EC2RouteTable',
'EC2Route',
'EC2SubnetAssociation',
'ExEC2AvailabilityZone',
'IdempotentParamError'
]
API_VERSION = '2013-10-15'
NAMESPACE = 'http://ec2.amazonaws.com/doc/%s/' % (API_VERSION)
# Eucalyptus Constants
DEFAULT_EUCA_API_VERSION = '3.3.0'
EUCA_NAMESPACE = 'http://msgs.eucalyptus.com/%s' % (DEFAULT_EUCA_API_VERSION)
"""
Sizes must be hardcoded, because Amazon doesn't provide an API to fetch them.
From http://aws.amazon.com/ec2/instance-types/
"""
INSTANCE_TYPES = {
't1.micro': {
'id': 't1.micro',
'name': 'Micro Instance',
'ram': 613,
'disk': 15,
'bandwidth': None
},
'm1.small': {
'id': 'm1.small',
'name': 'Small Instance',
'ram': 1740,
'disk': 160,
'bandwidth': None
},
'm1.medium': {
'id': 'm1.medium',
'name': 'Medium Instance',
'ram': 3700,
'disk': 410,
'bandwidth': None
},
'm1.large': {
'id': 'm1.large',
'name': 'Large Instance',
'ram': 7680,
'disk': 850,
'bandwidth': None
},
'm1.xlarge': {
'id': 'm1.xlarge',
'name': 'Extra Large Instance',
'ram': 15360,
'disk': 1690,
'bandwidth': None
},
'c1.medium': {
'id': 'c1.medium',
'name': 'High-CPU Medium Instance',
'ram': 1740,
'disk': 350,
'bandwidth': None
},
'c1.xlarge': {
'id': 'c1.xlarge',
'name': 'High-CPU Extra Large Instance',
'ram': 7680,
'disk': 1690,
'bandwidth': None
},
'm2.xlarge': {
'id': 'm2.xlarge',
'name': 'High-Memory Extra Large Instance',
'ram': 17510,
'disk': 420,
'bandwidth': None
},
'm2.2xlarge': {
'id': 'm2.2xlarge',
'name': 'High-Memory Double Extra Large Instance',
'ram': 35021,
'disk': 850,
'bandwidth': None
},
'm2.4xlarge': {
'id': 'm2.4xlarge',
'name': 'High-Memory Quadruple Extra Large Instance',
'ram': 70042,
'disk': 1690,
'bandwidth': None
},
'm3.medium': {
'id': 'm3.medium',
'name': 'Medium Instance',
'ram': 3840,
'disk': 4000,
'bandwidth': None
},
'm3.large': {
'id': 'm3.large',
'name': 'Large Instance',
'ram': 7168,
'disk': 32000,
'bandwidth': None
},
'm3.xlarge': {
'id': 'm3.xlarge',
'name': 'Extra Large Instance',
'ram': 15360,
'disk': 80000,
'bandwidth': None
},
'm3.2xlarge': {
'id': 'm3.2xlarge',
'name': 'Double Extra Large Instance',
'ram': 30720,
'disk': 160000,
'bandwidth': None
},
'cg1.4xlarge': {
'id': 'cg1.4xlarge',
'name': 'Cluster GPU Quadruple Extra Large Instance',
'ram': 22528,
'disk': 1690,
'bandwidth': None
},
'g2.2xlarge': {
'id': 'g2.2xlarge',
'name': 'Cluster GPU G2 Double Extra Large Instance',
'ram': 15000,
'disk': 60,
'bandwidth': None,
},
'cc1.4xlarge': {
'id': 'cc1.4xlarge',
'name': 'Cluster Compute Quadruple Extra Large Instance',
'ram': 23552,
'disk': 1690,
'bandwidth': None
},
'cc2.8xlarge': {
'id': 'cc2.8xlarge',
'name': 'Cluster Compute Eight Extra Large Instance',
'ram': 63488,
'disk': 3370,
'bandwidth': None
},
# c3 instances have 2 SSDs of the specified disk size
'c3.large': {
'id': 'c3.large',
'name': 'Compute Optimized Large Instance',
'ram': 3750,
'disk': 32, # x2
'bandwidth': None
},
'c3.xlarge': {
'id': 'c3.xlarge',
'name': 'Compute Optimized Extra Large Instance',
'ram': 7500,
'disk': 80, # x2
'bandwidth': None
},
'c3.2xlarge': {
'id': 'c3.2xlarge',
'name': 'Compute Optimized Double Extra Large Instance',
'ram': 15000,
'disk': 160, # x2
'bandwidth': None
},
'c3.4xlarge': {
'id': 'c3.4xlarge',
'name': 'Compute Optimized Quadruple Extra Large Instance',
'ram': 30000,
'disk': 320, # x2
'bandwidth': None
},
'c3.8xlarge': {
'id': 'c3.8xlarge',
'name': 'Compute Optimized Eight Extra Large Instance',
'ram': 60000,
'disk': 640, # x2
'bandwidth': None
},
'cr1.8xlarge': {
'id': 'cr1.8xlarge',
'name': 'High Memory Cluster Eight Extra Large',
'ram': 244000,
'disk': 240,
'bandwidth': None
},
'hs1.4xlarge': {
'id': 'hs1.4xlarge',
'name': 'High Storage Quadruple Extra Large Instance',
'ram': 61952,
'disk': 2048,
'bandwidth': None
},
'hs1.8xlarge': {
'id': 'hs1.8xlarge',
'name': 'High Storage Eight Extra Large Instance',
'ram': 119808,
'disk': 48000,
'bandwidth': None
},
# i2 instances have up to eight SSD drives
'i2.xlarge': {
'id': 'i2.xlarge',
'name': 'High Storage Optimized Extra Large Instance',
'ram': 31232,
'disk': 800,
'bandwidth': None
},
'i2.2xlarge': {
'id': 'i2.2xlarge',
'name': 'High Storage Optimized Double Extra Large Instance',
'ram': 62464,
'disk': 1600,
'bandwidth': None
},
'i2.4xlarge': {
'id': 'i2.4xlarge',
'name': 'High Storage Optimized Quadruple Large Instance',
'ram': 124928,
'disk': 3200,
'bandwidth': None
},
'i2.8xlarge': {
'id': 'i2.8xlarge',
'name': 'High Storage Optimized Eight Extra Large Instance',
'ram': 249856,
'disk': 6400,
'bandwidth': None
},
# 1x SSD
'r3.large': {
'id': 'r3.large',
'name': 'Memory Optimized Large instance',
'ram': 15000,
'disk': 32,
'bandwidth': None
},
'r3.xlarge': {
'id': 'r3.xlarge',
'name': 'Memory Optimized Extra Large instance',
'ram': 30500,
'disk': 80,
'bandwidth': None
},
'r3.2xlarge': {
'id': 'r3.2xlarge',
'name': 'Memory Optimized Double Extra Large instance',
'ram': 61000,
'disk': 160,
'bandwidth': None
},
'r3.4xlarge': {
'id': 'r3.4xlarge',
'name': 'Memory Optimized Quadruple Extra Large instance',
'ram': 122000,
'disk': 320,
'bandwidth': None
},
'r3.8xlarge': {
'id': 'r3.8xlarge',
'name': 'Memory Optimized Eight Extra Large instance',
'ram': 244000,
'disk': 320, # x2
'bandwidth': None
},
't2.micro': {
'id': 't2.micro',
'name': 'Burstable Performance Micro Instance',
'ram': 1024,
'disk': 0, # EBS Only
'bandwidth': None,
'extra': {
'cpu': 1
}
},
# Burstable Performance General Purpose
't2.small': {
'id': 't2.small',
'name': 'Burstable Performance Small Instance',
'ram': 2048,
'disk': 0, # EBS Only
'bandwidth': None,
'extra': {
'cpu': 11
}
},
't2.medium': {
'id': 't2.medium',
'name': 'Burstable Performance Medium Instance',
'ram': 4028,
'disk': 0, # EBS Only
'bandwidth': None,
'extra': {
'cpu': 2
}
}
}
REGION_DETAILS = {
# US East (Northern Virginia) Region
'us-east-1': {
'endpoint': 'ec2.us-east-1.amazonaws.com',
'api_name': 'ec2_us_east',
'country': 'USA',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'cc2.8xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'cg1.4xlarge',
'g2.2xlarge',
'cr1.8xlarge',
'hs1.8xlarge',
'i2.xlarge',
'i2.2xlarge',
'i2.4xlarge',
'i2.8xlarge',
'r3.large',
'r3.xlarge',
'r3.2xlarge',
'r3.4xlarge',
'r3.8xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
# US West (Northern California) Region
'us-west-1': {
'endpoint': 'ec2.us-west-1.amazonaws.com',
'api_name': 'ec2_us_west',
'country': 'USA',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'g2.2xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'i2.xlarge',
'i2.2xlarge',
'i2.4xlarge',
'i2.8xlarge',
'r3.large',
'r3.xlarge',
'r3.2xlarge',
'r3.4xlarge',
'r3.8xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
# US West (Oregon) Region
'us-west-2': {
'endpoint': 'ec2.us-west-2.amazonaws.com',
'api_name': 'ec2_us_west_oregon',
'country': 'US',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'g2.2xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'hs1.8xlarge',
'cc2.8xlarge',
'i2.xlarge',
'i2.2xlarge',
'i2.4xlarge',
'i2.8xlarge',
'r3.large',
'r3.xlarge',
'r3.2xlarge',
'r3.4xlarge',
'r3.8xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
# EU (Ireland) Region
'eu-west-1': {
'endpoint': 'ec2.eu-west-1.amazonaws.com',
'api_name': 'ec2_eu_west',
'country': 'Ireland',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'g2.2xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'hs1.8xlarge',
'cc2.8xlarge',
'i2.xlarge',
'i2.2xlarge',
'i2.4xlarge',
'i2.8xlarge',
'r3.large',
'r3.xlarge',
'r3.2xlarge',
'r3.4xlarge',
'r3.8xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
# Asia Pacific (Singapore) Region
'ap-southeast-1': {
'endpoint': 'ec2.ap-southeast-1.amazonaws.com',
'api_name': 'ec2_ap_southeast',
'country': 'Singapore',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'hs1.8xlarge',
'i2.xlarge',
'i2.2xlarge',
'i2.4xlarge',
'i2.8xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
# Asia Pacific (Tokyo) Region
'ap-northeast-1': {
'endpoint': 'ec2.ap-northeast-1.amazonaws.com',
'api_name': 'ec2_ap_northeast',
'country': 'Japan',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'g2.2xlarge',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'hs1.8xlarge',
'i2.xlarge',
'i2.2xlarge',
'i2.4xlarge',
'i2.8xlarge',
'r3.large',
'r3.xlarge',
'r3.2xlarge',
'r3.4xlarge',
'r3.8xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
# South America (Sao Paulo) Region
'sa-east-1': {
'endpoint': 'ec2.sa-east-1.amazonaws.com',
'api_name': 'ec2_sa_east',
'country': 'Brazil',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
# Asia Pacific (Sydney) Region
'ap-southeast-2': {
'endpoint': 'ec2.ap-southeast-2.amazonaws.com',
'api_name': 'ec2_ap_southeast_2',
'country': 'Australia',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'hs1.8xlarge',
'i2.xlarge',
'i2.2xlarge',
'i2.4xlarge',
'i2.8xlarge',
'r3.large',
'r3.xlarge',
'r3.2xlarge',
'r3.4xlarge',
'r3.8xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
'us-gov-west-1': {
'endpoint': 'ec2.us-gov-west-1.amazonaws.com',
'api_name': 'ec2_us_govwest',
'country': 'US',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.medium',
'm3.large',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'g2.2xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'hs1.4xlarge',
'hs1.8xlarge',
'i2.xlarge',
'i2.2xlarge',
'i2.4xlarge',
'i2.8xlarge',
'r3.large',
'r3.xlarge',
'r3.2xlarge',
'r3.4xlarge',
'r3.8xlarge',
't2.micro',
't2.small',
't2.medium'
]
},
'nimbus': {
# Nimbus clouds have 3 EC2-style instance types but their particular
# RAM allocations are configured by the admin
'country': 'custom',
'instance_types': [
'm1.small',
'm1.large',
'm1.xlarge'
]
}
}
"""
Sizes must be hardcoded because Outscale doesn't provide an API to fetch them.
Outscale cloud instances share some names with EC2 but have different
specifications so declare them in another constant.
"""
OUTSCALE_INSTANCE_TYPES = {
't1.micro': {
'id': 't1.micro',
'name': 'Micro Instance',
'ram': 615,
'disk': 0,
'bandwidth': None
},
'm1.small': {
'id': 'm1.small',
'name': 'Standard Small Instance',
'ram': 1740,
'disk': 150,
'bandwidth': None
},
'm1.medium': {
'id': 'm1.medium',
'name': 'Standard Medium Instance',
'ram': 3840,
'disk': 420,
'bandwidth': None
},
'm1.large': {
'id': 'm1.large',
'name': 'Standard Large Instance',
'ram': 7680,
'disk': 840,
'bandwidth': None
},
'm1.xlarge': {
'id': 'm1.xlarge',
'name': 'Standard Extra Large Instance',
'ram': 15360,
'disk': 1680,
'bandwidth': None
},
'c1.medium': {
'id': 'c1.medium',
'name': 'Compute Optimized Medium Instance',
'ram': 1740,
'disk': 340,
'bandwidth': None
},
'c1.xlarge': {
'id': 'c1.xlarge',
'name': 'Compute Optimized Extra Large Instance',
'ram': 7168,
'disk': 1680,
'bandwidth': None
},
'c3.large': {
'id': 'c3.large',
'name': 'Compute Optimized Large Instance',
'ram': 3840,
'disk': 32,
'bandwidth': None
},
'c3.xlarge': {
'id': 'c3.xlarge',
'name': 'Compute Optimized Extra Large Instance',
'ram': 7168,
'disk': 80,
'bandwidth': None
},
'c3.2xlarge': {
'id': 'c3.2xlarge',
'name': 'Compute Optimized Double Extra Large Instance',
'ram': 15359,
'disk': 160,
'bandwidth': None
},
'c3.4xlarge': {
'id': 'c3.4xlarge',
'name': 'Compute Optimized Quadruple Extra Large Instance',
'ram': 30720,
'disk': 320,
'bandwidth': None
},
'c3.8xlarge': {
'id': 'c3.8xlarge',
'name': 'Compute Optimized Eight Extra Large Instance',
'ram': 61440,
'disk': 640,
'bandwidth': None
},
'm2.xlarge': {
'id': 'm2.xlarge',
'name': 'High Memory Extra Large Instance',
'ram': 17510,
'disk': 420,
'bandwidth': None
},
'm2.2xlarge': {
'id': 'm2.2xlarge',
'name': 'High Memory Double Extra Large Instance',
'ram': 35020,
'disk': 840,
'bandwidth': None
},
'm2.4xlarge': {
'id': 'm2.4xlarge',
'name': 'High Memory Quadruple Extra Large Instance',
'ram': 70042,
'disk': 1680,
'bandwidth': None
},
'nv1.small': {
'id': 'nv1.small',
'name': 'GPU Small Instance',
'ram': 1739,
'disk': 150,
'bandwidth': None
},
'nv1.medium': {
'id': 'nv1.medium',
'name': 'GPU Medium Instance',
'ram': 3839,
'disk': 420,
'bandwidth': None
},
'nv1.large': {
'id': 'nv1.large',
'name': 'GPU Large Instance',
'ram': 7679,
'disk': 840,
'bandwidth': None
},
'nv1.xlarge': {
'id': 'nv1.xlarge',
'name': 'GPU Extra Large Instance',
'ram': 15358,
'disk': 1680,
'bandwidth': None
},
'g2.2xlarge': {
'id': 'g2.2xlarge',
'name': 'GPU Double Extra Large Instance',
'ram': 15360,
'disk': 60,
'bandwidth': None
},
'cc1.4xlarge': {
'id': 'cc1.4xlarge',
'name': 'Cluster Compute Quadruple Extra Large Instance',
'ram': 24576,
'disk': 1680,
'bandwidth': None
},
'cc2.8xlarge': {
'id': 'cc2.8xlarge',
'name': 'Cluster Compute Eight Extra Large Instance',
'ram': 65536,
'disk': 3360,
'bandwidth': None
},
'hi1.xlarge': {
'id': 'hi1.xlarge',
'name': 'High Storage Extra Large Instance',
'ram': 15361,
'disk': 1680,
'bandwidth': None
},
'm3.xlarge': {
'id': 'm3.xlarge',
'name': 'High Storage Optimized Extra Large Instance',
'ram': 15357,
'disk': 0,
'bandwidth': None
},
'm3.2xlarge': {
'id': 'm3.2xlarge',
'name': 'High Storage Optimized Double Extra Large Instance',
'ram': 30720,
'disk': 0,
'bandwidth': None
},
'm3s.xlarge': {
'id': 'm3s.xlarge',
'name': 'High Storage Optimized Extra Large Instance',
'ram': 15359,
'disk': 0,
'bandwidth': None
},
'm3s.2xlarge': {
'id': 'm3s.2xlarge',
'name': 'High Storage Optimized Double Extra Large Instance',
'ram': 30719,
'disk': 0,
'bandwidth': None
},
'cr1.8xlarge': {
'id': 'cr1.8xlarge',
'name': 'Memory Optimized Eight Extra Large Instance',
'ram': 249855,
'disk': 240,
'bandwidth': None
},
'os1.2xlarge': {
'id': 'os1.2xlarge',
'name': 'Memory Optimized, High Storage, Passthrough NIC Double Extra '
'Large Instance',
'ram': 65536,
'disk': 60,
'bandwidth': None
},
'os1.4xlarge': {
'id': 'os1.4xlarge',
'name': 'Memory Optimized, High Storage, Passthrough NIC Quadruple Ext'
'ra Large Instance',
'ram': 131072,
'disk': 120,
'bandwidth': None
},
'os1.8xlarge': {
'id': 'os1.8xlarge',
'name': 'Memory Optimized, High Storage, Passthrough NIC Eight Extra L'
'arge Instance',
'ram': 249856,
'disk': 500,
'bandwidth': None
},
'oc1.4xlarge': {
'id': 'oc1.4xlarge',
'name': 'Outscale Quadruple Extra Large Instance',
'ram': 24575,
'disk': 1680,
'bandwidth': None
},
'oc2.8xlarge': {
'id': 'oc2.8xlarge',
'name': 'Outscale Eight Extra Large Instance',
'ram': 65535,
'disk': 3360,
'bandwidth': None
}
}
"""
The function manipulating Outscale cloud regions will be overridden because
Outscale instances types are in a separate dict so also declare Outscale cloud
regions in some other constants.
"""
OUTSCALE_SAS_REGION_DETAILS = {
'eu-west-3': {
'endpoint': 'api-ppd.outscale.com',
'api_name': 'osc_sas_eu_west_3',
'country': 'FRANCE',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'c1.medium',
'c1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'nv1.small',
'nv1.medium',
'nv1.large',
'nv1.xlarge',
'cc1.4xlarge',
'cc2.8xlarge',
'm3.xlarge',
'm3.2xlarge',
'cr1.8xlarge',
'os1.8xlarge'
]
},
'eu-west-1': {
'endpoint': 'api.eu-west-1.outscale.com',
'api_name': 'osc_sas_eu_west_1',
'country': 'FRANCE',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'c1.medium',
'c1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'nv1.small',
'nv1.medium',
'nv1.large',
'nv1.xlarge',
'cc1.4xlarge',
'cc2.8xlarge',
'm3.xlarge',
'm3.2xlarge',
'cr1.8xlarge',
'os1.8xlarge'
]
},
'us-east-1': {
'endpoint': 'api.us-east-1.outscale.com',
'api_name': 'osc_sas_us_east_1',
'country': 'USA',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'c1.medium',
'c1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'nv1.small',
'nv1.medium',
'nv1.large',
'nv1.xlarge',
'cc1.4xlarge',
'cc2.8xlarge',
'm3.xlarge',
'm3.2xlarge',
'cr1.8xlarge',
'os1.8xlarge'
]
}
}
OUTSCALE_INC_REGION_DETAILS = {
'eu-west-1': {
'endpoint': 'api.eu-west-1.outscale.com',
'api_name': 'osc_inc_eu_west_1',
'country': 'FRANCE',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'c1.medium',
'c1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'nv1.small',
'nv1.medium',
'nv1.large',
'nv1.xlarge',
'cc1.4xlarge',
'cc2.8xlarge',
'm3.xlarge',
'm3.2xlarge',
'cr1.8xlarge',
'os1.8xlarge'
]
},
'eu-west-3': {
'endpoint': 'api-ppd.outscale.com',
'api_name': 'osc_inc_eu_west_3',
'country': 'FRANCE',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'c1.medium',
'c1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'nv1.small',
'nv1.medium',
'nv1.large',
'nv1.xlarge',
'cc1.4xlarge',
'cc2.8xlarge',
'm3.xlarge',
'm3.2xlarge',
'cr1.8xlarge',
'os1.8xlarge'
]
},
'us-east-1': {
'endpoint': 'api.us-east-1.outscale.com',
'api_name': 'osc_inc_us_east_1',
'country': 'USA',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'c1.medium',
'c1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'nv1.small',
'nv1.medium',
'nv1.large',
'nv1.xlarge',
'cc1.4xlarge',
'cc2.8xlarge',
'm3.xlarge',
'm3.2xlarge',
'cr1.8xlarge',
'os1.8xlarge'
]
}
}
"""
Define the extra dictionary for specific resources
"""
RESOURCE_EXTRA_ATTRIBUTES_MAP = {
'ebs_volume': {
'snapshot_id': {
'xpath': 'ebs/snapshotId',
'transform_func': str
},
'volume_id': {
'xpath': 'ebs/volumeId',
'transform_func': str
},
'volume_size': {
'xpath': 'ebs/volumeSize',
'transform_func': int
},
'delete': {
'xpath': 'ebs/deleteOnTermination',
'transform_func': str
},
'volume_type': {
'xpath': 'ebs/volumeType',
'transform_func': str
},
'iops': {
'xpath': 'ebs/iops',
'transform_func': int
}
},
'elastic_ip': {
'allocation_id': {
'xpath': 'allocationId',
'transform_func': str,
},
'association_id': {
'xpath': 'associationId',
'transform_func': str,
},
'interface_id': {
'xpath': 'networkInterfaceId',
'transform_func': str,
},
'owner_id': {
'xpath': 'networkInterfaceOwnerId',
'transform_func': str,
},
'private_ip': {
'xpath': 'privateIp',
'transform_func': str,
}
},
'image': {
'state': {
'xpath': 'imageState',
'transform_func': str
},
'owner_id': {
'xpath': 'imageOwnerId',
'transform_func': str
},
'owner_alias': {
'xpath': 'imageOwnerAlias',
'transform_func': str
},
'is_public': {
'xpath': 'isPublic',
'transform_func': str
},
'architecture': {
'xpath': 'architecture',
'transform_func': str
},
'image_type': {
'xpath': 'imageType',
'transform_func': str
},
'image_location': {
'xpath': 'imageLocation',
'transform_func': str
},
'platform': {
'xpath': 'platform',
'transform_func': str
},
'description': {
'xpath': 'description',
'transform_func': str
},
'root_device_type': {
'xpath': 'rootDeviceType',
'transform_func': str
},
'virtualization_type': {
'xpath': 'virtualizationType',
'transform_func': str
},
'hypervisor': {
'xpath': 'hypervisor',
'transform_func': str
},
'kernel_id': {
'xpath': 'kernelId',
'transform_func': str
},
'ramdisk_id': {
'xpath': 'ramdiskId',
'transform_func': str
}
},
'network': {
'state': {
'xpath': 'state',
'transform_func': str
},
'dhcp_options_id': {
'xpath': 'dhcpOptionsId',
'transform_func': str
},
'instance_tenancy': {
'xpath': 'instanceTenancy',
'transform_func': str
},
'is_default': {
'xpath': 'isDefault',
'transform_func': str
}
},
'network_interface': {
'subnet_id': {
'xpath': 'subnetId',
'transform_func': str
},
'vpc_id': {
'xpath': 'vpcId',
'transform_func': str
},
'zone': {
'xpath': 'availabilityZone',
'transform_func': str
},
'description': {
'xpath': 'description',
'transform_func': str
},
'owner_id': {
'xpath': 'ownerId',
'transform_func': str
},
'mac_address': {
'xpath': 'macAddress',
'transform_func': str
},
'private_dns_name': {
'xpath': 'privateIpAddressesSet/privateDnsName',
'transform_func': str
},
'source_dest_check': {
'xpath': 'sourceDestCheck',
'transform_func': str
}
},
'network_interface_attachment': {
'attachment_id': {
'xpath': 'attachment/attachmentId',
'transform_func': str
},
'instance_id': {
'xpath': 'attachment/instanceId',
'transform_func': str
},
'owner_id': {
'xpath': 'attachment/instanceOwnerId',
'transform_func': str
},
'device_index': {
'xpath': 'attachment/deviceIndex',
'transform_func': int
},
'status': {
'xpath': 'attachment/status',
'transform_func': str
},
'attach_time': {
'xpath': 'attachment/attachTime',
'transform_func': parse_date
},
'delete': {
'xpath': 'attachment/deleteOnTermination',
'transform_func': str
}
},
'node': {
'availability': {
'xpath': 'placement/availabilityZone',
'transform_func': str
},
'architecture': {
'xpath': 'architecture',
'transform_func': str
},
'client_token': {
'xpath': 'clientToken',
'transform_func': str
},
'dns_name': {
'xpath': 'dnsName',
'transform_func': str
},
'hypervisor': {
'xpath': 'hypervisor',
'transform_func': str
},
'iam_profile': {
'xpath': 'iamInstanceProfile/id',
'transform_func': str
},
'image_id': {
'xpath': 'imageId',
'transform_func': str
},
'instance_id': {
'xpath': 'instanceId',
'transform_func': str
},
'instance_lifecycle': {
'xpath': 'instanceLifecycle',
'transform_func': str
},
'instance_tenancy': {
'xpath': 'placement/tenancy',
'transform_func': str
},
'instance_type': {
'xpath': 'instanceType',
'transform_func': str
},
'key_name': {
'xpath': 'keyName',
'transform_func': str
},
'launch_index': {
'xpath': 'amiLaunchIndex',
'transform_func': int
},
'launch_time': {
'xpath': 'launchTime',
'transform_func': str
},
'kernel_id': {
'xpath': 'kernelId',
'transform_func': str
},
'monitoring': {
'xpath': 'monitoring/state',
'transform_func': str
},
'platform': {
'xpath': 'platform',
'transform_func': str
},
'private_dns': {
'xpath': 'privateDnsName',
'transform_func': str
},
'ramdisk_id': {
'xpath': 'ramdiskId',
'transform_func': str
},
'root_device_type': {
'xpath': 'rootDeviceType',
'transform_func': str
},
'root_device_name': {
'xpath': 'rootDeviceName',
'transform_func': str
},
'reason': {
'xpath': 'reason',
'transform_func': str
},
'source_dest_check': {
'xpath': 'sourceDestCheck',
'transform_func': str
},
'status': {
'xpath': 'instanceState/name',
'transform_func': str
},
'subnet_id': {
'xpath': 'subnetId',
'transform_func': str
},
'virtualization_type': {
'xpath': 'virtualizationType',
'transform_func': str
},
'ebs_optimized': {
'xpath': 'ebsOptimized',
'transform_func': str
},
'vpc_id': {
'xpath': 'vpcId',
'transform_func': str
}
},
'reserved_node': {
'instance_type': {
'xpath': 'instanceType',
'transform_func': str
},
'availability': {
'xpath': 'availabilityZone',
'transform_func': str
},
'start': {
'xpath': 'start',
'transform_func': str
},
'duration': {
'xpath': 'duration',
'transform_func': int
},
'usage_price': {
'xpath': 'usagePrice',
'transform_func': float
},
'fixed_price': {
'xpath': 'fixedPrice',
'transform_func': float
},
'instance_count': {
'xpath': 'instanceCount',
'transform_func': int
},
'description': {
'xpath': 'productDescription',
'transform_func': str
},
'instance_tenancy': {
'xpath': 'instanceTenancy',
'transform_func': str
},
'currency_code': {
'xpath': 'currencyCode',
'transform_func': str
},
'offering_type': {
'xpath': 'offeringType',
'transform_func': str
}
},
'security_group': {
'vpc_id': {
'xpath': 'vpcId',
'transform_func': str
},
'description': {
'xpath': 'groupDescription',
'transform_func': str
},
'owner_id': {
'xpath': 'ownerId',
'transform_func': str
}
},
'snapshot': {
'volume_id': {
'xpath': 'volumeId',
'transform_func': str
},
'state': {
'xpath': 'status',
'transform_func': str
},
'description': {
'xpath': 'description',
'transform_func': str
},
'progress': {
'xpath': 'progress',
'transform_func': str
},
'start_time': {
'xpath': 'startTime',
'transform_func': parse_date
}
},
'subnet': {
'cidr_block': {
'xpath': 'cidrBlock',
'transform_func': str
},
'available_ips': {
'xpath': 'availableIpAddressCount',
'transform_func': int
},
'zone': {
'xpath': 'availabilityZone',
'transform_func': str
},
'vpc_id': {
'xpath': 'vpcId',
'transform_func': str
}
},
'volume': {
'device': {
'xpath': 'attachmentSet/item/device',
'transform_func': str
},
'snapshot_id': {
'xpath': 'snapshotId',
'transform_func': lambda v: str(v) or None
},
'iops': {
'xpath': 'iops',
'transform_func': int
},
'zone': {
'xpath': 'availabilityZone',
'transform_func': str
},
'create_time': {
'xpath': 'createTime',
'transform_func': parse_date
},
'state': {
'xpath': 'status',
'transform_func': str
},
'attach_time': {
'xpath': 'attachmentSet/item/attachTime',
'transform_func': parse_date
},
'attachment_status': {
'xpath': 'attachmentSet/item/status',
'transform_func': str
},
'instance_id': {
'xpath': 'attachmentSet/item/instanceId',
'transform_func': str
},
'delete': {
'xpath': 'attachmentSet/item/deleteOnTermination',
'transform_func': str
}
},
'route_table': {
'vpc_id': {
'xpath': 'vpcId',
'transform_func': str
}
}
}
VALID_EC2_REGIONS = REGION_DETAILS.keys()
VALID_EC2_REGIONS = [r for r in VALID_EC2_REGIONS if r != 'nimbus']
class EC2NodeLocation(NodeLocation):
def __init__(self, id, name, country, driver, availability_zone):
super(EC2NodeLocation, self).__init__(id, name, country, driver)
self.availability_zone = availability_zone
def __repr__(self):
return (('<EC2NodeLocation: id=%s, name=%s, country=%s, '
'availability_zone=%s driver=%s>')
% (self.id, self.name, self.country,
self.availability_zone, self.driver.name))
class EC2Response(AWSBaseResponse):
"""
EC2 specific response parsing and error handling.
"""
def parse_error(self):
err_list = []
# Okay, so for Eucalyptus, you can get a 403, with no body,
# if you are using the wrong user/password.
msg = "Failure: 403 Forbidden"
if self.status == 403 and self.body[:len(msg)] == msg:
raise InvalidCredsError(msg)
try:
body = ET.XML(self.body)
except:
raise MalformedResponseError("Failed to parse XML",
body=self.body, driver=EC2NodeDriver)
for err in body.findall('Errors/Error'):
code, message = err.getchildren()
err_list.append('%s: %s' % (code.text, message.text))
if code.text == 'InvalidClientTokenId':
raise InvalidCredsError(err_list[-1])
if code.text == 'SignatureDoesNotMatch':
raise InvalidCredsError(err_list[-1])
if code.text == 'AuthFailure':
raise InvalidCredsError(err_list[-1])
if code.text == 'OptInRequired':
raise InvalidCredsError(err_list[-1])
if code.text == 'IdempotentParameterMismatch':
raise IdempotentParamError(err_list[-1])
if code.text == 'InvalidKeyPair.NotFound':
# TODO: Use connection context instead
match = re.match(r'.*\'(.+?)\'.*', message.text)
if match:
name = match.groups()[0]
else:
name = None
raise KeyPairDoesNotExistError(name=name,
driver=self.connection.driver)
return '\n'.join(err_list)
class EC2Connection(SignedAWSConnection):
"""
Represents a single connection to the EC2 Endpoint.
"""
version = API_VERSION
host = REGION_DETAILS['us-east-1']['endpoint']
responseCls = EC2Response
class ExEC2AvailabilityZone(object):
"""
Extension class which stores information about an EC2 availability zone.
Note: This class is EC2 specific.
"""
def __init__(self, name, zone_state, region_name):
self.name = name
self.zone_state = zone_state
self.region_name = region_name
def __repr__(self):
return (('<ExEC2AvailabilityZone: name=%s, zone_state=%s, '
'region_name=%s>')
% (self.name, self.zone_state, self.region_name))
class EC2ReservedNode(Node):
"""
Class which stores information about EC2 reserved instances/nodes
Inherits from Node and passes in None for name and private/public IPs
Note: This class is EC2 specific.
"""
def __init__(self, id, state, driver, size=None, image=None, extra=None):
super(EC2ReservedNode, self).__init__(id=id, name=None, state=state,
public_ips=None,
private_ips=None,
driver=driver, extra=extra)
def __repr__(self):
return (('<EC2ReservedNode: id=%s>') % (self.id))
class EC2SecurityGroup(object):
"""
Represents information about a Security group
Note: This class is EC2 specific.
"""
def __init__(self, id, name, ingress_rules, egress_rules, extra=None):
self.id = id
self.name = name
self.ingress_rules = ingress_rules
self.egress_rules = egress_rules
self.extra = extra or {}
def __repr__(self):
return (('<EC2SecurityGroup: id=%s, name=%s')
% (self.id, self.name))
class EC2PlacementGroup(object):
"""
Represents information about a Placement Grous
Note: This class is EC2 specific.
"""
def __init__(self, name, state, strategy='cluster', extra=None):
self.name = name
self.strategy = strategy
self.extra = extra or {}
def __repr__(self):
return '<EC2PlacementGroup: name=%s, state=%s>' % (self.name,
self.strategy)
class EC2Network(object):
"""
Represents information about a VPC (Virtual Private Cloud) network
Note: This class is EC2 specific.
"""
def __init__(self, id, name, cidr_block, extra=None):
self.id = id
self.name = name
self.cidr_block = cidr_block
self.extra = extra or {}
def __repr__(self):
return (('<EC2Network: id=%s, name=%s')
% (self.id, self.name))
class EC2NetworkSubnet(object):
"""
Represents information about a VPC (Virtual Private Cloud) subnet
Note: This class is EC2 specific.
"""
def __init__(self, id, name, state, extra=None):
self.id = id
self.name = name
self.state = state
self.extra = extra or {}
def __repr__(self):
return (('<EC2NetworkSubnet: id=%s, name=%s') % (self.id, self.name))
class EC2NetworkInterface(object):
"""
Represents information about a VPC network interface
Note: This class is EC2 specific. The state parameter denotes the current
status of the interface. Valid values for state are attaching, attached,
detaching and detached.
"""
def __init__(self, id, name, state, extra=None):
self.id = id
self.name = name
self.state = state
self.extra = extra or {}
def __repr__(self):
return (('<EC2NetworkInterface: id=%s, name=%s')
% (self.id, self.name))
class ElasticIP(object):
"""
Represents information about an elastic IP address
:param ip: The elastic IP address
:type ip: ``str``
:param domain: The domain that the IP resides in (EC2-Classic/VPC).
EC2 classic is represented with standard and VPC
is represented with vpc.
:type domain: ``str``
:param instance_id: The identifier of the instance which currently
has the IP associated.
:type instance_id: ``str``
Note: This class is used to support both EC2 and VPC IPs.
For VPC specific attributes are stored in the extra
dict to make promotion to the base API easier.
"""
def __init__(self, ip, domain, instance_id, extra=None):
self.ip = ip
self.domain = domain
self.instance_id = instance_id
self.extra = extra or {}
def __repr__(self):
return (('<ElasticIP: ip=%s, domain=%s, instance_id=%s>')
% (self.ip, self.domain, self.instance_id))
class VPCInternetGateway(object):
"""
Class which stores information about VPC Internet Gateways.
Note: This class is VPC specific.
"""
def __init__(self, id, name, vpc_id, state, driver, extra=None):
self.id = id
self.name = name
self.vpc_id = vpc_id
self.state = state
self.extra = extra or {}
def __repr__(self):
return (('<VPCInternetGateway: id=%s>') % (self.id))
class EC2RouteTable(object):
"""
Class which stores information about VPC Route Tables.
Note: This class is VPC specific.
"""
def __init__(self, id, name, routes, subnet_associations,
propagating_gateway_ids, extra=None):
"""
:param id: The ID of the route table.
:type id: ``str``
:param name: The name of the route table.
:type name: ``str``
:param routes: A list of routes in the route table.
:type routes: ``list`` of :class:`EC2Route`
:param subnet_associations: A list of associations between the
route table and one or more subnets.
:type subnet_associations: ``list`` of
:class:`EC2SubnetAssociation`
:param propagating_gateway_ids: The list of IDs of any virtual
private gateways propagating the
routes.
:type propagating_gateway_ids: ``list``
"""
self.id = id
self.name = name
self.routes = routes
self.subnet_associations = subnet_associations
self.propagating_gateway_ids = propagating_gateway_ids
self.extra = extra or {}
def __repr__(self):
return (('<EC2RouteTable: id=%s>') % (self.id))
class EC2Route(object):
"""
Class which stores information about a Route.
Note: This class is VPC specific.
"""
def __init__(self, cidr, gateway_id, instance_id, owner_id,
interface_id, state, origin, vpc_peering_connection_id):
"""
:param cidr: The CIDR block used for the destination match.
:type cidr: ``str``
:param gateway_id: The ID of a gateway attached to the VPC.
:type gateway_id: ``str``
:param instance_id: The ID of a NAT instance in the VPC.
:type instance_id: ``str``
:param owner_id: The AWS account ID of the owner of the instance.
:type owner_id: ``str``
:param interface_id: The ID of the network interface.
:type interface_id: ``str``
:param state: The state of the route (active | blackhole).
:type state: ``str``
:param origin: Describes how the route was created.
:type origin: ``str``
:param vpc_peering_connection_id: The ID of the VPC
peering connection.
:type vpc_peering_connection_id: ``str``
"""
self.cidr = cidr
self.gateway_id = gateway_id
self.instance_id = instance_id
self.owner_id = owner_id
self.interface_id = interface_id
self.state = state
self.origin = origin
self.vpc_peering_connection_id = vpc_peering_connection_id
def __repr__(self):
return (('<EC2Route: cidr=%s>') % (self.cidr))
class EC2SubnetAssociation(object):
"""
Class which stores information about Route Table associated with
a given Subnet in a VPC
Note: This class is VPC specific.
"""
def __init__(self, id, route_table_id, subnet_id, main=False):
"""
:param id: The ID of the subnet association in the VPC.
:type id: ``str``
:param route_table_id: The ID of a route table in the VPC.
:type route_table_id: ``str``
:param subnet_id: The ID of a subnet in the VPC.
:type subnet_id: ``str``
:param main: If true, means this is a main VPC route table.
:type main: ``bool``
"""
self.id = id
self.route_table_id = route_table_id
self.subnet_id = subnet_id
self.main = main
def __repr__(self):
return (('<EC2SubnetAssociation: id=%s>') % (self.id))
class BaseEC2NodeDriver(NodeDriver):
"""
Base Amazon EC2 node driver.
Used for main EC2 and other derivate driver classes to inherit from it.
"""
connectionCls = EC2Connection
features = {'create_node': ['ssh_key']}
path = '/'
NODE_STATE_MAP = {
'pending': NodeState.PENDING,
'running': NodeState.RUNNING,
'shutting-down': NodeState.UNKNOWN,
'terminated': NodeState.TERMINATED
}
def list_nodes(self, ex_node_ids=None, ex_filters=None):
"""
List all nodes
Ex_node_ids parameter is used to filter the list of
nodes that should be returned. Only the nodes
with the corresponding node ids will be returned.
:param ex_node_ids: List of ``node.id``
:type ex_node_ids: ``list`` of ``str``
:param ex_filters: The filters so that the response includes
information for only certain nodes.
:type ex_filters: ``dict``
:rtype: ``list`` of :class:`Node`
"""
params = {'Action': 'DescribeInstances'}
if ex_node_ids:
params.update(self._pathlist('InstanceId', ex_node_ids))
if ex_filters:
params.update(self._build_filters(ex_filters))
elem = self.connection.request(self.path, params=params).object
nodes = []
for rs in findall(element=elem, xpath='reservationSet/item',
namespace=NAMESPACE):
nodes += self._to_nodes(rs, 'instancesSet/item')
nodes_elastic_ips_mappings = self.ex_describe_addresses(nodes)
for node in nodes:
ips = nodes_elastic_ips_mappings[node.id]
node.public_ips.extend(ips)
return nodes
def list_sizes(self, location=None):
available_types = REGION_DETAILS[self.region_name]['instance_types']
sizes = []
for instance_type in available_types:
attributes = INSTANCE_TYPES[instance_type]
attributes = copy.deepcopy(attributes)
price = self._get_size_price(size_id=instance_type)
attributes.update({'price': price})
sizes.append(NodeSize(driver=self, **attributes))
return sizes
def list_images(self, location=None, ex_image_ids=None, ex_owner=None,
ex_executableby=None, ex_filters=None):
"""
List all images
@inherits: :class:`NodeDriver.list_images`
Ex_image_ids parameter is used to filter the list of
images that should be returned. Only the images
with the corresponding image ids will be returned.
Ex_owner parameter is used to filter the list of
images that should be returned. Only the images
with the corresponding owner will be returned.
Valid values: amazon|aws-marketplace|self|all|aws id
Ex_executableby parameter describes images for which
the specified user has explicit launch permissions.
The user can be an AWS account ID, self to return
images for which the sender of the request has
explicit launch permissions, or all to return
images with public launch permissions.
Valid values: all|self|aws id
Ex_filters parameter is used to filter the list of
images that should be returned. Only images matchind
the filter will be returned.
:param ex_image_ids: List of ``NodeImage.id``
:type ex_image_ids: ``list`` of ``str``
:param ex_owner: Owner name
:type ex_owner: ``str``
:param ex_executableby: Executable by
:type ex_executableby: ``str``
:param ex_filters: Filter by
:type ex_filters: ``dict``
:rtype: ``list`` of :class:`NodeImage`
"""
params = {'Action': 'DescribeImages'}
if ex_owner:
params.update({'Owner.1': ex_owner})
if ex_executableby:
params.update({'ExecutableBy.1': ex_executableby})
if ex_image_ids:
for index, image_id in enumerate(ex_image_ids):
index += 1
params.update({'ImageId.%s' % (index): image_id})
if ex_filters:
params.update(self._build_filters(ex_filters))
images = self._to_images(
self.connection.request(self.path, params=params).object
)
return images
def get_image(self, image_id):
"""
Get an image based on an image_id
:param image_id: Image identifier
:type image_id: ``str``
:return: A NodeImage object
:rtype: :class:`NodeImage`
"""
images = self.list_images(ex_image_ids=[image_id])
image = images[0]
return image
def list_locations(self):
locations = []
for index, availability_zone in \
enumerate(self.ex_list_availability_zones()):
locations.append(EC2NodeLocation(
index, availability_zone.name, self.country, self,
availability_zone)
)
return locations
def list_volumes(self, node=None):
params = {
'Action': 'DescribeVolumes',
}
if node:
filters = {'attachment.instance-id': node.id}
params.update(self._build_filters(filters))
response = self.connection.request(self.path, params=params).object
volumes = [self._to_volume(el) for el in response.findall(
fixxpath(xpath='volumeSet/item', namespace=NAMESPACE))
]
return volumes
def create_node(self, **kwargs):
"""
Create a new EC2 node.
Reference: http://bit.ly/8ZyPSy [docs.amazonwebservices.com]
@inherits: :class:`NodeDriver.create_node`
:keyword ex_keyname: The name of the key pair
:type ex_keyname: ``str``
:keyword ex_userdata: User data
:type ex_userdata: ``str``
:keyword ex_security_groups: A list of names of security groups to
assign to the node.
:type ex_security_groups: ``list``
:keyword ex_security_group_ids: A list of ids of security groups to
assign to the node.[for VPC nodes only]
:type ex_security_group_ids: ``list``
:keyword ex_metadata: Key/Value metadata to associate with a node
:type ex_metadata: ``dict``
:keyword ex_mincount: Minimum number of instances to launch
:type ex_mincount: ``int``
:keyword ex_maxcount: Maximum number of instances to launch
:type ex_maxcount: ``int``
:keyword ex_clienttoken: Unique identifier to ensure idempotency
:type ex_clienttoken: ``str``
:keyword ex_blockdevicemappings: ``list`` of ``dict`` block device
mappings.
:type ex_blockdevicemappings: ``list`` of ``dict``
:keyword ex_iamprofile: Name or ARN of IAM profile
:type ex_iamprofile: ``str``
:keyword ex_ebs_optimized: EBS-Optimized if True
:type ex_ebs_optimized: ``bool``
:keyword ex_subnet: The subnet to launch the instance into.
:type ex_subnet: :class:`.EC2Subnet`
:keyword ex_placement_group: The name of the placement group to
launch the instance into.
:type ex_placement_group: ``str``
"""
image = kwargs["image"]
size = kwargs["size"]
params = {
'Action': 'RunInstances',
'ImageId': image.id,
'MinCount': str(kwargs.get('ex_mincount', '1')),
'MaxCount': str(kwargs.get('ex_maxcount', '1')),
'InstanceType': size.id
}
if 'ex_security_groups' in kwargs and 'ex_securitygroup' in kwargs:
raise ValueError('You can only supply ex_security_groups or'
' ex_securitygroup')
# ex_securitygroup is here for backward compatibility
ex_security_groups = kwargs.get('ex_security_groups', None)
ex_securitygroup = kwargs.get('ex_securitygroup', None)
security_groups = ex_security_groups or ex_securitygroup
if security_groups:
if not isinstance(security_groups, (tuple, list)):
security_groups = [security_groups]
for sig in range(len(security_groups)):
params['SecurityGroup.%d' % (sig + 1,)] =\
security_groups[sig]
if 'ex_security_group_ids' in kwargs and 'ex_subnet' not in kwargs:
raise ValueError('You can only supply ex_security_group_ids'
' combinated with ex_subnet')
security_group_ids = kwargs.get('ex_security_group_ids', None)
if security_group_ids:
if not isinstance(security_group_ids, (tuple, list)):
security_group_ids = [security_group_ids]
for sig in range(len(security_group_ids)):
params['SecurityGroupId.%d' % (sig + 1,)] =\
security_group_ids[sig]
if 'location' in kwargs:
availability_zone = getattr(kwargs['location'],
'availability_zone', None)
if availability_zone:
if availability_zone.region_name != self.region_name:
raise AttributeError('Invalid availability zone: %s'
% (availability_zone.name))
params['Placement.AvailabilityZone'] = availability_zone.name
if 'auth' in kwargs and 'ex_keyname' in kwargs:
raise AttributeError('Cannot specify auth and ex_keyname together')
if 'auth' in kwargs:
auth = self._get_and_check_auth(kwargs['auth'])
key = self.ex_find_or_import_keypair_by_key_material(auth.pubkey)
params['KeyName'] = key['keyName']
if 'ex_keyname' in kwargs:
params['KeyName'] = kwargs['ex_keyname']
if 'ex_userdata' in kwargs:
params['UserData'] = base64.b64encode(b(kwargs['ex_userdata']))\
.decode('utf-8')
if 'ex_clienttoken' in kwargs:
params['ClientToken'] = kwargs['ex_clienttoken']
if 'ex_blockdevicemappings' in kwargs:
params.update(self._get_block_device_mapping_params(
kwargs['ex_blockdevicemappings']))
if 'ex_iamprofile' in kwargs:
if not isinstance(kwargs['ex_iamprofile'], basestring):
raise AttributeError('ex_iamprofile not string')
if kwargs['ex_iamprofile'].startswith('arn:aws:iam:'):
params['IamInstanceProfile.Arn'] = kwargs['ex_iamprofile']
else:
params['IamInstanceProfile.Name'] = kwargs['ex_iamprofile']
if 'ex_ebs_optimized' in kwargs:
params['EbsOptimized'] = kwargs['ex_ebs_optimized']
if 'ex_subnet' in kwargs:
params['SubnetId'] = kwargs['ex_subnet'].id
if 'ex_placement_group' in kwargs and kwargs['ex_placement_group']:
params['Placement.GroupName'] = kwargs['ex_placement_group']
object = self.connection.request(self.path, params=params).object
nodes = self._to_nodes(object, 'instancesSet/item')
for node in nodes:
tags = {'Name': kwargs['name']}
if 'ex_metadata' in kwargs:
tags.update(kwargs['ex_metadata'])
try:
self.ex_create_tags(resource=node, tags=tags)
except Exception:
continue
node.name = kwargs['name']
node.extra.update({'tags': tags})
if len(nodes) == 1:
return nodes[0]
else:
return nodes
def reboot_node(self, node):
params = {'Action': 'RebootInstances'}
params.update(self._pathlist('InstanceId', [node.id]))
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def destroy_node(self, node):
params = {'Action': 'TerminateInstances'}
params.update(self._pathlist('InstanceId', [node.id]))
res = self.connection.request(self.path, params=params).object
return self._get_terminate_boolean(res)
def create_volume(self, size, name, location=None, snapshot=None,
ex_volume_type='standard', ex_iops=None):
"""
Create a new volume.
:param size: Size of volume in gigabytes (required)
:type size: ``int``
:param name: Name of the volume to be created
:type name: ``str``
:param location: Which data center to create a volume in. If
empty, undefined behavior will be selected.
(optional)
:type location: :class:`.NodeLocation`
:param snapshot: Snapshot from which to create the new
volume. (optional)
:type snapshot: :class:`.VolumeSnapshot`
:param location: Datacenter in which to create a volume in.
:type location: :class:`.ExEC2AvailabilityZone`
:param ex_volume_type: Type of volume to create.
:type ex_volume_type: ``str``
:param iops: The number of I/O operations per second (IOPS)
that the volume supports. Only used if ex_volume_type
is io1.
:type iops: ``int``
:return: The newly created volume.
:rtype: :class:`StorageVolume`
"""
valid_volume_types = ['standard', 'io1', 'gp2']
params = {
'Action': 'CreateVolume',
'Size': str(size)}
if ex_volume_type and ex_volume_type not in valid_volume_types:
raise ValueError('Invalid volume type specified: %s' %
(ex_volume_type))
if snapshot:
params['SnapshotId'] = snapshot.id
if location is not None:
params['AvailabilityZone'] = location.availability_zone.name
if ex_volume_type:
params['VolumeType'] = ex_volume_type
if ex_volume_type == 'io1' and ex_iops:
params['Iops'] = ex_iops
volume = self._to_volume(
self.connection.request(self.path, params=params).object,
name=name)
if self.ex_create_tags(volume, {'Name': name}):
volume.extra['tags']['Name'] = name
return volume
def attach_volume(self, node, volume, device):
params = {
'Action': 'AttachVolume',
'VolumeId': volume.id,
'InstanceId': node.id,
'Device': device}
self.connection.request(self.path, params=params)
return True
def detach_volume(self, volume):
params = {
'Action': 'DetachVolume',
'VolumeId': volume.id}
self.connection.request(self.path, params=params)
return True
def destroy_volume(self, volume):
params = {
'Action': 'DeleteVolume',
'VolumeId': volume.id}
response = self.connection.request(self.path, params=params).object
return self._get_boolean(response)
def create_volume_snapshot(self, volume, name=None):
"""
Create snapshot from volume
:param volume: Instance of ``StorageVolume``
:type volume: ``StorageVolume``
:param name: Name of snapshot
:type name: ``str``
:rtype: :class:`VolumeSnapshot`
"""
params = {
'Action': 'CreateSnapshot',
'VolumeId': volume.id,
}
if name:
params.update({
'Description': name,
})
response = self.connection.request(self.path, params=params).object
snapshot = self._to_snapshot(response, name)
if name and self.ex_create_tags(snapshot, {'Name': name}):
snapshot.extra['tags']['Name'] = name
return snapshot
def list_volume_snapshots(self, volume):
return [snapshot for snapshot in self.list_snapshots(owner='self')
if snapshot.extra["volume_id"] == volume.id]
def list_snapshots(self, snapshot=None, owner=None):
"""
Describe all snapshots.
:param snapshot: If provided, only return snapshot information for the
provided snapshot.
:param owner: Owner for snapshot: self|amazon|ID
:type owner: ``str``
:rtype: ``list`` of :class:`VolumeSnapshot`
"""
params = {
'Action': 'DescribeSnapshots',
}
if snapshot:
params.update({
'SnapshotId.1': snapshot.id,
})
if owner:
params.update({
'Owner.1': owner,
})
response = self.connection.request(self.path, params=params).object
snapshots = self._to_snapshots(response)
return snapshots
def destroy_volume_snapshot(self, snapshot):
params = {
'Action': 'DeleteSnapshot',
'SnapshotId': snapshot.id
}
response = self.connection.request(self.path, params=params).object
return self._get_boolean(response)
# Key pair management methods
def list_key_pairs(self):
params = {
'Action': 'DescribeKeyPairs'
}
response = self.connection.request(self.path, params=params)
elems = findall(element=response.object, xpath='keySet/item',
namespace=NAMESPACE)
key_pairs = self._to_key_pairs(elems=elems)
return key_pairs
def get_key_pair(self, name):
params = {
'Action': 'DescribeKeyPairs',
'KeyName': name
}
response = self.connection.request(self.path, params=params)
elems = findall(element=response.object, xpath='keySet/item',
namespace=NAMESPACE)
key_pair = self._to_key_pairs(elems=elems)[0]
return key_pair
def create_key_pair(self, name):
params = {
'Action': 'CreateKeyPair',
'KeyName': name
}
response = self.connection.request(self.path, params=params)
elem = response.object
key_pair = self._to_key_pair(elem=elem)
return key_pair
def import_key_pair_from_string(self, name, key_material):
base64key = ensure_string(base64.b64encode(b(key_material)))
params = {
'Action': 'ImportKeyPair',
'KeyName': name,
'PublicKeyMaterial': base64key
}
response = self.connection.request(self.path, params=params)
elem = response.object
key_pair = self._to_key_pair(elem=elem)
return key_pair
def delete_key_pair(self, key_pair):
params = {
'Action': 'DeleteKeyPair',
'KeyName': key_pair.name
}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def copy_image(self, image, source_region, name=None, description=None):
"""
Copy an Amazon Machine Image from the specified source region
to the current region.
@inherits: :class:`NodeDriver.copy_image`
:param source_region: The region where the image resides
:type source_region: ``str``
:param image: Instance of class NodeImage
:type image: :class:`NodeImage`
:param name: The name of the new image
:type name: ``str``
:param description: The description of the new image
:type description: ``str``
:return: Instance of class ``NodeImage``
:rtype: :class:`NodeImage`
"""
params = {'Action': 'CopyImage',
'SourceRegion': source_region,
'SourceImageId': image.id}
if name is not None:
params['Name'] = name
if description is not None:
params['Description'] = description
image = self._to_image(
self.connection.request(self.path, params=params).object)
return image
def create_image(self, node, name, description=None, reboot=False,
block_device_mapping=None):
"""
Create an Amazon Machine Image based off of an EBS-backed instance.
@inherits: :class:`NodeDriver.create_image`
:param node: Instance of ``Node``
:type node: :class: `Node`
:param name: The name for the new image
:type name: ``str``
:param block_device_mapping: A dictionary of the disk layout
An example of this dict is included
below.
:type block_device_mapping: ``list`` of ``dict``
:param reboot: Whether or not to shutdown the instance before
creation. Amazon calls this NoReboot and
sets it to false by default to ensure a
clean image.
:type reboot: ``bool``
:param description: An optional description for the new image
:type description: ``str``
An example block device mapping dictionary is included:
mapping = [{'VirtualName': None,
'Ebs': {'VolumeSize': 10,
'VolumeType': 'standard',
'DeleteOnTermination': 'true'},
'DeviceName': '/dev/sda1'}]
:return: Instance of class ``NodeImage``
:rtype: :class:`NodeImage`
"""
params = {'Action': 'CreateImage',
'InstanceId': node.id,
'Name': name,
'NoReboot': not reboot}
if description is not None:
params['Description'] = description
if block_device_mapping is not None:
params.update(self._get_block_device_mapping_params(
block_device_mapping))
image = self._to_image(
self.connection.request(self.path, params=params).object)
return image
def delete_image(self, image):
"""
Deletes an image at Amazon given a NodeImage object
@inherits: :class:`NodeDriver.delete_image`
:param image: Instance of ``NodeImage``
:type image: :class: `NodeImage`
:rtype: ``bool``
"""
params = {'Action': 'DeregisterImage',
'ImageId': image.id}
response = self.connection.request(self.path, params=params).object
return self._get_boolean(response)
def ex_create_placement_group(self, name):
"""
Creates new Placement Group
:param name: Name for new placement Group
:type name: ``str``
:rtype: ``bool``
"""
params = {'Action': 'CreatePlacementGroup',
'Strategy': 'cluster',
'GroupName': name}
response = self.connection.request(self.path, params=params).object
return self._get_boolean(response)
def ex_delete_placement_group(self, name):
"""
Deletes Placement Group
:param name: Placement Group name
:type name: ``str``
:rtype: ``bool``
"""
params = {'Action': 'DeletePlacementGroup',
'GroupName': name}
response = self.connection.request(self.path, params=params).object
return self._get_boolean(response)
def ex_list_placement_groups(self, names=None):
"""
List Placement Groups
:param names: Placement Group names
:type names: ``list`` of ``str``
:rtype: ``list`` of :class:`.EC2PlacementGroup`
"""
names = names or []
params = {'Action': 'DescribePlacementGroups'}
for index, name in enumerate(names):
params['GroupName.%s' % index + 1] = name
response = self.connection.request(self.path, params=params).object
return self._to_placement_groups(response)
def ex_register_image(self, name, description=None, architecture=None,
image_location=None, root_device_name=None,
block_device_mapping=None, kernel_id=None,
ramdisk_id=None, virtualization_type=None):
"""
Registers an Amazon Machine Image based off of an EBS-backed instance.
Can also be used to create images from snapshots. More information
can be found at http://goo.gl/hqZq0a.
:param name: The name for the AMI being registered
:type name: ``str``
:param description: The description of the AMI (optional)
:type description: ``str``
:param architecture: The architecture of the AMI (i386/x86_64)
(optional)
:type architecture: ``str``
:param image_location: The location of the AMI within Amazon S3
Required if registering an instance
store-backed AMI
:type image_location: ``str``
:param root_device_name: The device name for the root device
Required if registering an EBS-backed AMI
:type root_device_name: ``str``
:param block_device_mapping: A dictionary of the disk layout
(optional)
:type block_device_mapping: ``dict``
:param kernel_id: Kernel id for AMI (optional)
:type kernel_id: ``str``
:param ramdisk_id: RAM disk for AMI (optional)
:type ramdisk_id: ``str``
:param virtualization_type: The type of virtualization for the
AMI you are registering, paravirt
or hvm (optional)
:type virtualization_type: ``str``
:rtype: :class:`NodeImage`
"""
params = {'Action': 'RegisterImage',
'Name': name}
if description is not None:
params['Description'] = description
if architecture is not None:
params['Architecture'] = architecture
if image_location is not None:
params['ImageLocation'] = image_location
if root_device_name is not None:
params['RootDeviceName'] = root_device_name
if block_device_mapping is not None:
params.update(self._get_block_device_mapping_params(
block_device_mapping))
if kernel_id is not None:
params['KernelId'] = kernel_id
if ramdisk_id is not None:
params['RamDiskId'] = ramdisk_id
if virtualization_type is not None:
params['VirtualizationType'] = virtualization_type
image = self._to_image(
self.connection.request(self.path, params=params).object
)
return image
def ex_list_networks(self, network_ids=None, filters=None):
"""
Return a list of :class:`EC2Network` objects for the
current region.
:param network_ids: Return only networks matching the provided
network IDs. If not specified, a list of all
the networks in the corresponding region
is returned.
:type network_ids: ``list``
:param filters: The filters so that the response includes
information for only certain networks.
:type filters: ``dict``
:rtype: ``list`` of :class:`EC2Network`
"""
params = {'Action': 'DescribeVpcs'}
if network_ids:
params.update(self._pathlist('VpcId', network_ids))
if filters:
params.update(self._build_filters(filters))
return self._to_networks(
self.connection.request(self.path, params=params).object
)
def ex_create_network(self, cidr_block, name=None,
instance_tenancy='default'):
"""
Create a network/VPC
:param cidr_block: The CIDR block assigned to the network
:type cidr_block: ``str``
:param name: An optional name for the network
:type name: ``str``
:param instance_tenancy: The allowed tenancy of instances launched
into the VPC.
Valid values: default/dedicated
:type instance_tenancy: ``str``
:return: Dictionary of network properties
:rtype: ``dict``
"""
params = {'Action': 'CreateVpc',
'CidrBlock': cidr_block,
'InstanceTenancy': instance_tenancy}
response = self.connection.request(self.path, params=params).object
element = response.findall(fixxpath(xpath='vpc',
namespace=NAMESPACE))[0]
network = self._to_network(element, name)
if name and self.ex_create_tags(network, {'Name': name}):
network.extra['tags']['Name'] = name
return network
def ex_delete_network(self, vpc):
"""
Deletes a network/VPC.
:param vpc: VPC to delete.
:type vpc: :class:`.EC2Network`
:rtype: ``bool``
"""
params = {'Action': 'DeleteVpc', 'VpcId': vpc.id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_list_subnets(self, subnet_ids=None, filters=None):
"""
Return a list of :class:`EC2NetworkSubnet` objects for the
current region.
:param subnet_ids: Return only subnets matching the provided
subnet IDs. If not specified, a list of all
the subnets in the corresponding region
is returned.
:type subnet_ids: ``list``
:param filters: The filters so that the response includes
information for only certain subnets.
:type filters: ``dict``
:rtype: ``list`` of :class:`EC2NetworkSubnet`
"""
params = {'Action': 'DescribeSubnets'}
if subnet_ids:
params.update(self._pathlist('SubnetId', subnet_ids))
if filters:
params.update(self._build_filters(filters))
return self._to_subnets(
self.connection.request(self.path, params=params).object
)
def ex_create_subnet(self, vpc_id, cidr_block,
availability_zone, name=None):
"""
Create a network subnet within a VPC
:param vpc_id: The ID of the VPC that the subnet should be
associated with
:type vpc_id: ``str``
:param cidr_block: The CIDR block assigned to the subnet
:type cidr_block: ``str``
:param availability_zone: The availability zone where the subnet
should reside
:type availability_zone: ``str``
:param name: An optional name for the network
:type name: ``str``
:rtype: :class: `EC2NetworkSubnet`
"""
params = {'Action': 'CreateSubnet',
'VpcId': vpc_id,
'CidrBlock': cidr_block,
'AvailabilityZone': availability_zone}
response = self.connection.request(self.path, params=params).object
element = response.findall(fixxpath(xpath='subnet',
namespace=NAMESPACE))[0]
subnet = self._to_subnet(element, name)
if name and self.ex_create_tags(subnet, {'Name': name}):
subnet.extra['tags']['Name'] = name
return subnet
def ex_delete_subnet(self, subnet):
"""
Deletes a VPC subnet.
:param subnet: The subnet to delete
:type subnet: :class:`.EC2NetworkSubnet`
:rtype: ``bool``
"""
params = {'Action': 'DeleteSubnet', 'SubnetId': subnet.id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_list_security_groups(self):
"""
List existing Security Groups.
@note: This is a non-standard extension API, and only works for EC2.
:rtype: ``list`` of ``str``
"""
params = {'Action': 'DescribeSecurityGroups'}
response = self.connection.request(self.path, params=params).object
groups = []
for group in findall(element=response, xpath='securityGroupInfo/item',
namespace=NAMESPACE):
name = findtext(element=group, xpath='groupName',
namespace=NAMESPACE)
groups.append(name)
return groups
def ex_get_security_groups(self, group_ids=None,
group_names=None, filters=None):
"""
Return a list of :class:`EC2SecurityGroup` objects for the
current region.
:param group_ids: Return only groups matching the provided
group IDs.
:type group_ids: ``list``
:param group_names: Return only groups matching the provided
group names.
:type group_ids: ``list``
:param filters: The filters so that the response includes
information for only specific security groups.
:type filters: ``dict``
:rtype: ``list`` of :class:`EC2SecurityGroup`
"""
params = {'Action': 'DescribeSecurityGroups'}
if group_ids:
params.update(self._pathlist('GroupId', group_ids))
if group_names:
for name_idx, group_name in enumerate(group_names):
name_idx += 1 # We want 1-based indexes
name_key = 'GroupName.%s' % (name_idx)
params[name_key] = group_name
if filters:
params.update(self._build_filters(filters))
response = self.connection.request(self.path, params=params)
return self._to_security_groups(response.object)
def ex_create_security_group(self, name, description, vpc_id=None):
"""
Creates a new Security Group in EC2-Classic or a targeted VPC.
:param name: The name of the security group to Create.
This must be unique.
:type name: ``str``
:param description: Human readable description of a Security
Group.
:type description: ``str``
:param vpc_id: Optional identifier for VPC networks
:type vpc_id: ``str``
:rtype: ``dict``
"""
params = {'Action': 'CreateSecurityGroup',
'GroupName': name,
'GroupDescription': description}
if vpc_id is not None:
params['VpcId'] = vpc_id
response = self.connection.request(self.path, params=params).object
group_id = findattr(element=response, xpath='groupId',
namespace=NAMESPACE)
return {
'group_id': group_id
}
def ex_delete_security_group_by_id(self, group_id):
"""
Deletes a new Security Group using the group id.
:param group_id: The ID of the security group
:type group_id: ``str``
:rtype: ``bool``
"""
params = {'Action': 'DeleteSecurityGroup', 'GroupId': group_id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_delete_security_group_by_name(self, group_name):
"""
Deletes a new Security Group using the group name.
:param group_name: The name of the security group
:type group_name: ``str``
:rtype: ``bool``
"""
params = {'Action': 'DeleteSecurityGroup', 'GroupName': group_name}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_delete_security_group(self, name):
"""
Wrapper method which calls ex_delete_security_group_by_name.
:param name: The name of the security group
:type name: ``str``
:rtype: ``bool``
"""
return self.ex_delete_security_group_by_name(name)
def ex_authorize_security_group(self, name, from_port, to_port, cidr_ip,
protocol='tcp'):
"""
Edit a Security Group to allow specific traffic.
@note: This is a non-standard extension API, and only works for EC2.
:param name: The name of the security group to edit
:type name: ``str``
:param from_port: The beginning of the port range to open
:type from_port: ``str``
:param to_port: The end of the port range to open
:type to_port: ``str``
:param cidr_ip: The ip to allow traffic for.
:type cidr_ip: ``str``
:param protocol: tcp/udp/icmp
:type protocol: ``str``
:rtype: ``bool``
"""
params = {'Action': 'AuthorizeSecurityGroupIngress',
'GroupName': name,
'IpProtocol': protocol,
'FromPort': str(from_port),
'ToPort': str(to_port),
'CidrIp': cidr_ip}
try:
res = self.connection.request(
self.path, params=params.copy()).object
return self._get_boolean(res)
except Exception:
e = sys.exc_info()[1]
if e.args[0].find('InvalidPermission.Duplicate') == -1:
raise e
def ex_authorize_security_group_ingress(self, id, from_port, to_port,
cidr_ips=None, group_pairs=None,
protocol='tcp'):
"""
Edit a Security Group to allow specific ingress traffic using
CIDR blocks or either a group ID, group name or user ID (account).
:param id: The id of the security group to edit
:type id: ``str``
:param from_port: The beginning of the port range to open
:type from_port: ``int``
:param to_port: The end of the port range to open
:type to_port: ``int``
:param cidr_ips: The list of ip ranges to allow traffic for.
:type cidr_ips: ``list``
:param group_pairs: Source user/group pairs to allow traffic for.
More info can be found at http://goo.gl/stBHJF
EC2 Classic Example: To allow access from any system
associated with the default group on account 1234567890
[{'group_name': 'default', 'user_id': '1234567890'}]
VPC Example: Allow access from any system associated with
security group sg-47ad482e on your own account
[{'group_id': ' sg-47ad482e'}]
:type group_pairs: ``list`` of ``dict``
:param protocol: tcp/udp/icmp
:type protocol: ``str``
:rtype: ``bool``
"""
params = self._get_common_security_group_params(id,
protocol,
from_port,
to_port,
cidr_ips,
group_pairs)
params["Action"] = 'AuthorizeSecurityGroupIngress'
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_authorize_security_group_egress(self, id, from_port, to_port,
cidr_ips, group_pairs=None,
protocol='tcp'):
"""
Edit a Security Group to allow specific egress traffic using
CIDR blocks or either a group ID, group name or user ID (account).
This call is not supported for EC2 classic and only works for VPC
groups.
:param id: The id of the security group to edit
:type id: ``str``
:param from_port: The beginning of the port range to open
:type from_port: ``int``
:param to_port: The end of the port range to open
:type to_port: ``int``
:param cidr_ips: The list of ip ranges to allow traffic for.
:type cidr_ips: ``list``
:param group_pairs: Source user/group pairs to allow traffic for.
More info can be found at http://goo.gl/stBHJF
EC2 Classic Example: To allow access from any system
associated with the default group on account 1234567890
[{'group_name': 'default', 'user_id': '1234567890'}]
VPC Example: Allow access from any system associated with
security group sg-47ad482e on your own account
[{'group_id': ' sg-47ad482e'}]
:type group_pairs: ``list`` of ``dict``
:param protocol: tcp/udp/icmp
:type protocol: ``str``
:rtype: ``bool``
"""
params = self._get_common_security_group_params(id,
protocol,
from_port,
to_port,
cidr_ips,
group_pairs)
params["Action"] = 'AuthorizeSecurityGroupEgress'
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_revoke_security_group_ingress(self, id, from_port, to_port,
cidr_ips=None, group_pairs=None,
protocol='tcp'):
"""
Edit a Security Group to revoke specific ingress traffic using
CIDR blocks or either a group ID, group name or user ID (account).
:param id: The id of the security group to edit
:type id: ``str``
:param from_port: The beginning of the port range to open
:type from_port: ``int``
:param to_port: The end of the port range to open
:type to_port: ``int``
:param cidr_ips: The list of ip ranges to allow traffic for.
:type cidr_ips: ``list``
:param group_pairs: Source user/group pairs to allow traffic for.
More info can be found at http://goo.gl/stBHJF
EC2 Classic Example: To allow access from any system
associated with the default group on account 1234567890
[{'group_name': 'default', 'user_id': '1234567890'}]
VPC Example: Allow access from any system associated with
security group sg-47ad482e on your own account
[{'group_id': ' sg-47ad482e'}]
:type group_pairs: ``list`` of ``dict``
:param protocol: tcp/udp/icmp
:type protocol: ``str``
:rtype: ``bool``
"""
params = self._get_common_security_group_params(id,
protocol,
from_port,
to_port,
cidr_ips,
group_pairs)
params["Action"] = 'RevokeSecurityGroupIngress'
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_revoke_security_group_egress(self, id, from_port, to_port,
cidr_ips=None, group_pairs=None,
protocol='tcp'):
"""
Edit a Security Group to revoke specific egress traffic using
CIDR blocks or either a group ID, group name or user ID (account).
This call is not supported for EC2 classic and only works for
VPC groups.
:param id: The id of the security group to edit
:type id: ``str``
:param from_port: The beginning of the port range to open
:type from_port: ``int``
:param to_port: The end of the port range to open
:type to_port: ``int``
:param cidr_ips: The list of ip ranges to allow traffic for.
:type cidr_ips: ``list``
:param group_pairs: Source user/group pairs to allow traffic for.
More info can be found at http://goo.gl/stBHJF
EC2 Classic Example: To allow access from any system
associated with the default group on account 1234567890
[{'group_name': 'default', 'user_id': '1234567890'}]
VPC Example: Allow access from any system associated with
security group sg-47ad482e on your own account
[{'group_id': ' sg-47ad482e'}]
:type group_pairs: ``list`` of ``dict``
:param protocol: tcp/udp/icmp
:type protocol: ``str``
:rtype: ``bool``
"""
params = self._get_common_security_group_params(id,
protocol,
from_port,
to_port,
cidr_ips,
group_pairs)
params['Action'] = 'RevokeSecurityGroupEgress'
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_authorize_security_group_permissive(self, name):
"""
Edit a Security Group to allow all traffic.
@note: This is a non-standard extension API, and only works for EC2.
:param name: The name of the security group to edit
:type name: ``str``
:rtype: ``list`` of ``str``
"""
results = []
params = {'Action': 'AuthorizeSecurityGroupIngress',
'GroupName': name,
'IpProtocol': 'tcp',
'FromPort': '0',
'ToPort': '65535',
'CidrIp': '0.0.0.0/0'}
try:
results.append(
self.connection.request(self.path, params=params.copy()).object
)
except Exception:
e = sys.exc_info()[1]
if e.args[0].find("InvalidPermission.Duplicate") == -1:
raise e
params['IpProtocol'] = 'udp'
try:
results.append(
self.connection.request(self.path, params=params.copy()).object
)
except Exception:
e = sys.exc_info()[1]
if e.args[0].find("InvalidPermission.Duplicate") == -1:
raise e
params.update({'IpProtocol': 'icmp', 'FromPort': '-1', 'ToPort': '-1'})
try:
results.append(
self.connection.request(self.path, params=params.copy()).object
)
except Exception:
e = sys.exc_info()[1]
if e.args[0].find("InvalidPermission.Duplicate") == -1:
raise e
return results
def ex_list_availability_zones(self, only_available=True):
"""
Return a list of :class:`ExEC2AvailabilityZone` objects for the
current region.
Note: This is an extension method and is only available for EC2
driver.
:keyword only_available: If true, return only availability zones
with state 'available'
:type only_available: ``str``
:rtype: ``list`` of :class:`ExEC2AvailabilityZone`
"""
params = {'Action': 'DescribeAvailabilityZones'}
filters = {'region-name': self.region_name}
if only_available:
filters['state'] = 'available'
params.update(self._build_filters(filters))
result = self.connection.request(self.path,
params=params.copy()).object
availability_zones = []
for element in findall(element=result,
xpath='availabilityZoneInfo/item',
namespace=NAMESPACE):
name = findtext(element=element, xpath='zoneName',
namespace=NAMESPACE)
zone_state = findtext(element=element, xpath='zoneState',
namespace=NAMESPACE)
region_name = findtext(element=element, xpath='regionName',
namespace=NAMESPACE)
availability_zone = ExEC2AvailabilityZone(
name=name,
zone_state=zone_state,
region_name=region_name
)
availability_zones.append(availability_zone)
return availability_zones
def ex_describe_tags(self, resource):
"""
Return a dictionary of tags for a resource (e.g. Node or
StorageVolume).
:param resource: resource which should be used
:type resource: any resource class, such as :class:`Node,`
:class:`StorageVolume,` or :class:NodeImage`
:return: dict Node tags
:rtype: ``dict``
"""
params = {'Action': 'DescribeTags'}
filters = {
'resource-id': resource.id
}
params.update(self._build_filters(filters))
result = self.connection.request(self.path, params=params).object
return self._get_resource_tags(result)
def ex_create_tags(self, resource, tags):
"""
Create tags for a resource (Node or StorageVolume).
:param resource: Resource to be tagged
:type resource: :class:`Node` or :class:`StorageVolume`
:param tags: A dictionary or other mapping of strings to strings,
associating tag names with tag values.
:type tags: ``dict``
:rtype: ``bool``
"""
if not tags:
return
params = {'Action': 'CreateTags',
'ResourceId.0': resource.id}
for i, key in enumerate(tags):
params['Tag.%d.Key' % i] = key
params['Tag.%d.Value' % i] = tags[key]
res = self.connection.request(self.path,
params=params.copy()).object
return self._get_boolean(res)
def ex_delete_tags(self, resource, tags):
"""
Delete tags from a resource.
:param resource: Resource to be tagged
:type resource: :class:`Node` or :class:`StorageVolume`
:param tags: A dictionary or other mapping of strings to strings,
specifying the tag names and tag values to be deleted.
:type tags: ``dict``
:rtype: ``bool``
"""
if not tags:
return
params = {'Action': 'DeleteTags',
'ResourceId.0': resource.id}
for i, key in enumerate(tags):
params['Tag.%d.Key' % i] = key
params['Tag.%d.Value' % i] = tags[key]
res = self.connection.request(self.path,
params=params.copy()).object
return self._get_boolean(res)
def ex_get_metadata_for_node(self, node):
"""
Return the metadata associated with the node.
:param node: Node instance
:type node: :class:`Node`
:return: A dictionary or other mapping of strings to strings,
associating tag names with tag values.
:rtype tags: ``dict``
"""
return node.extra['tags']
def ex_allocate_address(self, domain='standard'):
"""
Allocate a new Elastic IP address for EC2 classic or VPC
:param domain: The domain to allocate the new address in
(standard/vpc)
:type domain: ``str``
:return: Instance of ElasticIP
:rtype: :class:`ElasticIP`
"""
params = {'Action': 'AllocateAddress'}
if domain == 'vpc':
params['Domain'] = domain
response = self.connection.request(self.path, params=params).object
return self._to_address(response, only_associated=False)
def ex_release_address(self, elastic_ip, domain=None):
"""
Release an Elastic IP address using the IP (EC2-Classic) or
using the allocation ID (VPC)
:param elastic_ip: Elastic IP instance
:type elastic_ip: :class:`ElasticIP`
:param domain: The domain where the IP resides (vpc only)
:type domain: ``str``
:return: True on success, False otherwise.
:rtype: ``bool``
"""
params = {'Action': 'ReleaseAddress'}
if domain is not None and domain != 'vpc':
raise AttributeError('Domain can only be set to vpc')
if domain is None:
params['PublicIp'] = elastic_ip.ip
else:
params['AllocationId'] = elastic_ip.extra['allocation_id']
response = self.connection.request(self.path, params=params).object
return self._get_boolean(response)
def ex_describe_all_addresses(self, only_associated=False):
"""
Return all the Elastic IP addresses for this account
optionally, return only addresses associated with nodes
:param only_associated: If true, return only those addresses
that are associated with an instance.
:type only_associated: ``bool``
:return: List of ElasticIP instances.
:rtype: ``list`` of :class:`ElasticIP`
"""
params = {'Action': 'DescribeAddresses'}
response = self.connection.request(self.path, params=params).object
# We will send our only_associated boolean over to
# shape how the return data is sent back
return self._to_addresses(response, only_associated)
def ex_associate_address_with_node(self, node, elastic_ip, domain=None):
"""
Associate an Elastic IP address with a particular node.
:param node: Node instance
:type node: :class:`Node`
:param elastic_ip: Elastic IP instance
:type elastic_ip: :class:`ElasticIP`
:param domain: The domain where the IP resides (vpc only)
:type domain: ``str``
:return: A string representation of the association ID which is
required for VPC disassociation. EC2/standard
addresses return None
:rtype: ``None`` or ``str``
"""
params = {'Action': 'AssociateAddress', 'InstanceId': node.id}
if domain is not None and domain != 'vpc':
raise AttributeError('Domain can only be set to vpc')
if domain is None:
params.update({'PublicIp': elastic_ip.ip})
else:
params.update({'AllocationId': elastic_ip.extra['allocation_id']})
response = self.connection.request(self.path, params=params).object
association_id = findtext(element=response,
xpath='associationId',
namespace=NAMESPACE)
return association_id
def ex_associate_addresses(self, node, elastic_ip, domain=None):
"""
Note: This method has been deprecated in favor of
the ex_associate_address_with_node method.
"""
return self.ex_associate_address_with_node(node=node,
elastic_ip=elastic_ip,
domain=domain)
def ex_disassociate_address(self, elastic_ip, domain=None):
"""
Disassociate an Elastic IP address using the IP (EC2-Classic)
or the association ID (VPC)
:param elastic_ip: ElasticIP instance
:type elastic_ip: :class:`ElasticIP`
:param domain: The domain where the IP resides (vpc only)
:type domain: ``str``
:return: True on success, False otherwise.
:rtype: ``bool``
"""
params = {'Action': 'DisassociateAddress'}
if domain is not None and domain != 'vpc':
raise AttributeError('Domain can only be set to vpc')
if domain is None:
params['PublicIp'] = elastic_ip.ip
else:
params['AssociationId'] = elastic_ip.extra['association_id']
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_describe_addresses(self, nodes):
"""
Return Elastic IP addresses for all the nodes in the provided list.
:param nodes: List of :class:`Node` instances
:type nodes: ``list`` of :class:`Node`
:return: Dictionary where a key is a node ID and the value is a
list with the Elastic IP addresses associated with
this node.
:rtype: ``dict``
"""
if not nodes:
return {}
params = {'Action': 'DescribeAddresses'}
if len(nodes) == 1:
self._add_instance_filter(params, nodes[0])
result = self.connection.request(self.path, params=params).object
node_instance_ids = [node.id for node in nodes]
nodes_elastic_ip_mappings = {}
# We will set only_associated to True so that we only get back
# IPs which are associated with instances
only_associated = True
for node_id in node_instance_ids:
nodes_elastic_ip_mappings.setdefault(node_id, [])
for addr in self._to_addresses(result,
only_associated):
instance_id = addr.instance_id
if node_id == instance_id:
nodes_elastic_ip_mappings[instance_id].append(
addr.ip)
return nodes_elastic_ip_mappings
def ex_describe_addresses_for_node(self, node):
"""
Return a list of Elastic IP addresses associated with this node.
:param node: Node instance
:type node: :class:`Node`
:return: list Elastic IP addresses attached to this node.
:rtype: ``list`` of ``str``
"""
node_elastic_ips = self.ex_describe_addresses([node])
return node_elastic_ips[node.id]
# Network interface management methods
def ex_list_network_interfaces(self):
"""
Return all network interfaces
:return: List of EC2NetworkInterface instances
:rtype: ``list`` of :class `EC2NetworkInterface`
"""
params = {'Action': 'DescribeNetworkInterfaces'}
return self._to_interfaces(
self.connection.request(self.path, params=params).object
)
def ex_create_network_interface(self, subnet, name=None,
description=None,
private_ip_address=None):
"""
Create a network interface within a VPC subnet.
:param subnet: EC2NetworkSubnet instance
:type subnet: :class:`EC2NetworkSubnet`
:param name: Optional name of the interface
:type name: ``str``
:param description: Optional description of the network interface
:type description: ``str``
:param private_ip_address: Optional address to assign as the
primary private IP address of the
interface. If one is not provided then
Amazon will automatically auto-assign
an available IP. EC2 allows assignment
of multiple IPs, but this will be
the primary.
:type private_ip_address: ``str``
:return: EC2NetworkInterface instance
:rtype: :class `EC2NetworkInterface`
"""
params = {'Action': 'CreateNetworkInterface',
'SubnetId': subnet.id}
if description:
params['Description'] = description
if private_ip_address:
params['PrivateIpAddress'] = private_ip_address
response = self.connection.request(self.path, params=params).object
element = response.findall(fixxpath(xpath='networkInterface',
namespace=NAMESPACE))[0]
interface = self._to_interface(element, name)
if name and self.ex_create_tags(interface, {'Name': name}):
interface.extra['tags']['Name'] = name
return interface
def ex_delete_network_interface(self, network_interface):
"""
Deletes a network interface.
:param network_interface: EC2NetworkInterface instance
:type network_interface: :class:`EC2NetworkInterface`
:rtype: ``bool``
"""
params = {'Action': 'DeleteNetworkInterface',
'NetworkInterfaceId': network_interface.id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_attach_network_interface_to_node(self, network_interface,
node, device_index):
"""
Attach a network interface to an instance.
:param network_interface: EC2NetworkInterface instance
:type network_interface: :class:`EC2NetworkInterface`
:param node: Node instance
:type node: :class:`Node`
:param device_index: The interface device index
:type device_index: ``int``
:return: String representation of the attachment id.
This is required to detach the interface.
:rtype: ``str``
"""
params = {'Action': 'AttachNetworkInterface',
'NetworkInterfaceId': network_interface.id,
'InstanceId': node.id,
'DeviceIndex': device_index}
response = self.connection.request(self.path, params=params).object
attachment_id = findattr(element=response, xpath='attachmentId',
namespace=NAMESPACE)
return attachment_id
def ex_detach_network_interface(self, attachment_id, force=False):
"""
Detach a network interface from an instance.
:param attachment_id: The attachment ID associated with the
interface
:type attachment_id: ``str``
:param force: Forces the detachment.
:type force: ``bool``
:return: ``True`` on successful detachment, ``False`` otherwise.
:rtype: ``bool``
"""
params = {'Action': 'DetachNetworkInterface',
'AttachmentId': attachment_id}
if force:
params['Force'] = True
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_modify_instance_attribute(self, node, attributes):
"""
Modify node attributes.
A list of valid attributes can be found at http://goo.gl/gxcj8
:param node: Node instance
:type node: :class:`Node`
:param attributes: Dictionary with node attributes
:type attributes: ``dict``
:return: True on success, False otherwise.
:rtype: ``bool``
"""
attributes = attributes or {}
attributes.update({'InstanceId': node.id})
params = {'Action': 'ModifyInstanceAttribute'}
params.update(attributes)
res = self.connection.request(self.path,
params=params.copy()).object
return self._get_boolean(res)
def ex_modify_image_attribute(self, image, attributes):
"""
Modify image attributes.
:param image: NodeImage instance
:type image: :class:`NodeImage`
:param attributes: Dictionary with node attributes
:type attributes: ``dict``
:return: True on success, False otherwise.
:rtype: ``bool``
"""
attributes = attributes or {}
attributes.update({'ImageId': image.id})
params = {'Action': 'ModifyImageAttribute'}
params.update(attributes)
res = self.connection.request(self.path,
params=params.copy()).object
return self._get_boolean(res)
def ex_change_node_size(self, node, new_size):
"""
Change the node size.
Note: Node must be turned of before changing the size.
:param node: Node instance
:type node: :class:`Node`
:param new_size: NodeSize intance
:type new_size: :class:`NodeSize`
:return: True on success, False otherwise.
:rtype: ``bool``
"""
if 'instancetype' in node.extra:
current_instance_type = node.extra['instancetype']
if current_instance_type == new_size.id:
raise ValueError('New instance size is the same as' +
'the current one')
attributes = {'InstanceType.Value': new_size.id}
return self.ex_modify_instance_attribute(node, attributes)
def ex_start_node(self, node):
"""
Start the node by passing in the node object, does not work with
instance store backed instances
:param node: Node which should be used
:type node: :class:`Node`
:rtype: ``bool``
"""
params = {'Action': 'StartInstances'}
params.update(self._pathlist('InstanceId', [node.id]))
res = self.connection.request(self.path, params=params).object
return self._get_state_boolean(res)
def ex_stop_node(self, node):
"""
Stop the node by passing in the node object, does not work with
instance store backed instances
:param node: Node which should be used
:type node: :class:`Node`
:rtype: ``bool``
"""
params = {'Action': 'StopInstances'}
params.update(self._pathlist('InstanceId', [node.id]))
res = self.connection.request(self.path, params=params).object
return self._get_state_boolean(res)
def ex_get_console_output(self, node):
"""
Get console output for the node.
:param node: Node which should be used
:type node: :class:`Node`
:return: Dictionary with the following keys:
- instance_id (``str``)
- timestamp (``datetime.datetime``) - ts of the last output
- output (``str``) - console output
:rtype: ``dict``
"""
params = {
'Action': 'GetConsoleOutput',
'InstanceId': node.id
}
response = self.connection.request(self.path, params=params).object
timestamp = findattr(element=response,
xpath='timestamp',
namespace=NAMESPACE)
encoded_string = findattr(element=response,
xpath='output',
namespace=NAMESPACE)
timestamp = parse_date(timestamp)
if encoded_string:
output = base64.b64decode(b(encoded_string)).decode('utf-8')
else:
# No console output
output = None
return {'instance_id': node.id,
'timestamp': timestamp,
'output': output}
def ex_list_reserved_nodes(self):
"""
List all reserved instances/nodes which can be purchased from Amazon
for one or three year terms. Reservations are made at a region level
and reduce the hourly charge for instances.
More information can be found at http://goo.gl/ulXCC7.
:rtype: ``list`` of :class:`.EC2ReservedNode`
"""
params = {'Action': 'DescribeReservedInstances'}
response = self.connection.request(self.path, params=params).object
return self._to_reserved_nodes(response, 'reservedInstancesSet/item')
# Account specific methods
def ex_get_limits(self):
"""
Retrieve account resource limits.
:rtype: ``dict``
"""
attributes = ['max-instances', 'max-elastic-ips',
'vpc-max-elastic-ips']
params = {}
params['Action'] = 'DescribeAccountAttributes'
for index, attribute in enumerate(attributes):
params['AttributeName.%s' % (index)] = attribute
response = self.connection.request(self.path, params=params)
data = response.object
elems = data.findall(fixxpath(xpath='accountAttributeSet/item',
namespace=NAMESPACE))
result = {'resource': {}}
for elem in elems:
name = findtext(element=elem, xpath='attributeName',
namespace=NAMESPACE)
value = findtext(element=elem,
xpath='attributeValueSet/item/attributeValue',
namespace=NAMESPACE)
result['resource'][name] = int(value)
return result
# Deprecated extension methods
def ex_list_keypairs(self):
"""
Lists all the keypair names and fingerprints.
:rtype: ``list`` of ``dict``
"""
warnings.warn('This method has been deprecated in favor of '
'list_key_pairs method')
key_pairs = self.list_key_pairs()
result = []
for key_pair in key_pairs:
item = {
'keyName': key_pair.name,
'keyFingerprint': key_pair.fingerprint,
}
result.append(item)
return result
def ex_describe_all_keypairs(self):
"""
Return names for all the available key pairs.
@note: This is a non-standard extension API, and only works for EC2.
:rtype: ``list`` of ``str``
"""
names = [key_pair.name for key_pair in self.list_key_pairs()]
return names
def ex_describe_keypairs(self, name):
"""
Here for backward compatibility.
"""
return self.ex_describe_keypair(name=name)
def ex_describe_keypair(self, name):
"""
Describes a keypair by name.
@note: This is a non-standard extension API, and only works for EC2.
:param name: The name of the keypair to describe.
:type name: ``str``
:rtype: ``dict``
"""
params = {
'Action': 'DescribeKeyPairs',
'KeyName.1': name
}
response = self.connection.request(self.path, params=params).object
key_name = findattr(element=response, xpath='keySet/item/keyName',
namespace=NAMESPACE)
fingerprint = findattr(element=response,
xpath='keySet/item/keyFingerprint',
namespace=NAMESPACE).strip()
return {
'keyName': key_name,
'keyFingerprint': fingerprint
}
def ex_create_keypair(self, name):
"""
Creates a new keypair
@note: This is a non-standard extension API, and only works for EC2.
:param name: The name of the keypair to Create. This must be
unique, otherwise an InvalidKeyPair.Duplicate exception is raised.
:type name: ``str``
:rtype: ``dict``
"""
warnings.warn('This method has been deprecated in favor of '
'create_key_pair method')
key_pair = self.create_key_pair(name=name)
result = {
'keyMaterial': key_pair.private_key,
'keyFingerprint': key_pair.fingerprint
}
return result
def ex_delete_keypair(self, keypair):
"""
Delete a key pair by name.
@note: This is a non-standard extension API, and only works with EC2.
:param keypair: The name of the keypair to delete.
:type keypair: ``str``
:rtype: ``bool``
"""
warnings.warn('This method has been deprecated in favor of '
'delete_key_pair method')
keypair = KeyPair(name=keypair, public_key=None, fingerprint=None,
driver=self)
return self.delete_key_pair(keypair)
def ex_import_keypair_from_string(self, name, key_material):
"""
imports a new public key where the public key is passed in as a string
@note: This is a non-standard extension API, and only works for EC2.
:param name: The name of the public key to import. This must be
unique, otherwise an InvalidKeyPair.Duplicate exception is raised.
:type name: ``str``
:param key_material: The contents of a public key file.
:type key_material: ``str``
:rtype: ``dict``
"""
warnings.warn('This method has been deprecated in favor of '
'import_key_pair_from_string method')
key_pair = self.import_key_pair_from_string(name=name,
key_material=key_material)
result = {
'keyName': key_pair.name,
'keyFingerprint': key_pair.fingerprint
}
return result
def ex_import_keypair(self, name, keyfile):
"""
imports a new public key where the public key is passed via a filename
@note: This is a non-standard extension API, and only works for EC2.
:param name: The name of the public key to import. This must be
unique, otherwise an InvalidKeyPair.Duplicate exception is raised.
:type name: ``str``
:param keyfile: The filename with path of the public key to import.
:type keyfile: ``str``
:rtype: ``dict``
"""
warnings.warn('This method has been deprecated in favor of '
'import_key_pair_from_file method')
key_pair = self.import_key_pair_from_file(name=name,
key_file_path=keyfile)
result = {
'keyName': key_pair.name,
'keyFingerprint': key_pair.fingerprint
}
return result
def ex_find_or_import_keypair_by_key_material(self, pubkey):
"""
Given a public key, look it up in the EC2 KeyPair database. If it
exists, return any information we have about it. Otherwise, create it.
Keys that are created are named based on their comment and fingerprint.
:rtype: ``dict``
"""
key_fingerprint = get_pubkey_ssh2_fingerprint(pubkey)
key_comment = get_pubkey_comment(pubkey, default='unnamed')
key_name = '%s-%s' % (key_comment, key_fingerprint)
key_pairs = self.list_key_pairs()
key_pairs = [key_pair for key_pair in key_pairs if
key_pair.fingerprint == key_fingerprint]
if len(key_pairs) >= 1:
key_pair = key_pairs[0]
result = {
'keyName': key_pair.name,
'keyFingerprint': key_pair.fingerprint
}
else:
result = self.ex_import_keypair_from_string(key_name, pubkey)
return result
def ex_list_internet_gateways(self, gateway_ids=None, filters=None):
"""
Describes available Internet gateways and whether or not they are
attached to a VPC. These are required for VPC nodes to communicate
over the Internet.
:param gateway_ids: Return only intenet gateways matching the
provided internet gateway IDs. If not
specified, a list of all the internet
gateways in the corresponding region is
returned.
:type gateway_ids: ``list``
:param filters: The filters so that the response includes
information for only certain gateways.
:type filters: ``dict``
:rtype: ``list`` of :class:`.VPCInternetGateway`
"""
params = {'Action': 'DescribeInternetGateways'}
if gateway_ids:
params.update(self._pathlist('InternetGatewayId', gateway_ids))
if filters:
params.update(self._build_filters(filters))
response = self.connection.request(self.path, params=params).object
return self._to_internet_gateways(response, 'internetGatewaySet/item')
def ex_create_internet_gateway(self, name=None):
"""
Delete a VPC Internet gateway
:rtype: ``bool``
"""
params = {'Action': 'CreateInternetGateway'}
resp = self.connection.request(self.path, params=params).object
element = resp.findall(fixxpath(xpath='internetGateway',
namespace=NAMESPACE))
gateway = self._to_internet_gateway(element[0], name)
if name and self.ex_create_tags(gateway, {'Name': name}):
gateway.extra['tags']['Name'] = name
return gateway
def ex_delete_internet_gateway(self, gateway):
"""
Delete a VPC Internet gateway
:param gateway: The gateway to delete
:type gateway: :class:`.VPCInternetGateway`
:rtype: ``bool``
"""
params = {'Action': 'DeleteInternetGateway',
'InternetGatewayId': gateway.id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_attach_internet_gateway(self, gateway, network):
"""
Attach an Internet gateway to a VPC
:param gateway: The gateway to attach
:type gateway: :class:`.VPCInternetGateway`
:param network: The VPC network to attach to
:type network: :class:`.EC2Network`
:rtype: ``bool``
"""
params = {'Action': 'AttachInternetGateway',
'InternetGatewayId': gateway.id,
'VpcId': network.id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_detach_internet_gateway(self, gateway, network):
"""
Detach an Internet gateway from a VPC
:param gateway: The gateway to detach
:type gateway: :class:`.VPCInternetGateway`
:param network: The VPC network to detach from
:type network: :class:`.EC2Network`
:rtype: ``bool``
"""
params = {'Action': 'DetachInternetGateway',
'InternetGatewayId': gateway.id,
'VpcId': network.id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_list_route_tables(self, route_table_ids=None, filters=None):
"""
Describes one or more of a VPC's route tables.
These are used to determine where network traffic is directed.
:param route_table_ids: Return only route tables matching the
provided route table IDs. If not specified,
a list of all the route tables in the
corresponding region is returned.
:type route_table_ids: ``list``
:param filters: The filters so that the response includes
information for only certain route tables.
:type filters: ``dict``
:rtype: ``list`` of :class:`.EC2RouteTable`
"""
params = {'Action': 'DescribeRouteTables'}
if route_table_ids:
params.update(self._pathlist('RouteTableId', route_table_ids))
if filters:
params.update(self._build_filters(filters))
response = self.connection.request(self.path, params=params)
return self._to_route_tables(response.object)
def ex_create_route_table(self, network, name=None):
"""
Create a route table within a VPC.
:param vpc_id: The VPC that the subnet should be created in.
:type vpc_id: :class:`.EC2Network`
:rtype: :class: `.EC2RouteTable`
"""
params = {'Action': 'CreateRouteTable',
'VpcId': network.id}
response = self.connection.request(self.path, params=params).object
element = response.findall(fixxpath(xpath='routeTable',
namespace=NAMESPACE))[0]
route_table = self._to_route_table(element, name=name)
if name and self.ex_create_tags(route_table, {'Name': name}):
route_table.extra['tags']['Name'] = name
return route_table
def ex_delete_route_table(self, route_table):
"""
Deletes a VPC route table.
:param route_table: The route table to delete.
:type route_table: :class:`.EC2RouteTable`
:rtype: ``bool``
"""
params = {'Action': 'DeleteRouteTable',
'RouteTableId': route_table.id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_associate_route_table(self, route_table, subnet):
"""
Associates a route table with a subnet within a VPC.
Note: A route table can be associated with multiple subnets.
:param route_table: The route table to associate.
:type route_table: :class:`.EC2RouteTable`
:param subnet: The subnet to associate with.
:type subnet: :class:`.EC2Subnet`
:return: Route table association ID.
:rtype: ``str``
"""
params = {'Action': 'AssociateRouteTable',
'RouteTableId': route_table.id,
'SubnetId': subnet.id}
result = self.connection.request(self.path, params=params).object
association_id = findtext(element=result,
xpath='associationId',
namespace=NAMESPACE)
return association_id
def ex_dissociate_route_table(self, subnet_association):
"""
Dissociates a subnet from a route table.
:param subnet_association: The subnet association object or
subnet association ID.
:type subnet_association: :class:`.EC2SubnetAssociation` or
``str``
:rtype: ``bool``
"""
if isinstance(subnet_association, EC2SubnetAssociation):
subnet_association_id = subnet_association.id
else:
subnet_association_id = subnet_association
params = {'Action': 'DisassociateRouteTable',
'AssociationId': subnet_association_id}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_replace_route_table_association(self, subnet_association,
route_table):
"""
Changes the route table associated with a given subnet in a VPC.
Note: This method can be used to change which table is the main route
table in the VPC (Specify the main route table's association ID
and the route table to be the new main route table).
:param subnet_association: The subnet association object or
subnet association ID.
:type subnet_association: :class:`.EC2SubnetAssociation` or
``str``
:param route_table: The new route table to associate.
:type route_table: :class:`.EC2RouteTable`
:return: New route table association ID.
:rtype: ``str``
"""
if isinstance(subnet_association, EC2SubnetAssociation):
subnet_association_id = subnet_association.id
else:
subnet_association_id = subnet_association
params = {'Action': 'ReplaceRouteTableAssociation',
'AssociationId': subnet_association_id,
'RouteTableId': route_table.id}
result = self.connection.request(self.path, params=params).object
new_association_id = findtext(element=result,
xpath='newAssociationId',
namespace=NAMESPACE)
return new_association_id
def ex_create_route(self, route_table, cidr,
internet_gateway=None, node=None,
network_interface=None, vpc_peering_connection=None):
"""
Creates a route entry in the route table.
:param route_table: The route table to create the route in.
:type route_table: :class:`.EC2RouteTable`
:param cidr: The CIDR block used for the destination match.
:type cidr: ``str``
:param internet_gateway: The internet gateway to route
traffic through.
:type internet_gateway: :class:`.VPCInternetGateway`
:param node: The NAT instance to route traffic through.
:type node: :class:`Node`
:param network_interface: The network interface of the node
to route traffic through.
:type network_interface: :class:`.EC2NetworkInterface`
:param vpc_peering_connection: The VPC peering connection.
:type vpc_peering_connection: :class:`.VPCPeeringConnection`
:rtype: ``bool``
Note: You must specify one of the following: internet_gateway,
node, network_interface, vpc_peering_connection.
"""
params = {'Action': 'CreateRoute',
'RouteTableId': route_table.id,
'DestinationCidrBlock': cidr}
if internet_gateway:
params['GatewayId'] = internet_gateway.id
if node:
params['InstanceId'] = node.id
if network_interface:
params['NetworkInterfaceId'] = network_interface.id
if vpc_peering_connection:
params['VpcPeeringConnectionId'] = vpc_peering_connection.id
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_delete_route(self, route_table, cidr):
"""
Deletes a route entry from the route table.
:param route_table: The route table to delete the route from.
:type route_table: :class:`.EC2RouteTable`
:param cidr: The CIDR block used for the destination match.
:type cidr: ``str``
:rtype: ``bool``
"""
params = {'Action': 'DeleteRoute',
'RouteTableId': route_table.id,
'DestinationCidrBlock': cidr}
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def ex_replace_route(self, route_table, cidr,
internet_gateway=None, node=None,
network_interface=None, vpc_peering_connection=None):
"""
Replaces an existing route entry within a route table in a VPC.
:param route_table: The route table to replace the route in.
:type route_table: :class:`.EC2RouteTable`
:param cidr: The CIDR block used for the destination match.
:type cidr: ``str``
:param internet_gateway: The new internet gateway to route
traffic through.
:type internet_gateway: :class:`.VPCInternetGateway`
:param node: The new NAT instance to route traffic through.
:type node: :class:`Node`
:param network_interface: The new network interface of the node
to route traffic through.
:type network_interface: :class:`.EC2NetworkInterface`
:param vpc_peering_connection: The new VPC peering connection.
:type vpc_peering_connection: :class:`.VPCPeeringConnection`
:rtype: ``bool``
Note: You must specify one of the following: internet_gateway,
node, network_interface, vpc_peering_connection.
"""
params = {'Action': 'ReplaceRoute',
'RouteTableId': route_table.id,
'DestinationCidrBlock': cidr}
if internet_gateway:
params['GatewayId'] = internet_gateway.id
if node:
params['InstanceId'] = node.id
if network_interface:
params['NetworkInterfaceId'] = network_interface.id
if vpc_peering_connection:
params['VpcPeeringConnectionId'] = vpc_peering_connection.id
res = self.connection.request(self.path, params=params).object
return self._get_boolean(res)
def _to_nodes(self, object, xpath):
return [self._to_node(el)
for el in object.findall(fixxpath(xpath=xpath,
namespace=NAMESPACE))]
def _to_node(self, element):
try:
state = self.NODE_STATE_MAP[findattr(element=element,
xpath="instanceState/name",
namespace=NAMESPACE)
]
except KeyError:
state = NodeState.UNKNOWN
instance_id = findtext(element=element, xpath='instanceId',
namespace=NAMESPACE)
public_ip = findtext(element=element, xpath='ipAddress',
namespace=NAMESPACE)
public_ips = [public_ip] if public_ip else []
private_ip = findtext(element=element, xpath='privateIpAddress',
namespace=NAMESPACE)
private_ips = [private_ip] if private_ip else []
product_codes = []
for p in findall(element=element,
xpath="productCodesSet/item/productCode",
namespace=NAMESPACE):
product_codes.append(p)
# Get our tags
tags = self._get_resource_tags(element)
name = tags.get('Name', instance_id)
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['node'])
# Add additional properties to our extra dictionary
extra['block_device_mapping'] = self._to_device_mappings(element)
extra['groups'] = self._get_security_groups(element)
extra['network_interfaces'] = self._to_interfaces(element)
extra['product_codes'] = product_codes
extra['tags'] = tags
return Node(id=instance_id, name=name, state=state,
public_ips=public_ips, private_ips=private_ips,
driver=self.connection.driver, extra=extra)
def _to_images(self, object):
return [self._to_image(el) for el in object.findall(
fixxpath(xpath='imagesSet/item', namespace=NAMESPACE))
]
def _to_image(self, element):
id = findtext(element=element, xpath='imageId', namespace=NAMESPACE)
name = findtext(element=element, xpath='name', namespace=NAMESPACE)
# Build block device mapping
block_device_mapping = self._to_device_mappings(element)
# Get our tags
tags = self._get_resource_tags(element)
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['image'])
# Add our tags and block device mapping
extra['tags'] = tags
extra['block_device_mapping'] = block_device_mapping
return NodeImage(id=id, name=name, driver=self, extra=extra)
def _to_volume(self, element, name=None):
"""
Parse the XML element and return a StorageVolume object.
:param name: An optional name for the volume. If not provided
then either tag with a key "Name" or volume ID
will be used (which ever is available first in that
order).
:type name: ``str``
:rtype: :class:`StorageVolume`
"""
volId = findtext(element=element, xpath='volumeId',
namespace=NAMESPACE)
size = findtext(element=element, xpath='size', namespace=NAMESPACE)
# Get our tags
tags = self._get_resource_tags(element)
# If name was not passed into the method then
# fall back then use the volume id
name = name if name else tags.get('Name', volId)
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['volume'])
extra['tags'] = tags
return StorageVolume(id=volId,
name=name,
size=int(size),
driver=self,
extra=extra)
def _to_snapshots(self, response):
return [self._to_snapshot(el) for el in response.findall(
fixxpath(xpath='snapshotSet/item', namespace=NAMESPACE))
]
def _to_snapshot(self, element, name=None):
snapId = findtext(element=element, xpath='snapshotId',
namespace=NAMESPACE)
size = findtext(element=element, xpath='volumeSize',
namespace=NAMESPACE)
created = parse_date(findtext(element=element, xpath='startTime',
namespace=NAMESPACE))
# Get our tags
tags = self._get_resource_tags(element)
# If name was not passed into the method then
# fall back then use the snapshot id
name = name if name else tags.get('Name', snapId)
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['snapshot'])
# Add tags and name to the extra dict
extra['tags'] = tags
extra['name'] = name
return VolumeSnapshot(snapId, size=int(size),
driver=self, extra=extra, created=created)
def _to_key_pairs(self, elems):
key_pairs = [self._to_key_pair(elem=elem) for elem in elems]
return key_pairs
def _to_key_pair(self, elem):
name = findtext(element=elem, xpath='keyName', namespace=NAMESPACE)
fingerprint = findtext(element=elem, xpath='keyFingerprint',
namespace=NAMESPACE).strip()
private_key = findtext(element=elem, xpath='keyMaterial',
namespace=NAMESPACE)
key_pair = KeyPair(name=name,
public_key=None,
fingerprint=fingerprint,
private_key=private_key,
driver=self)
return key_pair
def _to_security_groups(self, response):
return [self._to_security_group(el) for el in response.findall(
fixxpath(xpath='securityGroupInfo/item', namespace=NAMESPACE))
]
def _to_security_group(self, element):
# security group id
sg_id = findtext(element=element,
xpath='groupId',
namespace=NAMESPACE)
# security group name
name = findtext(element=element,
xpath='groupName',
namespace=NAMESPACE)
# Get our tags
tags = self._get_resource_tags(element)
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['security_group'])
# Add tags to the extra dict
extra['tags'] = tags
# Get ingress rules
ingress_rules = self._to_security_group_rules(
element, 'ipPermissions/item'
)
# Get egress rules
egress_rules = self._to_security_group_rules(
element, 'ipPermissionsEgress/item'
)
return EC2SecurityGroup(sg_id, name, ingress_rules,
egress_rules, extra=extra)
def _to_security_group_rules(self, element, xpath):
return [self._to_security_group_rule(el) for el in element.findall(
fixxpath(xpath=xpath, namespace=NAMESPACE))
]
def _to_security_group_rule(self, element):
"""
Parse the XML element and return a SecurityGroup object.
:rtype: :class:`EC2SecurityGroup`
"""
rule = {}
rule['protocol'] = findtext(element=element,
xpath='ipProtocol',
namespace=NAMESPACE)
rule['from_port'] = findtext(element=element,
xpath='fromPort',
namespace=NAMESPACE)
rule['to_port'] = findtext(element=element,
xpath='toPort',
namespace=NAMESPACE)
# get security groups
elements = element.findall(fixxpath(
xpath='groups/item',
namespace=NAMESPACE
))
rule['group_pairs'] = []
for element in elements:
item = {
'user_id': findtext(
element=element,
xpath='userId',
namespace=NAMESPACE),
'group_id': findtext(
element=element,
xpath='groupId',
namespace=NAMESPACE),
'group_name': findtext(
element=element,
xpath='groupName',
namespace=NAMESPACE)
}
rule['group_pairs'].append(item)
# get ip ranges
elements = element.findall(fixxpath(
xpath='ipRanges/item',
namespace=NAMESPACE
))
rule['cidr_ips'] = [
findtext(
element=element,
xpath='cidrIp',
namespace=NAMESPACE
) for element in elements]
return rule
def _to_networks(self, response):
return [self._to_network(el) for el in response.findall(
fixxpath(xpath='vpcSet/item', namespace=NAMESPACE))
]
def _to_network(self, element, name=None):
# Get the network id
vpc_id = findtext(element=element,
xpath='vpcId',
namespace=NAMESPACE)
# Get our tags
tags = self._get_resource_tags(element)
# Set our name if the Name key/value if available
# If we don't get anything back then use the vpc_id
name = name if name else tags.get('Name', vpc_id)
cidr_block = findtext(element=element,
xpath='cidrBlock',
namespace=NAMESPACE)
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['network'])
# Add tags to the extra dict
extra['tags'] = tags
return EC2Network(vpc_id, name, cidr_block, extra=extra)
def _to_addresses(self, response, only_associated):
"""
Builds a list of dictionaries containing elastic IP properties.
:param only_associated: If true, return only those addresses
that are associated with an instance.
If false, return all addresses.
:type only_associated: ``bool``
:rtype: ``list`` of :class:`ElasticIP`
"""
addresses = []
for el in response.findall(fixxpath(xpath='addressesSet/item',
namespace=NAMESPACE)):
addr = self._to_address(el, only_associated)
if addr is not None:
addresses.append(addr)
return addresses
def _to_address(self, element, only_associated):
instance_id = findtext(element=element, xpath='instanceId',
namespace=NAMESPACE)
public_ip = findtext(element=element,
xpath='publicIp',
namespace=NAMESPACE)
domain = findtext(element=element,
xpath='domain',
namespace=NAMESPACE)
# Build our extra dict
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['elastic_ip'])
# Return NoneType if only associated IPs are requested
if only_associated and not instance_id:
return None
return ElasticIP(public_ip, domain, instance_id, extra=extra)
def _to_placement_groups(self, response):
return [self._to_placement_group(el)
for el in response.findall(
fixxpath(xpath='placementGroupSet/item',
namespace=NAMESPACE))]
def _to_placement_group(self, element):
name = findtext(element=element,
xpath='groupName',
namespace=NAMESPACE)
state = findtext(element=element,
xpath='state',
namespace=NAMESPACE)
strategy = findtext(element=element,
xpath='strategy',
namespace=NAMESPACE)
return EC2PlacementGroup(name, state, strategy)
def _to_subnets(self, response):
return [self._to_subnet(el) for el in response.findall(
fixxpath(xpath='subnetSet/item', namespace=NAMESPACE))
]
def _to_subnet(self, element, name=None):
# Get the subnet ID
subnet_id = findtext(element=element,
xpath='subnetId',
namespace=NAMESPACE)
# Get our tags
tags = self._get_resource_tags(element)
# If we don't get anything back then use the subnet_id
name = name if name else tags.get('Name', subnet_id)
state = findtext(element=element,
xpath='state',
namespace=NAMESPACE)
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['subnet'])
# Also include our tags
extra['tags'] = tags
return EC2NetworkSubnet(subnet_id, name, state, extra=extra)
def _to_interfaces(self, response):
return [self._to_interface(el) for el in response.findall(
fixxpath(xpath='networkInterfaceSet/item', namespace=NAMESPACE))
]
def _to_interface(self, element, name=None):
"""
Parse the XML element and return an EC2NetworkInterface object.
:param name: An optional name for the interface. If not provided
then either tag with a key "Name" or the interface ID
will be used (whichever is available first in that
order).
:type name: ``str``
:rtype: :class: `EC2NetworkInterface`
"""
interface_id = findtext(element=element,
xpath='networkInterfaceId',
namespace=NAMESPACE)
state = findtext(element=element,
xpath='status',
namespace=NAMESPACE)
# Get tags
tags = self._get_resource_tags(element)
name = name if name else tags.get('Name', interface_id)
# Build security groups
groups = self._get_security_groups(element)
# Build private IPs
priv_ips = []
for item in findall(element=element,
xpath='privateIpAddressesSet/item',
namespace=NAMESPACE):
priv_ips.append({'private_ip': findtext(element=item,
xpath='privateIpAddress',
namespace=NAMESPACE),
'private_dns': findtext(element=item,
xpath='privateDnsName',
namespace=NAMESPACE),
'primary': findtext(element=item,
xpath='primary',
namespace=NAMESPACE)})
# Build our attachment dictionary which we will add into extra later
attributes_map = \
RESOURCE_EXTRA_ATTRIBUTES_MAP['network_interface_attachment']
attachment = self._get_extra_dict(element, attributes_map)
# Build our extra dict
attributes_map = RESOURCE_EXTRA_ATTRIBUTES_MAP['network_interface']
extra = self._get_extra_dict(element, attributes_map)
# Include our previously built items as well
extra['tags'] = tags
extra['attachment'] = attachment
extra['private_ips'] = priv_ips
extra['groups'] = groups
return EC2NetworkInterface(interface_id, name, state, extra=extra)
def _to_reserved_nodes(self, object, xpath):
return [self._to_reserved_node(el)
for el in object.findall(fixxpath(xpath=xpath,
namespace=NAMESPACE))]
def _to_reserved_node(self, element):
"""
Build an EC2ReservedNode object using the reserved instance properties.
Information on these properties can be found at http://goo.gl/ulXCC7.
"""
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['reserved_node'])
try:
size = [size for size in self.list_sizes() if
size.id == extra['instance_type']][0]
except IndexError:
size = None
return EC2ReservedNode(id=findtext(element=element,
xpath='reservedInstancesId',
namespace=NAMESPACE),
state=findattr(element=element,
xpath='state',
namespace=NAMESPACE),
driver=self,
size=size,
extra=extra)
def _to_device_mappings(self, object):
return [self._to_device_mapping(el) for el in object.findall(
fixxpath(xpath='blockDeviceMapping/item', namespace=NAMESPACE))
]
def _to_device_mapping(self, element):
"""
Parse the XML element and return a dictionary of device properties.
Additional information can be found at http://goo.gl/GjWYBf.
@note: EBS volumes do not have a virtual name. Only ephemeral
disks use this property.
:rtype: ``dict``
"""
mapping = {}
mapping['device_name'] = findattr(element=element,
xpath='deviceName',
namespace=NAMESPACE)
mapping['virtual_name'] = findattr(element=element,
xpath='virtualName',
namespace=NAMESPACE)
# If virtual name does not exist then this is an EBS volume.
# Build the EBS dictionary leveraging the _get_extra_dict method.
if mapping['virtual_name'] is None:
mapping['ebs'] = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['ebs_volume'])
return mapping
def _to_internet_gateways(self, object, xpath):
return [self._to_internet_gateway(el)
for el in object.findall(fixxpath(xpath=xpath,
namespace=NAMESPACE))]
def _to_internet_gateway(self, element, name=None):
id = findtext(element=element,
xpath='internetGatewayId',
namespace=NAMESPACE)
vpc_id = findtext(element=element,
xpath='attachmentSet/item/vpcId',
namespace=NAMESPACE)
state = findtext(element=element,
xpath='attachmentSet/item/state',
namespace=NAMESPACE)
# If there's no attachment state, let's
# set it to available
if not state:
state = 'available'
# Get our tags
tags = self._get_resource_tags(element)
# If name was not passed into the method then
# fall back then use the gateway id
name = name if name else tags.get('Name', id)
return VPCInternetGateway(id=id, name=name, vpc_id=vpc_id,
state=state, driver=self.connection.driver,
extra={'tags': tags})
def _to_route_tables(self, response):
return [self._to_route_table(el) for el in response.findall(
fixxpath(xpath='routeTableSet/item', namespace=NAMESPACE))
]
def _to_route_table(self, element, name=None):
# route table id
route_table_id = findtext(element=element,
xpath='routeTableId',
namespace=NAMESPACE)
# Get our tags
tags = self._get_resource_tags(element)
# Get our extra dictionary
extra = self._get_extra_dict(
element, RESOURCE_EXTRA_ATTRIBUTES_MAP['route_table'])
# Add tags to the extra dict
extra['tags'] = tags
# Get routes
routes = self._to_routes(element, 'routeSet/item')
# Get subnet associations
subnet_associations = self._to_subnet_associations(
element, 'associationSet/item')
# Get propagating routes virtual private gateways (VGW) IDs
propagating_gateway_ids = []
for el in element.findall(fixxpath(xpath='propagatingVgwSet/item',
namespace=NAMESPACE)):
propagating_gateway_ids.append(findtext(element=el,
xpath='gatewayId',
namespace=NAMESPACE))
name = name if name else tags.get('Name', id)
return EC2RouteTable(route_table_id, name, routes, subnet_associations,
propagating_gateway_ids, extra=extra)
def _to_routes(self, element, xpath):
return [self._to_route(el) for el in element.findall(
fixxpath(xpath=xpath, namespace=NAMESPACE))
]
def _to_route(self, element):
"""
Parse the XML element and return a route object
:rtype: :class: `EC2Route`
"""
destination_cidr = findtext(element=element,
xpath='destinationCidrBlock',
namespace=NAMESPACE)
gateway_id = findtext(element=element,
xpath='gatewayId',
namespace=NAMESPACE)
instance_id = findtext(element=element,
xpath='instanceId',
namespace=NAMESPACE)
owner_id = findtext(element=element,
xpath='instanceOwnerId',
namespace=NAMESPACE)
interface_id = findtext(element=element,
xpath='networkInterfaceId',
namespace=NAMESPACE)
state = findtext(element=element,
xpath='state',
namespace=NAMESPACE)
origin = findtext(element=element,
xpath='origin',
namespace=NAMESPACE)
vpc_peering_connection_id = findtext(element=element,
xpath='vpcPeeringConnectionId',
namespace=NAMESPACE)
return EC2Route(destination_cidr, gateway_id, instance_id, owner_id,
interface_id, state, origin, vpc_peering_connection_id)
def _to_subnet_associations(self, element, xpath):
return [self._to_subnet_association(el) for el in element.findall(
fixxpath(xpath=xpath, namespace=NAMESPACE))
]
def _to_subnet_association(self, element):
"""
Parse the XML element and return a route table association object
:rtype: :class: `EC2SubnetAssociation`
"""
association_id = findtext(element=element,
xpath='routeTableAssociationId',
namespace=NAMESPACE)
route_table_id = findtext(element=element,
xpath='routeTableId',
namespace=NAMESPACE)
subnet_id = findtext(element=element,
xpath='subnetId',
namespace=NAMESPACE)
main = findtext(element=element,
xpath='main',
namespace=NAMESPACE)
main = True if main else False
return EC2SubnetAssociation(association_id, route_table_id,
subnet_id, main)
def _pathlist(self, key, arr):
"""
Converts a key and an array of values into AWS query param format.
"""
params = {}
i = 0
for value in arr:
i += 1
params['%s.%s' % (key, i)] = value
return params
def _get_boolean(self, element):
tag = '{%s}%s' % (NAMESPACE, 'return')
return element.findtext(tag) == 'true'
def _get_terminate_boolean(self, element):
status = element.findtext(".//{%s}%s" % (NAMESPACE, 'name'))
return any([term_status == status
for term_status
in ('shutting-down', 'terminated')])
def _add_instance_filter(self, params, node):
"""
Add instance filter to the provided params dictionary.
"""
filters = {'instance-id': node.id}
params.update(self._build_filters(filters))
return params
def _get_state_boolean(self, element):
"""
Checks for the instances's state
"""
state = findall(element=element,
xpath='instancesSet/item/currentState/name',
namespace=NAMESPACE)[0].text
return state in ('stopping', 'pending', 'starting')
def _get_extra_dict(self, element, mapping):
"""
Extract attributes from the element based on rules provided in the
mapping dictionary.
:param element: Element to parse the values from.
:type element: xml.etree.ElementTree.Element.
:param mapping: Dictionary with the extra layout
:type node: :class:`Node`
:rtype: ``dict``
"""
extra = {}
for attribute, values in mapping.items():
transform_func = values['transform_func']
value = findattr(element=element,
xpath=values['xpath'],
namespace=NAMESPACE)
if value is not None:
extra[attribute] = transform_func(value)
else:
extra[attribute] = None
return extra
def _get_resource_tags(self, element):
"""
Parse tags from the provided element and return a dictionary with
key/value pairs.
:rtype: ``dict``
"""
tags = {}
# Get our tag set by parsing the element
tag_set = findall(element=element,
xpath='tagSet/item',
namespace=NAMESPACE)
for tag in tag_set:
key = findtext(element=tag,
xpath='key',
namespace=NAMESPACE)
value = findtext(element=tag,
xpath='value',
namespace=NAMESPACE)
tags[key] = value
return tags
def _get_block_device_mapping_params(self, block_device_mapping):
"""
Return a list of dictionaries with query parameters for
a valid block device mapping.
:param mapping: List of dictionaries with the drive layout
:type mapping: ``list`` or ``dict``
:return: Dictionary representation of the drive mapping
:rtype: ``dict``
"""
if not isinstance(block_device_mapping, (list, tuple)):
raise AttributeError(
'block_device_mapping not list or tuple')
params = {}
for idx, mapping in enumerate(block_device_mapping):
idx += 1 # We want 1-based indexes
if not isinstance(mapping, dict):
raise AttributeError(
'mapping %s in block_device_mapping '
'not a dict' % mapping)
for k, v in mapping.items():
if not isinstance(v, dict):
params['BlockDeviceMapping.%d.%s' % (idx, k)] = str(v)
else:
for key, value in v.items():
params['BlockDeviceMapping.%d.%s.%s'
% (idx, k, key)] = str(value)
return params
def _get_common_security_group_params(self, group_id, protocol,
from_port, to_port, cidr_ips,
group_pairs):
"""
Return a dictionary with common query parameters which are used when
operating on security groups.
:rtype: ``dict``
"""
params = {'GroupId': group_id,
'IpPermissions.1.IpProtocol': protocol,
'IpPermissions.1.FromPort': from_port,
'IpPermissions.1.ToPort': to_port}
if cidr_ips is not None:
ip_ranges = {}
for index, cidr_ip in enumerate(cidr_ips):
index += 1
ip_ranges['IpPermissions.1.IpRanges.%s.CidrIp'
% (index)] = cidr_ip
params.update(ip_ranges)
if group_pairs is not None:
user_groups = {}
for index, group_pair in enumerate(group_pairs):
index += 1
if 'group_id' in group_pair.keys():
user_groups['IpPermissions.1.Groups.%s.GroupId'
% (index)] = group_pair['group_id']
if 'group_name' in group_pair.keys():
user_groups['IpPermissions.1.Groups.%s.GroupName'
% (index)] = group_pair['group_name']
if 'user_id' in group_pair.keys():
user_groups['IpPermissions.1.Groups.%s.UserId'
% (index)] = group_pair['user_id']
params.update(user_groups)
return params
def _get_security_groups(self, element):
"""
Parse security groups from the provided element and return a
list of security groups with the id ane name key/value pairs.
:rtype: ``list`` of ``dict``
"""
groups = []
for item in findall(element=element,
xpath='groupSet/item',
namespace=NAMESPACE):
groups.append({
'group_id': findtext(element=item,
xpath='groupId',
namespace=NAMESPACE),
'group_name': findtext(element=item,
xpath='groupName',
namespace=NAMESPACE)
})
return groups
def _build_filters(self, filters):
"""
Return a dictionary with filter query parameters which are used when
listing networks, security groups, etc.
:param filters: Dict of filter names and filter values
:type filters: ``dict``
:rtype: ``dict``
"""
filter_entries = {}
for filter_idx, filter_data in enumerate(filters.items()):
filter_idx += 1 # We want 1-based indexes
filter_name, filter_values = filter_data
filter_key = 'Filter.%s.Name' % (filter_idx)
filter_entries[filter_key] = filter_name
if isinstance(filter_values, list):
for value_idx, value in enumerate(filter_values):
value_idx += 1 # We want 1-based indexes
value_key = 'Filter.%s.Value.%s' % (filter_idx,
value_idx)
filter_entries[value_key] = value
else:
value_key = 'Filter.%s.Value.1' % (filter_idx)
filter_entries[value_key] = filter_values
return filter_entries
class EC2NodeDriver(BaseEC2NodeDriver):
"""
Amazon EC2 node driver.
"""
connectionCls = EC2Connection
type = Provider.EC2
name = 'Amazon EC2'
website = 'http://aws.amazon.com/ec2/'
path = '/'
NODE_STATE_MAP = {
'pending': NodeState.PENDING,
'running': NodeState.RUNNING,
'shutting-down': NodeState.UNKNOWN,
'terminated': NodeState.TERMINATED,
'stopped': NodeState.STOPPED
}
def __init__(self, key, secret=None, secure=True, host=None, port=None,
region='us-east-1', **kwargs):
if hasattr(self, '_region'):
region = self._region
if region not in VALID_EC2_REGIONS:
raise ValueError('Invalid region: %s' % (region))
details = REGION_DETAILS[region]
self.region_name = region
self.api_name = details['api_name']
self.country = details['country']
host = host or details['endpoint']
super(EC2NodeDriver, self).__init__(key=key, secret=secret,
secure=secure, host=host,
port=port, **kwargs)
class IdempotentParamError(LibcloudError):
"""
Request used the same client token as a previous,
but non-identical request.
"""
def __str__(self):
return repr(self.value)
class EC2EUNodeDriver(EC2NodeDriver):
"""
Driver class for EC2 in the Western Europe Region.
"""
name = 'Amazon EC2 (eu-west-1)'
_region = 'eu-west-1'
class EC2USWestNodeDriver(EC2NodeDriver):
"""
Driver class for EC2 in the Western US Region
"""
name = 'Amazon EC2 (us-west-1)'
_region = 'us-west-1'
class EC2USWestOregonNodeDriver(EC2NodeDriver):
"""
Driver class for EC2 in the US West Oregon region.
"""
name = 'Amazon EC2 (us-west-2)'
_region = 'us-west-2'
class EC2APSENodeDriver(EC2NodeDriver):
"""
Driver class for EC2 in the Southeast Asia Pacific Region.
"""
name = 'Amazon EC2 (ap-southeast-1)'
_region = 'ap-southeast-1'
class EC2APNENodeDriver(EC2NodeDriver):
"""
Driver class for EC2 in the Northeast Asia Pacific Region.
"""
name = 'Amazon EC2 (ap-northeast-1)'
_region = 'ap-northeast-1'
class EC2SAEastNodeDriver(EC2NodeDriver):
"""
Driver class for EC2 in the South America (Sao Paulo) Region.
"""
name = 'Amazon EC2 (sa-east-1)'
_region = 'sa-east-1'
class EC2APSESydneyNodeDriver(EC2NodeDriver):
"""
Driver class for EC2 in the Southeast Asia Pacific (Sydney) Region.
"""
name = 'Amazon EC2 (ap-southeast-2)'
_region = 'ap-southeast-2'
class EucConnection(EC2Connection):
"""
Connection class for Eucalyptus
"""
host = None
class EucNodeDriver(BaseEC2NodeDriver):
"""
Driver class for Eucalyptus
"""
name = 'Eucalyptus'
website = 'http://www.eucalyptus.com/'
api_name = 'ec2_us_east'
region_name = 'us-east-1'
connectionCls = EucConnection
def __init__(self, key, secret=None, secure=True, host=None,
path=None, port=None, api_version=DEFAULT_EUCA_API_VERSION):
"""
@inherits: :class:`EC2NodeDriver.__init__`
:param path: The host where the API can be reached.
:type path: ``str``
:param api_version: The API version to extend support for
Eucalyptus proprietary API calls
:type api_version: ``str``
"""
super(EucNodeDriver, self).__init__(key, secret, secure, host, port)
if path is None:
path = '/services/Eucalyptus'
self.path = path
self.EUCA_NAMESPACE = 'http://msgs.eucalyptus.com/%s' % (api_version)
def list_locations(self):
raise NotImplementedError(
'list_locations not implemented for this driver')
def _to_sizes(self, response):
return [self._to_size(el) for el in response.findall(
fixxpath(xpath='instanceTypeDetails/item',
namespace=self.EUCA_NAMESPACE))]
def _to_size(self, el):
name = findtext(element=el,
xpath='name',
namespace=self.EUCA_NAMESPACE)
cpu = findtext(element=el,
xpath='cpu',
namespace=self.EUCA_NAMESPACE)
disk = findtext(element=el,
xpath='disk',
namespace=self.EUCA_NAMESPACE)
memory = findtext(element=el,
xpath='memory',
namespace=self.EUCA_NAMESPACE)
return NodeSize(id=name,
name=name,
ram=int(memory),
disk=int(disk),
bandwidth=None,
price=None,
driver=EucNodeDriver,
extra={
'cpu': int(cpu)
})
def list_sizes(self):
"""
List available instance flavors/sizes
:rtype: ``list`` of :class:`NodeSize`
"""
params = {'Action': 'DescribeInstanceTypes'}
response = self.connection.request(self.path, params=params).object
return self._to_sizes(response)
def _add_instance_filter(self, params, node):
"""
Eucalyptus driver doesn't support filtering on instance id so this is a
no-op.
"""
pass
class NimbusConnection(EC2Connection):
"""
Connection class for Nimbus
"""
host = None
class NimbusNodeDriver(BaseEC2NodeDriver):
"""
Driver class for Nimbus
"""
type = Provider.NIMBUS
name = 'Nimbus'
website = 'http://www.nimbusproject.org/'
country = 'Private'
api_name = 'nimbus'
region_name = 'nimbus'
friendly_name = 'Nimbus Private Cloud'
connectionCls = NimbusConnection
def ex_describe_addresses(self, nodes):
"""
Nimbus doesn't support elastic IPs, so this is a pass-through.
@inherits: :class:`EC2NodeDriver.ex_describe_addresses`
"""
nodes_elastic_ip_mappings = {}
for node in nodes:
# empty list per node
nodes_elastic_ip_mappings[node.id] = []
return nodes_elastic_ip_mappings
def ex_create_tags(self, resource, tags):
"""
Nimbus doesn't support creating tags, so this is a pass-through.
@inherits: :class:`EC2NodeDriver.ex_create_tags`
"""
pass
class OutscaleConnection(EC2Connection):
"""
Connection class for Outscale
"""
host = None
class OutscaleNodeDriver(BaseEC2NodeDriver):
"""
Base Outscale FCU node driver.
Outscale per provider driver classes inherit from it.
"""
connectionCls = OutscaleConnection
name = 'Outscale'
website = 'http://www.outscale.com'
path = '/'
NODE_STATE_MAP = {
'pending': NodeState.PENDING,
'running': NodeState.RUNNING,
'shutting-down': NodeState.UNKNOWN,
'terminated': NodeState.TERMINATED,
'stopped': NodeState.STOPPED
}
def __init__(self, key, secret=None, secure=True, host=None, port=None,
region='us-east-1', region_details=None, **kwargs):
if hasattr(self, '_region'):
region = self._region
if region_details is None:
raise ValueError('Invalid region_details argument')
if region not in region_details.keys():
raise ValueError('Invalid region: %s' % (region))
self.region_name = region
self.region_details = region_details
details = self.region_details[region]
self.api_name = details['api_name']
self.country = details['country']
self.connectionCls.host = details['endpoint']
self._not_implemented_msg =\
'This method is not supported in the Outscale driver'
super(BaseEC2NodeDriver, self).__init__(key=key, secret=secret,
secure=secure, host=host,
port=port, **kwargs)
def create_node(self, **kwargs):
"""
Create a new Outscale node. The ex_iamprofile keyword is not supported.
@inherits: :class:`BaseEC2NodeDriver.create_node`
:keyword ex_keyname: The name of the key pair
:type ex_keyname: ``str``
:keyword ex_userdata: User data
:type ex_userdata: ``str``
:keyword ex_security_groups: A list of names of security groups to
assign to the node.
:type ex_security_groups: ``list``
:keyword ex_metadata: Key/Value metadata to associate with a node
:type ex_metadata: ``dict``
:keyword ex_mincount: Minimum number of instances to launch
:type ex_mincount: ``int``
:keyword ex_maxcount: Maximum number of instances to launch
:type ex_maxcount: ``int``
:keyword ex_clienttoken: Unique identifier to ensure idempotency
:type ex_clienttoken: ``str``
:keyword ex_blockdevicemappings: ``list`` of ``dict`` block device
mappings.
:type ex_blockdevicemappings: ``list`` of ``dict``
:keyword ex_ebs_optimized: EBS-Optimized if True
:type ex_ebs_optimized: ``bool``
"""
if 'ex_iamprofile' in kwargs:
raise NotImplementedError("ex_iamprofile not implemented")
return super(OutscaleNodeDriver, self).create_node(**kwargs)
def ex_create_network(self, cidr_block, name=None):
"""
Create a network/VPC. Outscale does not support instance_tenancy.
:param cidr_block: The CIDR block assigned to the network
:type cidr_block: ``str``
:param name: An optional name for the network
:type name: ``str``
:return: Dictionary of network properties
:rtype: ``dict``
"""
return super(OutscaleNodeDriver, self).ex_create_network(cidr_block,
name=name)
def ex_modify_instance_attribute(self, node, disable_api_termination=None,
ebs_optimized=None, group_id=None,
source_dest_check=None, user_data=None,
instance_type=None):
"""
Modify node attributes.
Ouscale support the following attributes:
'DisableApiTermination.Value', 'EbsOptimized', 'GroupId.n',
'SourceDestCheck.Value', 'UserData.Value',
'InstanceType.Value'
:param node: Node instance
:type node: :class:`Node`
:param attributes: Dictionary with node attributes
:type attributes: ``dict``
:return: True on success, False otherwise.
:rtype: ``bool``
"""
attributes = {}
if disable_api_termination is not None:
attributes['DisableApiTermination.Value'] = disable_api_termination
if ebs_optimized is not None:
attributes['EbsOptimized'] = ebs_optimized
if group_id is not None:
attributes['GroupId.n'] = group_id
if source_dest_check is not None:
attributes['SourceDestCheck.Value'] = source_dest_check
if user_data is not None:
attributes['UserData.Value'] = user_data
if instance_type is not None:
attributes['InstanceType.Value'] = instance_type
return super(OutscaleNodeDriver, self).ex_modify_instance_attribute(
node, attributes)
def ex_register_image(self, name, description=None, architecture=None,
root_device_name=None, block_device_mapping=None):
"""
Registers a Machine Image based off of an EBS-backed instance.
Can also be used to create images from snapshots.
Outscale does not support image_location, kernel_id and ramdisk_id.
:param name: The name for the AMI being registered
:type name: ``str``
:param description: The description of the AMI (optional)
:type description: ``str``
:param architecture: The architecture of the AMI (i386/x86_64)
(optional)
:type architecture: ``str``
:param root_device_name: The device name for the root device
Required if registering an EBS-backed AMI
:type root_device_name: ``str``
:param block_device_mapping: A dictionary of the disk layout
(optional)
:type block_device_mapping: ``dict``
:rtype: :class:`NodeImage`
"""
return super(OutscaleNodeDriver, self).ex_register_image(
name, description=description, architecture=architecture,
root_device_name=root_device_name,
block_device_mapping=block_device_mapping)
def ex_copy_image(self, source_region, image, name=None, description=None):
"""
Outscale does not support copying images.
@inherits: :class:`EC2NodeDriver.ex_copy_image`
"""
raise NotImplementedError(self._not_implemented_msg)
def ex_get_limits(self):
"""
Outscale does not support getting limits.
@inherits: :class:`EC2NodeDriver.ex_get_limits`
"""
raise NotImplementedError(self._not_implemented_msg)
def ex_create_network_interface(self, subnet, name=None,
description=None,
private_ip_address=None):
"""
Outscale does not support creating a network interface within a VPC.
@inherits: :class:`EC2NodeDriver.ex_create_network_interface`
"""
raise NotImplementedError(self._not_implemented_msg)
def ex_delete_network_interface(self, network_interface):
"""
Outscale does not support deleting a network interface within a VPC.
@inherits: :class:`EC2NodeDriver.ex_delete_network_interface`
"""
raise NotImplementedError(self._not_implemented_msg)
def ex_attach_network_interface_to_node(self, network_interface,
node, device_index):
"""
Outscale does not support attaching a network interface.
@inherits: :class:`EC2NodeDriver.ex_attach_network_interface_to_node`
"""
raise NotImplementedError(self._not_implemented_msg)
def ex_detach_network_interface(self, attachment_id, force=False):
"""
Outscale does not support detaching a network interface
@inherits: :class:`EC2NodeDriver.ex_detach_network_interface`
"""
raise NotImplementedError(self._not_implemented_msg)
def list_sizes(self, location=None):
"""
List available instance flavors/sizes
This override the EC2 default method in order to use Outscale infos.
:rtype: ``list`` of :class:`NodeSize`
"""
available_types =\
self.region_details[self.region_name]['instance_types']
sizes = []
for instance_type in available_types:
attributes = OUTSCALE_INSTANCE_TYPES[instance_type]
attributes = copy.deepcopy(attributes)
price = self._get_size_price(size_id=instance_type)
attributes.update({'price': price})
sizes.append(NodeSize(driver=self, **attributes))
return sizes
class OutscaleSASNodeDriver(OutscaleNodeDriver):
"""
Outscale SAS node driver
"""
name = 'Outscale SAS'
type = Provider.OUTSCALE_SAS
def __init__(self, key, secret=None, secure=True, host=None, port=None,
region='us-east-1', region_details=None, **kwargs):
super(OutscaleSASNodeDriver, self).__init__(
key=key, secret=secret, secure=secure, host=host, port=port,
region=region, region_details=OUTSCALE_SAS_REGION_DETAILS,
**kwargs)
class OutscaleINCNodeDriver(OutscaleNodeDriver):
"""
Outscale INC node driver
"""
name = 'Outscale INC'
type = Provider.OUTSCALE_INC
def __init__(self, key, secret=None, secure=True, host=None, port=None,
region='us-east-1', region_details=None, **kwargs):
super(OutscaleINCNodeDriver, self).__init__(
key=key, secret=secret, secure=secure, host=host, port=port,
region=region, region_details=OUTSCALE_INC_REGION_DETAILS,
**kwargs)
| stewnorriss/LibCloud | libcloud/compute/drivers/ec2.py | Python | apache-2.0 | 194,697 |
# coding: utf-8
import wolframalpha
from .exceptions import APIError
from .clients import turingclient, baiduclient
from .utils import get_mac_address, get_audio_info
class Wolfram(object):
"""A client for request Wolfram.
Attributes:
key: The key string got from https://www.wolframalpha.com.
"""
def __init__(self, key):
self.key = key
def ask_wolfram(self, question):
client = wolframalpha.Client(self.key)
res = client.query(question)
if len(res.pods) > 0:
pod = res.pods[1]
if pod.text:
texts = pod.text
else:
raise APIError('Wolfram API failed.')
# to skip ascii character in case of error
texts = texts.encode('ascii', 'ignore')
return texts
else:
raise APIError('Wolfram API failed.')
class TuringRobot(object):
"""A client for request Turing Robot.
Attributes:
key: The key string got from http://www.tuling123.com.
"""
def __init__(self, key):
self.key = key
def ask_turing(self, question):
params = {
'key': self.key,
'info': question
}
ret = turingclient.query_turing(params)
code = ret.get('code')
if code == 100000:
return ret['text'].encode('utf-8')
else:
raise APIError('Cannot handle this ret code: %s' % code)
class BaiduVoice(object):
"""A client for request Turing Robot.
Attributes:
token: The token string got from https://openapi.baidu.com/oauth/2.0/token.
cuid: Unique identification of user, default is MAC address.
"""
def __init__(self, token):
self.token = token
self.cuid = get_mac_address()
def asr(self, file_, format_='wav',
cuid=None, ptc=1, lan='zh'):
"""Constructs and sends an Automatic Speech Recognition request.
Args:
file_: the open file with methods write(), close(), tell(), seek()
set through the __init__() method.
format_:(optional) the audio format, default is 'wav'
cuid:(optional) Unique identification of user, default is MAC address.
ptc:(optional) nbest results, the number of results.
lan:(optional) language, default is 'zh'.
Returns:
A list of recognition results.
Raises:
ValueError
RecognitionError
VerifyError
APIError
QuotaError
"""
if format_ != 'wav':
raise ValueError('Unsupported audio format')
params = {
'format': format_,
'token': self.token,
'cuid': cuid or self.cuid,
'ptc': ptc,
'lan': lan
}
try:
audio_info = get_audio_info(file_)
except Exception, e:
raise e
params['len'], params['rate'] = audio_info['nframes'], audio_info['framerate']
return baiduclient.asr(audio_info['content'], params)
def tts(self, tex, lan='zh', ctp=1,
cuid=None, spd=5, pit=5, vol=5, per=0):
"""Constructs and sends an Text To Speech request.
Args:
tex: The text for conversion.
lan:(optional) language, default is 'zh'.
ctp:(optional) Client type, default is 1.
cuid:(optional) Unique identification of user, default is MAC address.
spd:(optional) speed, range 0-9, default is 5.
pit:(optional) pitch, range 0-9, default is 5.
vol:(optional) volume, range 0-9, default is 5.
per:(optional) voice of male or female, default is 0 for female voice.
Returns:
A binary string of MP3 format audio.
Raises:
ValueError
VerifyError
APIError
"""
params = {
'tex': tex,
'lan': lan,
'tok': self.token,
'ctp': ctp,
'cuid': cuid or self.cuid,
'spd': spd,
'pit': pit,
'vol': vol,
'per': per
}
return baiduclient.tts(params)
@staticmethod
def get_baidu_token(api_key, secret_key):
"""Get Baidu Voice Service token by api key and secret.
Functions of other args of response are not confirmed, so the whole
response dict will be returned, you can access the token by ret['access_token'].
"""
params = {
'grant_type': 'client_credentials',
'client_id': api_key,
'client_secret': secret_key
}
return baiduclient.get_token(params)
| namco1992/voicetools | voicetools/api.py | Python | apache-2.0 | 4,729 |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Classes implementing a multi-worker ps DistributionStrategy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
from tensorflow.python.distribute import cross_device_ops as cross_device_ops_lib
from tensorflow.python.distribute import device_util
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.distribute import input_lib
from tensorflow.python.distribute import mirrored_strategy
from tensorflow.python.distribute import multi_worker_util
from tensorflow.python.distribute import numpy_dataset
from tensorflow.python.distribute import values
from tensorflow.python.distribute.cluster_resolver import SimpleClusterResolver
from tensorflow.python.distribute.cluster_resolver import TFConfigClusterResolver
from tensorflow.python.eager import context
from tensorflow.python.framework import device as tf_device
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training import device_setter
from tensorflow.python.util import nest
from tensorflow.python.util.tf_export import tf_export
_LOCAL_CPU = "/device:CPU:0"
_LOCAL_GPU_0 = "/device:GPU:0"
# TODO(yuefengz): maybe cache variables on local CPU.
@tf_export("distribute.experimental.ParameterServerStrategy")
class ParameterServerStrategy(distribute_lib.DistributionStrategy):
"""A parameter server DistributionStrategy.
This strategy class works for both local training and between-graph replicated
training for multiple workers. It uses `TFConfigClusterResolver` to detect
configurations for multi-worker training. In multi-worker training mode, i.e.
`TFConfigClusterResolver` has detected 'TF_CONFIG' environment variable and
'TF_CONFIG' has a cluster spec, variables and updates to those variables are
assigned to parameter servers and other operations are assigned to workers.
In local training mode, variables are assigned to local CPU or the only GPU.
When each worker has more than one GPU, operations will be replicated on these
GPUs. In both cases, operations are replicated but variables are not and these
workers share a common view for which parameter server a variable is assigned
to.
This class assumes between-graph replication will be used and works on a graph
for a particular worker. Note that each graph and worker is independent.
This means that while each worker will synchronously compute a single gradient
update across all GPUs, updates between workers proceed asynchronously.
Operations that occur only on the first replica (such as incrementing the
global step), will occur on the first replica *of every worker*.
It is expected to call `call_for_each_replica(fn, ...)` for any
operations which potentially can be replicated across replicas (i.e. multiple
GPUs) even if there is only CPU or one GPU. When defining the `fn`, extra
caution needs to be taken:
1) It is generally not recommended to open a device scope under the strategy's
scope. A device scope (i.e. calling `tf.device`) will be merged with or
override the device for operations but will not change the device for
variables.
2) It is also not recommended to open a colocation scope (i.e. calling
`tf.colocate_with`) under the strategy's scope. For colocating variables, use
`strategy.extended.colocate_vars_with` instead. Colocation of ops will
possibly create conflicts of device assignment.
"""
def __init__(self):
"""Initializes this strategy with default TFConfigClusterResolver."""
super(ParameterServerStrategy, self).__init__(
ParameterServerStrategyExtended(self))
class ParameterServerStrategyExtended(
distribute_lib.DistributionStrategyExtended):
"""Implementation of ParameterServerStrategy."""
def __init__(self,
container_strategy,
cluster_resolver=TFConfigClusterResolver()):
super(ParameterServerStrategyExtended, self).__init__(container_strategy)
self._initialize_strategy(cluster_resolver)
# We typically don't need to do all-reduce in this strategy.
self._cross_device_ops = (
cross_device_ops_lib.ReductionToOneDevice(reduce_to_device=_LOCAL_CPU))
def _initialize_strategy(self, cluster_resolver):
if cluster_resolver.cluster_spec().as_dict():
self._initialize_multi_worker(cluster_resolver)
else:
self._initialize_local(cluster_resolver)
def _initialize_multi_worker(self, cluster_resolver):
"""Initialize devices for multiple workers.
It creates variable devices and compute devices. Variables and operations
will be assigned to them respectively. We have one compute device per
replica. The variable device is a device function or device string. The
default variable device assigns variables to parameter servers in a
round-robin fashion.
Args:
cluster_resolver: a descendant of `ClusterResolver` object.
Raises:
ValueError: if the cluster doesn't have ps jobs.
"""
# TODO(b/126786766): TFConfigClusterResolver returns wrong number of GPUs in
# some cases.
if isinstance(cluster_resolver, TFConfigClusterResolver):
num_gpus = context.num_gpus()
else:
num_gpus = cluster_resolver.num_accelerators().get("GPU", 0)
# Save the num_gpus_per_worker for configure method.
self._num_gpus_per_worker = num_gpus
cluster_spec = cluster_resolver.cluster_spec()
task_type = cluster_resolver.task_type
task_id = cluster_resolver.task_id
if not task_type or task_id is None:
raise ValueError("When `cluster_spec` is given, you must also specify "
"`task_type` and `task_id`")
cluster_spec = multi_worker_util.normalize_cluster_spec(cluster_spec)
assert cluster_spec.as_dict()
worker_device = "/job:%s/task:%d" % (task_type, task_id)
self._input_host_device = numpy_dataset.SingleDevice(worker_device)
# Define compute devices which is a list of device strings and one for each
# replica. When there are GPUs, replicate operations on these GPUs.
# Otherwise, place operations on CPU.
if num_gpus > 0:
compute_devices = tuple(
"%s/device:GPU:%d" % (worker_device, i) for i in range(num_gpus))
else:
compute_devices = (worker_device,)
self._device_map = values.ReplicaDeviceMap(compute_devices)
self._input_workers = input_lib.InputWorkers(
self._device_map, [(worker_device, compute_devices)])
# In distributed mode, place variables on ps jobs in a round-robin fashion.
# Note that devices returned from `replica_device_setter` are not
# canonical and therefore we don't canonicalize all variable devices to
# make them consistent.
# TODO(yuefengz): support passing a strategy object to control variable
# assignment.
# TODO(yuefengz): merge the logic of replica_device_setter into this
# class.
num_ps_replicas = len(cluster_spec.as_dict().get("ps", []))
if num_ps_replicas == 0:
raise ValueError("The cluster spec needs to have `ps` jobs.")
self._variable_device = device_setter.replica_device_setter(
ps_tasks=num_ps_replicas,
worker_device=worker_device,
merge_devices=True,
cluster=cluster_spec)
# The `_parameter_devices` is needed for the `parameter_devices` property
# and is a list of all variable devices. Here parameter devices are all
# tasks of the "ps" job.
self._parameter_devices = tuple(map("/job:ps/task:{}".format,
range(num_ps_replicas)))
# Add a default device so that ops without specified devices will not end up
# on other workers.
self._default_device = worker_device
self._is_chief = multi_worker_util.is_chief(cluster_spec, task_type,
task_id)
self._cluster_spec = cluster_spec
self._task_type = task_type
self._task_id = task_id
logging.info(
"Multi-worker ParameterServerStrategy with "
"cluster_spec = %r, task_type = %r, task_id = %r, "
"num_ps_replicas = %r, is_chief = %r, device_map = %r, "
"variable_device = %r", cluster_spec.as_dict(), task_type, task_id,
num_ps_replicas, self._is_chief, self._device_map,
self._variable_device)
def _initialize_local(self, cluster_resolver):
"""Initialize internal devices for local training."""
worker_device = device_util.canonicalize("/device:CPU:0")
self._input_host_device = numpy_dataset.SingleDevice(worker_device)
# TODO(b/126786766): TFConfigClusterResolver returns wrong number of GPUs in
# some cases.
if isinstance(cluster_resolver, TFConfigClusterResolver):
num_gpus = context.num_gpus()
else:
num_gpus = cluster_resolver.num_accelerators().get("GPU", 0)
# Save the num_gpus_per_worker for configure method.
self._num_gpus_per_worker = num_gpus
# Define compute devices which is a list of device strings and one for each
# replica. When there are GPUs, replicate operations on these GPUs.
# Otherwise, place operations on CPU.
if num_gpus > 0:
compute_devices = tuple(map("/device:GPU:{}".format, range(num_gpus)))
else:
compute_devices = (_LOCAL_CPU,)
self._device_map = values.ReplicaDeviceMap(compute_devices)
self._input_workers = input_lib.InputWorkers(
self._device_map, [(worker_device, compute_devices)])
# If there is only one GPU, put everything on that GPU. Otherwise, place
# variables on CPU.
if num_gpus == 1:
assert len(compute_devices) == 1
self._variable_device = _LOCAL_GPU_0
self._parameter_devices = (_LOCAL_GPU_0,)
else:
self._variable_device = _LOCAL_CPU
self._parameter_devices = (_LOCAL_CPU,)
self._is_chief = True
self._cluster_spec = None
self._task_type = None
self._task_id = None
logging.info(
"ParameterServerStrategy with compute_devices = %r, "
"variable_device = %r", compute_devices, self._variable_device)
def _validate_colocate_with_variable(self, colocate_with_variable):
values.validate_colocate(colocate_with_variable, self)
def _make_dataset_iterator(self, dataset):
return input_lib.DatasetIterator(dataset, self._input_workers,
self._num_replicas_in_sync)
def _make_input_fn_iterator(
self,
input_fn,
replication_mode=distribute_lib.InputReplicationMode.PER_WORKER):
"""Distributes the dataset to each local GPU."""
if self._cluster_spec:
input_pipeline_id = multi_worker_util.id_in_cluster(
self._cluster_spec, self._task_type, self._task_id)
num_input_pipelines = multi_worker_util.worker_count(
self._cluster_spec, self._task_type)
else:
input_pipeline_id = 0
num_input_pipelines = 1
input_context = distribute_lib.InputContext(
num_input_pipelines=num_input_pipelines,
input_pipeline_id=input_pipeline_id,
num_replicas_in_sync=self._num_replicas_in_sync)
return input_lib.InputFunctionIterator(input_fn, self._input_workers,
[input_context])
def _experimental_make_numpy_dataset(self, numpy_input, session):
return numpy_dataset.one_host_numpy_dataset(
numpy_input, self._input_host_device, session)
def _broadcast_to(self, tensor, destinations):
# This is both a fast path for Python constants, and a way to delay
# converting Python values to a tensor until we know what type it
# should be converted to. Otherwise we have trouble with:
# global_step.assign_add(1)
# since the `1` gets broadcast as an int32 but global_step is int64.
if isinstance(tensor, (float, int)):
return tensor
if not cross_device_ops_lib.check_destinations(destinations):
# TODO(josh11b): Use current logical device instead of 0 here.
destinations = values.LogicalDeviceSpec(
device_map=self._device_map, logical_device=0)
return self._cross_device_ops.broadcast(tensor, destinations)
def _allow_variable_partition(self):
return not context.executing_eagerly()
# TODO(yuefengz): not all ops in device_setter.STANDARD_PS_OPS will go through
# this creator, such as "MutableHashTable".
def _create_variable(self, next_creator, *args, **kwargs):
if self._num_replicas_in_sync > 1:
aggregation = kwargs.pop("aggregation", vs.VariableAggregation.NONE)
if aggregation not in (
vs.VariableAggregation.NONE,
vs.VariableAggregation.SUM,
vs.VariableAggregation.MEAN,
vs.VariableAggregation.ONLY_FIRST_REPLICA
):
raise ValueError("Invalid variable aggregation mode: " + aggregation +
" for variable: " + kwargs["name"])
def var_creator(*args, **kwargs):
"""Create an AggregatingVariable and fix up collections."""
# Record what collections this variable should be added to.
collections = kwargs.pop("collections", None)
if collections is None:
collections = [ops.GraphKeys.GLOBAL_VARIABLES]
kwargs["collections"] = []
# Create and wrap the variable.
v = next_creator(*args, **kwargs)
wrapped = values.AggregatingVariable(
self._container_strategy(), v, aggregation)
# Add the wrapped variable to the requested collections.
# The handling of eager mode and the global step matches
# ResourceVariable._init_from_args().
if not context.executing_eagerly():
g = ops.get_default_graph()
# If "trainable" is True, next_creator() will add the contained
# variable to the TRAINABLE_VARIABLES collection, so we manually
# remove it and replace with the wrapper. We can't set "trainable"
# to False for next_creator() since that causes functions like
# implicit_gradients to skip those variables.
if kwargs.get("trainable", True):
collections.append(ops.GraphKeys.TRAINABLE_VARIABLES)
l = g.get_collection_ref(ops.GraphKeys.TRAINABLE_VARIABLES)
if v in l:
l.remove(v)
g.add_to_collections(collections, wrapped)
elif ops.GraphKeys.GLOBAL_STEP in collections:
ops.add_to_collections(ops.GraphKeys.GLOBAL_STEP, wrapped)
return wrapped
else:
var_creator = next_creator
if "colocate_with" in kwargs:
colocate_with = kwargs["colocate_with"]
if isinstance(colocate_with, numpy_dataset.SingleDevice):
with ops.device(colocate_with.device):
return var_creator(*args, **kwargs)
with ops.device(None):
with ops.colocate_with(colocate_with):
return var_creator(*args, **kwargs)
with ops.colocate_with(None, ignore_existing=True):
with ops.device(self._variable_device):
return var_creator(*args, **kwargs)
def _call_for_each_replica(self, fn, args, kwargs):
# pylint: disable=protected-access
return mirrored_strategy._call_for_each_replica(
self._container_strategy(), self._device_map, fn, args, kwargs)
def _verify_destinations_not_different_worker(self, destinations):
if not self._cluster_spec:
return
if destinations is None:
return
for d in cross_device_ops_lib.get_devices_from(destinations):
d_spec = tf_device.DeviceSpec.from_string(d)
if d_spec.job == self._task_type and d_spec.task != self._task_id:
raise ValueError(
"Cannot reduce to another worker: %r, current worker is %r" %
(d, self._input_workers.worker_devices[0]))
def _reduce_to(self, reduce_op, value, destinations):
self._verify_destinations_not_different_worker(destinations)
if not isinstance(value, values.DistributedValues):
# pylint: disable=protected-access
return cross_device_ops_lib.reduce_non_distributed_value(
reduce_op, self._device_map, value, destinations)
return self._cross_device_ops.reduce(
reduce_op, value, destinations=destinations)
def _batch_reduce_to(self, reduce_op, value_destination_pairs):
for _, destinations in value_destination_pairs:
self._verify_destinations_not_different_worker(destinations)
return self._cross_device_ops.batch_reduce(reduce_op,
value_destination_pairs)
def _select_single_value(self, structured):
"""Select any single values in `structured`."""
def _select_fn(x): # pylint: disable=g-missing-docstring
if isinstance(x, values.Mirrored):
if len(x.devices) == 1:
return x.primary
else:
raise ValueError(
"You cannot update variable with a Mirrored object with multiple "
"components %r when using ParameterServerStrategy. You must "
"specify a single value or a Mirrored with a single value." % x)
elif isinstance(x, values.PerReplica):
raise ValueError(
"You cannot update variable with a PerReplica object %r when using "
"ParameterServerStrategy. You must specify a single value or a "
"Mirrored with a single value" % x)
else:
return x
return nest.map_structure(_select_fn, structured)
def _update(self, var, fn, args, kwargs, group):
if isinstance(var, values.AggregatingVariable):
var = var.get()
if not isinstance(var, resource_variable_ops.ResourceVariable):
raise ValueError(
"You can not update `var` %r. It must be a Variable." % var)
with ops.colocate_with(var), distribute_lib.UpdateContext(var.device):
result = fn(var, *self._select_single_value(args),
**self._select_single_value(kwargs))
if group:
return result
else:
return nest.map_structure(self._local_results, result)
# TODO(yuefengz): does it need to call _select_single_value?
def _update_non_slot(self, colocate_with, fn, args, kwargs, group):
with ops.device(
colocate_with.device), distribute_lib.UpdateContext(colocate_with):
result = fn(*args, **kwargs)
if group:
return result
else:
return nest.map_structure(self._local_results, result)
def _local_results(self, val):
if isinstance(val, values.DistributedValues):
return val.values
return (val,)
def value_container(self, val):
if (hasattr(val, "_aggregating_container") and
not isinstance(val, values.AggregatingVariable)):
wrapper = val._aggregating_container() # pylint: disable=protected-access
if wrapper is not None:
return wrapper
return val
def read_var(self, var):
# No need to distinguish between normal variables and replica-local
# variables.
return array_ops.identity(var)
def _configure(self,
session_config=None,
cluster_spec=None,
task_type=None,
task_id=None):
"""Configures the strategy class.
The strategy object will be re-initialized if `cluster_spec` is given but
was not passed in the constructor.
Args:
session_config: not used currently.
cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the
cluster configurations.
task_type: the current task type.
task_id: the current task id.
Raises:
ValueError: if `cluster_spec` is given but `task_type` or `task_id` is
not.
"""
if cluster_spec:
# Use the num_gpus_per_worker recorded in constructor since _configure
# doesn't take num_gpus.
cluster_resolver = SimpleClusterResolver(
cluster_spec=multi_worker_util.normalize_cluster_spec(cluster_spec),
task_type=task_type,
task_id=task_id,
num_accelerators={"GPU": self._num_gpus_per_worker})
self._initialize_multi_worker(cluster_resolver)
if session_config:
session_config.CopyFrom(self._update_config_proto(session_config))
def _update_config_proto(self, config_proto):
updated_config = copy.deepcopy(config_proto)
if not self._cluster_spec:
updated_config.isolate_session_state = True
return updated_config
updated_config.isolate_session_state = False
assert self._task_type
assert self._task_id is not None
# The device filters prevent communication between workers.
del updated_config.device_filters[:]
if self._task_type in ["chief", "worker"]:
updated_config.device_filters.extend(
["/job:%s/task:%d" % (self._task_type, self._task_id), "/job:ps"])
elif self._task_type == "evaluator":
updated_config.device_filters.append(
"/job:%s/task:%d" % (self._task_type, self._task_id))
return updated_config
@property
def _num_replicas_in_sync(self):
return self._device_map.num_replicas_in_graph
@property
def worker_devices(self):
return self._device_map.all_devices
@property
def worker_devices_by_replica(self):
return self._device_map.devices_by_replica
@property
def parameter_devices(self):
return self._parameter_devices
def non_slot_devices(self, var_list):
return min(var_list, key=lambda x: x.name)
@property
def experimental_between_graph(self):
# TODO(yuefengz): Should this return False in the local case?
return True
@property
def experimental_should_init(self):
return self._is_chief
@property
def should_checkpoint(self):
return self._is_chief
@property
def should_save_summary(self):
return self._is_chief
# TODO(priyag): Delete this once all strategies use global batch size.
@property
def _global_batch_size(self):
"""`make_dataset_iterator` and `make_numpy_iterator` use global batch size.
`make_input_fn_iterator` assumes per-replica batching.
Returns:
Boolean.
"""
return True
| kevin-coder/tensorflow-fork | tensorflow/python/distribute/parameter_server_strategy.py | Python | apache-2.0 | 22,870 |
from twisted.words.protocols.irc import ERR_NORECIPIENT, ERR_NOTEXTTOSEND, ERR_NOSUCHNICK
class Command(object):
"""
PRIVMSG is used to send private messages between users, as well as to
send messages to channels. <msgtarget> is usually the nickname of
the recipient of the message, or a channel name.
The <msgtarget> parameter may also be a host mask (#<mask>) or server
mask ($<mask>). In both cases the server will only send the PRIVMSG
to those who have a server or host matching the mask. The mask MUST
have at least 1 (one) "." in it and no wildcards following the last
".". This requirement exists to prevent people sending messages to
"#*" or "$*", which would broadcast to all users. Wildcards are the
'*' and '?' characters. This extension to the PRIVMSG command is
only available to operators.
Numeric Replies:
ERR_NORECIPIENT ERR_NOTEXTTOSEND
ERR_CANNOTSENDTOCHAN ERR_NOTOPLEVEL
ERR_WILDTOPLEVEL ERR_TOOMANYTARGETS
ERR_NOSUCHNICK
RPL_AWAY
Examples:
:Angel!wings@irc.org PRIVMSG Wiz :Are you receiving this message ?
; Message from Angel to Wiz.
PRIVMSG Angel :yes I'm receiving it !
; Command to send a message to Angel.
PRIVMSG jto@tolsun.oulu.fi :Hello !
; Command to send a message to a user
on server tolsun.oulu.fi with
username of "jto".
PRIVMSG kalt%millennium.stealth.net@irc.stealth.net :Are you a frog?
; Message to a user on server
irc.stealth.net with username of
"kalt", and connected from the host
millennium.stealth.net.
PRIVMSG kalt%millennium.stealth.net :Do you like cheese?
; Message to a user on the local
server with username of "kalt", and
connected from the host
millennium.stealth.net.
PRIVMSG Wiz!jto@tolsun.oulu.fi :Hello !
; Message to the user with nickname
Wiz who is connected from the host
tolsun.oulu.fi and has the username
"jto".
PRIVMSG $*.fi :Server tolsun.oulu.fi rebooting.
; Message to everyone on a server
which has a name matching *.fi.
PRIVMSG #*.edu :NSFNet is undergoing work, expect interruptions
; Message to all users who come from
a host which has a name matching
*.edu.
"""
@staticmethod
def can_privmsg(server, client, target=None, message=None):
if not target:
return ERR_NORECIPIENT
if not message:
return ERR_NOTEXTTOSEND
# Check if user exists.
entity = server.get_user(target)
if entity:
return 0
# Check if channel exists.
entity = server.get_channel(target)
if entity:
return 0
return ERR_NOSUCHNICK
@staticmethod
def on_privmsg(server, client, target, message):
user = server.get_user(target)
if user:
user.send_privmsg(client.hostmask, user.nickname, message)
return
channel = server.get_channel(target)
for user in channel.users:
if user == client:
continue
user.send_privmsg(client.hostmask, target, message) | kevelbreh/betternet | betternet/command/privmsg.py | Python | apache-2.0 | 3,895 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=unused-variable,invalid-name,unused-argument
"""
Decorators for registering tunable templates to TOPI.
These decorators can make your simple implementation be able to use different configurations
for different workloads.
Here we directly use all arguments to the TOPI call as "workload", so make sure all the arguments
(except tvm.Tensor) in you calls are hashable. For tvm.Tensor, we will serialize it to a hashable
tuple.
See tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.
"""
from ... import _api_internal, tensor, placeholder
from .task import args_to_workload, dispatcher, register
from ..util import get_const_tuple
# A table that records all registered dispatcher for all targets
_REGISTERED_DISPATCHER = {
}
def serialize_args(args):
"""serialize arguments of a topi function to a hashable tuple.
Parameters
----------
args: list of hashable or Tensor
"""
ret = []
for t in args:
if isinstance(t, tensor.Tensor):
ret.append(('TENSOR', get_const_tuple(t.shape), t.dtype))
else:
ret.append(t)
return tuple(ret)
def deserialize_args(args):
"""The inverse function of :code:`serialize_args`.
Parameters
----------
args: list of hashable or Tensor
"""
ret = []
for t in args:
if isinstance(t, tuple) and t[0] == 'TENSOR':
ret.append(placeholder(shape=t[1], dtype=t[2]))
else:
ret.append(t)
return ret
# Task extractor for nnvm graph, relay program
class TaskExtractEnv:
"""Global environment for extracting tuning tasks from nnvm graph"""
current = None
registered = None
def __init__(self, allow_duplicate=False):
import topi
# topi compute -> autotvm task name
self.topi_to_task = {
topi.nn.conv2d: "topi_nn_conv2d",
topi.nn.depthwise_conv2d_nchw: "topi_nn_depthwise_conv2d_nchw",
topi.nn.group_conv2d_nchw: "topi_nn_group_conv2d_nchw",
topi.nn.conv2d_transpose_nchw: "topi_nn_conv2d_transpose_nchw",
topi.nn.conv2d_NCHWc: "topi_x86_conv2d_NCHWc",
topi.nn.conv2d_NCHWc_int8: "topi_x86_conv2d_NCHWc_int8",
topi.nn.dense: "topi_nn_dense",
topi.nn.bitserial_conv2d_nchw: "topi_nn_bitserial_conv2d_nchw",
topi.nn.bitserial_conv2d_nhwc: "topi_nn_bitserial_conv2d_nhwc",
topi.nn.bitserial_dense: "topi_nn_bitserial_dense",
topi.nn.deformable_conv2d_nchw: "topi_nn_deformable_conv2d_nchw",
}
self.topi_to_schedule = {
topi.nn.conv2d: [topi.generic.schedule_conv2d_nchw,
topi.generic.schedule_conv2d_nhwc],
topi.nn.depthwise_conv2d_nchw: [topi.generic.schedule_depthwise_conv2d_nchw,
topi.generic.schedule_depthwise_conv2d_nhwc],
topi.nn.group_conv2d_nchw: [topi.generic.schedule_group_conv2d_nchw],
topi.nn.conv2d_transpose_nchw: [topi.generic.schedule_conv2d_transpose_nchw],
topi.nn.conv2d_NCHWc: [topi.generic.schedule_conv2d_NCHWc],
topi.nn.conv2d_NCHWc_int8: [topi.generic.schedule_conv2d_NCHWc_int8],
topi.nn.dense: [topi.generic.schedule_dense],
topi.nn.bitserial_conv2d_nchw: [topi.generic.schedule_bitserial_conv2d_nchw],
topi.nn.bitserial_conv2d_nhwc: [topi.generic.schedule_bitserial_conv2d_nhwc],
topi.nn.bitserial_dense: [topi.generic.schedule_bitserial_dense],
topi.nn.deformable_conv2d_nchw: [topi.generic.schedule_deformable_conv2d_nchw],
}
# function reflection for tracing
self.func_to_reflection = {
topi.nn.conv2d: lambda x: setattr(topi.nn, 'conv2d', x),
topi.nn.conv2d_NCHWc: lambda x: setattr(topi.nn, 'conv2d_NCHWc', x),
topi.nn.conv2d_NCHWc_int8: lambda x: setattr(topi.nn, 'conv2d_NCHWc_int8', x),
topi.nn.depthwise_conv2d_nchw: lambda x: setattr(topi.nn, 'depthwise_conv2d_nchw', x),
topi.nn.group_conv2d_nchw: lambda x: setattr(topi.nn, 'group_conv2d_nchw', x),
topi.nn.conv2d_transpose_nchw: lambda x: setattr(topi.nn, 'conv2d_transpose_nchw', x),
topi.nn.dense: lambda x: setattr(topi.nn, 'dense', x),
topi.nn.bitserial_conv2d_nchw: lambda x: setattr(topi.nn, 'bitserial_conv2d_nchw', x),
topi.nn.bitserial_conv2d_nhwc: lambda x: setattr(topi.nn, 'bitserial_conv2d_nhwc', x),
topi.nn.bitserial_dense: lambda x: setattr(topi.nn, 'bitserial_dense', x),
topi.nn.deformable_conv2d_nchw: lambda x: setattr(topi.nn, 'deformable_conv2d_nchw', x),
}
self.allow_duplicate = allow_duplicate
self._register_topi_task()
self.task_collection = []
self.wanted_topi_funcs = list(self.topi_to_task.keys())
self.modified_funcs = []
def __enter__(self):
self.task_collection = []
self.modified_funcs = []
for topi_compute in self.wanted_topi_funcs:
def _local_scope(compute_func):
"""start a scope to hold the local function in for loop"""
def _tracing_wrapper(*args, **kwargs):
assert not kwargs, "Do not support extracting tuning tasks when " \
"kwargs is used in TOPI function call. " \
"Please modify it to use only positional args."
key = (self.topi_to_task[compute_func], serialize_args(args))
if self.allow_duplicate or key not in self.task_collection:
self.task_collection.append(key)
return compute_func(*args, **kwargs)
self.func_to_reflection[compute_func](_tracing_wrapper)
self.modified_funcs.append(compute_func)
_local_scope(topi_compute)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# revert modification
for func in self.modified_funcs:
self.func_to_reflection[func](func)
def _register_topi_task(self):
"""register tuning wrapper for topi function"""
import topi
# Avoid double registration for certain targets
if TaskExtractEnv.registered:
return
TaskExtractEnv.registered = True
# Tuning wrapper for topi functions
@register("topi_nn_conv2d")
def _topi_nn_conv2d(*args, **kwargs):
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
A, W = args[:2]
layout = args[-2]
assert layout == 'NCHW', "only support NCHW currently"
C = topi.nn.conv2d(*args, **kwargs)
s = topi.generic.schedule_conv2d_nchw([C])
return s, [A, W, C]
@register("topi_nn_depthwise_conv2d_nchw")
def _topi_nn_depthwise_conv2d_nchw(*args, **kwargs):
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
A, W = args[:2]
C = topi.nn.depthwise_conv2d_nchw(*args, **kwargs)
s = topi.generic.schedule_depthwise_conv2d_nchw([C])
return s, [A, W, C]
@register("topi_nn_group_conv2d_nchw")
def _topi_nn_group_conv2d_nchw(*args, **kwargs):
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
A, W = args[:2]
C = topi.nn.group_conv2d_nchw(*args, **kwargs)
s = topi.generic.schedule_group_conv2d_nchw([C])
return s, [A, W, C]
@register("topi_nn_conv2d_transpose_nchw")
def _topi_nn_conv2d_transpose_nchw(*args, **kwargs):
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
A, W = args[:2]
C = topi.nn.conv2d_transpose_nchw(*args, **kwargs)
s = topi.generic.schedule_conv2d_transpose_nchw([C])
return s, [A, W, C]
@register("topi_nn_dense")
def _topi_nn_dense(*args, **kwargs):
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
if len(args) > 2:
data, weight, bias = args[:3]
else:
data, weight = args
bias = None
C = topi.nn.dense(*args, **kwargs)
s = topi.generic.schedule_dense([C])
if bias is not None:
return s, [data, weight, bias, C]
return s, [data, weight, C]
@register("topi_nn_bitserial_conv2d_nhwc")
def _topi_bitserial_conv2d_nhwc(*args, **kwargs):
args = deserialize_args(args)
C = topi.nn.bitserial_conv2d_nhwc(*args, **kwargs)
s = topi.generic.nn.schedule_bitserial_conv2d_nhwc([C])
A, W = args[:2]
return s, [A, W, C]
@register("topi_nn_bitserial_conv2d_nchw")
def _topi_bitserial_conv2d_nchw(*args, **kwargs):
args = deserialize_args(args)
C = topi.nn.bitserial_conv2d_nchw(*args, **kwargs)
s = topi.generic.nn.schedule_bitserial_conv2d_nchw([C])
A, W = args[:2]
return s, [A, W, C]
@register("topi_nn_bitserial_dense")
def _topi_nn_bitserial_dense(*args, **kwargs):
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
A, W = args[:2]
C = topi.nn.bitserial_dense(*args, **kwargs)
s = topi.generic.schedule_bitserial_dense([C])
return s, [A, W, C]
@register("topi_nn_deformable_conv2d_nchw")
def _topi_nn_deformable_conv2d_nchw(*args, **kwargs):
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
A, Offset, W = args[:3]
C = topi.nn.deformable_conv2d_nchw(*args, **kwargs)
s = topi.generic.schedule_deformable_conv2d_nchw([C])
return s, [A, Offset, W, C]
@register("topi_nn_conv2d_NCHWc")
def _topi_nn_conv2d_NCHWc(*args, **kwargs):
assert not kwargs, "Do not support kwargs in template function call"
args = deserialize_args(args)
A, W = args[:2]
C = topi.nn.conv2d_NCHWc(*args, **kwargs)
s = topi.generic.schedule_conv2d_NCHWc([C])
return s, [A, W, C]
def reset(self, wanted_topi_funcs):
"""Reset task collections
Parameters
----------
wanted_topi_funcs: List of function
The topi function to be extracted
"""
self.task_collection = []
self.wanted_topi_funcs = wanted_topi_funcs
def get_tasks(self):
"""Get collected tasks
Returns
-------
tasks: List of tuple(name, args)
A list of tasks extracted from the nnvm graph
"""
return self.task_collection
@staticmethod
def get(allow_duplicate=False):
"""Get the single instance of TaskExtractEnv
Parameters
----------
allow_duplicate : boolean
Whether to fetch all workloads in the network,
even though some of them are the same. This is
useful for graph tuning.
Returns
-------
env: TaskExtractEnv
The single instance of TaskExtractEnv
"""
if not TaskExtractEnv.current:
TaskExtractEnv.current = TaskExtractEnv(allow_duplicate)
else:
TaskExtractEnv.current.allow_duplicate = allow_duplicate
return TaskExtractEnv.current
def register_topi_compute(topi_compute, target_keys, template_keys, func=None, override=False):
"""Register a tunable template for a topi compute function.
After the registration, this topi compute will become a configuration dispatcher. It uses
all its argument as workload and dispatches configurations according to the input workload.
It also stores this "workload" to its final ComputeOp, which can be used to reconstruct
"workload" in the following topi_schedule call.
Parameters
----------
topi_compute: GenericFunc
The topi compute function that will be overloaded
target_keys: str or list of str
The compilation target. The same as the argument of GenericFunc.register.
template_keys: str or list of str
The template key.
We might have several strategies for a single operator (e.g. direct, im2col, winograd).
The template key is used to identity the algorithm strategy.
Every operator must have a "direct" template, which is used by default.
func: None or callable
If it is None, return a decorator.
If is callable, decorate this function.
Returns
-------
decorator: callable
A decorator
Examples
--------
See tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.
"""
def _decorator(f):
targets = [target_keys] if isinstance(target_keys, str) else target_keys
for target_key in targets:
if target_key not in _REGISTERED_DISPATCHER:
_REGISTERED_DISPATCHER[target_key] = {}
if topi_compute not in _REGISTERED_DISPATCHER[target_key]:
@topi_compute.register(target_key)
@dispatcher
def config_dispatcher(*args, **kwargs):
"""override topi call as a config dispatcher"""
assert not kwargs, "Do not support kwargs in template function call"
return args_to_workload(args, topi_compute)
_REGISTERED_DISPATCHER[target_key][topi_compute] = config_dispatcher
config_dispatcher = _REGISTERED_DISPATCHER[target_key][topi_compute]
@config_dispatcher.register(template_keys, override=override)
def template_call(cfg, *args, **kwargs):
"""call the topi func and attach workload to compute node"""
assert not kwargs, "Do not support kwargs in template function call"
if f == topi_compute.fdefault:
node = f(*args, **kwargs)
else:
node = f(cfg, *args, **kwargs)
# attach workload to return op
op = node.op
attrs = {}
for k, v in node.op.attrs.items():
attrs[k] = v
attrs['workload'] = args_to_workload(args, topi_compute)
if isinstance(op, tensor.ComputeOp):
op = _api_internal._ComputeOp(
op.name, op.tag, attrs, op.axis, op.body)
elif isinstance(op, tensor.ExternOp):
op = _api_internal._ExternOp(
op.name, op.tag, attrs,
op.inputs, op.input_placeholders,
op.output_placeholders, op.body)
else:
raise RuntimeError("Unsupported op type: " + str(type(op)))
if isinstance(node, tensor.Tensor):
return op.output(0)
return [op.output(i) for i in range(len(node))]
return f
if func:
_decorator(func)
return _decorator
def register_topi_schedule(topi_schedule, target_keys, template_keys, func=None, override=False):
"""Register a tunable template for a topi schedule function.
After the registration. This topi schedule will become a configuration dispatcher. It dispatches
configurations according to the input workload.
Note that this function will try to find "workload" from all the ComputeOp in the input.
You can attach "workload" to your compute op by using :any:`register_topi_compute`.
Parameters
----------
topi_schedule: GenericFunc
The topi schedule function that will be overloaded
target_keys: str or list of str
The compilation target
template_keys: str or list of str
The template key.
We might have several strategies for a single operator (e.g. direct, im2col, winograd).
The template key is used to identity the algorithm strategy.
Every operator must have a "direct" template, which is used by default.
func: None or callable
If it is None, return a decorator.
If is callable, decorate this function.
Returns
-------
decorator: callable
A decorator
Examples
--------
See tvm/topi/python/topi/arm_cpu/depthwise_conv2d.py for example usage.
"""
def _decorator(f):
targets = [target_keys] if isinstance(target_keys, str) else target_keys
for target_key in targets:
if target_key not in _REGISTERED_DISPATCHER:
_REGISTERED_DISPATCHER[target_key] = {}
if topi_schedule not in _REGISTERED_DISPATCHER[target_key]:
@topi_schedule.register(target_key)
@dispatcher
def config_dispatcher(outs, *args, **kwargs):
"""override topi call as a workload dispatcher"""
def traverse(tensors):
"""traverse all ops to find attached workload"""
for t in tensors:
op = t.op
if 'workload' in op.attrs:
return op.attrs['workload']
wkl = traverse(op.input_tensors)
if wkl:
return wkl
return None
outs = [outs] if isinstance(outs, tensor.Tensor) else outs
workload = traverse(outs)
if workload is None:
raise RuntimeError("Cannot find workload in attribute of this schedule")
return args_to_workload(workload)
_REGISTERED_DISPATCHER[target_key][topi_schedule] = config_dispatcher
config_dispatcher = _REGISTERED_DISPATCHER[target_key][topi_schedule]
@config_dispatcher.register(template_keys, override=override)
def template_call(cfg, outs, *args, **kwargs):
"""call the schedule func"""
if f == topi_schedule.fdefault:
return f(outs, *args, **kwargs)
return f(cfg, outs, *args, **kwargs)
return f
if func:
_decorator(func)
return _decorator
| Huyuwei/tvm | python/tvm/autotvm/task/topi_integration.py | Python | apache-2.0 | 19,668 |
"""
Django signals for the app.
"""
import logging
from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.sites.models import Site
from .models import Response, UnitLesson
from .ct_util import get_middle_indexes
from core.common.mongo import c_milestone_orct
from core.common.utils import send_email, suspending_receiver
log = logging.getLogger(__name__)
@suspending_receiver(post_save, sender=Response)
def run_courselet_notif_flow(sender, instance, **kwargs):
# TODO: add check that Response has a text, as an obj can be created before a student submits
# TODO: exclude self eval submissions other than a response submission (e.g. "just guessing")
if (instance.kind == Response.ORCT_RESPONSE and not
(instance.unitLesson.kind == UnitLesson.RESOLVES or
instance.is_test or instance.is_preview or not instance.unitLesson.order)):
course = instance.course
course_id = course.id if course else None
instructors = course.get_users(role="prof")
lesson = instance.lesson
lesson_id = lesson.id if lesson else None
student = instance.author
student_id = student.id if student else None
unit_lesson = instance.unitLesson
unit_lesson_id = unit_lesson.id if unit_lesson else None # it's a thread
# Exclude instructors, e.g. the ones submitting in preview mode
for instructor in instructors:
if student_id == instructor.id:
return
# Define if it's a milestone question (either first, middle, or last)
milestone = None
questions = unit_lesson.unit.all_orct()
i = [_[0] for _ in questions.values_list('id')].index(unit_lesson_id)
if i == 0:
milestone = "first"
elif i == len(questions) - 1:
milestone = "last"
elif i in get_middle_indexes(questions):
milestone = "middle" # TODO consider returning a single number
# If milestone, store the record
if milestone:
to_save = {
"milestone": milestone,
"lesson_title": lesson.title if lesson else None,
"lesson_id": lesson_id,
"unit_lesson_id": unit_lesson_id,
"course_title": course.title if course else None,
"course_id": course_id,
"student_username": student.username if student else None,
"student_id": student_id,
# "datetime": datetime.datetime.now() # TODO: consider changing to UTC (and making it a timestamp)
}
# Do not store if such `student_id`-`lesson_id` row is already present
milestone_orct_answers_cursor = c_milestone_orct(use_secondary=False).find({
"milestone": milestone,
"lesson_id": lesson_id
})
initial_milestone_orct_answers_number = milestone_orct_answers_cursor.count()
milestone_orct_answers = (a for a in milestone_orct_answers_cursor)
already_exists = False
for answer in milestone_orct_answers:
if answer.get("student_id") == student_id:
already_exists = True
break
if not already_exists:
c_milestone_orct(use_secondary=False).save(to_save)
milestone_orct_answers_number = initial_milestone_orct_answers_number + 1
# If N students responded to a milestone question, send an email.
# The threshold holds for each milestone separately.
if milestone_orct_answers_number == settings.MILESTONE_ORCT_NUMBER:
context_data = {
"milestone": milestone,
"students_number": milestone_orct_answers_number,
"course_title": course.title if course else None,
"lesson_title": lesson.title if lesson else None,
"current_site": Site.objects.get_current(),
"course_id": course_id,
"unit_lesson_id": unit_lesson_id,
"courselet_pk": unit_lesson.unit.id if unit_lesson.unit else None
} # pragma: no cover
log.info("""Courselet notification with data:
Course title - {course_title},
Lesson title - {lesson_title},
Students number - {students_number},
Unit lesson id - {unit_lesson_id},
Course id - {course_id},
Milestone - {milestone}
""".format(**context_data)) # pragma: no cover
send_email(
context_data=context_data,
from_email=settings.EMAIL_FROM,
to_email=[instructor.email for instructor in instructors],
template_subject="ct/email/milestone_ortc_notify_subject",
template_text="ct/email/milestone_ortc_notify_text"
)
| cjlee112/socraticqs2 | mysite/ct/signals.py | Python | apache-2.0 | 5,199 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import functools
from oslo_utils import excutils
import six
def rollback_wrapper(original):
@functools.wraps(original)
def wrap(self):
try:
return original(self)
except Exception as ex:
with excutils.save_and_reraise_exception():
self.rollback(ex)
return wrap
@six.add_metaclass(abc.ABCMeta)
class TaskBase(object):
def __init__(self, context, instance):
self.context = context
self.instance = instance
@rollback_wrapper
def execute(self):
"""Run task's logic, written in _execute() method
"""
return self._execute()
@abc.abstractmethod
def _execute(self):
"""Descendants should place task's logic here, while resource
initialization should be performed over __init__
"""
pass
def rollback(self, ex):
"""Rollback failed task
Descendants should implement this method to allow task user to
rollback status to state before execute method was call
"""
pass
| rahulunair/nova | nova/conductor/tasks/base.py | Python | apache-2.0 | 1,651 |
#!/usr/bin/python
# coding=utf-8
# Copyright 2012-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import tempfile
from uuid import uuid4
from mongo_orchestration.common import (
BaseModel, DEFAULT_SUBJECT, DEFAULT_CLIENT_CERT)
from mongo_orchestration.container import Container
from mongo_orchestration.errors import ShardedClusterError
from mongo_orchestration.servers import Servers
from mongo_orchestration.replica_sets import ReplicaSets
from mongo_orchestration.singleton import Singleton
from pymongo import MongoClient
logger = logging.getLogger(__name__)
class ShardedCluster(BaseModel):
"""class represents Sharding configuration"""
def __init__(self, params):
"""init configuration acording params"""
self.id = params.get('id', None) or str(uuid4())
self.admin_added = False
self.login = params.get('login', '')
self.password = params.get('password', '')
self.auth_key = params.get('auth_key', None)
self.auth_source = params.get('authSource', 'admin')
self._version = params.get('version')
self._configsvrs = []
self._routers = []
self._shards = {}
self.tags = {}
self.sslParams = params.get('sslParams', {})
self.kwargs = {}
self.restart_required = self.login or self.auth_key
self.x509_extra_user = False
if self.sslParams:
self.kwargs['ssl'] = True
self.kwargs['ssl_certfile'] = DEFAULT_CLIENT_CERT
configsvr_configs = params.get('configsvrs', [{}])
self.__init_configsvr(configsvr_configs)
for r in params.get('routers', [{}]):
self.router_add(r)
for cfg in params.get('shards', []):
shard_params = cfg.get('shardParams', {})
shard_tags = shard_params.pop('tags', None)
info = self.member_add(cfg.get('id', None), shard_params)
if shard_tags:
self.tags[info['id']] = shard_tags
if self.tags:
for sh_id in self.tags:
logger.debug('Add tags %r to %s' % (self.tags[sh_id], sh_id))
self.connection().config.shards.update(
{'_id': sh_id},
{'$addToSet': {'$each': self.tags[sh_id]}})
if self.login:
# Do we need to add an extra x509 user?
def only_x509(config):
set_params = config.get('setParameter', {})
auth_mechs = set_params.get('authenticationMechanisms', '')
auth_mechs = auth_mechs.split(',')
if len(auth_mechs) == 1 and auth_mechs[0] == 'MONGODB-X509':
return True
return False
any_only_x509 = lambda l: any(map(only_x509, l))
shard_configs = [s.get('shardParams', {}).get('procParams', {})
for s in params.get('shards', [])]
rs_shard_configs = [
m.get('procParams', {})
for s in params.get('shards', [])
for m in s.get('shardParams', {}).get('members', [])
]
router_configs = params.get('routers', [])
self.x509_extra_user = (any_only_x509(configsvr_configs) or
any_only_x509(shard_configs) or
any_only_x509(rs_shard_configs) or
any_only_x509(router_configs))
self._add_users(self.connection()[self.auth_source])
# Secondary user given from request.
secondary_login = {
'name': self.login,
'roles': self._user_roles
}
if self.password:
secondary_login['password'] = self.password
# Do the same for the shards.
for shard_id, config in zip(self._shards, shard_configs):
shard = self._shards[shard_id]
instance_id = shard['_id']
if shard.get('isServer'):
client = Servers()._storage[instance_id].connection
elif shard.get('isReplicaSet'):
client = ReplicaSets()._storage[instance_id].connection()
db = client[self.auth_source]
if self.x509_extra_user:
db.add_user(DEFAULT_SUBJECT, roles=self._user_roles)
if self.login:
db.add_user(**secondary_login)
if self.restart_required:
# Do we need to add clusterAuthMode back?
cluster_auth_mode = None
for cfg in shard_configs:
cam = cfg.get('clusterAuthMode')
if cam:
cluster_auth_mode = cam
break
def restart_with_auth(server_or_rs):
server_or_rs.x509_extra_user = self.x509_extra_user
server_or_rs.auth_source = self.auth_source
server_or_rs.ssl_params = self.sslParams
server_or_rs.login = self.login
server_or_rs.password = self.password
server_or_rs.auth_key = self.auth_key
def add_auth(cfg):
if self.auth_key:
cfg['keyFile'] = self.key_file
# Add clusterAuthMode back in.
if cluster_auth_mode:
cfg['clusterAuthMode'] = cam
return cfg
server_or_rs.restart(config_callback=add_auth)
for server_id in self._configsvrs:
server = Servers()._storage[server_id]
restart_with_auth(server)
for server_id in self._routers:
server = Servers()._storage[server_id]
restart_with_auth(server)
for shard_id in self._shards:
shard = self._shards[shard_id]
instance_id = shard['_id']
klass = ReplicaSets if shard.get('isReplicaSet') else Servers
instance = klass()._storage[instance_id]
restart_with_auth(instance)
self.restart_required = False
def __init_configsvr(self, params):
"""create and start config servers"""
self._configsvrs = []
for cfg in params:
# Remove flags that turn on auth.
cfg = self._strip_auth(cfg)
server_id = cfg.pop('server_id', None)
cfg.update({'configsvr': True})
self._configsvrs.append(Servers().create(
'mongod', cfg, sslParams=self.sslParams, autostart=True,
version=self._version, server_id=server_id))
def __len__(self):
return len(self._shards)
@property
def configsvrs(self):
"""return list of config servers"""
return [{'id': h_id, 'hostname': Servers().hostname(h_id)} for h_id in self._configsvrs]
@property
def routers(self):
"""return list of routers"""
return [{'id': h_id, 'hostname': Servers().hostname(h_id)} for h_id in self._routers]
@property
def members(self):
"""return list of members"""
# return [{'id': shard, 'hostname': Servers().hostname(info['_id'])} for shard, info in self._shards.items()]
return [self.member_info(item) for item in self._shards]
@property
def router(self):
"""return first available router"""
for server in self._routers:
info = Servers().info(server)
if info['procInfo'].get('alive', False):
return {'id': server, 'hostname': Servers().hostname(server)}
def router_add(self, params):
"""add new router (mongos) into existing configuration"""
cfgs = ','.join([Servers().hostname(item) for item in self._configsvrs])
server_id = params.pop('server_id', None)
params.update({'configdb': cfgs})
# Remove flags that turn auth on.
params = self._strip_auth(params)
self._routers.append(Servers().create(
'mongos', params, sslParams=self.sslParams, autostart=True,
version=self._version, server_id=server_id))
return {'id': self._routers[-1], 'hostname': Servers().hostname(self._routers[-1])}
def connection(self):
c = MongoClient(self.router['hostname'],
w='majority', fsync=True, **self.kwargs)
if self.login and not self.restart_required:
try:
c.admin.authenticate(self.login, self.password)
except:
logger.exception(
"Could not authenticate to %s as %s/%s"
% (self.router['hostname'], self.login, self.password))
raise
return c
def router_command(self, command, arg=None, is_eval=False):
"""run command on the router server
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
return command's result
"""
mode = is_eval and 'eval' or 'command'
if isinstance(arg, tuple):
name, d = arg
else:
name, d = arg, {}
result = getattr(self.connection().admin, mode)(command, name, **d)
return result
def router_remove(self, router_id):
"""remove """
result = Servers().remove(router_id)
del self._routers[ self._routers.index(router_id) ]
return { "ok": 1, "routers": self._routers }
def _add(self, shard_uri, name):
"""execute addShard command"""
return self.router_command("addShard", (shard_uri, {"name": name}), is_eval=False)
def member_add(self, member_id=None, params=None):
"""add new member into existing configuration"""
member_id = member_id or str(uuid4())
if 'members' in params:
# is replica set
rs_params = params.copy()
# Turn 'rs_id' -> 'id', to be consistent with 'server_id' below.
rs_params['id'] = rs_params.pop('rs_id', None)
rs_params.update({'sslParams': self.sslParams})
if self._version:
rs_params['version'] = self._version
rs_params['members'] = map(self._strip_auth, rs_params['members'])
rs_id = ReplicaSets().create(rs_params)
members = ReplicaSets().members(rs_id)
cfgs = rs_id + r"/" + ','.join([item['host'] for item in members])
result = self._add(cfgs, member_id)
if result.get('ok', 0) == 1:
self._shards[result['shardAdded']] = {'isReplicaSet': True, '_id': rs_id}
# return self._shards[result['shardAdded']].copy()
return self.member_info(member_id)
else:
# is single server
params.update({'autostart': True, 'sslParams': self.sslParams})
params = params.copy()
params['procParams'] = self._strip_auth(
params.get('procParams', {}))
if self._version:
params['version'] = self._version
logger.debug("servers create params: {params}".format(**locals()))
server_id = Servers().create('mongod', **params)
result = self._add(Servers().hostname(server_id), member_id)
if result.get('ok', 0) == 1:
self._shards[result['shardAdded']] = {'isServer': True, '_id': server_id}
return self.member_info(member_id)
def member_info(self, member_id):
"""return info about member"""
info = self._shards[member_id].copy()
info['id'] = member_id
info['tags'] = self.tags.get(member_id, list())
return info
def _remove(self, shard_name):
"""remove member from configuration"""
result = self.router_command("removeShard", shard_name, is_eval=False)
if result['ok'] == 1 and result['state'] == 'completed':
shard = self._shards.pop(shard_name)
if shard.get('isServer', False):
Servers().remove(shard['_id'])
if shard.get('isReplicaSet', False):
ReplicaSets().remove(shard['_id'])
return result
def member_remove(self, member_id):
"""remove member from configuration"""
return self._remove(member_id)
def reset(self):
"""Ensure all shards, configs, and routers are running and available."""
# Ensure all shards by calling "reset" on each.
for shard_id in self._shards:
if self._shards[shard_id].get('isReplicaSet'):
singleton = ReplicaSets()
elif self._shards[shard_id].get('isServer'):
singleton = Servers()
singleton.command(self._shards[shard_id]['_id'], 'reset')
# Ensure all config servers by calling "reset" on each.
for config_id in self._configsvrs:
Servers().command(config_id, 'reset')
# Ensure all routers by calling "reset" on each.
for router_id in self._routers:
Servers().command(router_id, 'reset')
return self.info()
def info(self):
"""return info about configuration"""
uri = ','.join(x['hostname'] for x in self.routers)
mongodb_uri = 'mongodb://' + uri
return {'id': self.id,
'shards': self.members,
'configsvrs': self.configsvrs,
'routers': self.routers,
'mongodb_uri': mongodb_uri,
'orchestration': 'sharded_clusters'}
def cleanup(self):
"""cleanup configuration: stop and remove all servers"""
for _id, shard in self._shards.items():
if shard.get('isServer', False):
Servers().remove(shard['_id'])
if shard.get('isReplicaSet', False):
ReplicaSets().remove(shard['_id'])
for mongos in self._routers:
Servers().remove(mongos)
for configsvr in self._configsvrs:
Servers().remove(configsvr)
self._configsvrs = []
self._routers = []
self._shards = {}
class ShardedClusters(Singleton, Container):
""" ShardedClusters is a dict-like collection for ShardedCluster objects"""
_name = 'shards'
_obj_type = ShardedCluster
releases = {}
pids_file = tempfile.mktemp(prefix="mongo-")
def set_settings(self, releases=None, default_release=None):
"""set path to storage"""
super(ShardedClusters, self).set_settings(releases, default_release)
ReplicaSets().set_settings(releases, default_release)
def __getitem__(self, key):
return self.info(key)
def cleanup(self):
"""remove all servers with their data"""
for server in self:
self.remove(server)
def create(self, params):
"""create new ShardedCluster
Args:
params - dictionary with specific params for instance
Return cluster_id
where cluster_id - id which can use to take the cluster from servers collection
"""
sh_id = params.get('id', str(uuid4()))
if sh_id in self:
raise ShardedClusterError(
"Sharded cluster with id %s already exists." % sh_id)
params['id'] = sh_id
cluster = ShardedCluster(params)
self[cluster.id] = cluster
return cluster.id
def remove(self, cluster_id):
"""remove cluster and data stuff
Args:
cluster_id - cluster identity
"""
cluster = self._storage.pop(cluster_id)
cluster.cleanup()
def info(self, cluster_id):
"""return dictionary object with info about cluster
Args:
cluster_id - cluster identity
"""
return self._storage[cluster_id].info()
def configsvrs(self, cluster_id):
"""return list of config servers"""
return self._storage[cluster_id].configsvrs
def routers(self, cluster_id):
"""return list of routers"""
return self._storage[cluster_id].routers
def router_add(self, cluster_id, params):
"""add new router"""
cluster = self._storage[cluster_id]
result = cluster.router_add(params)
self._storage[cluster_id] = cluster
return result
def router_del(self, cluster_id, router_id):
"""remove router from the ShardedCluster"""
cluster = self._storage[cluster_id]
result = cluster.router_remove(router_id)
self._storage[cluster_id] = cluster
return result
def members(self, cluster_id):
"""return list of members"""
return self._storage[cluster_id].members
def member_info(self, cluster_id, member_id):
"""return info about member"""
cluster = self._storage[cluster_id]
return cluster.member_info(member_id)
def command(self, cluster_id, command, *args):
"""Call a ShardedCluster method."""
cluster = self._storage[cluster_id]
try:
return getattr(cluster, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ShardedCluster %s"
% (command, cluster_id))
def member_del(self, cluster_id, member_id):
"""remove member from cluster cluster"""
cluster = self._storage[cluster_id]
result = cluster.member_remove(member_id)
self._storage[cluster_id] = cluster
return result
def member_add(self, cluster_id, params):
"""add new member into configuration"""
cluster = self._storage[cluster_id]
result = cluster.member_add(params.get('id', None), params.get('shardParams', {}))
self._storage[cluster_id] = cluster
return result
| amidvidy/mongo-orchestration | mongo_orchestration/sharded_clusters.py | Python | apache-2.0 | 18,384 |
#!/usr/bin/env python
"""
Calculate entropies of each leaf on each branch node of a tree for each column
Usage:
entropy.py -a ali.s9t100.fa -n gpcrdb_gapped_tm_numbering.csv -t ali.s9t100.ph > ali.s9t100.entropies
"""
import argparse
import collections
import logging
import math
from Bio import Phylo, AlignIO
import snooker
def calculate_entropies(tree_file, alignment_file, numbering_file,
min_node_size, max_node_size, number_format):
numberings = snooker.Numberings.from_file(numbering_file)
ali2gpcrdb = numberings.lookup(snooker.ALIGNMENT_POSITION, number_format)
alignment = AlignIO.read(alignment_file, 'fasta')
id2seq = {row.id: row.seq for row in alignment}
tree = Phylo.read(tree_file, 'newick')
all_leafs = set([leaf.name for leaf in tree.get_terminals()])
# for each column determine the aa distribution
all_counters = {}
for col in ali2gpcrdb:
all_counters[col] = collections.Counter([seq[col - 1] for seq in id2seq.values()])
print('{},{},{},{},{},{},{},{}'.format('node_id',
'alignment_pos',
number_format,
'entropy_inside',
'entropy_outside',
'score',
'variability_inside',
'variability_outside',
))
for node_id, node in enumerate(tree.get_nonterminals()):
leafs_of_node = set([leaf.name for leaf in node.get_terminals()])
if not (min_node_size <= len(leafs_of_node) <= max_node_size):
msg = '{} has {} leafs, skipping'.format(node, len(leafs_of_node))
logging.info(msg)
continue
leafs_outside_node = all_leafs - leafs_of_node
seqs_inside = [id2seq[v] for v in leafs_of_node]
nr_inside = float(len(leafs_of_node))
nr_outside = float(len(leafs_outside_node))
# loop over columns
for col in ali2gpcrdb:
aa_inside = collections.Counter([seq[col - 1] for seq in seqs_inside])
f_i_inside = 0
for count in aa_inside.values():
f_i_inside += count / nr_inside * math.log(count / nr_inside)
entropy_inside = -1 * f_i_inside
variability_inside = len(aa_inside)
aa_outside = all_counters[col] - aa_inside
f_i_outside = 0
for aa, count in aa_outside.items():
f_i_outside += count / nr_outside * math.log(count / nr_outside)
entropy_outside = -1 * f_i_outside
variability_outside = len(aa_outside)
distinct_aa = 21 # all amino acids and gap (-)
score = math.sqrt(pow(abs(math.log(1.0 / distinct_aa)) - entropy_outside, 2)
+ pow(entropy_inside, 2))
print('{},{},{},{},{},{},{},{}'.format(node_id,
col,
ali2gpcrdb[col],
entropy_inside,
entropy_outside,
score,
variability_inside,
variability_outside,
))
parser = argparse.ArgumentParser(description='Calculate entropies of each leaf on each branch node of a tree for each column')
parser.add_argument('-a', '--alignment', type=argparse.FileType('r'), required=True, help='Multiple sequence alignment (fasta format)')
parser.add_argument('-n', '--numbering', type=argparse.FileType('r'), required=True, help='Numbering file, translate sequence alignment position into generic numbering scheme')
parser.add_argument('-t', '--tree', type=argparse.FileType('r'), required=True, help='Tree of multiple sequence alignment (newick format)')
parser.add_argument('--min_node_size', type=int, default=20, help='Calculate entropies for nodes with a minimum number of leafs')
parser.add_argument('--max_node_size', type=int, default=20, help='Calculate entropies for nodes with a maximum number of leafs')
parser.add_argument('--number_format', default='gpcrdb_alignment', help='Column from numbering file to include in output')
args = parser.parse_args()
calculate_entropies(args.tree, args.alignment, args.numbering,
args.min_node_size, args.max_node_size, args.number_format)
| 3D-e-Chem/snooker-alignment | scripts/entropy.py | Python | apache-2.0 | 4,710 |
from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
class ShareModelSerializer(serializers.ModelSerializer):
# http://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
def to_representation(self, instance):
def not_none(value):
return value is not None
ret = super(ShareModelSerializer, self).to_representation(instance)
ret = OrderedDict(list(filter(lambda x: not_none(x[1]), ret.items())))
return ret
class RawDataSerializer(ShareModelSerializer):
class Meta:
model = models.RawData
fields = ('id', 'source', 'app_label', 'provider_doc_id', 'data', 'sha256', 'date_seen', 'date_harvested')
class ProviderRegistrationSerializer(ShareModelSerializer):
status = serializers.SerializerMethodField()
submitted_at = serializers.DateTimeField(read_only=True)
submitted_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
def get_status(self, obj):
return ProviderRegistration.STATUS[obj.status]
class Meta:
model = models.ProviderRegistration
fields = '__all__'
class FullNormalizedDataSerializer(serializers.ModelSerializer):
tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=CeleryProviderTask.objects.all())
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source', 'raw', 'tasks')
class BasicNormalizedDataSerializer(serializers.ModelSerializer):
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source')
class ChangeSerializer(ShareModelSerializer):
self = serializers.HyperlinkedIdentityField(view_name='api:change-detail')
target_type = serializers.StringRelatedField()
class Meta:
model = models.Change
fields = ('self', 'id', 'change', 'node_id', 'type', 'target_type', 'target_id')
class ShareUserSerializer(ShareModelSerializer):
def __init__(self, *args, token=None, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
if token:
self.fields.update({
'token': serializers.SerializerMethodField()
})
self.fields.update({
'🦄': serializers.SerializerMethodField(method_name='is_superuser'),
'🤖': serializers.SerializerMethodField(method_name='is_robot'),
})
def is_robot(self, obj):
if not isinstance(obj, AnonymousUser):
return obj.is_robot
return False
def get_token(self, obj):
try:
return obj.accesstoken_set.first().token
except AttributeError:
return None
def is_superuser(self, obj):
return obj.is_superuser
class Meta:
model = models.ShareUser
fields = (
'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login',
'is_active', 'gravatar', 'locale', 'time_zone'
)
class ChangeSetSerializer(ShareModelSerializer):
# changes = ChangeSerializer(many=True)
change_count = serializers.SerializerMethodField()
self = serializers.HyperlinkedIdentityField(view_name='api:changeset-detail')
source = ShareUserSerializer(source='normalized_data.source')
status = serializers.SerializerMethodField()
def get_status(self, obj):
return ChangeSet.STATUS[obj.status]
def get_change_count(self, obj):
return obj.changes.count()
class Meta:
model = models.ChangeSet
fields = ('self', 'id', 'submitted_at', 'change_count', 'source', 'status')
class ProviderSerializer(ShareUserSerializer):
def __init__(self, *args, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
self.fields.update({
'🤖': serializers.SerializerMethodField(method_name='is_robot'),
'provider_name': serializers.SerializerMethodField(method_name='provider_name')
})
def provider_name(self, obj):
return obj.username.replace('providers.', '')
class Meta:
model = models.ShareUser
fields = ('home_page', 'long_title', 'date_joined', 'gravatar')
| zamattiac/SHARE | api/serializers.py | Python | apache-2.0 | 4,542 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pyre-unsafe
"""
Common base for asyncio and Trollius (the Python 2 asyncio backport).
Ideally this would be all that's necessary but we can't use the async/await
syntax on Python 2 so we had to abstract coroutines away.
Look for them in TAsyncioServer and TTrolliusServer respectively.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import struct
import warnings
from collections import defaultdict
from io import BytesIO
import six
import thrift
from thrift.protocol.THeaderProtocol import THeaderProtocolFactory
from thrift.server.TServer import TConnectionContext
from thrift.Thrift import (
TApplicationException,
TMessageType,
)
from thrift.transport.THeaderTransport import (
THeaderTransport,
HEADER_FLAG,
MAX_FRAME_SIZE,
CLIENT_TYPE,
)
from thrift.transport.TTransport import (
TTransportBase,
TTransportException,
)
if six.PY3:
import asyncio
else:
# pyre-fixme[21]: Could not find module `trollius`.
import trollius as asyncio
# We support the deprecated FRAMED transport for old fb303
# clients that were otherwise failing miserably.
THEADER_CLIENT_TYPES = {
CLIENT_TYPE.HEADER,
CLIENT_TYPE.FRAMED_DEPRECATED,
}
_default_thpfactory = THeaderProtocolFactory(client_types=THEADER_CLIENT_TYPES)
THeaderProtocol = _default_thpfactory.getProtocol
logger = logging.getLogger(__name__)
if six.PY2:
class PermissionError(IOError):
pass
class ResourceWarning(RuntimeWarning):
pass
class TReadOnlyBuffer(TTransportBase):
"""Leaner version of TMemoryBuffer that is resettable."""
def __init__(self, value=b""):
self._open = True
self._value = value
self.reset()
def isOpen(self):
return self._open
def close(self):
self._io.close()
self._open = False
def read(self, sz):
return self._io.read(sz)
def write(self, buf):
raise PermissionError("This is a read-only buffer")
def reset(self):
self._io = BytesIO(self._value)
class TWriteOnlyBuffer(TTransportBase):
"""Leaner version of TMemoryBuffer that is resettable."""
def __init__(self):
self._open = True
self.reset()
def isOpen(self):
return self._open
def close(self):
self._io.close()
self._open = False
def read(self, sz):
raise EOFError("This is a write-only buffer")
def write(self, buf):
self._io.write(buf)
def getvalue(self):
return self._io.getvalue()
def reset(self):
self._io = BytesIO()
class TReadWriteBuffer(TTransportBase):
"""TMemoryBuffer equivalent with separate buffers to read and write."""
def __init__(self, value=b""):
self._read_io = TReadOnlyBuffer(value=value)
self._write_io = TWriteOnlyBuffer()
self.read = self._read_io.read
self.write = self._write_io.write
self.getvalue = self._write_io.getvalue
self.reset()
def isOpen(self):
return self._read_io._open and self._write_io._open
def close(self):
self._read_io.close()
self._write_io.close()
def reset(self):
self._read_io.reset()
self._write_io.reset()
# Note: read()/write()/getvalue() methods are bound in __init__().
class WrappedTransport(TWriteOnlyBuffer):
"""Wraps an asyncio.Transport in a Thrift Transport interface."""
MAX_QUEUE_SIZE = 1024
def __init__(self, trans, proto, loop):
super(WrappedTransport, self).__init__()
self._trans = trans
self._proto = proto
self._loop = loop
self._queue = asyncio.Queue(
maxsize=self.MAX_QUEUE_SIZE,
loop=self._loop,
)
self._consumer = self._loop.create_task(self._send())
self._producers = []
async def _send(self):
raise NotImplementedError
def send_message(self, msg):
self._producers.append(
self._loop.create_task(self._queue.put(msg)),
)
def flush(self):
msg = self.getvalue()
tmi = TReadOnlyBuffer(msg)
iprot = THeaderProtocol(tmi)
fname, mtype, seqid = iprot.readMessageBegin()
fname = fname.decode()
self._proto.schedule_timeout(fname, seqid)
self.send_message(msg)
self.reset()
def _clean_producers(self):
self._producers = [
p for p in self._producers if not p.done() and not p.cancelled()
]
def close(self):
try:
self._consumer.cancel()
for producer in self._producers:
if not producer.done() and not producer.cancelled():
producer.cancel()
super(WrappedTransport, self).close()
self._consumer = None
del self._producers
finally:
self._trans.close()
def __del__(self):
if self._consumer and (
not self._consumer.done() or not self._consumer.cancelled()
):
logger.debug(
"WrappedTransport did not finish properly"
" as the consumer asyncio.Task is still pending."
" Make sure to call .close() on this object."
)
if self.isOpen():
warnings.warn(
"WrappedTransport is being garbage collected"
" while still open."
" Make sure to call .close() on this object.",
ResourceWarning,
)
# pyre-fixme[11]: Annotation `Protocol` is not defined as a type.
class FramedProtocol(asyncio.Protocol):
"""Unpacks Thrift frames and reads them asynchronously."""
def __init__(self, loop=None):
self.loop = loop or asyncio.get_event_loop()
self.recvd = b""
async def message_received(self, frame):
raise NotImplementedError
def data_received(self, data):
"""Implements asyncio.Protocol.data_received."""
self.recvd = self.recvd + data
while len(self.recvd) >= 4:
(length,) = struct.unpack("!I", self.recvd[:4])
if length > MAX_FRAME_SIZE:
logger.error(
"Frame size %d too large for THeaderProtocol",
length,
)
self.transport.close()
return
elif length == 0:
logger.error("Empty frame")
self.transport.close()
return
if len(self.recvd) < length + 4:
return
frame = self.recvd[0 : 4 + length]
self.recvd = self.recvd[4 + length :]
self.loop.create_task(self.message_received(frame))
def eof_received(self):
"""Implements asyncio.Protocol.eof_received."""
return self.connection_lost(exc=None)
# Don't forget to implement connection_made/connection_lost in your
# subclass. There's also pause_writing/resume_writing but it seems we're
# fine without it.
class ThriftHeaderClientProtocolBase(FramedProtocol):
"""asyncio THeader protocol wrapper for client use.
This is abstract, missing implementation of an async TTransport
wrapper and the `message_received` coroutine function.
"""
DEFAULT_TIMEOUT = 60.0
THEADER_PROTOCOL_FACTORY = THeaderProtocolFactory
_exception_serializer = None
def __init__(
self,
client_class,
loop=None,
timeouts=None,
client_type=None,
):
super(ThriftHeaderClientProtocolBase, self).__init__(loop=loop)
self.client_class = client_class
if timeouts is None:
timeouts = {}
default_timeout = timeouts.get("") or self.DEFAULT_TIMEOUT
self.timeouts = defaultdict(lambda: default_timeout)
self.timeouts.update(timeouts)
self.client_type = client_type
self.client = None
self.pending_tasks = {}
self.transport = None # TTransport wrapping an asyncio.Transport
async def message_received(self, frame):
self._handle_message(frame, clear_timeout=True)
async def timeout_task(self, fname, delay):
# timeout_task must to be implemented in a subclass
raise NotImplementedError
def _handle_timeout(self, fname, seqid):
exc = TApplicationException(
TApplicationException.TIMEOUT, "Call to {} timed out".format(fname)
)
serialized_exc = self.serialize_texception(fname, seqid, exc)
self._handle_message(serialized_exc, clear_timeout=False)
def wrapAsyncioTransport(self, asyncio_transport):
raise NotImplementedError
def connection_made(self, transport):
"""Implements asyncio.Protocol.connection_made."""
assert self.transport is None, "Thrift transport already instantiated here."
assert self.client is None, "Client already instantiated here."
self.transport = self.wrapAsyncioTransport(transport)
thrift_protocol = self.THEADER_PROTOCOL_FACTORY(
client_type=self.client_type,
).getProtocol(self.transport)
thrift_protocol.trans.set_header_flag(HEADER_FLAG.SUPPORT_OUT_OF_ORDER)
self.client = self.client_class(thrift_protocol, self.loop)
def connection_lost(self, exc):
"""Implements asyncio.Protocol.connection_lost."""
te = TTransportException(
type=TTransportException.END_OF_FILE, message="Connection closed"
)
self.fail_all_futures(te)
def fail_all_futures(self, exc):
for fut in self.client._futures.values():
if not fut.done():
fut.set_exception(exc)
def _handle_message(self, frame, clear_timeout):
try:
tmi = TReadOnlyBuffer(frame)
iprot = self.THEADER_PROTOCOL_FACTORY(
client_type=self.client_type,
).getProtocol(tmi)
(fname, mtype, seqid) = iprot.readMessageBegin()
except TTransportException as ex:
self.fail_all_futures(ex)
self.transport.close()
return
except Exception as ex:
te = TTransportException(
type=TTransportException.END_OF_FILE, message=str(ex)
)
self.fail_all_futures(te)
self.transport.close()
return
if clear_timeout:
try:
timeout_task = self.pending_tasks.pop(seqid)
except KeyError:
# Task doesn't have a timeout or has already been cancelled
# and pruned from `pending_tasks`.
pass
else:
timeout_task.cancel()
self._handle_message_received(iprot, fname, mtype, seqid)
def _handle_message_received(self, iprot, fname, mtype, seqid):
method = getattr(self.client, "recv_" + fname.decode(), None)
if method is None:
logger.error("Method %r is not supported", fname)
self.close()
return
try:
method(iprot, mtype, seqid)
except (
asyncio.CancelledError,
asyncio.InvalidStateError,
) as e:
logger.warning("Method %r cancelled: %s", fname, str(e))
def update_pending_tasks(self, seqid, task):
no_longer_pending = [
_seqid
for _seqid, _task in self.pending_tasks.items()
if _task.done() or _task.cancelled()
]
for _seqid in no_longer_pending:
del self.pending_tasks[_seqid]
assert seqid not in self.pending_tasks, "seqid already pending for timeout"
self.pending_tasks[seqid] = task
def schedule_timeout(self, fname, seqid):
timeout = self.timeouts[fname]
if not timeout:
return
timeout_task = asyncio.Task(
self.timeout_task(fname, seqid, delay=timeout),
loop=self.loop,
)
self.update_pending_tasks(seqid, timeout_task)
def close(self):
for task in self.pending_tasks.values():
if not task.done() and not task.cancelled():
task.cancel()
if not self.transport:
return
try:
# Closing the wrapped sender transport will cascade closing
# of the underlying tranports, too.
self.transport.close()
except Exception:
pass
@classmethod
def serialize_texception(cls, fname, seqid, exception):
"""This saves us a bit of processing time for timeout handling by
reusing the Thrift structs involved in exception serialization.
NOTE: this is not thread-safe nor it is meant to be.
"""
# the serializer is a singleton
if cls._exception_serializer is None:
buffer = TWriteOnlyBuffer()
transport = THeaderTransport(buffer)
cls._exception_serializer = THeaderProtocol(transport)
else:
transport = cls._exception_serializer.trans
buffer = transport.getTransport()
buffer.reset()
serializer = cls._exception_serializer
serializer.writeMessageBegin(fname, TMessageType.EXCEPTION, seqid)
exception.write(serializer)
serializer.writeMessageEnd()
serializer.trans.flush()
return buffer.getvalue()
class AsyncioRpcConnectionContext(TConnectionContext):
def __init__(self, client_socket):
self._client_socket = client_socket
def getPeerName(self):
return self._client_socket.getpeername()
def getSockName(self):
return self._client_socket.getsockname()
| facebook/fbthrift | thrift/lib/py/async_common.py | Python | apache-2.0 | 14,364 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Base Estimator class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import os
import tempfile
import numpy as np
import six
from google.protobuf import message
from tensorflow.core.framework import summary_pb2
from tensorflow.python.client import session as tf_session
from tensorflow.python.eager import context
from tensorflow.python.estimator import model_fn as model_fn_lib
from tensorflow.python.estimator import run_config
from tensorflow.python.estimator import util as estimator_util
from tensorflow.python.estimator.export import export as export_helpers
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import metrics as metrics_lib
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import utils_impl as saved_model_utils
from tensorflow.python.summary import summary
from tensorflow.python.summary.writer import writer_cache
from tensorflow.python.training import basic_session_run_hooks
from tensorflow.python.training import checkpoint_management
from tensorflow.python.training import device_setter
from tensorflow.python.training import distribute as distribute_lib
from tensorflow.python.training import evaluation
from tensorflow.python.training import monitored_session
from tensorflow.python.training import saver
from tensorflow.python.training import training
from tensorflow.python.training import training_util
from tensorflow.python.training import warm_starting_util
from tensorflow.python.util import compat
from tensorflow.python.util import compat_internal
from tensorflow.python.util import function_utils
from tensorflow.python.util import nest
from tensorflow.python.util.tf_export import estimator_export
_VALID_MODEL_FN_ARGS = set(
['features', 'labels', 'mode', 'params', 'self', 'config'])
@estimator_export('estimator.Estimator')
class Estimator(object):
"""Estimator class to train and evaluate TensorFlow models.
The `Estimator` object wraps a model which is specified by a `model_fn`,
which, given inputs and a number of other parameters, returns the ops
necessary to perform training, evaluation, or predictions.
All outputs (checkpoints, event files, etc.) are written to `model_dir`, or a
subdirectory thereof. If `model_dir` is not set, a temporary directory is
used.
The `config` argument can be passed `tf.estimator.RunConfig` object containing
information about the execution environment. It is passed on to the
`model_fn`, if the `model_fn` has a parameter named "config" (and input
functions in the same manner). If the `config` parameter is not passed, it is
instantiated by the `Estimator`. Not passing config means that defaults useful
for local execution are used. `Estimator` makes config available to the model
(for instance, to allow specialization based on the number of workers
available), and also uses some of its fields to control internals, especially
regarding checkpointing.
The `params` argument contains hyperparameters. It is passed to the
`model_fn`, if the `model_fn` has a parameter named "params", and to the input
functions in the same manner. `Estimator` only passes params along, it does
not inspect it. The structure of `params` is therefore entirely up to the
developer.
None of `Estimator`'s methods can be overridden in subclasses (its
constructor enforces this). Subclasses should use `model_fn` to configure
the base class, and may add methods implementing specialized functionality.
@compatibility(eager)
Calling methods of `Estimator` will work while eager execution is enabled.
However, the `model_fn` and `input_fn` is not executed eagerly, `Estimator`
will switch to graph model before calling all user-provided functions (incl.
hooks), so their code has to be compatible with graph mode execution. Note
that `input_fn` code using `tf.data` generally works in both graph and eager
modes.
@end_compatibility
"""
def __init__(self, model_fn, model_dir=None, config=None, params=None,
warm_start_from=None):
"""Constructs an `Estimator` instance.
See [estimators](https://tensorflow.org/guide/estimators) for more
information.
To warm-start an `Estimator`:
```python
estimator = tf.estimator.DNNClassifier(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256],
warm_start_from="/path/to/checkpoint/dir")
```
For more details on warm-start configuration, see
`tf.estimator.WarmStartSettings`.
Args:
model_fn: Model function. Follows the signature:
* Args:
* `features`: This is the first item returned from the `input_fn`
passed to `train`, `evaluate`, and `predict`. This should be a
single `tf.Tensor` or `dict` of same.
* `labels`: This is the second item returned from the `input_fn`
passed to `train`, `evaluate`, and `predict`. This should be a
single `tf.Tensor` or `dict` of same (for multi-head models).
If mode is @{tf.estimator.ModeKeys.PREDICT}, `labels=None` will
be passed. If the `model_fn`'s signature does not accept
`mode`, the `model_fn` must still be able to handle
`labels=None`.
* `mode`: Optional. Specifies if this training, evaluation or
prediction. See `tf.estimator.ModeKeys`.
* `params`: Optional `dict` of hyperparameters. Will receive what
is passed to Estimator in `params` parameter. This allows
to configure Estimators from hyper parameter tuning.
* `config`: Optional `estimator.RunConfig` object. Will receive what
is passed to Estimator as its `config` parameter, or a default
value. Allows setting up things in your `model_fn` based on
configuration such as `num_ps_replicas`, or `model_dir`.
* Returns:
`tf.estimator.EstimatorSpec`
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into an estimator to
continue training a previously saved model. If `PathLike` object, the
path will be resolved. If `None`, the model_dir in `config` will be used
if set. If both are set, they must be same. If both are `None`, a
temporary directory will be used.
config: `estimator.RunConfig` configuration object.
params: `dict` of hyper parameters that will be passed into `model_fn`.
Keys are names of parameters, values are basic python types.
warm_start_from: Optional string filepath to a checkpoint or SavedModel to
warm-start from, or a `tf.estimator.WarmStartSettings`
object to fully configure warm-starting. If the string
filepath is provided instead of a
`tf.estimator.WarmStartSettings`, then all variables are
warm-started, and it is assumed that vocabularies
and `tf.Tensor` names are unchanged.
Raises:
ValueError: parameters of `model_fn` don't match `params`.
ValueError: if this is called via a subclass and if that class overrides
a member of `Estimator`.
"""
Estimator._assert_members_are_not_overridden(self)
self._config = maybe_overwrite_model_dir_and_session_config(config,
model_dir)
# The distribute field contains an instance of DistributionStrategy.
self._train_distribution = self._config.train_distribute
self._eval_distribution = self._config.eval_distribute
# Model directory.
self._model_dir = self._config.model_dir
self._session_config = self._config.session_config
logging.info('Using config: %s', str(vars(self._config)))
self._device_fn = (
self._config.device_fn or _get_replica_device_setter(self._config))
if model_fn is None:
raise ValueError('model_fn must be provided to Estimator.')
_verify_model_fn_args(model_fn, params)
self._model_fn = model_fn
self._params = copy.deepcopy(params or {})
# pylint: disable=protected-access
self._warm_start_settings = _get_default_warm_start_settings(
warm_start_from)
# pylint: enable=protected-access
@property
def model_dir(self):
return self._model_dir
@property
def config(self):
return copy.deepcopy(self._config)
@property
def params(self):
return copy.deepcopy(self._params)
@property
def model_fn(self):
"""Returns the `model_fn` which is bound to `self.params`.
Returns:
The `model_fn` with following signature:
`def model_fn(features, labels, mode, config)`
"""
def public_model_fn(features, labels, mode, config):
return self._call_model_fn(features, labels, mode, config)
return public_model_fn
# TODO(ispir): support a list of names
def get_variable_value(self, name):
"""Returns value of the variable given by name.
Args:
name: string or a list of string, name of the tensor.
Returns:
Numpy array - value of the tensor.
Raises:
ValueError: If the `Estimator` has not produced a checkpoint yet.
"""
_check_checkpoint_available(self.model_dir)
with context.graph_mode():
return training.load_variable(self.model_dir, name)
def get_variable_names(self):
"""Returns list of all variable names in this model.
Returns:
List of names.
Raises:
ValueError: If the `Estimator` has not produced a checkpoint yet.
"""
_check_checkpoint_available(self.model_dir)
with context.graph_mode():
return [name for name, _ in training.list_variables(self.model_dir)]
def latest_checkpoint(self):
"""Finds the filename of the latest saved checkpoint file in `model_dir`.
Returns:
The full path to the latest checkpoint or `None` if no checkpoint was
found.
"""
with context.graph_mode():
return checkpoint_management.latest_checkpoint(self.model_dir)
def train(self,
input_fn,
hooks=None,
steps=None,
max_steps=None,
saving_listeners=None):
"""Trains a model given training data `input_fn`.
Args:
input_fn: A function that provides input data for training as minibatches.
See [Premade Estimators](
https://tensorflow.org/guide/premade_estimators#create_input_functions)
for more information. The function should construct and return one of
the following: * A
`tf.data.Dataset` object: Outputs of `Dataset` object must be a tuple
`(features, labels)` with same constraints as below. * A tuple
`(features, labels)`: Where `features` is a `tf.Tensor` or a dictionary
of string feature name to `Tensor` and `labels` is a `Tensor` or a
dictionary of string label name to `Tensor`. Both `features` and
`labels` are consumed by `model_fn`. They should satisfy the expectation
of `model_fn` from inputs.
hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
callbacks inside the training loop.
steps: Number of steps for which to train the model. If `None`, train
forever or train until `input_fn` generates the `tf.errors.OutOfRange`
error or `StopIteration` exception. `steps` works incrementally. If you
call two times `train(steps=10)` then training occurs in total 20 steps.
If `OutOfRange` or `StopIteration` occurs in the middle, training stops
before 20 steps. If you don't want to have incremental behavior please
set `max_steps` instead. If set, `max_steps` must be `None`.
max_steps: Number of total steps for which to train model. If `None`,
train forever or train until `input_fn` generates the
`tf.errors.OutOfRange` error or `StopIteration` exception. If set,
`steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the
middle, training stops before `max_steps` steps. Two calls to
`train(steps=100)` means 200 training iterations. On the other hand, two
calls to `train(max_steps=100)` means that the second call will not do
any iteration since first call did all 100 steps.
saving_listeners: list of `CheckpointSaverListener` objects. Used for
callbacks that run immediately before or after checkpoint savings.
Returns:
`self`, for chaining.
Raises:
ValueError: If both `steps` and `max_steps` are not `None`.
ValueError: If either `steps` or `max_steps <= 0`.
"""
if self.config.task_type in (run_config.TaskType.EVALUATOR,
run_config.TaskType.PS):
raise ValueError(
'Train has been called wrong configuration. Please use '
'tf.estimator.train_and_evaluate which calls proper API according '
'to given configuration. Current configuration: {}.'.format(
self.config))
with context.graph_mode():
if (steps is not None) and (max_steps is not None):
raise ValueError('Can not provide both steps and max_steps.')
if steps is not None and steps <= 0:
raise ValueError('Must specify steps > 0, given: {}'.format(steps))
if max_steps is not None and max_steps <= 0:
raise ValueError(
'Must specify max_steps > 0, given: {}'.format(max_steps))
if max_steps is not None:
start_step = _load_global_step_from_checkpoint_dir(self._model_dir)
if max_steps <= start_step:
logging.info('Skipping training since max_steps has already saved.')
return self
hooks = _check_hooks_type(hooks)
hooks.extend(self._convert_train_steps_to_hooks(steps, max_steps))
saving_listeners = _check_listeners_type(saving_listeners)
loss = self._train_model(input_fn, hooks, saving_listeners)
logging.info('Loss for final step: %s.', loss)
return self
def _convert_train_steps_to_hooks(self, steps, max_steps):
"""Create hooks to run correct number of steps in training.
Args:
steps: number of steps to run during training.
max_steps: maximum number of steps to be run during training. It'll be
the maximum number of steps the model will train to after restoring
from checkpoint even across multiple estimator.train calls.
Returns:
List of hooks to be passed to the estimator.
"""
if steps is not None or max_steps is not None:
if self._train_distribution:
steps_per_run = getattr(self._train_distribution, 'steps_per_run', 1)
if steps_per_run > 1:
return [basic_session_run_hooks._MultiStepStopAtStepHook( # pylint: disable=protected-access
steps, max_steps, steps_per_run)]
return [training.StopAtStepHook(steps, max_steps)]
else:
return []
def eval_dir(self, name=None):
"""Shows the directory name where evaluation metrics are dumped.
Args:
name: Name of the evaluation if user needs to run multiple evaluations on
different data sets, such as on training data vs test data. Metrics for
different evaluations are saved in separate folders, and appear
separately in tensorboard.
Returns:
A string which is the path of directory contains evaluation metrics.
"""
return os.path.join(self._model_dir, 'eval' if not name else
'eval_' + name)
def evaluate(self, input_fn, steps=None, hooks=None, checkpoint_path=None,
name=None):
"""Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data.
Evaluates until:
- `steps` batches are processed, or
- `input_fn` raises an end-of-input exception (`tf.errors.OutOfRangeError`
or
`StopIteration`).
Args:
input_fn: A function that constructs the input data for evaluation. See
[Premade Estimators](
https://tensorflow.org/guide/premade#create_input_functions)
for more information. The
function should construct and return one of the following: * A
`tf.data.Dataset` object: Outputs of `Dataset` object must be a tuple
`(features, labels)` with same constraints as below. * A tuple
`(features, labels)`: Where `features` is a `tf.Tensor` or a dictionary
of string feature name to `Tensor` and `labels` is a `Tensor` or a
dictionary of string label name to `Tensor`. Both `features` and
`labels` are consumed by `model_fn`. They should satisfy the expectation
of `model_fn` from inputs.
steps: Number of steps for which to evaluate model. If `None`, evaluates
until `input_fn` raises an end-of-input exception.
hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
callbacks inside the evaluation call.
checkpoint_path: Path of a specific checkpoint to evaluate. If `None`, the
latest checkpoint in `model_dir` is used. If there are no checkpoints
in `model_dir`, evaluation is run with newly initialized `Variables`
instead of ones restored from checkpoint.
name: Name of the evaluation if user needs to run multiple evaluations on
different data sets, such as on training data vs test data. Metrics for
different evaluations are saved in separate folders, and appear
separately in tensorboard.
Returns:
A dict containing the evaluation metrics specified in `model_fn` keyed by
name, as well as an entry `global_step` which contains the value of the
global step for which this evaluation was performed. For canned
estimators, the dict contains the `loss` (mean loss per mini-batch) and
the `average_loss` (mean loss per sample). Canned classifiers also return
the `accuracy`. Canned regressors also return the `label/mean` and the
`prediction/mean`.
Raises:
ValueError: If `steps <= 0`.
ValueError: If no model has been trained, namely `model_dir`, or the
given `checkpoint_path` is empty.
"""
with context.graph_mode():
hooks = _check_hooks_type(hooks)
hooks.extend(self._convert_eval_steps_to_hooks(steps))
# Check that model has been trained (if nothing has been set explicitly).
if not checkpoint_path:
latest_path = checkpoint_management.latest_checkpoint(self._model_dir)
if not latest_path:
logging.info('Could not find trained model in model_dir: {}, running '
'initialization to evaluate.'.format(self._model_dir))
checkpoint_path = latest_path
def _evaluate():
(scaffold, update_op, eval_dict, all_hooks) = (
self._evaluate_build_graph(input_fn, hooks, checkpoint_path))
return self._evaluate_run(
checkpoint_path=checkpoint_path,
scaffold=scaffold,
update_op=update_op,
eval_dict=eval_dict,
all_hooks=all_hooks,
output_dir=self.eval_dir(name))
with ops.Graph().as_default():
if self._eval_distribution:
with self._eval_distribution.scope():
return _evaluate()
else:
return _evaluate()
def _convert_eval_steps_to_hooks(self, steps):
if steps is None:
return []
if steps <= 0:
raise ValueError('Must specify steps > 0, given: {}'.format(steps))
return [evaluation._StopAfterNEvalsHook(num_evals=steps)] # pylint: disable=protected-access
def predict(self,
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True):
"""Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See:
[issue/20506](
https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
Args:
input_fn: A function that constructs the features. Prediction continues
until `input_fn` raises an end-of-input exception
(`tf.errors.OutOfRangeError` or `StopIteration`).
See [Premade Estimators](
https://tensorflow.org/guide/premade_estimators#create_input_functions)
for more information. The function should construct and return one of
the following:
* A `tf.data.Dataset` object: Outputs of `Dataset` object must have
same constraints as below.
* features: A `tf.Tensor` or a dictionary of string feature name to
`Tensor`. features are consumed by `model_fn`. They should satisfy
the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
predict_keys: list of `str`, name of the keys to predict. It is used if
the `tf.estimator.EstimatorSpec.predictions` is a `dict`. If
`predict_keys` is used then rest of the predictions will be filtered
from the dictionary. If `None`, returns all.
hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
callbacks inside the prediction call.
checkpoint_path: Path of a specific checkpoint to predict. If `None`, the
latest checkpoint in `model_dir` is used. If there are no checkpoints
in `model_dir`, prediction is run with newly initialized `Variables`
instead of ones restored from checkpoint.
yield_single_examples: If `False`, yields the whole batch as returned by
the `model_fn` instead of decomposing the batch into individual
elements. This is useful if `model_fn` returns some tensors whose first
dimension is not equal to the batch size.
Yields:
Evaluated values of `predictions` tensors.
Raises:
ValueError: Could not find a trained model in `model_dir`.
ValueError: If batch length of predictions is not the same and
`yield_single_examples` is `True`.
ValueError: If there is a conflict between `predict_keys` and
`predictions`. For example if `predict_keys` is not `None` but
`tf.estimator.EstimatorSpec.predictions` is not a `dict`.
"""
with context.graph_mode():
hooks = _check_hooks_type(hooks)
# Check that model has been trained.
if not checkpoint_path:
checkpoint_path = checkpoint_management.latest_checkpoint(
self._model_dir)
if not checkpoint_path:
logging.info('Could not find trained model in model_dir: {}, running '
'initialization to predict.'.format(self._model_dir))
with ops.Graph().as_default() as g:
random_seed.set_random_seed(self._config.tf_random_seed)
self._create_and_assert_global_step(g)
features, input_hooks = self._get_features_from_input_fn(
input_fn, model_fn_lib.ModeKeys.PREDICT)
estimator_spec = self._call_model_fn(
features, None, model_fn_lib.ModeKeys.PREDICT, self.config)
# Call to warm_start has to be after model_fn is called.
self._maybe_warm_start(checkpoint_path)
predictions = self._extract_keys(
estimator_spec.predictions, predict_keys)
all_hooks = list(input_hooks)
all_hooks.extend(hooks)
all_hooks.extend(list(estimator_spec.prediction_hooks or []))
with training.MonitoredSession(
session_creator=training.ChiefSessionCreator(
checkpoint_filename_with_path=checkpoint_path,
master=self._config.master,
scaffold=estimator_spec.scaffold,
config=self._session_config),
hooks=all_hooks) as mon_sess:
while not mon_sess.should_stop():
preds_evaluated = mon_sess.run(predictions)
if not yield_single_examples:
yield preds_evaluated
elif not isinstance(predictions, dict):
for pred in preds_evaluated:
yield pred
else:
for i in range(self._extract_batch_length(preds_evaluated)):
yield {
key: value[i]
for key, value in six.iteritems(preds_evaluated)
}
def _assert_members_are_not_overridden(self):
"""Asserts members of `Estimator` are not overridden."""
# TPUEstimator is special cased (owned by TF).
if self.__class__.__name__ == 'TPUEstimator':
return
allowed_overrides = set([
'_create_and_assert_global_step',
'_tf_api_names', '_tf_api_names_v1', '_estimator_api_names',
'_estimator_api_names_v1', '_estimator_api_constants',
'_estimator_api_constants_v1',
])
estimator_members = set([m for m in Estimator.__dict__.keys()
if not m.startswith('__')])
subclass_members = set(self.__class__.__dict__.keys())
common_members = estimator_members & subclass_members - allowed_overrides
overridden_members = [
m for m in common_members
if Estimator.__dict__[m] != self.__class__.__dict__[m]]
if overridden_members:
raise ValueError(
'Subclasses of Estimator cannot override members of Estimator. '
'{} does override {}'.format(self.__class__, overridden_members))
def export_savedmodel(
self, export_dir_base, serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False):
# pylint: disable=line-too-long,g-doc-args,g-doc-return-or-yield
"""Exports inference graph as a `SavedModel` into the given dir.
Note that `export_to_savedmodel` will be renamed to `export_to_saved_model`
in TensorFlow 2.0. At that time, `export_to_savedmodel` without the
additional underscore will be available only through tf.compat.v1.
Please see `tf.estimator.Estimator.export_saved_model` for more information.
There is one additional arg versus the new method:
strip_default_attrs: This parameter is going away in TF 2.0, and
the new behavior will automatically strip all default attributes.
Boolean. If `True`, default-valued attributes will be
removed from the `NodeDef`s. For a detailed guide, see [Stripping
Default-Valued Attributes](
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
"""
# pylint: enable=line-too-long,g-doc-args,g-doc-return-or-yield
return self._export_saved_model_for_mode(
export_dir_base,
serving_input_receiver_fn,
assets_extra=assets_extra,
as_text=as_text,
checkpoint_path=checkpoint_path,
strip_default_attrs=strip_default_attrs,
mode=model_fn_lib.ModeKeys.PREDICT)
def export_saved_model(
self, export_dir_base, serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None):
# pylint: disable=line-too-long
"""Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide, see
[Using SavedModel with Estimators](https://tensorflow.org/guide/saved_model#using_savedmodel_with_estimators).
This method builds a new graph by first calling the
`serving_input_receiver_fn` to obtain feature `Tensor`s, and then calling
this `Estimator`'s `model_fn` to generate the model graph based on those
features. It restores the given checkpoint (or, lacking that, the most
recent checkpoint) into this graph in a fresh session. Finally it creates
a timestamped export directory below the given `export_dir_base`, and writes
a `SavedModel` into it containing a single `tf.MetaGraphDef` saved from this
session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each
element of the `export_outputs` dict returned from the `model_fn`, named
using
the same keys. One of these keys is always
`tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`,
indicating which
signature will be served when a serving request does not specify one.
For each signature, the outputs are provided by the corresponding
`tf.estimator.export.ExportOutput`s, and the inputs are always the input
receivers provided by
the `serving_input_receiver_fn`.
Extra assets may be written into the `SavedModel` via the `assets_extra`
argument. This should be a dict, where each key gives a destination path
(including the filename) relative to the assets.extra directory. The
corresponding value gives the full path of the source file to be copied.
For example, the simple case of copying a single file without renaming it
is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
Args:
export_dir_base: A string containing a directory in which to create
timestamped subdirectories containing exported `SavedModel`s.
serving_input_receiver_fn: A function that takes no argument and returns a
`tf.estimator.export.ServingInputReceiver` or
`tf.estimator.export.TensorServingInputReceiver`.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported `SavedModel`, or `None` if no extra assets are
needed.
as_text: whether to write the `SavedModel` proto in text format.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
Returns:
The string path to the exported directory.
Raises:
ValueError: if no `serving_input_receiver_fn` is provided, no
`export_outputs` are provided, or no checkpoint can be found.
"""
# pylint: enable=line-too-long
# TODO(b/111442174): `export_to_savedmodel` will be renamed to
# `export_to_saved_model` in TensorFlow 2.0. This function is a wrapper
# while staging the new version; do not add any logic here.
return self.export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=assets_extra,
as_text=as_text,
checkpoint_path=checkpoint_path,
strip_default_attrs=True)
def _export_saved_model_for_mode(
self, export_dir_base, input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False,
mode=model_fn_lib.ModeKeys.PREDICT):
# pylint: disable=line-too-long
"""Exports a single train/eval/predict graph as a `SavedModel`.
This method is a wrapper for `_export_all_saved_models`, and wraps a raw
`input_receiver_fn` in a dictionary to pass in to that function.
See `_export_all_saved_models` for full docs.
See `tf.contrib.estimator.export_saved_model_for_mode` for the currently
exposed version of this function.
Args:
export_dir_base: A string containing a directory in which to create
timestamped subdirectories containing exported `SavedModel`s.
input_receiver_fn: a function that takes no argument and returns the
appropriate subclass of `InputReceiver`.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported `SavedModel`, or `None` if no extra assets are
needed.
as_text: whether to write the `SavedModel` proto in text format.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
removed from the `NodeDef`s. For a detailed guide, see [Stripping
Default-Valued
Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
mode: `tf.estimator.ModeKeys` value indicating with mode will be exported.
Returns:
The string path to the exported directory.
Raises:
ValueError: if `input_receiver_fn` is `None`, no `export_outputs`
are provided, or no checkpoint can be found.
"""
# pylint: enable=line-too-long
if not input_receiver_fn:
raise ValueError('An input_receiver_fn must be defined.')
input_receiver_fn_map = {mode: input_receiver_fn}
return self._export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=assets_extra,
as_text=as_text,
checkpoint_path=checkpoint_path,
strip_default_attrs=strip_default_attrs)
def _export_all_saved_models(
self, export_dir_base, input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False):
# pylint: disable=line-too-long
"""Exports a `SavedModel` containing `tf.MetaGraphDefs` for each requested mode.
See `tf.contrib.estimator.export_all_saved_models` for the currently
exposed version of this function.
For each mode passed in via the `input_receiver_fn_map`,
this method builds a new graph by calling the `input_receiver_fn` to obtain
feature and label `Tensor`s. Next, this method calls the `Estimator`'s
`model_fn` in the passed mode to generate the model graph based on
those features and labels, and restores the given checkpoint
(or, lacking that, the most recent checkpoint) into the graph.
Only one of the modes is used for saving variables to the `SavedModel`
(order of preference: @{tf.estimator.ModeKeys#TRAIN$TRAIN},
@{tf.estimator.ModeKeys#EVAL$EVAL}, then
@{tf.estimator.ModeKeys#PREDICT$PREDICT}), such that up to three
`tf.MetaGraphDefs` are saved with a single set of variables in a single
`SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory
below
`export_dir_base`, and writes a `SavedModel` into it containing
the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef`
for each element of the `export_outputs` dict returned from the `model_fn`,
named using the same keys. One of these keys is always
`tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`,
indicating which
signature will be served when a serving request does not specify one.
For each signature, the outputs are provided by the corresponding
`tf.estimator.export.ExportOutput`s, and the inputs are always the input
receivers provided by
the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra
collection,
and loss, metrics, and predictions are included in a `SignatureDef` for the
mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra`
argument. This should be a dict, where each key gives a destination path
(including the filename) relative to the assets.extra directory. The
corresponding value gives the full path of the source file to be copied.
For example, the simple case of copying a single file without renaming it
is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
Args:
export_dir_base: A string containing a directory in which to create
timestamped subdirectories containing exported `SavedModel`s.
input_receiver_fn_map: dict of `tf.estimator.ModeKeys` to
`input_receiver_fn` mappings, where the `input_receiver_fn` is a
function that takes no arguments and returns the appropriate subclass of
`InputReceiver`.
assets_extra: A dict specifying how to populate the assets.extra directory
within the exported `SavedModel`, or `None` if no extra assets are
needed.
as_text: whether to write the `SavedModel` proto in text format.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
removed from the `NodeDef`s. For a detailed guide, see [Stripping
Default-Valued
Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
Returns:
A dict of `tf.estimator.ModeKeys` value to string path for each exported
directory.
Raises:
ValueError: if any `input_receiver_fn` is `None`, no `export_outputs`
are provided, or no checkpoint can be found.
"""
# pylint: enable=line-too-long
# TODO(b/65561022): Consider allowing multiple input_receiver_fns per mode.
with context.graph_mode():
if not checkpoint_path:
# Locate the latest checkpoint
checkpoint_path = checkpoint_management.latest_checkpoint(
self._model_dir)
if not checkpoint_path:
raise ValueError("Couldn't find trained model at %s." % self._model_dir)
export_dir = export_helpers.get_timestamped_export_dir(export_dir_base)
temp_export_dir = export_helpers.get_temp_export_dir(export_dir)
builder = saved_model_builder.SavedModelBuilder(temp_export_dir)
save_variables = True
# Note that the order in which we run here matters, as the first
# mode we pass through will be used to save the variables. We run TRAIN
# first, as that is also the mode used for checkpoints, and therefore
# we are not likely to have vars in PREDICT that are not in the checkpoint
# created by TRAIN.
if input_receiver_fn_map.get(model_fn_lib.ModeKeys.TRAIN):
self._add_meta_graph_for_mode(
builder, input_receiver_fn_map, checkpoint_path,
strip_default_attrs, save_variables,
mode=model_fn_lib.ModeKeys.TRAIN)
save_variables = False
if input_receiver_fn_map.get(model_fn_lib.ModeKeys.EVAL):
self._add_meta_graph_for_mode(
builder, input_receiver_fn_map, checkpoint_path,
strip_default_attrs, save_variables,
mode=model_fn_lib.ModeKeys.EVAL)
save_variables = False
if input_receiver_fn_map.get(model_fn_lib.ModeKeys.PREDICT):
self._add_meta_graph_for_mode(
builder, input_receiver_fn_map, checkpoint_path,
strip_default_attrs, save_variables,
mode=model_fn_lib.ModeKeys.PREDICT)
save_variables = False
if save_variables:
raise ValueError('No valid modes for exporting found. Got {}.'.format(
input_receiver_fn_map.keys()))
builder.save(as_text)
# Add the extra assets
if assets_extra:
assets_extra_path = os.path.join(compat.as_bytes(temp_export_dir),
compat.as_bytes('assets.extra'))
for dest_relative, source in assets_extra.items():
dest_absolute = os.path.join(compat.as_bytes(assets_extra_path),
compat.as_bytes(dest_relative))
dest_path = os.path.dirname(dest_absolute)
gfile.MakeDirs(dest_path)
gfile.Copy(source, dest_absolute)
gfile.Rename(temp_export_dir, export_dir)
return export_dir
def _add_meta_graph_for_mode(self,
builder,
input_receiver_fn_map,
checkpoint_path,
strip_default_attrs,
save_variables=True,
mode=model_fn_lib.ModeKeys.PREDICT,
export_tags=None,
check_variables=True):
# pylint: disable=line-too-long
"""Loads variables and adds them along with a `tf.MetaGraphDef` for saving.
Args:
builder: instance of `tf.saved_modle.builder.SavedModelBuilder` that will
be used for saving.
input_receiver_fn_map: dict of `tf.estimator.ModeKeys` to
`input_receiver_fn` mappings, where the `input_receiver_fn` is a
function that takes no argument and returns the appropriate subclass of
`InputReceiver`.
checkpoint_path: The checkpoint path to export. If `None` (the default),
the most recent checkpoint found within the model directory is chosen.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
removed from the `NodeDef`s. For a detailed guide, see [Stripping
Default-Valued
Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
save_variables: bool, whether variables should be saved. If `False`, just
the `tf.MetaGraphDef` will be saved. Note that `save_variables` should
only be `True` for the first call to this function, and the
`SavedModelBuilder` will raise an error if that is not the case.
mode: `tf.estimator.ModeKeys` value indicating which mode will be
exported.
export_tags: The set of tags with which to save `tf.MetaGraphDef`. If
`None`, a default set will be selected to matched the passed mode.
check_variables: bool, whether to check the checkpoint has all variables.
Raises:
ValueError: if `save_variables` is `True` and `check_variable` is `False`.
"""
# pylint: enable=line-too-long
if export_tags is None:
export_tags = model_fn_lib.EXPORT_TAG_MAP[mode]
input_receiver_fn = input_receiver_fn_map[mode]
with ops.Graph().as_default() as g:
self._create_and_assert_global_step(g)
random_seed.set_random_seed(self._config.tf_random_seed)
input_receiver = input_receiver_fn()
# Call the model_fn and collect the export_outputs.
estimator_spec = self._call_model_fn(
features=input_receiver.features,
labels=getattr(input_receiver, 'labels', None),
mode=mode,
config=self.config)
export_outputs = model_fn_lib.export_outputs_for_mode(
mode=estimator_spec.mode,
serving_export_outputs=estimator_spec.export_outputs,
predictions=estimator_spec.predictions,
loss=estimator_spec.loss,
metrics=estimator_spec.eval_metric_ops)
# Build the SignatureDefs from receivers and all outputs
signature_def_map = export_helpers.build_all_signature_defs(
input_receiver.receiver_tensors,
export_outputs,
getattr(input_receiver, 'receiver_tensors_alternatives', None),
serving_only=(mode == model_fn_lib.ModeKeys.PREDICT))
with tf_session.Session(config=self._session_config) as session:
if estimator_spec.scaffold.local_init_op is not None:
local_init_op = estimator_spec.scaffold.local_init_op
else:
local_init_op = monitored_session.Scaffold.default_local_init_op()
# This saver will be used both for restoring variables now,
# and in saving out the metagraph below. This ensures that any
# Custom Savers stored with the Scaffold are passed through to the
# SavedModel for restore later.
graph_saver = estimator_spec.scaffold.saver or saver.Saver(sharded=True)
if save_variables and not check_variables:
raise ValueError('If `save_variables` is `True, `check_variables`'
'must not be `False`.')
if check_variables:
try:
graph_saver.restore(session, checkpoint_path)
except errors.NotFoundError as e:
msg = ('Could not load all requested variables from checkpoint. '
'Please make sure your model_fn does not expect variables '
'that were not saved in the checkpoint.\n\n'
'Encountered error with mode `{}` while restoring '
'checkpoint from: `{}`. Full Traceback:\n\n{}').format(
mode, checkpoint_path, e)
raise ValueError(msg)
# We add the train op explicitly for now, so that we don't have to
# change the Builder public interface. Note that this is a no-op
# for prediction, where train_op is None.
builder._add_train_op(estimator_spec.train_op) # pylint: disable=protected-access
meta_graph_kwargs = dict(
tags=export_tags,
signature_def_map=signature_def_map,
assets_collection=ops.get_collection(
ops.GraphKeys.ASSET_FILEPATHS),
strip_default_attrs=strip_default_attrs,
legacy_init_op=local_init_op,
saver=graph_saver)
if save_variables:
builder.add_meta_graph_and_variables(
session, **meta_graph_kwargs)
else:
builder.add_meta_graph(**meta_graph_kwargs)
def _get_features_from_input_fn(self, input_fn, mode):
"""Extracts the `features` from return values of `input_fn`."""
result = self._call_input_fn(input_fn, mode)
result, _, hooks = estimator_util.parse_input_fn_result(result)
self._validate_features_in_predict_input(result)
return result, hooks
def _validate_features_in_predict_input(self, result):
if not _has_dataset_or_queue_runner(result):
logging.warning('Input graph does not use tf.data.Dataset or contain a '
'QueueRunner. That means predict yields forever. '
'This is probably a mistake.')
def _get_iterator_from_input_fn(self, input_fn, mode, distribution=None):
if distribution is not None:
result = distribution.distribute_dataset(
lambda: self._call_input_fn(input_fn, mode))
else:
result = self._call_input_fn(input_fn, mode)
iterator = result.make_initializable_iterator()
input_hooks = [estimator_util._DatasetInitializerHook(iterator)] # pylint: disable=protected-access
return iterator, input_hooks
def _get_features_and_labels_from_input_fn(self, input_fn, mode):
"""Extracts the `features` and labels from return values of `input_fn`."""
return estimator_util.parse_input_fn_result(
self._call_input_fn(input_fn, mode))
def _extract_batch_length(self, preds_evaluated):
"""Extracts batch length of predictions."""
batch_length = None
for key, value in six.iteritems(preds_evaluated):
batch_length = batch_length or value.shape[0]
if value.shape[0] != batch_length:
raise ValueError('Batch length of predictions should be same. %s has '
'different batch length than others.' % key)
return batch_length
def _extract_keys(self, predictions, predict_keys):
"""Extracts `predict_keys` from `predictions`."""
if not predict_keys:
return predictions
if not isinstance(predictions, dict):
raise ValueError(
'predict_keys argument is not valid in case of non-dict predictions.')
existing_keys = predictions.keys()
predictions = {
key: value
for key, value in six.iteritems(predictions) if key in predict_keys
}
if not predictions:
raise ValueError('Expected to run at least one output from %s, '
'provided %s.' % (existing_keys, predict_keys))
return predictions
def _create_global_step(self, graph):
"""Creates the global step tensor in graph.
The global step tensor must be an integer type with name 'global_step' and
be added to the collection @{tf.GraphKeys#GLOBAL_STEP$GLOBAL_STEP}.
Args:
graph: The graph in which to create the global step tensor.
Returns:
The global step `tf.Tensor`.
"""
return training.create_global_step(graph)
def _create_and_assert_global_step(self, graph):
"""Creates and asserts properties of the global step.
Args:
graph: The graph in which to create the global step tensor.
Returns:
The global step `tf.Tensor`.
"""
step = self._create_global_step(graph)
assert step == training.get_global_step()
assert step.dtype.is_integer
return step
def _call_input_fn(self, input_fn, mode):
"""Calls the input function.
Args:
input_fn: The input function.
mode: `tf.estimator.ModeKeys`
Returns:
The return value of the passed `input_fn`, which should be one of:
* A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a
tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a `Tensor` or a
dictionary of string feature name to `Tensor` and `labels` is a
`Tensor` or a dictionary of string label name to `Tensor`. Both
`features` and `labels` are consumed by `model_fn`. They should
satisfy the expectation of `model_fn` from inputs.
Raises:
ValueError: if `input_fn` takes invalid arguments.
"""
input_fn_args = function_utils.fn_args(input_fn)
kwargs = {}
if 'mode' in input_fn_args:
kwargs['mode'] = mode
if 'params' in input_fn_args:
kwargs['params'] = self.params
if 'config' in input_fn_args:
kwargs['config'] = self.config
with ops.device('/cpu:0'):
return input_fn(**kwargs)
def _call_model_fn(self, features, labels, mode, config):
"""Calls model function.
Args:
features: features dict.
labels: labels dict.
mode: `tf.estimator.ModeKeys`
config: `tf.estimator.RunConfig`
Returns:
An `tf.estimator.EstimatorSpec` object.
Raises:
ValueError: if `model_fn` returns invalid objects.
"""
model_fn_args = function_utils.fn_args(self._model_fn)
kwargs = {}
if 'labels' in model_fn_args:
kwargs['labels'] = labels
else:
if labels is not None:
raise ValueError(
'model_fn does not take labels, but input_fn returns labels.')
if 'mode' in model_fn_args:
kwargs['mode'] = mode
if 'params' in model_fn_args:
kwargs['params'] = self.params
if 'config' in model_fn_args:
kwargs['config'] = config
logging.info('Calling model_fn.')
model_fn_results = self._model_fn(features=features, **kwargs)
logging.info('Done calling model_fn.')
if not isinstance(model_fn_results, model_fn_lib.EstimatorSpec):
raise ValueError('model_fn should return an EstimatorSpec.')
return model_fn_results
def _train_model(self, input_fn, hooks, saving_listeners):
if self._train_distribution:
return self._train_model_distributed(input_fn, hooks, saving_listeners)
else:
return self._train_model_default(input_fn, hooks, saving_listeners)
def _train_model_default(self, input_fn, hooks, saving_listeners):
"""Initiate training with `input_fn`, without `DistributionStrategies`.
Args:
input_fn: A function that provides input data for training as minibatches.
hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
callbacks inside the training loop.
saving_listeners: list of `tf.train.CheckpointSaverListener` objects. Used
for callbacks that run immediately before or after checkpoint savings.
Returns:
Loss from training
"""
worker_hooks = []
with ops.Graph().as_default() as g, g.device(self._device_fn):
random_seed.set_random_seed(self._config.tf_random_seed)
global_step_tensor = self._create_and_assert_global_step(g)
# Skip creating a read variable if _create_and_assert_global_step
# returns None (e.g. tf.contrib.estimator.SavedModelEstimator).
if global_step_tensor is not None:
training_util._get_or_create_global_step_read(g) # pylint: disable=protected-access
features, labels, input_hooks = (
self._get_features_and_labels_from_input_fn(
input_fn, model_fn_lib.ModeKeys.TRAIN))
worker_hooks.extend(input_hooks)
estimator_spec = self._call_model_fn(
features, labels, model_fn_lib.ModeKeys.TRAIN, self.config)
global_step_tensor = training_util.get_global_step(g)
return self._train_with_estimator_spec(estimator_spec, worker_hooks,
hooks, global_step_tensor,
saving_listeners)
def _train_model_distributed(self, input_fn, hooks, saving_listeners):
"""Initiate training with `input_fn`, using `DistributionStrategies`.
Args:
input_fn: A function that provides input data for training as minibatches.
hooks: List of `tf.train.SessionRunHook` subclass instances. Used for
callbacks inside the training loop.
saving_listeners: list of `tf.train.CheckpointSaverListener` objects. Used
for callbacks that run immediately before or after checkpoint savings.
Returns:
Loss from training
"""
self._train_distribution.configure(self._session_config)
# TODO(sourabhbajaj): Remove this hack once we migrate the other strategies
# to use the new API
is_tpu_strategy = (
self._train_distribution.__class__.__name__ == 'TPUStrategy')
worker_hooks = []
with ops.Graph().as_default() as g:
# We want to create the iterations variable outside the distribution scope
# as that is just stored on the host and mainly used to drive the loop
# and doesn't need to be a Mirrored/Device variable.
if is_tpu_strategy:
steps_per_run_variable = training.get_or_create_steps_per_run_variable()
with self._train_distribution.scope():
random_seed.set_random_seed(self._config.tf_random_seed)
iterator, input_hooks = self._get_iterator_from_input_fn(
input_fn, model_fn_lib.ModeKeys.TRAIN, self._train_distribution)
worker_hooks.extend(input_hooks)
global_step_tensor = self._create_and_assert_global_step(g)
# we want to add to the global collection in the main thread not the
# tower threads.
ops.add_to_collection(
training_util.GLOBAL_STEP_READ_KEY,
self._train_distribution.read_var(global_step_tensor))
if is_tpu_strategy:
# Create a step_fn from the train_op of grouped_estimator_spec
def step_fn(ctx, features, labels=None):
"""A single step that is passed to run_on_dataset."""
estimator_spec = self._train_distribution.call_for_each_tower(
self._call_model_fn,
features,
labels,
model_fn_lib.ModeKeys.TRAIN,
self.config)
ctx.set_last_step_output(
name='loss',
output=estimator_spec.loss,
aggregation=distribute_lib.get_loss_reduction())
ctx.set_non_tensor_output(
name='estimator_spec', output=estimator_spec)
return estimator_spec.train_op
# Create new train_op post graph rewrites
initial_training_loss = constant_op.constant(1e7)
ctx = self._train_distribution.run_steps_on_dataset(
step_fn, iterator, iterations=steps_per_run_variable,
initial_loop_values={'loss': initial_training_loss})
distributed_train_op = ctx.run_op
loss = ctx.last_step_outputs['loss']
grouped_estimator_spec = ctx.non_tensor_outputs['estimator_spec']
else:
features, labels = estimator_util.parse_iterator_result(
iterator.get_next())
grouped_estimator_spec = self._train_distribution.call_for_each_tower(
self._call_model_fn,
features,
labels, # although this will be None it seems
model_fn_lib.ModeKeys.TRAIN,
self.config)
loss = self._train_distribution.unwrap(
self._train_distribution.reduce(
distribute_lib.get_loss_reduction(),
grouped_estimator_spec.loss,
destinations='/device:CPU:0'))[0]
distributed_train_op = grouped_estimator_spec.train_op
scaffold = _combine_distributed_scaffold(
grouped_estimator_spec.scaffold, self._train_distribution)
# TODO(yuefengz): add a test for unwrapping per_device_hooks.
def get_hooks_from_the_first_device(per_device_hooks):
return [
self._distribution.unwrap(per_device_hook)[0]
for per_device_hook in per_device_hooks
]
training_hooks = get_hooks_from_the_first_device(
grouped_estimator_spec.training_hooks)
training_chief_hooks = get_hooks_from_the_first_device(
grouped_estimator_spec.training_chief_hooks)
worker_hooks.append(
estimator_util.StrategyInitFinalizeHook(
self._train_distribution.initialize,
self._train_distribution.finalize))
estimator_spec = model_fn_lib.EstimatorSpec(
mode=grouped_estimator_spec.mode,
loss=loss,
train_op=self._train_distribution.group(distributed_train_op),
training_hooks=training_hooks,
training_chief_hooks=training_chief_hooks,
scaffold=scaffold)
return self._train_with_estimator_spec(estimator_spec, worker_hooks,
hooks, global_step_tensor,
saving_listeners)
def _train_with_estimator_spec(self, estimator_spec, worker_hooks, hooks,
global_step_tensor, saving_listeners):
"""Train a model with the given Estimator Spec."""
if self._warm_start_settings:
logging.info('Warm-starting with WarmStartSettings: %s' %
(self._warm_start_settings,))
warm_starting_util.warm_start(*self._warm_start_settings)
# Check if the user created a loss summary, and add one if they didn't.
# We assume here that the summary is called 'loss'. If it is not, we will
# make another one with the name 'loss' to ensure it shows up in the right
# graph in TensorBoard.
if not any([x.op.name == 'loss'
for x in ops.get_collection(ops.GraphKeys.SUMMARIES)]):
summary.scalar('loss', estimator_spec.loss)
ops.add_to_collection(ops.GraphKeys.LOSSES, estimator_spec.loss)
worker_hooks.extend(hooks)
worker_hooks.append(
training.NanTensorHook(estimator_spec.loss)
)
if self._config.log_step_count_steps is not None:
worker_hooks.append(
training.LoggingTensorHook(
{
'loss': estimator_spec.loss,
'step': global_step_tensor
},
every_n_iter=self._config.log_step_count_steps)
)
worker_hooks.extend(estimator_spec.training_hooks)
if not (estimator_spec.scaffold.saver or
ops.get_collection(ops.GraphKeys.SAVERS)):
ops.add_to_collection(
ops.GraphKeys.SAVERS,
training.Saver(
sharded=True,
max_to_keep=self._config.keep_checkpoint_max,
keep_checkpoint_every_n_hours=(
self._config.keep_checkpoint_every_n_hours),
defer_build=True,
save_relative_paths=True))
chief_hooks = []
all_hooks = worker_hooks + list(estimator_spec.training_chief_hooks)
saver_hooks = [
h for h in all_hooks if isinstance(h, training.CheckpointSaverHook)]
if (self._config.save_checkpoints_secs or
self._config.save_checkpoints_steps):
if not saver_hooks:
chief_hooks = [
training.CheckpointSaverHook(
self._model_dir,
save_secs=self._config.save_checkpoints_secs,
save_steps=self._config.save_checkpoints_steps,
scaffold=estimator_spec.scaffold)
]
saver_hooks = [chief_hooks[0]]
if saving_listeners:
if not saver_hooks:
raise ValueError(
'There should be a CheckpointSaverHook to use saving_listeners. '
'Please set one of the RunConfig.save_checkpoints_steps or '
'RunConfig.save_checkpoints_secs.')
else:
# It is expected to have one CheckpointSaverHook. If multiple, we pick
# up the first one to add listener.
saver_hooks[0]._listeners.extend(saving_listeners) # pylint: disable=protected-access
with training.MonitoredTrainingSession(
master=self._config.master,
is_chief=self._config.is_chief,
checkpoint_dir=self._model_dir,
scaffold=estimator_spec.scaffold,
hooks=worker_hooks,
chief_only_hooks=(
tuple(chief_hooks) + tuple(estimator_spec.training_chief_hooks)),
save_checkpoint_secs=0, # Saving is handled by a hook.
save_summaries_steps=self._config.save_summary_steps,
config=self._session_config,
log_step_count_steps=self._config.log_step_count_steps) as mon_sess:
loss = None
while not mon_sess.should_stop():
_, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss])
return loss
def _evaluate_build_graph(self, input_fn, hooks=None, checkpoint_path=None):
"""Builds the graph and related hooks to run evaluation."""
random_seed.set_random_seed(self._config.tf_random_seed)
self._create_and_assert_global_step(ops.get_default_graph())
if self._eval_distribution:
(scaffold, evaluation_hooks, input_hooks, update_op, eval_dict) = (
self._call_model_fn_eval_distributed(input_fn, self.config))
else:
(scaffold, evaluation_hooks, input_hooks, update_op, eval_dict) = (
self._call_model_fn_eval(input_fn, self.config))
global_step_tensor = training_util.get_global_step(ops.get_default_graph())
# Call to warm_start has to be after model_fn is called.
self._maybe_warm_start(checkpoint_path)
if ops.GraphKeys.GLOBAL_STEP in eval_dict:
raise ValueError(
'Metric with name `global_step` is not allowed, because Estimator '
'already defines a default metric with the same name.')
eval_dict[ops.GraphKeys.GLOBAL_STEP] = global_step_tensor
all_hooks = list(input_hooks)
all_hooks.extend(hooks)
all_hooks.extend(list(evaluation_hooks or []))
# New local variables have been added, so update the estimator spec's
# local init op if it was defined.
if scaffold and scaffold.local_init_op:
# Ensure that eval step has been created before updating local init op.
evaluation._get_or_create_eval_step() # pylint: disable=protected-access
scaffold = monitored_session.Scaffold(
local_init_op=control_flow_ops.group(
scaffold.local_init_op,
monitored_session.Scaffold.default_local_init_op()),
copy_from_scaffold=scaffold
)
return scaffold, update_op, eval_dict, all_hooks
def _call_model_fn_eval(self, input_fn, config):
"""Call model_fn for evaluation and handle return values."""
features, labels, input_hooks = self._get_features_and_labels_from_input_fn(
input_fn, model_fn_lib.ModeKeys.EVAL)
estimator_spec = self._call_model_fn(
features, labels, model_fn_lib.ModeKeys.EVAL, config)
eval_metric_ops = _verify_and_create_loss_metric(
estimator_spec.eval_metric_ops, estimator_spec.loss)
update_op, eval_dict = _extract_metric_update_ops(eval_metric_ops)
return (estimator_spec.scaffold, estimator_spec.evaluation_hooks,
input_hooks, update_op, eval_dict)
def _call_model_fn_eval_distributed(self, input_fn, config):
"""Call model_fn in distribution mode and handle return values."""
iterator, input_hooks = self._get_iterator_from_input_fn(
input_fn, model_fn_lib.ModeKeys.EVAL, self._eval_distribution)
is_tpu_strategy = (
self._eval_distribution.__class__.__name__ == 'TPUStrategy')
if is_tpu_strategy:
def step_fn(ctx, features, labels=None):
"""Runs one step of the eval computation and captures outputs."""
estimator_spec = self._eval_distribution.call_for_each_tower(
self._call_model_fn, features, labels, model_fn_lib.ModeKeys.EVAL,
config)
eval_metric_ops = _verify_and_create_loss_metric(
estimator_spec.eval_metric_ops, estimator_spec.loss,
self._eval_distribution)
update_op, eval_dict = _extract_metric_update_ops(
eval_metric_ops, self._eval_distribution)
ctx.set_non_tensor_output(name='estimator_spec', output=estimator_spec)
ctx.set_non_tensor_output(name='eval_dict', output=eval_dict)
return update_op
# TODO(priyag): Fix eval step hook to account for steps_per_run.
ctx = self._eval_distribution.run_steps_on_dataset(
step_fn, iterator, iterations=self._eval_distribution.steps_per_run)
update_op = ctx.run_op
eval_dict = ctx.non_tensor_outputs['eval_dict']
grouped_estimator_spec = ctx.non_tensor_outputs['estimator_spec']
else:
features, labels = estimator_util.parse_iterator_result(
iterator.get_next())
grouped_estimator_spec = self._eval_distribution.call_for_each_tower(
self._call_model_fn, features, labels,
model_fn_lib.ModeKeys.EVAL, config)
eval_metric_ops = _verify_and_create_loss_metric(
grouped_estimator_spec.eval_metric_ops, grouped_estimator_spec.loss,
self._eval_distribution)
update_op, eval_dict = _extract_metric_update_ops(
eval_metric_ops, self._eval_distribution)
scaffold = _combine_distributed_scaffold(
grouped_estimator_spec.scaffold, self._eval_distribution)
evaluation_hooks = self._eval_distribution.unwrap(
grouped_estimator_spec.evaluation_hooks)[0]
evaluation_hooks = evaluation_hooks + (
estimator_util.StrategyInitFinalizeHook(
self._eval_distribution.initialize,
self._eval_distribution.finalize),)
return (scaffold, evaluation_hooks, input_hooks, update_op, eval_dict)
def _evaluate_run(self, checkpoint_path, scaffold, update_op, eval_dict,
all_hooks, output_dir):
"""Run evaluation."""
eval_results = evaluation._evaluate_once( # pylint: disable=protected-access
checkpoint_path=checkpoint_path,
master=self._config.evaluation_master,
scaffold=scaffold,
eval_ops=update_op,
final_ops=eval_dict,
hooks=all_hooks,
config=self._session_config)
current_global_step = eval_results[ops.GraphKeys.GLOBAL_STEP]
_write_dict_to_summary(
output_dir=output_dir,
dictionary=eval_results,
current_global_step=current_global_step)
if checkpoint_path:
_write_checkpoint_path_to_summary(
output_dir=output_dir,
checkpoint_path=checkpoint_path,
current_global_step=current_global_step)
return eval_results
def _maybe_warm_start(self, checkpoint_path):
if not checkpoint_path and self._warm_start_settings:
logging.info('Warm-starting with WarmStartSettings: %s' %
(self._warm_start_settings,))
warm_starting_util.warm_start(*self._warm_start_settings)
def _verify_and_create_loss_metric(eval_metric_ops, loss, distribution=None):
"""Creates a metric for loss and throws an error if one already exists."""
if model_fn_lib.LOSS_METRIC_KEY in eval_metric_ops:
raise ValueError(
'Metric with name "%s" is not allowed, because Estimator ' %
(model_fn_lib.LOSS_METRIC_KEY) +
'already defines a default metric with the same name.')
if distribution is None:
loss_metric = metrics_lib.mean(loss)
else:
loss_metric = distribution.call_for_each_tower(
metrics_lib.mean, loss)
eval_metric_ops[model_fn_lib.LOSS_METRIC_KEY] = loss_metric
return eval_metric_ops
def maybe_overwrite_model_dir_and_session_config(config, model_dir):
"""Overwrite estimator config by `model_dir` and `session_config` if needed.
Args:
config: Original estimator config.
model_dir: Estimator model checkpoint directory.
Returns:
Overwritten estimator config.
Raises:
ValueError: Model directory inconsistent between `model_dir` and `config`.
"""
if config is None:
config = run_config.RunConfig()
logging.info('Using default config.')
if not isinstance(config, run_config.RunConfig):
raise ValueError(
'config must be an instance of `RunConfig`, but provided %s.' % config)
if config.session_config is None:
session_config = run_config.get_default_session_config()
config = run_config.RunConfig.replace(config, session_config=session_config)
model_dir = compat_internal.path_to_str(model_dir)
if model_dir is not None:
if (getattr(config, 'model_dir', None) is not None and
config.model_dir != model_dir):
raise ValueError(
"`model_dir` are set both in constructor and `RunConfig`, but with "
"different values. In constructor: '{}', in `RunConfig`: "
"'{}' ".format(model_dir, config.model_dir))
if model_dir:
config = run_config.RunConfig.replace(config, model_dir=model_dir)
elif getattr(config, 'model_dir', None) is None:
model_dir = tempfile.mkdtemp()
logging.warning('Using temporary folder as model directory: %s', model_dir)
config = run_config.RunConfig.replace(config, model_dir=model_dir)
return config
def create_per_tower_ready_for_local_init_op(scaffold):
"""Create a `tf.train.Scaffold.ready_for_local_init_op` inside a tower."""
if scaffold.ready_for_local_init_op:
return scaffold.ready_for_local_init_op
def default_ready_for_local_init_op():
return variables.report_uninitialized_variables(
variables.global_variables())
return monitored_session.Scaffold.get_or_default(
'ready_for_local_init_op', ops.GraphKeys.READY_FOR_LOCAL_INIT_OP,
default_ready_for_local_init_op)
def _combine_distributed_scaffold(grouped_scaffold, distribution):
"""Combines scaffold(s) returned from `distribution.call_for_each_tower`."""
# TODO(anjalisridhar): Figure out how to resolve the following scaffold
# parameters: init_feed_dict, init_fn.
scaffold_list = distribution.unwrap(grouped_scaffold)
init_feed_dict = [
s.init_feed_dict
for s in scaffold_list
if s.init_feed_dict is not None
]
if init_feed_dict:
init_feed_dict = distribution.group(init_feed_dict)
else:
init_feed_dict = None
init_fn = [s.init_fn for s in scaffold_list if s.init_fn is not None]
if init_fn:
init_fn = distribution.group(init_fn)
else:
init_fn = None
init_op = [s.init_op for s in scaffold_list if s.init_op is not None]
if init_op:
init_op = distribution.group(init_op)
else:
init_op = None
def _unwrap_and_concat(value):
value = nest.flatten(distribution.unwrap(value))
if len(value) != 1:
return array_ops.concat(value, 0)
return value[0]
ready_op = distribution.call_for_each_tower(
lambda scaffold: scaffold.ready_op, grouped_scaffold)
if ready_op is not None:
ready_op = _unwrap_and_concat(ready_op)
ready_for_local_init_op = distribution.call_for_each_tower(
create_per_tower_ready_for_local_init_op, grouped_scaffold)
if ready_for_local_init_op is not None:
ready_for_local_init_op = _unwrap_and_concat(ready_for_local_init_op)
else:
ready_for_local_init_op = None
local_init_op = [
s.local_init_op
for s in scaffold_list
if s.local_init_op is not None
]
if local_init_op:
local_init_op = distribution.group(local_init_op)
else:
local_init_op = None
summary_op = [
s.summary_op for s in scaffold_list if s.summary_op is not None
]
if summary_op:
summary_op = distribution.group(summary_op)
else:
summary_op = None
scaffold = monitored_session.Scaffold(
init_op=init_op,
ready_op=ready_op,
ready_for_local_init_op=ready_for_local_init_op,
local_init_op=local_init_op,
summary_op=summary_op,
init_feed_dict=init_feed_dict,
init_fn=init_fn)
return scaffold
def _check_checkpoint_available(model_dir):
latest_path = checkpoint_management.latest_checkpoint(model_dir)
if not latest_path:
raise ValueError(
'Could not find trained model in model_dir: {}.'.format(model_dir))
def _check_hooks_type(hooks):
"""Returns hooks if all are `SessionRunHook`, raises TypeError otherwise."""
hooks = list(hooks or [])
for h in hooks:
if not isinstance(h, training.SessionRunHook):
raise TypeError('Hooks must be a SessionRunHook, given: {}'.format(h))
return hooks
def _check_listeners_type(saving_listeners):
"""Check listeners type."""
listeners = list(saving_listeners or [])
for l in listeners:
if not isinstance(l, training.CheckpointSaverListener):
raise TypeError(
'saving_listeners must be a list of CheckpointSaverListener, '
'given: {}'.format(l))
return listeners
def _get_replica_device_setter(config):
"""Creates a replica device setter if required as a default `device_fn`.
`Estimator` uses `tf.train.ReplicaDeviceSetter` as a default device placer. It
sets the
distributed related arguments such as number of `ps_replicas` based on given
`config`.
Args:
config: A `tf.estimator.RunConfig` instance.
Returns:
A replica device setter, or `None`.
"""
if config.task_type:
worker_device = '/job:%s/task:%d' % (config.task_type, config.task_id)
else:
worker_device = '/job:worker'
if config.num_ps_replicas > 0:
return training.replica_device_setter(
ps_tasks=config.num_ps_replicas,
worker_device=worker_device,
merge_devices=True,
ps_ops=list(device_setter.STANDARD_PS_OPS),
cluster=config.cluster_spec)
else:
return None
def _verify_model_fn_args(model_fn, params):
"""Verifies `model_fn` arguments."""
args = set(function_utils.fn_args(model_fn))
if 'features' not in args:
raise ValueError('model_fn (%s) must include features argument.' % model_fn)
if params is not None and 'params' not in args:
raise ValueError('model_fn (%s) does not include params argument, '
'but params (%s) is passed to Estimator.' % (model_fn,
params))
if params is None and 'params' in args:
logging.warning('Estimator\'s model_fn (%s) includes params '
'argument, but params are not passed to Estimator.',
model_fn)
non_valid_args = list(args - _VALID_MODEL_FN_ARGS)
if non_valid_args:
raise ValueError('model_fn (%s) has following not expected args: %s' %
(model_fn, non_valid_args))
def _load_global_step_from_checkpoint_dir(checkpoint_dir):
try:
checkpoint_reader = training.NewCheckpointReader(
training.latest_checkpoint(checkpoint_dir))
return checkpoint_reader.get_tensor(ops.GraphKeys.GLOBAL_STEP)
except: # pylint: disable=bare-except
return 0
def _extract_metric_update_ops(eval_dict, distribution=None):
"""Separate update operations from metric value operations."""
update_ops = []
value_ops = {}
# Sort metrics lexicographically so graph is identical every time.
for name, value in sorted(six.iteritems(eval_dict)):
value_ops[name] = value[0]
update_ops.append(
distribution.group(value[1]) if distribution else value[1])
update_op = control_flow_ops.group(*update_ops) if update_ops else None
return update_op, value_ops
def _dict_to_str(dictionary):
"""Get a `str` representation of a `dict`.
Args:
dictionary: The `dict` to be represented as `str`.
Returns:
A `str` representing the `dictionary`.
"""
return ', '.join('%s = %s' % (k, v)
for k, v in sorted(six.iteritems(dictionary))
if not isinstance(v, six.binary_type))
def _write_dict_to_summary(output_dir,
dictionary,
current_global_step):
"""Writes a `dict` into summary file in given output directory.
Args:
output_dir: `str`, directory to write the summary file in.
dictionary: the `dict` to be written to summary file.
current_global_step: `int`, the current global step.
"""
logging.info('Saving dict for global step %d: %s', current_global_step,
_dict_to_str(dictionary))
summary_writer = writer_cache.FileWriterCache.get(output_dir)
summary_proto = summary_pb2.Summary()
for key in dictionary:
if dictionary[key] is None:
continue
if key == 'global_step':
continue
if (isinstance(dictionary[key], np.float32) or
isinstance(dictionary[key], float)):
summary_proto.value.add(tag=key, simple_value=float(dictionary[key]))
elif (isinstance(dictionary[key], np.int64) or
isinstance(dictionary[key], np.int32) or
isinstance(dictionary[key], int)):
summary_proto.value.add(tag=key, simple_value=int(dictionary[key]))
elif isinstance(dictionary[key], six.binary_type):
try:
summ = summary_pb2.Summary.FromString(dictionary[key])
for i, _ in enumerate(summ.value):
summ.value[i].tag = '%s/%d' % (key, i)
summary_proto.value.extend(summ.value)
except message.DecodeError:
logging.warn('Skipping summary for %s, cannot parse string to Summary.',
key)
continue
elif isinstance(dictionary[key], np.ndarray):
value = summary_proto.value.add()
value.tag = key
value.node_name = key
tensor_proto = tensor_util.make_tensor_proto(dictionary[key])
value.tensor.CopyFrom(tensor_proto)
# pylint: disable=line-too-long
logging.info(
'Summary for np.ndarray is not visible in Tensorboard by default. '
'Consider using a Tensorboard plugin for visualization (see '
'https://github.com/tensorflow/tensorboard-plugin-example/blob/master/README.md'
' for more information).')
# pylint: enable=line-too-long
else:
logging.warn(
'Skipping summary for %s, must be a float, np.float32, np.int64, '
'np.int32 or int or np.ndarray or a serialized string of Summary.',
key)
summary_writer.add_summary(summary_proto, current_global_step)
summary_writer.flush()
def _write_checkpoint_path_to_summary(output_dir, checkpoint_path,
current_global_step):
"""Writes `checkpoint_path` into summary file in the given output directory.
Args:
output_dir: `str`, directory to write the summary file in.
checkpoint_path: `str`, checkpoint file path to be written to summary file.
current_global_step: `int`, the current global step.
"""
checkpoint_path_tag = 'checkpoint_path'
logging.info('Saving \'%s\' summary for global step %d: %s',
checkpoint_path_tag, current_global_step, checkpoint_path)
summary_proto = summary_pb2.Summary()
summary_proto.value.add(
tag=checkpoint_path_tag,
tensor=tensor_util.make_tensor_proto(
checkpoint_path, dtype=dtypes.string))
summary_writer = writer_cache.FileWriterCache.get(output_dir)
summary_writer.add_summary(summary_proto, current_global_step)
summary_writer.flush()
def _has_dataset_or_queue_runner(maybe_tensor):
"""Returns `True` if `Dataset` or `QueueRunner` has been used."""
# Check TF dataset first. Here, we use a simple algorithm to check the top
# level Tensors only, which should be sufficient for most users.
tensors = [x for x in nest.flatten(maybe_tensor) if isinstance(x, ops.Tensor)]
if any([t.op.type == 'IteratorGetNext' for t in tensors]):
return True
# Now, check queue.
return ops.get_default_graph().get_collection(ops.GraphKeys.QUEUE_RUNNERS)
VocabInfo = warm_starting_util.VocabInfo # pylint: disable=invalid-name
estimator_export('estimator.VocabInfo')(VocabInfo)
@estimator_export('estimator.WarmStartSettings')
class WarmStartSettings(
collections.namedtuple('WarmStartSettings', [
'ckpt_to_initialize_from',
'vars_to_warm_start',
'var_name_to_vocab_info',
'var_name_to_prev_var_name',
])):
"""Settings for warm-starting in `tf.estimator.Estimators`.
Example Use with canned `tf.estimator.DNNEstimator`:
```
emb_vocab_file = tf.feature_column.embedding_column(
tf.feature_column.categorical_column_with_vocabulary_file(
"sc_vocab_file", "new_vocab.txt", vocab_size=100),
dimension=8)
emb_vocab_list = tf.feature_column.embedding_column(
tf.feature_column.categorical_column_with_vocabulary_list(
"sc_vocab_list", vocabulary_list=["a", "b"]),
dimension=8)
estimator = tf.estimator.DNNClassifier(
hidden_units=[128, 64], feature_columns=[emb_vocab_file, emb_vocab_list],
warm_start_from=ws)
```
where `ws` could be defined as:
Warm-start all weights in the model (input layer and hidden weights).
Either the directory or a specific checkpoint can be provided (in the case
of the former, the latest checkpoint will be used):
```
ws = WarmStartSettings(ckpt_to_initialize_from="/tmp")
ws = WarmStartSettings(ckpt_to_initialize_from="/tmp/model-1000")
```
Warm-start only the embeddings (input layer):
```
ws = WarmStartSettings(ckpt_to_initialize_from="/tmp",
vars_to_warm_start=".*input_layer.*")
```
Warm-start all weights but the embedding parameters corresponding to
`sc_vocab_file` have a different vocab from the one used in the current
model:
```
vocab_info = tf.estimator.VocabInfo(
new_vocab=sc_vocab_file.vocabulary_file,
new_vocab_size=sc_vocab_file.vocabulary_size,
num_oov_buckets=sc_vocab_file.num_oov_buckets,
old_vocab="old_vocab.txt"
)
ws = WarmStartSettings(
ckpt_to_initialize_from="/tmp",
var_name_to_vocab_info={
"input_layer/sc_vocab_file_embedding/embedding_weights": vocab_info
})
```
Warm-start only `sc_vocab_file` embeddings (and no other variables), which
have a different vocab from the one used in the current model:
```
vocab_info = tf.estimator.VocabInfo(
new_vocab=sc_vocab_file.vocabulary_file,
new_vocab_size=sc_vocab_file.vocabulary_size,
num_oov_buckets=sc_vocab_file.num_oov_buckets,
old_vocab="old_vocab.txt"
)
ws = WarmStartSettings(
ckpt_to_initialize_from="/tmp",
vars_to_warm_start=None,
var_name_to_vocab_info={
"input_layer/sc_vocab_file_embedding/embedding_weights": vocab_info
})
```
Warm-start all weights but the parameters corresponding to `sc_vocab_file`
have a different vocab from the one used in current checkpoint, and only
100 of those entries were used:
```
vocab_info = tf.estimator.VocabInfo(
new_vocab=sc_vocab_file.vocabulary_file,
new_vocab_size=sc_vocab_file.vocabulary_size,
num_oov_buckets=sc_vocab_file.num_oov_buckets,
old_vocab="old_vocab.txt",
old_vocab_size=100
)
ws = WarmStartSettings(
ckpt_to_initialize_from="/tmp",
var_name_to_vocab_info={
"input_layer/sc_vocab_file_embedding/embedding_weights": vocab_info
})
```
Warm-start all weights but the parameters corresponding to `sc_vocab_file`
have a different vocab from the one used in current checkpoint and the
parameters corresponding to `sc_vocab_list` have a different name from the
current checkpoint:
```
vocab_info = tf.estimator.VocabInfo(
new_vocab=sc_vocab_file.vocabulary_file,
new_vocab_size=sc_vocab_file.vocabulary_size,
num_oov_buckets=sc_vocab_file.num_oov_buckets,
old_vocab="old_vocab.txt",
old_vocab_size=100
)
ws = WarmStartSettings(
ckpt_to_initialize_from="/tmp",
var_name_to_vocab_info={
"input_layer/sc_vocab_file_embedding/embedding_weights": vocab_info
},
var_name_to_prev_var_name={
"input_layer/sc_vocab_list_embedding/embedding_weights":
"old_tensor_name"
})
```
Attributes:
ckpt_to_initialize_from: [Required] A string specifying the directory with
checkpoint file(s) or path to checkpoint from which to warm-start the
model parameters.
vars_to_warm_start: [Optional] One of the following: - A regular expression
(string) that captures which variables to warm-start (see
`tf.get_collection`). This expression will only consider variables in the
`TRAINABLE_VARIABLES` collection. - A list of Variables to warm-start. - A
list of strings, each representing a full variable name to warm-start. -
`None`, in which case only variables specified in `var_name_to_vocab_info`
will be warm-started. Defaults to `'.*'`, which warm-starts all variables
in the `TRAINABLE_VARIABLES` collection. Note that this excludes
variables such as accumulators and moving statistics from batch norm.
var_name_to_vocab_info: [Optional] Dict of variable names (strings) to
`tf.estimator.VocabInfo`. The variable names should be "full" variables,
not the names of the partitions. If not explicitly provided, the variable
is assumed to have no (changes to) vocabulary.
var_name_to_prev_var_name: [Optional] Dict of variable names (strings) to
name of the previously-trained variable in `ckpt_to_initialize_from`. If
not explicitly provided, the name of the variable is assumed to be same
between previous checkpoint and current model.
"""
def __new__(cls,
ckpt_to_initialize_from,
vars_to_warm_start='.*',
var_name_to_vocab_info=None,
var_name_to_prev_var_name=None):
if not ckpt_to_initialize_from:
raise ValueError(
'`ckpt_to_initialize_from` MUST be set in WarmStartSettings')
return super(WarmStartSettings, cls).__new__(
cls,
ckpt_to_initialize_from,
vars_to_warm_start,
var_name_to_vocab_info or {},
var_name_to_prev_var_name or {},
)
def _get_saved_model_ckpt(saved_model_dir):
"""Return path to variables checkpoint in a `SavedModel` directory."""
if not gfile.Exists(
os.path.join(saved_model_utils.get_variables_dir(saved_model_dir),
compat.as_text('variables.index'))):
raise ValueError('Directory provided has an invalid SavedModel format: %s'
% saved_model_dir)
return saved_model_utils.get_variables_path(saved_model_dir)
def _get_default_warm_start_settings(warm_start_from):
"""Returns default `tf.estimator.WarmStartSettings`.
Args:
warm_start_from: Either a string representing the filepath of a checkpoint
or `SavedModel` to initialize from, or an instance of
`tf.estimator.WarmStartSettings`.
Returns:
Either None or an instance of `WarmStartSettings`.
Raises:
ValueError: If `warm_start_from` is not `None` but is neither a string nor
an
instance of `WarmStartSettings`.
"""
if warm_start_from is None:
return None
if isinstance(warm_start_from, (six.string_types, six.binary_type)):
# Infer that this is a SavedModel if export_path +
# 'variables/variables.index' exists, and if so, construct the
# WarmStartSettings pointing to the variables path
# (export_path + 'variables/variables').
if gfile.Exists(os.path.join(
saved_model_utils.get_variables_dir(warm_start_from),
compat.as_text('variables.index'))):
logging.info('Warm-starting from a SavedModel')
return WarmStartSettings(
ckpt_to_initialize_from=saved_model_utils.get_variables_path(
warm_start_from))
return WarmStartSettings(ckpt_to_initialize_from=warm_start_from)
elif isinstance(warm_start_from, WarmStartSettings):
return warm_start_from
else:
raise ValueError('warm_start_from must be a string or a WarmStartSettings, '
'instead got {}'.format(type(warm_start_from)))
| xodus7/tensorflow | tensorflow/python/estimator/estimator.py | Python | apache-2.0 | 89,962 |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required(login_url='/accounts/login/')
def home(request):
return render(request, "base/index.html", {})
def home_files(request, filename):
return render(request, filename, {}, content_type="text/plain")
| MVilstrup/Django-Base | Base/views.py | Python | apache-2.0 | 339 |
#
# Copyright (c) 2021 Project CHIP Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from chip.native import GetLibraryHandle, NativeLibraryHandleMethodArguments
from chip.exceptions import ChipStackError
from ctypes import CFUNCTYPE, c_char_p, c_int32, c_uint8
class SetupPayload:
# AttributeVisitor: void(const char* name, const char* value)
AttributeVisitor = CFUNCTYPE(None, c_char_p, c_char_p)
# VendorAttributeVisitor: void(uint8_t tag, const char* value)
VendorAttributeVisitor = CFUNCTYPE(None, c_uint8, c_char_p)
def __init__(self):
self.chipLib = GetLibraryHandle()
self.__InitNativeFunctions(self.chipLib)
self.attributes = {}
self.vendor_attributes = {}
def AddAttribute(name, value):
self.attributes[name.decode()] = value.decode()
def AddVendorAttribute(tag, value):
self.vendor_attributes[tag] = value.decode()
self.attribute_visitor = SetupPayload.AttributeVisitor(AddAttribute)
self.vendor_attribute_visitor = SetupPayload.VendorAttributeVisitor(
AddVendorAttribute)
def ParseQrCode(self, qrCode: str):
self.Clear()
err = self.chipLib.pychip_SetupPayload_ParseQrCode(qrCode.upper().encode(),
self.attribute_visitor,
self.vendor_attribute_visitor)
if err != 0:
raise ChipStackError(err)
return self
def ParseManualPairingCode(self, manualPairingCode: str):
self.Clear()
err = self.chipLib.pychip_SetupPayload_ParseManualPairingCode(manualPairingCode.encode(),
self.attribute_visitor,
self.vendor_attribute_visitor)
if err != 0:
raise ChipStackError(err)
return self
def PrintOnboardingCodes(self, passcode, vendorId, productId, discriminator, customFlow, capabilities, version):
self.Clear()
err = self.chipLib.pychip_SetupPayload_PrintOnboardingCodes(
passcode, vendorId, productId, discriminator, customFlow, capabilities, version)
if err != 0:
raise ChipStackError(err)
def Print(self):
for name, value in self.attributes.items():
decorated_value = self.__DecorateValue(name, value)
decorated_value = f" [{decorated_value}]" if decorated_value else ""
print(f"{name}: {value}{decorated_value}")
for tag in self.vendor_attributes:
print(
f"Vendor attribute '{tag:>3}': {self.vendor_attributes[tag]}")
def Clear(self):
self.attributes.clear()
self.vendor_attributes.clear()
def __DecorateValue(self, name, value):
if name == "RendezvousInformation":
rendezvous_methods = []
if int(value) & 0b001:
rendezvous_methods += ["SoftAP"]
if int(value) & 0b010:
rendezvous_methods += ["BLE"]
if int(value) & 0b100:
rendezvous_methods += ["OnNetwork"]
return ', '.join(rendezvous_methods)
return None
def __InitNativeFunctions(self, chipLib):
if chipLib.pychip_SetupPayload_ParseQrCode is not None:
return
setter = NativeLibraryHandleMethodArguments(chipLib)
setter.Set("pychip_SetupPayload_ParseQrCode",
c_int32,
[c_char_p, SetupPayload.AttributeVisitor, SetupPayload.VendorAttributeVisitor])
setter.Set("pychip_SetupPayload_ParseManualPairingCode",
c_int32,
[c_char_p, SetupPayload.AttributeVisitor, SetupPayload.VendorAttributeVisitor])
setter.Set("pychip_SetupPayload_PrintOnboardingCodes",
c_int32,
[c_uint32, c_uint16, c_uint16, c_uint16, uint8_t, uint8_t, uint8_t])
| project-chip/connectedhomeip | src/controller/python/chip/setup_payload/setup_payload.py | Python | apache-2.0 | 4,568 |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import multiprocessing
__all__ = ['MultiSlotDataGenerator']
class DataGenerator(object):
def __init__(self):
self._proto_info = None
def _set_filelist(self, filelist):
if not isinstance(filelist, list) and not isinstance(filelist, tuple):
raise ValueError("filelist%s must be in list or tuple type" %
type(filelist))
if not filelist:
raise ValueError("filelist can not be empty")
self._filelist = filelist
def _set_process_num(self, process_num):
if not isinstance(process_num, int):
raise ValueError("process_num%s must be in int type" %
type(process_num))
if process_num < 1:
raise ValueError("process_num can not less than 1")
self._process_num = process_num
def _set_line_limit(self, line_limit):
if not isinstance(line_limit, int):
raise ValueError("line_limit%s must be in int type" %
type(line_limit))
if line_limit < 1:
raise ValueError("line_limit can not less than 1")
self._line_limit = line_limit
def _set_output_dir(self, output_dir):
if not isinstance(output_dir, str):
raise ValueError("output_dir%s must be in str type" %
type(output_dir))
if not output_dir:
raise ValueError("output_dir can not be empty")
self._output_dir = output_dir
def _set_output_prefix(self, output_prefix):
if not isinstance(output_prefix, str):
raise ValueError("output_prefix%s must be in str type" %
type(output_prefix))
self._output_prefix = output_prefix
def _set_output_fill_digit(self, output_fill_digit):
if not isinstance(output_fill_digit, int):
raise ValueError("output_fill_digit%s must be in int type" %
type(output_fill_digit))
if output_fill_digit < 1:
raise ValueError("output_fill_digit can not less than 1")
self._output_fill_digit = output_fill_digit
def _set_proto_filename(self, proto_filename):
if not isinstance(proto_filename, str):
raise ValueError("proto_filename%s must be in str type" %
type(proto_filename))
if not proto_filename:
raise ValueError("proto_filename can not be empty")
self._proto_filename = proto_filename
def _print_info(self):
'''
Print the configuration information
(Called only in the run_from_stdin function).
'''
sys.stderr.write("=" * 16 + " config " + "=" * 16 + "\n")
sys.stderr.write(" filelist size: %d\n" % len(self._filelist))
sys.stderr.write(" process num: %d\n" % self._process_num)
sys.stderr.write(" line limit: %d\n" % self._line_limit)
sys.stderr.write(" output dir: %s\n" % self._output_dir)
sys.stderr.write(" output prefix: %s\n" % self._output_prefix)
sys.stderr.write(" output fill digit: %d\n" % self._output_fill_digit)
sys.stderr.write(" proto filename: %s\n" % self._proto_filename)
sys.stderr.write("==== This may take a few minutes... ====\n")
def _get_output_filename(self, output_index, lock=None):
'''
This function is used to get the name of the output file and
update output_index.
Args:
output_index(manager.Value(i)): the index of output file.
lock(manager.Lock): The lock for processes safe.
Return:
Return the name(string) of output file.
'''
if lock is not None: lock.acquire()
file_index = output_index.value
output_index.value += 1
if lock is not None: lock.release()
filename = os.path.join(self._output_dir, self._output_prefix) \
+ str(file_index).zfill(self._output_fill_digit)
sys.stderr.write("[%d] write data to file: %s\n" %
(os.getpid(), filename))
return filename
def run_from_stdin(self,
is_local=True,
hadoop_host=None,
hadoop_ugi=None,
proto_path=None,
proto_filename="data_feed.proto"):
'''
This function reads the data row from stdin, parses it with the
process function, and further parses the return value of the
process function with the _gen_str function. The parsed data will
be wrote to stdout and the corresponding protofile will be
generated. If local is set to False, the protofile will be
uploaded to hadoop.
Args:
is_local(bool): Whether to execute locally. If it is False, the
protofile will be uploaded to hadoop. The
default value is True.
hadoop_host(str): The host name of the hadoop. It should be
in this format: "hdfs://${HOST}:${PORT}".
hadoop_ugi(str): The ugi of the hadoop. It should be in this
format: "${USERNAME},${PASSWORD}".
proto_path(str): The hadoop path you want to upload the
protofile to.
proto_filename(str): The name of protofile. The default value
is "data_feed.proto". It is not
recommended to modify it.
'''
if is_local:
print \
'''\033[1;34m=======================================================
Pay attention to that the version of Python in Hadoop
may inconsistent with local version. Please check the
Python version of Hadoop to ensure that it is >= 2.7.
=======================================================\033[0m'''
else:
if hadoop_ugi is None or \
hadoop_host is None or \
proto_path is None:
raise ValueError(
"pls set hadoop_ugi, hadoop_host, and proto_path")
self._set_proto_filename(proto_filename)
for line in sys.stdin:
user_parsed_line = self.process(line)
sys.stdout.write(self._gen_str(user_parsed_line))
if self._proto_info is not None:
# maybe some task do not catch files
with open(self._proto_filename, "w") as f:
f.write(self._get_proto_desc(self._proto_info))
if is_local == False:
cmd = "$HADOOP_HOME/bin/hadoop fs" \
+ " -Dhadoop.job.ugi=" + hadoop_ugi \
+ " -Dfs.default.name=" + hadoop_host \
+ " -put " + self._proto_filename + " " + proto_path
os.system(cmd)
def run_from_files(self,
filelist,
line_limit,
process_num=1,
output_dir="./output_dataset",
output_prefix="part-",
output_fill_digit=8,
proto_filename="data_feed.proto"):
'''
This function will run process_num processes to process the files
in the filelist. It will create the output data folder(output_dir)
in the current directory, and write the processed data into the
output_dir folder(each file line_limit data, the prefix of filename
is output_prefix, the suffix of filename is output_fill_digit
numbers). And the proto_info is generated at the same time. the
name of proto file will be proto_filename.
Args:
filelist(list or tuple): Files that need to be processed.
line_limit(int): Maximum number of data stored per file.
process_num(int): Number of processes running simultaneously.
output_dir(str): The name of the folder where the output
data file is stored.
output_prefix(str): The prefix of output data file.
output_fill_digit(int): The number of suffix numbers of the
output data file.
proto_filename(str): The name of protofile.
'''
self._set_filelist(filelist)
self._set_line_limit(line_limit)
self._set_process_num(min(process_num, len(filelist)))
self._set_output_dir(output_dir)
self._set_output_prefix(output_prefix)
self._set_output_fill_digit(output_fill_digit)
self._set_proto_filename(proto_filename)
self._print_info()
if not os.path.exists(self._output_dir):
os.makedirs(self._output_dir)
elif not os.path.isdir(self._output_dir):
raise ValueError("%s is not a directory" % self._output_dir)
processes = multiprocessing.Pool()
manager = multiprocessing.Manager()
output_index = manager.Value('i', 0)
file_queue = manager.Queue()
lock = manager.Lock()
remaining_queue = manager.Queue()
for file in self._filelist:
file_queue.put(file)
info_result = []
for i in range(self._process_num):
info_result.append(processes.apply_async(subprocess_wrapper, \
(self, file_queue, remaining_queue, output_index, lock, )))
processes.close()
processes.join()
infos = [
result.get() for result in info_result if result.get() is not None
]
proto_info = self._combine_infos(infos)
with open(os.path.join(self._output_dir, self._proto_filename),
"w") as f:
f.write(self._get_proto_desc(proto_info))
while not remaining_queue.empty():
with open(self._get_output_filename(output_index), "w") as f:
for i in range(min(self._line_limit, remaining_queue.qsize())):
f.write(remaining_queue.get(False))
def _subprocess(self, file_queue, remaining_queue, output_index, lock):
'''
This function will be called by multiple processes. It is used to
continuously fetch files from file_queue, using process() function
(defined by user) and _gen_str() function(defined by concrete classes)
to process data in units of rows. Write the processed data to the
file(each file will be self._line_limit line). If the file in the
file_queue has been consumed, but the file is not full, the data
that is less than the self._line_limit line will be stored in the
remaining_queue.
Args:
file_queue(manager.Queue): The queue contains all the file
names to be processed.
remaining_queue(manager.Queue): The queue contains the data that
is less than the self._line_limit
line.
output_index(manager.Value(i)): The index(suffix) of the
output file.
lock(manager.Lock): The lock for processes safe.
Returns:
Return a proto_info which can be translated into a proto string.
'''
buffer = []
while not file_queue.empty():
try:
filename = file_queue.get(False)
except: # file_queue empty
break
with open(filename, 'r') as f:
for line in f:
buffer.append(self._gen_str(self.process(line)))
if len(buffer) == self._line_limit:
with open(
self._get_output_filename(output_index, lock),
"w") as wf:
for x in buffer:
wf.write(x)
buffer = []
if buffer:
for x in buffer:
remaining_queue.put(x)
return self._proto_info
def _gen_str(self, line):
'''
Further processing the output of the process() function rewritten by
user, outputting data that can be directly read by the datafeed,and
updating proto_info infomation.
Args:
line(str): the output of the process() function rewritten by user.
Returns:
Return a string data that can be read directly by the datafeed.
'''
raise NotImplementedError(
"pls use MultiSlotDataGenerator or PairWiseDataGenerator")
def _combine_infos(self, infos):
'''
This function is used to merge proto_info information from different
processes. In general, the proto_info of each process is consistent.
Args:
infos(list): the list of proto_infos from different processes.
Returns:
Return a unified proto_info.
'''
raise NotImplementedError(
"pls use MultiSlotDataGenerator or PairWiseDataGenerator")
def _get_proto_desc(self, proto_info):
'''
This function outputs the string of the proto file(can be directly
written to the file) according to the proto_info information.
Args:
proto_info: The proto information used to generate the proto
string. The type of the variable will be determined
by the subclass. In the MultiSlotDataGenerator,
proto_info variable is a list of tuple.
Returns:
Returns a string of the proto file.
'''
raise NotImplementedError(
"pls use MultiSlotDataGenerator or PairWiseDataGenerator")
def process(self, line):
'''
This function needs to be overridden by the user to process the
original data row into a list or tuple.
Args:
line(str): the original data row
Returns:
Returns the data processed by the user.
The data format is list or tuple:
[(name, [feasign, ...]), ...]
or ((name, [feasign, ...]), ...)
For example:
[("words", [1926, 08, 17]), ("label", [1])]
or (("words", [1926, 08, 17]), ("label", [1]))
Note:
The type of feasigns must be in int or float. Once the float
element appears in the feasign, the type of that slot will be
processed into a float.
'''
raise NotImplementedError(
"pls rewrite this function to return a list or tuple: " +
"[(name, [feasign, ...]), ...] or ((name, [feasign, ...]), ...)")
def subprocess_wrapper(instance, file_queue, remaining_queue, output_index,
lock):
'''
In order to use the class function as a process, you need to wrap it.
'''
return instance._subprocess(file_queue, remaining_queue, output_index, lock)
class MultiSlotDataGenerator(DataGenerator):
def _combine_infos(self, infos):
'''
This function is used to merge proto_info information from different
processes. In general, the proto_info of each process is consistent.
The type of input infos is list, and the type of element of infos is
tuple. The format of element of infos will be (name, type).
Args:
infos(list): the list of proto_infos from different processes.
Returns:
Return a unified proto_info.
Note:
This function is only called by the run_from_files function, so
when using the run_from_stdin function(usually used for hadoop),
the output of the process function(rewritten by the user) does
not allow that the same field to have both float and int type
values.
'''
proto_info = infos[0]
for info in infos:
for index, slot in enumerate(info):
name, type = slot
if name != proto_info[index][0]:
raise ValueError(
"combine infos error, pls contact the maintainer of this code~"
)
if type == "float" and proto_info[index][1] == "uint64":
proto_info[index] = (name, type)
return proto_info
def _get_proto_desc(self, proto_info):
'''
Generate a string of proto file based on the proto_info information.
The proto_info will be a list of tuples:
>>> [(Name, Type), ...]
The string of proto file will be in this format:
>>> name: "MultiSlotDataFeed"
>>> batch_size: 32
>>> multi_slot_desc {
>>> slots {
>>> name: Name
>>> type: Type
>>> is_dense: false
>>> is_used: false
>>> }
>>> }
Args:
proto_info(list): The proto information used to generate the
proto string.
Returns:
Returns a string of the proto file.
'''
proto_str = "name: \"MultiSlotDataFeed\"\n" \
+ "batch_size: 32\nmulti_slot_desc {\n"
for elem in proto_info:
proto_str += " slots {\n" \
+ " name: \"%s\"\n" % elem[0]\
+ " type: \"%s\"\n" % elem[1]\
+ " is_dense: false\n" \
+ " is_used: false\n" \
+ " }\n"
proto_str += "}"
return proto_str
def _gen_str(self, line):
'''
Further processing the output of the process() function rewritten by
user, outputting data that can be directly read by the MultiSlotDataFeed,
and updating proto_info infomation.
The input line will be in this format:
>>> [(name, [feasign, ...]), ...]
>>> or ((name, [feasign, ...]), ...)
The output will be in this format:
>>> [ids_num id1 id2 ...] ...
The proto_info will be in this format:
>>> [(name, type), ...]
For example, if the input is like this:
>>> [("words", [1926, 08, 17]), ("label", [1])]
>>> or (("words", [1926, 08, 17]), ("label", [1]))
the output will be:
>>> 3 1234 2345 3456 1 1
the proto_info will be:
>>> [("words", "uint64"), ("label", "uint64")]
Args:
line(str): the output of the process() function rewritten by user.
Returns:
Return a string data that can be read directly by the MultiSlotDataFeed.
'''
if not isinstance(line, list) and not isinstance(line, tuple):
raise ValueError(
"the output of process() must be in list or tuple type")
output = ""
if self._proto_info is None:
self._proto_info = []
for item in line:
name, elements = item
if not isinstance(name, str):
raise ValueError("name%s must be in str type" % type(name))
if not isinstance(elements, list):
raise ValueError("elements%s must be in list type" %
type(elements))
if not elements:
raise ValueError(
"the elements of each field can not be empty, you need padding it in process()."
)
self._proto_info.append((name, "uint64"))
if output:
output += " "
output += str(len(elements))
for elem in elements:
if isinstance(elem, float):
self._proto_info[-1] = (name, "float")
elif not isinstance(elem, int) and not isinstance(elem,
long):
raise ValueError(
"the type of element%s must be in int or float" %
type(elem))
output += " " + str(elem)
else:
if len(line) != len(self._proto_info):
raise ValueError(
"the complete field set of two given line are inconsistent.")
for index, item in enumerate(line):
name, elements = item
if not isinstance(name, str):
raise ValueError("name%s must be in str type" % type(name))
if not isinstance(elements, list):
raise ValueError("elements%s must be in list type" %
type(elements))
if not elements:
raise ValueError(
"the elements of each field can not be empty, you need padding it in process()."
)
if name != self._proto_info[index][0]:
raise ValueError(
"the field name of two given line are not match: require<%s>, get<%d>."
% (self._proto_info[index][0], name))
if output:
output += " "
output += str(len(elements))
for elem in elements:
if self._proto_info[index][1] != "float":
if isinstance(elem, float):
self._proto_info[index] = (name, "float")
elif not isinstance(elem, int) and not isinstance(elem,
long):
raise ValueError(
"the type of element%s must be in int or float"
% type(elem))
output += " " + str(elem)
return output + "\n"
| kuke/models | fluid/PaddleNLP/text_classification/async_executor/data_generator/data_generator.py | Python | apache-2.0 | 22,716 |
"""
A job is an object with states: CREATED, RUNNING, DONE, FAILED, CANCELLED
A job can be polled for completion and reports the progress so far if it is still RUNNING.
"""
from connection import H2OConnection
import time
import sys
class H2OJob(object):
"""
A class representing an H2O Job.
"""
def __init__(self, jobs, job_type):
if "jobs" in jobs:
job = jobs["jobs"][0]
else:
job = jobs["job"]
self.jobs = jobs
self.job = job
self.status = job["status"]
self.job_key = job['key']['name']
self.dest_key = job['dest']['name']
self.progress = 0
self._100_percent = False
self._progress_bar_width = 50
self._job_type = job_type
self.exception = job['exception'] if 'exception' in job else None
def poll(self):
sleep = 0.1
running = True
print # create a new line for distinguished progress bar
while running:
self._update_progress()
time.sleep(sleep)
if sleep < 1.0: sleep += 0.1
self._refresh_job_view()
running = self._is_running()
self._update_progress()
print
# check if failed... and politely print relevant message
if self.status == "CANCELLED":
raise EnvironmentError("Job with key {} was cancelled by the user.".format(self.job_key))
if self.status == "FAILED":
raise EnvironmentError("Job with key {} failed with an exception: {}".format(self.job_key, self.exception))
return self
def _refresh_job_view(self):
jobs = H2OConnection.get_json(url_suffix="Jobs/" + self.job_key)
self.job = jobs["jobs"][0] if "jobs" in jobs else jobs["job"][0]
self.status = self.job["status"]
self.progress = self.job["progress"]
def _is_running(self):
return self.status == "RUNNING" or self.status == "CREATED"
def _update_progress(self):
if self._100_percent: return
progress = min(self.progress, 1)
if progress == 1:
self._100_percent = True
p = int(self._progress_bar_width * progress)
sys.stdout.write("\r" + self._job_type + " Progress: [%s%s] %02d%%" %
("#" * p, " " * (self._progress_bar_width - p), 100 * progress))
sys.stdout.flush()
| bikash/h2o-dev | h2o-py/h2o/job.py | Python | apache-2.0 | 2,183 |
# coding=utf-8
"""
Ingest data from the command-line.
"""
from __future__ import absolute_import, division
import uuid
import logging
from xml.etree import ElementTree
from pathlib import Path
import yaml
import click
from osgeo import gdal, osr
from dateutil import parser
def get_coords(geo_ref_points, spatial_ref):
spatial_ref = osr.SpatialReference(spatial_ref)
t = osr.CoordinateTransformation(spatial_ref, spatial_ref.CloneGeogCS())
def transform(p):
lon, lat, z = t.TransformPoint(p['x'], p['y'])
return {'lon': lon, 'lat': lat}
return {key: transform(p) for key, p in geo_ref_points.items()}
def populate_coord(doc):
proj = doc['grid_spatial']['projection']
doc['extent']['coord'] = get_coords(proj['geo_ref_points'], proj['spatial_reference'])
def fill_image_data(doc, granule_path):
format_ = None
bands = {}
gran_file = gdal.Open(str(granule_path))
quoted = '"' + str(granule_path) + '"'
for subds in gran_file.GetSubDatasets():
index = subds[0].find(quoted)
if not format_:
ds = gdal.Open(subds[0])
projection = ds.GetProjection()
t = ds.GetGeoTransform()
bounds = t[0], t[3], t[0] + t[1] * ds.RasterXSize, t[3] + t[5] * ds.RasterYSize
del ds
format_ = subds[0][:index - 1]
else:
assert format_ == subds[0][:index - 1]
layer = subds[0][index + len(quoted) + 1:]
bands[layer.split(':')[-1]] = {
'path': granule_path.name,
'layer': layer
}
del gran_file
if not format_:
raise RuntimeError('empty dataset')
doc['image'] = {'bands': bands}
doc['format'] = {'name': format_}
doc['grid_spatial'] = {
'projection': {
'geo_ref_points': {
'ul': {'x': min(bounds[0], bounds[2]), 'y': max(bounds[1], bounds[3])},
'ur': {'x': max(bounds[0], bounds[2]), 'y': max(bounds[1], bounds[3])},
'll': {'x': min(bounds[0], bounds[2]), 'y': min(bounds[1], bounds[3])},
'lr': {'x': max(bounds[0], bounds[2]), 'y': min(bounds[1], bounds[3])},
},
'spatial_reference': projection,
}
}
def prepare_dataset(path):
root = ElementTree.parse(str(path)).getroot()
# level = root.findall('./*/Product_Info/PROCESSING_LEVEL')[0].text
product_type = root.findall('./GranuleURMetaData/CollectionMetaData/ShortName')[0].text
station = root.findall('./DataCenterId')[0].text
ct_time = parser.parse(root.findall('./GranuleURMetaData/InsertTime')[0].text)
from_dt = parser.parse('%s %s' % (root.findall('./GranuleURMetaData/RangeDateTime/RangeBeginningDate')[0].text,
root.findall('./GranuleURMetaData/RangeDateTime/RangeBeginningTime')[0].text))
to_dt = parser.parse('%s %s' % (root.findall('./GranuleURMetaData/RangeDateTime/RangeEndingDate')[0].text,
root.findall('./GranuleURMetaData/RangeDateTime/RangeEndingTime')[0].text))
granules = [granule.text for granule in
root.findall('./GranuleURMetaData/DataFiles/DataFileContainer/DistributedFileName')]
documents = []
for granule in granules:
doc = {
'id': str(uuid.uuid4()),
# 'processing_level': level.replace('Level-', 'L'),
'product_type': product_type,
'creation_dt': ct_time.isoformat(),
'platform': {'code': 'AQUA_TERRA'},
'instrument': {'name': 'MODIS'},
'acquisition': {'groundstation': {'code': station}},
'extent': {
'from_dt': from_dt.isoformat(),
'to_dt': to_dt.isoformat(),
'center_dt': (from_dt + (to_dt - from_dt) // 2).isoformat(),
# 'coord': get_coords(geo_ref_points, spatial_ref),
},
'lineage': {'source_datasets': {}},
}
documents.append(doc)
fill_image_data(doc, path.parent.joinpath(granule))
populate_coord(doc)
return documents
@click.command(help="Prepare MODIS datasets for ingestion into the Data Cube.")
@click.argument('datasets',
type=click.Path(exists=True, readable=True, writable=True),
nargs=-1)
def main(datasets):
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)
for dataset in datasets:
path = Path(dataset)
if path.is_dir():
paths = list(path.glob('*.xml'))
elif path.suffix != '.xml':
raise RuntimeError('want xml')
else:
paths = [path]
documents = []
for path in paths:
logging.info("Processing %s...", path)
try:
documents += prepare_dataset(path)
except Exception as e:
logging.info("Failed: %s", e)
if documents:
yaml_path = str(path.parent.joinpath('agdc-metadata.yaml'))
logging.info("Writing %s dataset(s) into %s", len(documents), yaml_path)
with open(yaml_path, 'w') as stream:
yaml.dump_all(documents, stream)
else:
logging.info("No datasets discovered. Bye!")
if __name__ == "__main__":
main()
| ceos-seo/Data_Cube_v2 | agdc-v2/utils/modisprepare.py | Python | apache-2.0 | 5,331 |
#!/usr/bin/env python
#encoding=utf8
'''
Author: xmuyoo@163.com
Date: 2015/12/04
Content:
生成新闻特征数据
输入:
1、无特征样本数据
2、topic_view的文件
3、文章分词过滤后的文件
输出:
1、特征样本数据
'''
import pdb
from collections import Counter
DATA_DIR = 'tmp_data/topic_train'
MAX_SCORE = 10.0
MIN_WORDS_COUNT = 3
TOPIC_BELONG_LIMIT = 5
def load_topic_word():
''''''
topic_fname = '%s/topic_view.topic' % DATA_DIR
word_topic_dic = {}
topic_num = 0
topic_counter = Counter()
with open(topic_fname, 'r') as reader:
for line in reader:
topic, _, words = line.strip().partition('\t')
for word in words.split():
word, _sep, score = word.partition(':')
score = float(score)
# 保留分数大于10的
if score < MAX_SCORE:
continue
topic_counter[topic_num] += 1
word_topic_dic[word] = int(topic)
topic_num += 1
pool_topic = set([t for t, cnt in topic_counter.iteritems() \
if cnt <= MIN_WORDS_COUNT])
tmp_words_dic = {}
for word, topic in word_topic_dic.iteritems():
if topic in pool_topic:
continue
tmp_words_dic[word] = topic
return tmp_words_dic, topic_num
def load_date_word():
''''''
doc_fname = '%s/filtered.rst' % DATA_DIR
date_word_dic = {}
with open(doc_fname, 'r') as reader:
for line in reader:
tmp_dic = Counter()
data = line.strip().split('\t', 2)
if len(data) != 3:
continue
doc_id, date, words = data
if date not in date_word_dic:
date_word_dic[date] = set()
for wd in words.split():
tmp_dic[wd] += 1
date_word_dic[date] |= set([item[0] \
for item in tmp_dic.iteritems()])
return date_word_dic
def init_features(topic_set):
''''''
return dict([(t, '0') for t in topic_set])
def scan_topics(date, date_word_dic, word_topic_dic):
''''''
if date not in date_word_dic:
return
words_set = date_word_dic[date]
tmp_counter = Counter()
for word in words_set:
if word not in word_topic_dic:
continue
tmp_counter[word_topic_dic[word]] += 1
return set([topic for topic, cnt in \
filter(lambda x:x[1] >= TOPIC_BELONG_LIMIT, tmp_counter.iteritems())])
def generate(reader, output_fname, mongo_source):
''''''
print 'Feature: News'
writer = open(output_fname, 'w')
word_topic_dic, topic_num = load_topic_word()
topic_lst = sorted(set(word_topic_dic.values()))
date_word_dic = load_date_word()
title_str = 'label %s\n' % ' '.join(['news_%s' % t for t in topic_lst])
writer.write(title_str)
for line in reader:
data = line.strip().split(' ', 4)
label = int(data[1])
date = data[2]
features = init_features(topic_lst)
tmp_topic_set = scan_topics(date, date_word_dic, word_topic_dic)
if not tmp_topic_set:
raise Exception('Error date: \n%s' % date)
#if label == -1:
# pdb.set_trace()
for topic in tmp_topic_set:
features[topic] = '1'
outstr = '%s %s\n' % (label, ' '.join([features[t] for t in topic_lst]))
writer.write(outstr)
writer.close()
| Muyoo/gold_pred | feature_creator/news.py | Python | apache-2.0 | 3,497 |
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Cert manager manages x509 certificates.
**Related Flags**
:cert_topic: What :mod:`rpc` topic to listen to (default: `cert`).
:cert_manager: The module name of a class derived from
:class:`manager.Manager` (default:
:class:`nova.cert.manager.Manager`).
"""
import base64
from oslo import messaging
from nova import crypto
from nova import manager
class CertManager(manager.Manager):
target = messaging.Target(version='2.0')
def __init__(self, *args, **kwargs):
super(CertManager, self).__init__(service_name='cert',
*args, **kwargs)
def init_host(self):
crypto.ensure_ca_filesystem()
def revoke_certs_by_user(self, context, user_id):
"""Revoke all user certs."""
return crypto.revoke_certs_by_user(user_id)
def revoke_certs_by_project(self, context, project_id):
"""Revoke all project certs."""
return crypto.revoke_certs_by_project(project_id)
def revoke_certs_by_user_and_project(self, context, user_id, project_id):
"""Revoke certs for user in project."""
return crypto.revoke_certs_by_user_and_project(user_id, project_id)
def generate_x509_cert(self, context, user_id, project_id):
"""Generate and sign a cert for user in project."""
return crypto.generate_x509_cert(user_id, project_id)
def fetch_ca(self, context, project_id):
"""Get root ca for a project."""
return crypto.fetch_ca(project_id)
def fetch_crl(self, context, project_id):
"""Get crl for a project."""
return crypto.fetch_crl(project_id)
def decrypt_text(self, context, project_id, text):
"""Decrypt base64 encoded text using the projects private key."""
return crypto.decrypt_text(project_id, base64.b64decode(text))
| leilihh/novaha | nova/cert/manager.py | Python | apache-2.0 | 2,464 |
import numpy as np
import numpy.ma as ma
from numpy import linalg as LA
import matplotlib.pyplot as plt
import itertools
import collections
from scipy import stats
def acf(x, lags=500, exclude=None):
if exclude is None:
exclude = np.zeros(x.shape)
exclude = np.cumsum(exclude.astype(int))
# from stackexchange
x = x - x.mean() # remove mean
if type(lags) is int:
lags = range(lags)
C = ma.zeros((len(lags),))
sigma2 = x.var()
for i, l in enumerate(lags):
if l == 0:
C[i] = 1
elif l >= x.shape[0]:
C[i] = ma.masked
else:
x0 = x[:-l].copy()
x1 = x[l:].copy()
reject = (exclude[l:]-exclude[:-l])>0
x0[reject] = ma.masked
x1[reject] = ma.masked
C[i] = (x0*x1).mean()/sigma2
return C
def ccf(x, y, lags, exclude=None):
if exclude is None:
exclude = np.zeros(x.shape)
exclude = np.cumsum(exclude.astype(int))
x = x - x.mean() # remove mean
y = y - y.mean()
if type(lags) is int:
lags = np.arange(-lags,lags)
C = ma.zeros((len(lags),))
sigma2 = x.std()*y.std()
for i, l in enumerate(lags):
if l == 0:
C[i] = (x*y).mean()/sigma2
else:
if l > 0:
x0 = x[:-l].copy()
y1 = y[l:].copy()
else:
x0 = y[:l].copy()
y1 = x[-l:].copy()
reject = (exclude[l:]-exclude[:-l])>0
x0[reject] = ma.masked
y1[reject] = ma.masked
C[i] = (x0*y1).mean()/sigma2
return C
def acv(k, List):
'''
Autocovariance
k is the lag order
'''
y = List.copy()
y = y - y.mean()
if k == 0:
return (y*y).mean()
else:
return (y[:-k]*y[k:]).mean()
def dotacf(x, lags=500, exclude=None):
if exclude is None:
exclude = np.zeros(x.shape)
exclude = np.cumsum(exclude.astype(int))
if type(lags) is int:
lags = xrange(lags)
C = ma.zeros((len(lags),))
for i, l in enumerate(lags):
if l == 0:
C[i] = (x*x).sum(axis=1).mean()
else:
x0 = x[:-l, :].copy()
x1 = x[l:, :].copy()
reject = (exclude[l:]-exclude[:-l])>0
x0[reject, :] = ma.masked
x1[reject, :] = ma.masked
C[i] = (x0*x1).sum(axis=1).mean()
return C
def pacfe(p,j,List):
'''
Partial autocorrelation function estimates
p is the order of the AR(p) process
j is the coefficient in an AR(p) process
'''
if p==2 and j==1:
return (acf(j,List)*(1-acf(p,List)))/(1-(acf(j,List))**2)
elif p==2 and j==2:
return (acf(2,List)-(acf(1,List))**2)/(1-(acf(1,List))**2)
elif p==j and p!=2 and j!=2:
c=0
for a in range(1,p):
c+=pacfe(p-1,a,List)*acf(p-a,List)
d=0
for b in range(1,p):
d+=pacfe(p-1,b,List)*acf(b,List)
return (acf(p,List)-c)/(1-d)
else:
return pacfe(p-1,j,List)-pacfe(p,p,List)*pacfe(p-1,p-j,List)
def drift(x, lags=500, exclude=None):
if exclude is None:
exclude = np.zeros(x.shape)
exclude = np.cumsum(exclude.astype(int))
if type(lags) is int:
lags = xrange(lags)
mu = ma.zeros((len(lags),))
for i, lag in enumerate(lags):
if lag==0:
mu[i] = 0
elif lag >= x.shape[0]:
mu[i] = ma.masked
else:
x0 = x[lag:].copy()
x1 = x[:-lag].copy()
reject = (exclude[lag:]-exclude[:-lag])>0
x0[reject] = ma.masked
x1[reject] = ma.masked
displacements = x0 - x1
mu[i] = displacements.mean()
return mu
def unwrapma(x):
# Adapted from numpy unwrap, this version ignores missing data
idx = ma.array(np.arange(0,x.shape[0]), mask=x.mask)
idxc = idx.compressed()
xc = x.compressed()
dd = np.diff(xc)
ddmod = np.mod(dd+np.pi, 2*np.pi)-np.pi
ddmod[(ddmod==-np.pi) & (dd > 0)] = np.pi
phc_correct = ddmod - dd
phc_correct[np.abs(dd)<np.pi] = 0
ph_correct = np.zeros(x.shape)
ph_correct[idxc[1:]] = phc_correct
up = x + ph_correct.cumsum()
return up
def nextpow2(n):
'''
Returns the next highest power of 2 from n
'''
m_f = np.log2(n)
m_i = np.ceil(m_f)
return 2**m_i
def phaserand(X, independent=False, reduceHighFreqNoise=True):
'''
Generates a randomized surrogate dataset for X, preserving linear temporal
correlations. If independent is False (default), linear correlations
between columns of x are also preserved.
If X contains missing values, they are filled with the mean of that
channel.
The algorithm works by randomizing the phases in the Fourier domain. For
non-independent shuffling, the same random phases are used for each
channel.
References:
Theiler, J., Eubank, S., Longtin, A., Galdrikian, B., & Doyne Farmer, J.
(1992). Testing for nonlinearity in time series: the method of
surrogate data. Physica D: Nonlinear Phenomena, 58(1), 77-94.
Prichard, D. and Theiler, J. (1994) Generating surrogate data for time
series with several simultaneously measured variables. Phys. Rev.
Lett. 73(7), 951-954.
Podobnik, B., Fu, D. F., Stanley, H. E., & Ivanov, P. C. (2007).
Power-law autocorrelated stochastic processes with long-range
cross-correlations. The European Physical Journal B, 56(1), 47-52.
'''
# Deal with array vs matrix by adding new axis
if len(X.shape) == 1:
X = X[:, np.newaxis]
# Deal with missing data
if isinstance(X, ma.MaskedArray):
# truncate all missing data at beginning and end
idxNotAllMissing = (~np.all(X.mask, axis=1)).nonzero()[0]
X = X[idxNotAllMissing[0]:idxNotAllMissing[-1], :]
X = X.filled(X.mean(axis=0)) # fill interior mask with the mean
# Reduce high-frequency noise by min difference between first and last
if reduceHighFreqNoise:
delta = X - X[0, :]
threshold = 1e-3*np.std(X, axis=0)
# find last pt in which all the channels are about the same as the beginning
# and also the index is even
goodEndPt = np.nonzero((np.all(np.abs(delta) < threshold, axis=1)) &
(np.arange(0, X.shape[1]) % 2 == 0))[0][-1]
if goodEndPt > X.shape[0]/2: # make sure we keep at least half the data
X = X[:goodEndPt, :]
# Fourier transform and extract amplitude and phases
# The frequencies are shifted so 0 is centered (fftshift)
N = X.shape[0] #int(nextpow2(X.shape[0])) # size for FFT
if N % 2 != 0:
N = N-1
h = np.floor(N/2) # half the length of the data
Z = np.fft.fft(X, N, axis=0)
M = np.fft.fftshift(np.abs(Z), axes=0) # the amplitudes
phase = np.fft.fftshift(np.angle(Z), axes=0) # the original phases
# Randomize the phases. The phases need to be symmetric for postivie and
# negative frequencies.
if independent: # generate random phases for each channel
randphase = 2.*np.pi*np.random.rand((h-1, X.shape[1])) # random phases
newphase = np.zeros((N, X.shape[1])) # new phases to use
newphase[0, :] = phase[0, :] # keep the zero freq (don't know why)
newphase[1:h, :] = randphase[::-1, :]
newphase[h, :] = phase[h, :]
newphase[h+1:, :] = -randphase
else: # generate one set of random phases (same as above)
randphase = 2.*np.pi*np.random.rand(h-1)
newphase = np.zeros((N, X.shape[1]))
newphase[0, :] = phase[0, :]
newphase[1:h, :] = randphase[::-1, np.newaxis]
newphase[h, :] = phase[h, :]
newphase[h+1:, :] = -randphase[:, np.newaxis]
# Reconstruct the signal from the original amplitude and the new phases
z2 = M*np.exp(newphase*1.j)
# Return the time-domain signal
return np.fft.ifft(np.fft.ifftshift(z2, axes=0),
axis=0).real.squeeze()
| stephenhelms/WormTracker | python/tsstats.py | Python | apache-2.0 | 8,100 |
# Copyright (c) 2015, MapR Technologies
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sahara.i18n import _
import sahara.plugins.mapr.versions.version_handler_factory as vhf
import sahara.plugins.provisioning as p
class MapRPlugin(p.ProvisioningPluginBase):
title = 'MapR Hadoop Distribution'
description = _('The MapR Distribution provides a full Hadoop stack that'
' includes the MapR File System (MapR-FS), MapReduce,'
' a complete Hadoop ecosystem, and the MapR Control System'
' user interface')
def _get_handler(self, hadoop_version):
return vhf.VersionHandlerFactory.get().get_handler(hadoop_version)
def get_title(self):
return MapRPlugin.title
def get_description(self):
return MapRPlugin.description
def get_versions(self):
return vhf.VersionHandlerFactory.get().get_versions()
def get_node_processes(self, hadoop_version):
return self._get_handler(hadoop_version).get_node_processes()
def get_configs(self, hadoop_version):
return self._get_handler(hadoop_version).get_configs()
def configure_cluster(self, cluster):
self._get_handler(cluster.hadoop_version).configure_cluster(cluster)
def start_cluster(self, cluster):
self._get_handler(cluster.hadoop_version).start_cluster(cluster)
def validate(self, cluster):
self._get_handler(cluster.hadoop_version).validate(cluster)
def validate_scaling(self, cluster, existing, additional):
v_handler = self._get_handler(cluster.hadoop_version)
v_handler.validate_scaling(cluster, existing, additional)
def scale_cluster(self, cluster, instances):
v_handler = self._get_handler(cluster.hadoop_version)
v_handler.scale_cluster(cluster, instances)
def decommission_nodes(self, cluster, instances):
v_handler = self._get_handler(cluster.hadoop_version)
v_handler.decommission_nodes(cluster, instances)
def get_edp_engine(self, cluster, job_type):
v_handler = self._get_handler(cluster.hadoop_version)
return v_handler.get_edp_engine(cluster, job_type)
def get_open_ports(self, node_group):
v_handler = self._get_handler(node_group.cluster.hadoop_version)
return v_handler.get_open_ports(node_group)
| esikachev/scenario | sahara/plugins/mapr/plugin.py | Python | apache-2.0 | 2,850 |
# -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpRequest, QueryDict, HttpResponseRedirect
import json
import conekta
from store.models import *
from store.forms import *
### PETICIONES API PARA EL CARRITO
def delBasket(request):
id = str(request.GET.get('id'))
if request.GET.get('id'):
liston = request.session['basket']
if id in liston:
liston.remove(id)
request.session['basket'] = liston
msg = 'Success'
status = 'ok'
else:
msg = 'Error: Product not found in basket'
status = 'failed'
else:
msg = "Success"
status = 'ok'
try:
del request.session['basket']
except KeyError:
msg = 'Error: Cant delete basket'
status = 'failed'
"""
response_data = {}
response_data['result'] = status
response_data['message'] = msg
callback = request.GET.get('callback', '')
response = json.dumps(response_data)
response = callback + '(' + response + ');'
return HttpResponse(response,content_type="application/json")
"""
return HttpResponseRedirect("/store/checkout/")
def setBasket(request):
id = str(request.GET.get('id'))
if id.isdigit():
if request.session.get('basket',False):
# Se ha definido anteriormente
liston = request.session['basket']
if id in liston:
msg = 'Error: product already exists'
status = 'failed'
else:
liston.append(id)
request.session['basket'] = liston
msg = 'Success'
status = 'ok'
else:
# No se ha definido
msg = 'Success'
status = 'ok'
request.session['basket'] = [id]
else:
msg = 'Error en la peticion'
status = 'failed'
response_data = {}
response_data['result'] = status
response_data['message'] = msg
callback = request.GET.get('callback', '')
response = json.dumps(response_data)
response = callback + '(' + response + ');'
return HttpResponse(response,content_type="application/json")
import pprint
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def conektaio(request):
try:
data = json.loads(request.body)
except:
data = False
if data:
try:
pedido = Pedido.objects.get(custom=data['data']['object']['reference_id'])
except:
pedido = False
if pedido:
dato = { "status": "success" ,"id": pedido.id, "nombre":pedido.payment }
if data['data']['object']['status'] == "paid":
pedido.paid=True
pedido.save()
numero = 200
else:
debug = Debug.objects.create(texto=data)
debug.save()
dato = { "status":"ergo" }
numero = 200
else:
dato = { "status":"error" }
numero = 400
return HttpResponse(dato['status'],content_type="application/json",status=numero)
#### END API | zeickan/Django-Store | store/api.py | Python | apache-2.0 | 3,203 |
import logging
from .data import DefinedTable
logger = logging.getLogger(__name__)
def ensure_tables():
"""When called, ensure that all the tables that we need are created in the
database. The real work is supplied by the DefinedTable base class
"""
for tab in [Subject, ExpCondition]:
logger.debug("Creating table %s", tab.get_table_name())
tab.ensure_table()
class Subject(DefinedTable):
"""An experimental subject that we are tracking in an experimental condition
"""
@classmethod
def get_table_name(self):
return "Subjects"
@classmethod
def get_key_name(self):
return "subject_id"
def __init__(
self,
subject_id=None,
first_name=None,
last_name=None,
email=None,
exp_condition=None
):
self.subject_id = subject_id
self.first_name = first_name
self.last_name = last_name
self.email = email
self.exp_condition = exp_condition
def errors(self):
if not self.subject_id:
yield "Missing subject ID"
if not self.exp_condition:
yield "Missing Experimental Condition"
class ExpCondition(DefinedTable):
"""A single experimental condition that any number of subjects may be a part of
"""
@classmethod
def get_table_name(self):
return "Conditions"
@classmethod
def get_key_name(self):
return "condition_id"
def __init__(
self,
condition_id=None,
condition_name=None,
description=None
):
self.condition_id = condition_id
self.condition_name = condition_name
self.description = description
| memphis-iis/demo-track | demotrack/model.py | Python | apache-2.0 | 1,712 |
import hashlib
f = open('file_path', 'rb')
sh = hashlib.sha256()
sh.update(f.read())
print(sh.hexdigest())
f.close() | fanwenl/kindle-image | encryption/sha.py | Python | apache-2.0 | 119 |
from tableacc import TableAcc
class Brewers(TableAcc):
def __init__(self):
super(Brewers, self).__init__(
table_name='brewers',
cols=['id', 'name', 'location_id'],
upsert_proc='brewerupsert')
def bylocation_id(self, location_id, order_by=""):
return self._select(
cols=["id", "name"],
where="location_id = %s",
order_by=order_by,
param=[location_id] )
def has_recommended_beers_by_loc(self, location_id, order_by=""):
return self._view(view_name='brewerswithrecs',
where="location_id = %s",
order_by=order_by,
param=[location_id])
if __name__ == "__main__":
br = Brewers()
for r in br.has_recommended_beers_by_loc(15):
print r
| robhowley/nextbeeronme | src/db/brewers.py | Python | apache-2.0 | 753 |
# -*- encoding: utf-8 -*-
import pytest
from django.utils import timezone
from base.model_utils import BaseError
from example_base.models import FruitCake
from login.tests.factories import UserFactory
from .factories import FruitCakeFactory
@pytest.mark.django_db
def test_factory():
FruitCakeFactory()
@pytest.mark.django_db
def test_str():
str(FruitCakeFactory())
@pytest.mark.django_db
def test_set_deleted():
obj = FruitCakeFactory()
assert 0 == obj.deleted_version
user = UserFactory()
FruitCake.objects.set_deleted(obj, user)
obj.refresh_from_db()
assert obj.deleted is True
assert obj.user_deleted == user
assert obj.date_deleted is not None
assert 1 == obj.deleted_version
@pytest.mark.django_db
def test_set_deleted_multi():
user = UserFactory()
c1 = FruitCakeFactory(number=19, description='c1')
FruitCake.objects.set_deleted(c1, user)
c2 = FruitCakeFactory(number=19, description='c2')
FruitCake.objects.set_deleted(c2, user)
FruitCakeFactory(number=19, description='c3')
result = FruitCake.objects.filter(number=19).order_by('description')
assert 3 == result.count()
assert [
(19, True, 1),
(19, True, 2),
(19, False, 0),
] == [(o.number, o.deleted, o.deleted_version) for o in result]
@pytest.mark.django_db
def test_set_deleted_model():
"""Standard way to delete rows from non-versioned delete models"""
obj = FruitCakeFactory()
with pytest.raises(BaseError) as e:
obj.set_deleted(UserFactory())
assert 'model with deleted version tracking' in str(e.value)
@pytest.mark.django_db
def test_undelete():
obj = FruitCakeFactory()
user = UserFactory()
FruitCake.objects.set_deleted(obj, user)
assert obj.deleted_version > 0
obj.refresh_from_db()
obj.undelete()
obj.refresh_from_db()
assert obj.deleted is False
assert obj.user_deleted is None
assert obj.date_deleted is None
assert 0 == obj.deleted_version
| pkimber/base | example_base/tests/test_model_versioned_delete.py | Python | apache-2.0 | 2,006 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v9.errors",
marshal="google.ads.googleads.v9",
manifest={"AdParameterErrorEnum",},
)
class AdParameterErrorEnum(proto.Message):
r"""Container for enum describing possible ad parameter errors.
"""
class AdParameterError(proto.Enum):
r"""Enum describing possible ad parameter errors."""
UNSPECIFIED = 0
UNKNOWN = 1
AD_GROUP_CRITERION_MUST_BE_KEYWORD = 2
INVALID_INSERTION_TEXT_FORMAT = 3
__all__ = tuple(sorted(__protobuf__.manifest))
| googleads/google-ads-python | google/ads/googleads/v9/errors/types/ad_parameter_error.py | Python | apache-2.0 | 1,192 |
from __future__ import print_function
from __future__ import print_function
import sys, os
sys.path.insert(1, os.path.join("..","..","..",".."))
import h2o
from h2o.automl import H2OAutoML
from tests import pyunit_utils as pu
from _automl_utils import import_dataset
def test_default_automl_with_regression_task():
ds = import_dataset('regression')
aml = H2OAutoML(max_models=2,
project_name='aml_regression')
aml.train(y=ds.target, training_frame=ds.train, validation_frame=ds.valid, leaderboard_frame=ds.test)
print(aml.leader)
print(aml.leaderboard)
assert aml.leaderboard.columns == ["model_id", "mean_residual_deviance", "rmse", "mse", "mae", "rmsle"]
def test_workaround_for_distribution():
try:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "true"))
ds = import_dataset('regression')
aml = H2OAutoML(project_name="py_test",
algo_parameters=dict(
distribution='poisson',
family='poisson',
),
exclude_algos=['StackedEnsemble'],
max_runtime_secs=60,
seed=1)
aml.train(y=ds.target, training_frame=ds.train)
model_names = [aml.leaderboard[i, 0] for i in range(0, (aml.leaderboard.nrows))]
for mn in model_names:
m = h2o.get_model(mn)
dist = m.params['distribution'] if 'distribution' in m.params else m.params['family'] if 'family' in m.params else None
print("{}: distribution = {}".format(mn, dist))
except:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "false"))
pu.run_tests([
test_default_automl_with_regression_task,
test_workaround_for_distribution,
])
| h2oai/h2o-3 | h2o-py/tests/testdir_algos/automl/pyunit_automl_regression.py | Python | apache-2.0 | 1,901 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 25 21:46:31 2017
@author: sitibanc
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# =============================================================================
# Read CSV
# =============================================================================
df = pd.read_csv('TXF20112015.csv', sep=',', header = None) # dataframe (time, close, open, high, low, volume)
TAIEX = df.values # ndarray
tradeday = list(set(TAIEX[:, 0] // 10000)) # 交易日(YYYYMMDD)
tradeday.sort()
# =============================================================================
# Strategy 2.0: 開盤買進一口,30點停損,30點停利,收盤平倉
# =============================================================================
profit0 = np.zeros((len(tradeday),1))
for i in range(len(tradeday)):
date = tradeday[i]
idx = np.nonzero(TAIEX[:, 0] // 10000 == date)[0]
idx.sort()
p1 = TAIEX[idx[0], 2]
# 設定停損點
idx2 = np.nonzero(TAIEX[idx, 4] <= p1 - 30)[0] # 最低價跌破停損點
# 設定停利點
idx3 = np.nonzero(TAIEX[idx, 3] >= p1 + 30)[0] # 最高價衝破停利點
if len(idx2) == 0 and len(idx3) == 0: # 當日沒有觸及平損停利點
p2 = TAIEX[idx[-1], 1] # 當日收盤價賣出
elif len(idx3) == 0: # 當日沒有停利但停損
p2 = TAIEX[idx[idx2[0]], 1] # 停損點收盤價賣出
elif len(idx2) == 0: # 當日沒有停損但停利
p2 = TAIEX[idx[idx3[0]], 1] # 停利點收盤價賣出
elif idx2[0] > idx3[0]: # 當日停利點先出現
p2 = TAIEX[idx[idx3[0]], 1] # 停利點收盤價賣出
else: # 當日停損點先出現
p2 = TAIEX[idx[idx2[0]], 1] # 停損點收盤價賣出
profit0[i] = p2 - p1
print('Strategy 2.0: 當日以開盤價買進一口,30點停損,30點停利,當日收盤價平倉\n逐日損益折線圖')
profit02 = np.cumsum(profit0) # 逐日損益獲利
plt.plot(profit02) # 逐日損益折線圖
plt.show()
print('每日損益分佈圖')
plt.hist(profit0, bins = 100) # 每日損益的分佈圖(直方圖)
plt.show()
# 計算數據
ans1 = len(profit0) # 進場次數
ans2 = profit02[-1] # 總損益點數
ans3 = np.sum(profit0 > 0) / len(profit0) * 100 # 勝率
ans4 = np.mean(profit0[profit0 > 0]) # 獲利時的平均獲利點數
ans5 = np.mean(profit0[profit0 <= 0]) # 虧損時的平均虧損點數
print('進場次數:', ans1, '\n總損益點數:', ans2, '\n勝率:', ans3, '%')
print('賺錢時平均每次獲利點數', ans4, '\n輸錢時平均每次損失點數:', ans5, '\n')
# =============================================================================
# Strategy 2.1: 開盤賣出一口,30點停損,30點停利,收盤平倉
# =============================================================================
profit1 = np.zeros((len(tradeday),1))
for i in range(len(tradeday)):
date = tradeday[i]
idx = np.nonzero(TAIEX[:, 0] // 10000 == date)[0]
idx.sort()
p1 = TAIEX[idx[0], 2]
# 設定停損點
idx2 = np.nonzero(TAIEX[idx, 3] >= p1 + 30)[0] # 最高價衝破停損點
# 設定停利點
idx3 = np.nonzero(TAIEX[idx, 4] <= p1 - 30)[0] # 最低價跌破停利點
if len(idx2) == 0 and len(idx3) == 0: # 當日沒有觸及平損停利點
p2 = TAIEX[idx[-1], 1] # 當日收盤價買回
elif len(idx3) == 0: # 當日沒有停利但停損
p2 = TAIEX[idx[idx2[0]], 1] # 停損點收盤價買回
elif len(idx2) == 0: # 當日沒有停損但停利
p2 = TAIEX[idx[idx3[0]], 1] # 停利點收盤價買回
elif idx2[0] > idx3[0]: # 當日停利點先出現
p2 = TAIEX[idx[idx3[0]], 1] # 停利點收盤價買回
else: # 當日停損點先出現
p2 = TAIEX[idx[idx2[0]], 1] # 停損點收盤價買回
profit1[i] = p1 - p2
print('Strategy 2.1: 當日以開盤價賣出一口,30點停損,30點停利,當日收盤價平倉\n每日獲利折線圖')
profit12 = np.cumsum(profit1) # 逐日累積損益
plt.plot(profit12) # 逐日損益折線圖
plt.show()
print('每日損益分佈圖')
plt.hist(profit1, bins = 100) # 每日損益的分佈圖
plt.show()
# 計算數據
ans1 = len(profit1) # 進場次數
ans2 = profit12[-1] # 總損益點數
ans3 = np.sum(profit1 > 0) / len(profit1) * 100 # 勝率
ans4 = np.mean(profit1[profit1 > 0]) # 獲利時的平均獲利點數
ans5 = np.mean(profit1[profit1 <= 0]) # 虧損時的平均虧損點數
print('進場次數:', ans1, '\n總損益點數:', ans2, '\n勝率:', ans3, '%')
print('賺錢時平均每次獲利點數', ans4, '\n輸錢時平均每次損失點數:', ans5) | SitiBanc/1061_NCTU_IOMDS | 1025/Homework 5/HW5_2.py | Python | apache-2.0 | 6,016 |
#!/usr/bin/python
import os
import requests
from collections import defaultdict
from glob import glob
def convert(dpi, equation):
url = 'http://latex.codecogs.com/png.latex?'
r = requests.get(url, params='\dpi{' + str(dpi) + '} ' + equation)
print('HTTP response: ' + str(r.status_code))
if (r.status_code != 200):
raise "error in " + equation
return r.content
def main():
equations = readEquations('equations.txt')
outputDir = 'output'
mappingFile = outputDir + '/mapping.properties'
if not os.path.exists(outputDir):
os.mkdir(outputDir)
else:
for filename in glob(outputDir + "/*/*.png"):
os.remove(filename)
if os.path.exists(mappingFile):
os.remove(mappingFile)
dpis = [300, 600]
for dpi in dpis:
dir = outputDir + '/' + str(dpi)
if not os.path.exists(dir):
os.mkdir(dir)
with open(mappingFile, 'w') as mapping:
for k, v in sorted(equations.items()):
ki = 0
for equation in sorted(v):
print('converting' + str(k) + ' = ' + equation)
filename = 'eq' + str(k) + '_' + str(ki)
for dpi in dpis:
convertAndWrite(outputDir, filename, equation, dpi)
mapping.write(filename + '=' + str(k) + '\n')
ki = ki + 1
def convertAndWrite(outputDir, filename, w, dpi):
data = convert(dpi, w)
writeImage(outputDir + '/' + str(dpi) + '/' + filename + '.png', data)
def writeImage(filename, data):
with open(filename, 'w') as f:
f.write(data)
def readEquations(filepath):
md = defaultdict(list)
with open(filepath, "rt") as f:
for line in f:
l = line.strip()
if l and not l.startswith('#'):
key_value = l.split('=')
key = key_value[0].strip()
value = '='.join(key_value[1:]).strip('" \t')
if (len(key) > 0 and len(value) > 0):
md[int(key)].append(value)
return md
main()
| fodpeter/MathClock | equations/build.py | Python | apache-2.0 | 2,085 |
# Copyright 2013 Rackspace Hosting
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from webob import exc
from jacket.api.compute.openstack import common
from jacket.api.compute.openstack import extensions
from jacket.api.compute.openstack import wsgi
from jacket.compute import cloud
from jacket.i18n import _
from jacket.compute import utils
ALIAS = "os-instance-actions"
authorize = extensions.os_compute_authorizer(ALIAS)
soft_authorize = extensions.os_compute_soft_authorizer(ALIAS)
ACTION_KEYS = ['action', 'instance_uuid', 'request_id', 'user_id',
'project_id', 'start_time', 'message']
EVENT_KEYS = ['event', 'start_time', 'finish_time', 'result', 'traceback']
class InstanceActionsController(wsgi.Controller):
def __init__(self):
super(InstanceActionsController, self).__init__()
self.compute_api = cloud.API()
self.action_api = cloud.InstanceActionAPI()
def _format_action(self, action_raw):
action = {}
for key in ACTION_KEYS:
action[key] = action_raw.get(key)
return action
def _format_event(self, event_raw):
event = {}
for key in EVENT_KEYS:
event[key] = event_raw.get(key)
return event
@wsgi.Controller.api_version("2.1", "2.20")
def _get_instance(self, req, context, server_id):
return common.get_instance(self.compute_api, context, server_id)
@wsgi.Controller.api_version("2.21") # noqa
def _get_instance(self, req, context, server_id):
with utils.temporary_mutation(context, read_deleted='yes'):
return common.get_instance(self.compute_api, context, server_id)
@extensions.expected_errors(404)
def index(self, req, server_id):
"""Returns the list of actions recorded for a given instance."""
context = req.environ["compute.context"]
instance = self._get_instance(req, context, server_id)
authorize(context, target=instance)
actions_raw = self.action_api.actions_get(context, instance)
actions = [self._format_action(action) for action in actions_raw]
return {'instanceActions': actions}
@extensions.expected_errors(404)
def show(self, req, server_id, id):
"""Return data about the given instance action."""
context = req.environ['compute.context']
instance = self._get_instance(req, context, server_id)
authorize(context, target=instance)
action = self.action_api.action_get_by_request_id(context, instance,
id)
if action is None:
msg = _("Action %s not found") % id
raise exc.HTTPNotFound(explanation=msg)
action_id = action['id']
action = self._format_action(action)
if soft_authorize(context, action='events'):
events_raw = self.action_api.action_events_get(context, instance,
action_id)
action['events'] = [self._format_event(evt) for evt in events_raw]
return {'instanceAction': action}
class InstanceActions(extensions.V21APIExtensionBase):
"""View a log of actions and events taken on an instance."""
name = "InstanceActions"
alias = ALIAS
version = 1
def get_resources(self):
ext = extensions.ResourceExtension(ALIAS,
InstanceActionsController(),
parent=dict(
member_name='server',
collection_name='servers'))
return [ext]
def get_controller_extensions(self):
"""It's an abstract function V21APIExtensionBase and the extension
will not be loaded without it.
"""
return []
| HybridF5/jacket | jacket/api/compute/openstack/compute/instance_actions.py | Python | apache-2.0 | 4,402 |
from mpi4py import MPI
from utils.mpi_helper import finalize
from utils.mpi_helper import init
init()
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
print "process [", rank, "] - running"
if rank == 0:
data = {'name': "PROCESS-" + str(rank), 'msg': "Hello"}
req = comm.isend(data, dest=1, tag=11)
req.wait()
elif rank == 1:
req = comm.irecv(source=0, tag=11)
data = req.wait()
print "process-" + str(rank) + " receive:", data['name'], "say", data['msg']
finalize()
| balolam/university-mpi-python | practical_task_1/task2.py | Python | apache-2.0 | 516 |
import profile
def fib(n):
# from literateprograms.org
# http://bit.ly/hlOQ5m
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
def fib_seq(n):
seq = []
if n > 0:
seq.extend(fib_seq(n - 1))
seq.append(fib(n))
return seq
profile.run('print(fib_seq(20)); print()')
| jasonwee/asus-rt-n14uhp-mrtg | src/lesson_developer_tools/profile_fibonacci_raw.py | Python | apache-2.0 | 367 |
from cstool.parse_input import (read_input, check_settings, cstool_model)
from cstool.phonon import (phonon_cs_fn)
from cslib import (units)
import numpy as np
def test_phonon_cs_fn_single():
"""Tests that the phonon subroutine returns a function that
can handle arrays and returns correct units."""
settings = read_input('data/materials/pmma.yaml')
settings.phonon.model = 'single'
if not check_settings(settings, cstool_model):
raise ValueError("Parsed settings do not conform the model.")
fn = phonon_cs_fn(settings)
W = np.logspace(-2, 3, 100) * units.eV
theta = np.linspace(0, np.pi, 100) * units.rad
cs = fn(theta, W[:, None])
assert cs.shape == (100, 100)
assert cs.dimensionality == units('m²/sr').dimensionality
def test_phonon_cs_fn_dual():
"""Tests that the phonon subroutine returns a function that
can handle arrays and returns correct units."""
settings = read_input('data/materials/pmma.yaml')
if not check_settings(settings, cstool_model):
raise ValueError("Parsed settings do not conform the model.")
fn = phonon_cs_fn(settings)
W = np.logspace(-2, 3, 100) * units.eV
theta = np.linspace(0, np.pi, 100) * units.rad
cs = fn(theta, W[:, None])
assert cs.shape == (100, 100)
assert cs.dimensionality == units('m²/sr').dimensionality
| eScatter/cstool | test/test_phonon.py | Python | apache-2.0 | 1,357 |
"""Executor util helpers."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import contextlib
import logging
import queue
import sys
from threading import Thread
import time
import traceback
from .thread import async_raise
_LOGGER = logging.getLogger(__name__)
MAX_LOG_ATTEMPTS = 2
_JOIN_ATTEMPTS = 10
EXECUTOR_SHUTDOWN_TIMEOUT = 10
def _log_thread_running_at_shutdown(name: str, ident: int) -> None:
"""Log the stack of a thread that was still running at shutdown."""
frames = sys._current_frames() # pylint: disable=protected-access
stack = frames.get(ident)
formatted_stack = traceback.format_stack(stack)
_LOGGER.warning(
"Thread[%s] is still running at shutdown: %s",
name,
"".join(formatted_stack).strip(),
)
def join_or_interrupt_threads(
threads: set[Thread], timeout: float, log: bool
) -> set[Thread]:
"""Attempt to join or interrupt a set of threads."""
joined = set()
timeout_per_thread = timeout / len(threads)
for thread in threads:
thread.join(timeout=timeout_per_thread)
if not thread.is_alive() or thread.ident is None:
joined.add(thread)
continue
if log:
_log_thread_running_at_shutdown(thread.name, thread.ident)
with contextlib.suppress(SystemError):
# SystemError at this stage is usually a race condition
# where the thread happens to die right before we force
# it to raise the exception
async_raise(thread.ident, SystemExit)
return joined
class InterruptibleThreadPoolExecutor(ThreadPoolExecutor):
"""A ThreadPoolExecutor instance that will not deadlock on shutdown."""
def shutdown(self, *args, **kwargs) -> None: # type: ignore
"""Shutdown backport from cpython 3.9 with interrupt support added."""
with self._shutdown_lock: # type: ignore[attr-defined]
self._shutdown = True
# Drain all work items from the queue, and then cancel their
# associated futures.
while True:
try:
work_item = self._work_queue.get_nowait()
except queue.Empty:
break
if work_item is not None:
work_item.future.cancel()
# Send a wake-up to prevent threads calling
# _work_queue.get(block=True) from permanently blocking.
self._work_queue.put(None)
# The above code is backported from python 3.9
#
# For maintainability join_threads_or_timeout is
# a separate function since it is not a backport from
# cpython itself
#
self.join_threads_or_timeout()
def join_threads_or_timeout(self) -> None:
"""Join threads or timeout."""
remaining_threads = set(self._threads) # type: ignore[attr-defined]
start_time = time.monotonic()
timeout_remaining: float = EXECUTOR_SHUTDOWN_TIMEOUT
attempt = 0
while True:
if not remaining_threads:
return
attempt += 1
remaining_threads -= join_or_interrupt_threads(
remaining_threads,
timeout_remaining / _JOIN_ATTEMPTS,
attempt <= MAX_LOG_ATTEMPTS,
)
timeout_remaining = EXECUTOR_SHUTDOWN_TIMEOUT - (
time.monotonic() - start_time
)
if timeout_remaining <= 0:
return
| home-assistant/home-assistant | homeassistant/util/executor.py | Python | apache-2.0 | 3,555 |
#
# Copyright 2016 Dohop hf.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Setup script for building supervisor-logstash-notifier
"""
from setuptools import setup, find_packages
# 2 step 'with open' to be python2.6 compatible
with open('requirements.txt') as requirements:
with open('test_requirements.txt') as test_requirements:
setup(
name='supervisor-logstash-notifier',
version='0.2.5',
packages=find_packages(exclude=['tests']),
url='https://github.com/dohop/supervisor-logstash-notifier',
license='Apache 2.0',
author='aodj',
author_email='alexander@dohop.com',
description='Stream supervisor events to a logstash instance',
long_description=open('README.rst').read(),
entry_points={
'console_scripts': [
'logstash_notifier = logstash_notifier:main'
]
},
install_requires=requirements.read().splitlines(),
test_suite='tests',
tests_require=test_requirements.read().splitlines(),
)
| dohop/supervisor-logstash-notifier | setup.py | Python | apache-2.0 | 1,635 |
# -*- coding: utf-8; -*-
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. You may
# obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# However, if you have executed another commercial license agreement
# with Crate these terms will supersede the license and you may use the
# software solely pursuant to the terms of the relevant commercial agreement.
from unittest import TestCase
import sqlalchemy as sa
class SqlAlchemyConnectionTest(TestCase):
def setUp(self):
self.engine = sa.create_engine('crate://')
self.connection = self.engine.connect()
def test_default_connection(self):
engine = sa.create_engine('crate://')
conn = engine.raw_connection()
self.assertEqual("<Connection <Client ['http://127.0.0.1:4200']>>",
repr(conn.connection))
def test_connection_server(self):
engine = sa.create_engine(
"crate://otherhost:19201")
conn = engine.raw_connection()
self.assertEqual("<Connection <Client ['http://otherhost:19201']>>",
repr(conn.connection))
def test_connection_multiple_server(self):
engine = sa.create_engine(
"crate://", connect_args={
'servers': ['localhost:4201', 'localhost:4202']
}
)
conn = engine.raw_connection()
self.assertEqual(
"<Connection <Client ['http://localhost:4201', " +
"'http://localhost:4202']>>",
repr(conn.connection))
| crate/crate-python | src/crate/client/sqlalchemy/tests/connection_test.py | Python | apache-2.0 | 2,183 |
import logging
from json import JSONEncoder, dumps
from flask import current_app, make_response, request
__all__ = (
"serialize",
"jsonify",
)
log = logging.getLogger(__name__)
def serialize(rv):
log.debug("Serializing output")
if rv is None or (isinstance(rv, str) and not len(rv)):
log.info("No content")
rv = make_response("", 204)
elif (
isinstance(rv, current_app.response_class)
or callable(rv)
or isinstance(rv, str)
):
...
else:
log.info("Serializing")
rv = jsonify(rv)
if request.method == "POST":
make_response(rv, 201)
return rv
def jsonify(*args, **kwargs):
if args and kwargs:
raise TypeError("jsonify() behavior undefined when passed both args and kwargs")
elif len(args) == 1: # single args are passed directly to dumps()
data = args[0]
else:
data = args or kwargs
pretty_print = bool(
request.args.get(
"pretty-print", current_app.config["JSONIFY_PRETTYPRINT_REGULAR"]
)
)
indent = None
separators = (",", ":")
cls = current_app.json_encoder or JSONEncoder
if pretty_print is True and request.is_xhr is False:
indent = 2
separators = (", ", ": ")
if hasattr(request, "operation") and request.operation.produces:
mime_type = request.operation.produces[0]
elif "JSONIFY_MIMETYPE" in current_app.config:
mime_type = current_app.config["JSONIFY_MIMETYPE"]
else:
mime_type = "application/json; charset=utf-8"
json_str = dumps(data, indent=indent, separators=separators, cls=cls) + "\n"
json_str.encode("utf-8")
return current_app.response_class(json_str, mimetype=mime_type)
| pegasus-isi/pegasus | packages/pegasus-python/src/Pegasus/service/_serialize.py | Python | apache-2.0 | 1,770 |
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Layout to monitor hover status through full telemetry."""
from makani.gs.monitor2.apps.plugins import common
from makani.gs.monitor2.apps.plugins.layouts import hover_template
class DebugHoverLayout(hover_template.HoverLayout):
"""The hover layout."""
_NAME = 'Debug (Hover)'
_MODE = common.FULL_COMMS_MODE
| google/makani | gs/monitor2/apps/plugins/layouts/debug_hover_layout.py | Python | apache-2.0 | 909 |
#!/usr/bin/python
from setuptools import setup
setup(
name = "dhcpz",
version = "0.2.0",
author = [
"Nicholas VonHollen",
"Brian Lamar"
],
author_email = [
"nicholas.vonhollen@rackspace.com",
"brian.lamar@rackspace.com",
],
license = "Apache License 2.0",
packages = ['dhcpz', 'dhcpz.handlers'],
package_dir = {"":"src/py"},
install_requires = ['gevent', 'netifaces'],
data_files = [
('/etc', ['conf/dhcpz.conf']),
('/etc/init.d', ['src/init.d/dhcpz']),
('/usr/bin', ['src/bin/dhcpz']),
],
)
| blamarvt/dhcpz | setup.py | Python | apache-2.0 | 662 |
"""
WSGI config for tweeter project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tweeter.settings")
application = get_wsgi_application()
| pananormalny/mytweeter | tweeter/wsgi.py | Python | apache-2.0 | 391 |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
User-defined function related classes and functions
"""
import functools
import sys
from typing import Callable, Any, TYPE_CHECKING, Optional, cast, Union
from py4j.java_gateway import JavaObject # type: ignore[import]
from pyspark import SparkContext
from pyspark.rdd import _prepare_for_python_RDD, PythonEvalType # type: ignore[attr-defined]
from pyspark.sql.column import Column, _to_java_column, _to_seq
from pyspark.sql.types import (
StringType,
DataType,
StructType,
_parse_datatype_string,
)
from pyspark.sql.pandas.types import to_arrow_type
if TYPE_CHECKING:
from pyspark.sql._typing import DataTypeOrString, ColumnOrName, UserDefinedFunctionLike
from pyspark.sql.session import SparkSession
__all__ = ["UDFRegistration"]
def _wrap_function(
sc: SparkContext, func: Callable[..., Any], returnType: "DataTypeOrString"
) -> JavaObject:
command = (func, returnType)
pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command)
return sc._jvm.PythonFunction( # type: ignore[attr-defined]
bytearray(pickled_command),
env,
includes,
sc.pythonExec, # type: ignore[attr-defined]
sc.pythonVer, # type: ignore[attr-defined]
broadcast_vars,
sc._javaAccumulator, # type: ignore[attr-defined]
)
def _create_udf(
f: Callable[..., Any],
returnType: "DataTypeOrString",
evalType: int,
name: Optional[str] = None,
deterministic: bool = True,
) -> "UserDefinedFunctionLike":
# Set the name of the UserDefinedFunction object to be the name of function f
udf_obj = UserDefinedFunction(
f, returnType=returnType, name=name, evalType=evalType, deterministic=deterministic
)
return udf_obj._wrapped()
class UserDefinedFunction(object):
"""
User defined function in Python
.. versionadded:: 1.3
Notes
-----
The constructor of this class is not supposed to be directly called.
Use :meth:`pyspark.sql.functions.udf` or :meth:`pyspark.sql.functions.pandas_udf`
to create this instance.
"""
def __init__(
self,
func: Callable[..., Any],
returnType: "DataTypeOrString" = StringType(),
name: Optional[str] = None,
evalType: int = PythonEvalType.SQL_BATCHED_UDF,
deterministic: bool = True,
):
if not callable(func):
raise TypeError(
"Invalid function: not a function or callable (__call__ is not defined): "
"{0}".format(type(func))
)
if not isinstance(returnType, (DataType, str)):
raise TypeError(
"Invalid return type: returnType should be DataType or str "
"but is {}".format(returnType)
)
if not isinstance(evalType, int):
raise TypeError(
"Invalid evaluation type: evalType should be an int but is {}".format(evalType)
)
self.func = func
self._returnType = returnType
# Stores UserDefinedPythonFunctions jobj, once initialized
self._returnType_placeholder: Optional[DataType] = None
self._judf_placeholder = None
self._name = name or (
func.__name__ if hasattr(func, "__name__") else func.__class__.__name__
)
self.evalType = evalType
self.deterministic = deterministic
@property
def returnType(self) -> DataType:
# This makes sure this is called after SparkContext is initialized.
# ``_parse_datatype_string`` accesses to JVM for parsing a DDL formatted string.
if self._returnType_placeholder is None:
if isinstance(self._returnType, DataType):
self._returnType_placeholder = self._returnType
else:
self._returnType_placeholder = _parse_datatype_string(self._returnType)
if (
self.evalType == PythonEvalType.SQL_SCALAR_PANDAS_UDF
or self.evalType == PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF
):
try:
to_arrow_type(self._returnType_placeholder)
except TypeError:
raise NotImplementedError(
"Invalid return type with scalar Pandas UDFs: %s is "
"not supported" % str(self._returnType_placeholder)
)
elif self.evalType == PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF:
if isinstance(self._returnType_placeholder, StructType):
try:
to_arrow_type(self._returnType_placeholder)
except TypeError:
raise NotImplementedError(
"Invalid return type with grouped map Pandas UDFs or "
"at groupby.applyInPandas: %s is not supported"
% str(self._returnType_placeholder)
)
else:
raise TypeError(
"Invalid return type for grouped map Pandas "
"UDFs or at groupby.applyInPandas: return type must be a "
"StructType."
)
elif (
self.evalType == PythonEvalType.SQL_MAP_PANDAS_ITER_UDF
or self.evalType == PythonEvalType.SQL_MAP_ARROW_ITER_UDF
):
if isinstance(self._returnType_placeholder, StructType):
try:
to_arrow_type(self._returnType_placeholder)
except TypeError:
raise NotImplementedError(
"Invalid return type in mapInPandas: "
"%s is not supported" % str(self._returnType_placeholder)
)
else:
raise TypeError(
"Invalid return type in mapInPandas/mapInArrow: "
"return type must be a StructType."
)
elif self.evalType == PythonEvalType.SQL_COGROUPED_MAP_PANDAS_UDF:
if isinstance(self._returnType_placeholder, StructType):
try:
to_arrow_type(self._returnType_placeholder)
except TypeError:
raise NotImplementedError(
"Invalid return type in cogroup.applyInPandas: "
"%s is not supported" % str(self._returnType_placeholder)
)
else:
raise TypeError(
"Invalid return type in cogroup.applyInPandas: "
"return type must be a StructType."
)
elif self.evalType == PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF:
try:
# StructType is not yet allowed as a return type, explicitly check here to fail fast
if isinstance(self._returnType_placeholder, StructType):
raise TypeError
to_arrow_type(self._returnType_placeholder)
except TypeError:
raise NotImplementedError(
"Invalid return type with grouped aggregate Pandas UDFs: "
"%s is not supported" % str(self._returnType_placeholder)
)
return self._returnType_placeholder
@property
def _judf(self) -> JavaObject:
# It is possible that concurrent access, to newly created UDF,
# will initialize multiple UserDefinedPythonFunctions.
# This is unlikely, doesn't affect correctness,
# and should have a minimal performance impact.
if self._judf_placeholder is None:
self._judf_placeholder = self._create_judf()
return self._judf_placeholder
def _create_judf(self) -> JavaObject:
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
sc = spark.sparkContext
wrapped_func = _wrap_function(sc, self.func, self.returnType)
jdt = spark._jsparkSession.parseDataType(self.returnType.json())
judf = sc._jvm.org.apache.spark.sql.execution.python.UserDefinedPythonFunction( # type: ignore[attr-defined]
self._name, wrapped_func, jdt, self.evalType, self.deterministic
)
return judf
def __call__(self, *cols: "ColumnOrName") -> Column:
judf = self._judf
sc = SparkContext._active_spark_context # type: ignore[attr-defined]
return Column(judf.apply(_to_seq(sc, cols, _to_java_column)))
# This function is for improving the online help system in the interactive interpreter.
# For example, the built-in help / pydoc.help. It wraps the UDF with the docstring and
# argument annotation. (See: SPARK-19161)
def _wrapped(self) -> "UserDefinedFunctionLike":
"""
Wrap this udf with a function and attach docstring from func
"""
# It is possible for a callable instance without __name__ attribute or/and
# __module__ attribute to be wrapped here. For example, functools.partial. In this case,
# we should avoid wrapping the attributes from the wrapped function to the wrapper
# function. So, we take out these attribute names from the default names to set and
# then manually assign it after being wrapped.
assignments = tuple(
a for a in functools.WRAPPER_ASSIGNMENTS if a != "__name__" and a != "__module__"
)
@functools.wraps(self.func, assigned=assignments)
def wrapper(*args: "ColumnOrName") -> Column:
return self(*args)
wrapper.__name__ = self._name
wrapper.__module__ = (
self.func.__module__
if hasattr(self.func, "__module__")
else self.func.__class__.__module__
)
wrapper.func = self.func # type: ignore[attr-defined]
wrapper.returnType = self.returnType # type: ignore[attr-defined]
wrapper.evalType = self.evalType # type: ignore[attr-defined]
wrapper.deterministic = self.deterministic # type: ignore[attr-defined]
wrapper.asNondeterministic = functools.wraps( # type: ignore[attr-defined]
self.asNondeterministic
)(lambda: self.asNondeterministic()._wrapped())
wrapper._unwrapped = self # type: ignore[attr-defined]
return wrapper # type: ignore[return-value]
def asNondeterministic(self) -> "UserDefinedFunction":
"""
Updates UserDefinedFunction to nondeterministic.
.. versionadded:: 2.3
"""
# Here, we explicitly clean the cache to create a JVM UDF instance
# with 'deterministic' updated. See SPARK-23233.
self._judf_placeholder = None
self.deterministic = False
return self
class UDFRegistration(object):
"""
Wrapper for user-defined function registration. This instance can be accessed by
:attr:`spark.udf` or :attr:`sqlContext.udf`.
.. versionadded:: 1.3.1
"""
def __init__(self, sparkSession: "SparkSession"):
self.sparkSession = sparkSession
def register(
self,
name: str,
f: Union[Callable[..., Any], "UserDefinedFunctionLike"],
returnType: Optional["DataTypeOrString"] = None,
) -> "UserDefinedFunctionLike":
"""Register a Python function (including lambda function) or a user-defined function
as a SQL function.
.. versionadded:: 1.3.1
Parameters
----------
name : str,
name of the user-defined function in SQL statements.
f : function, :meth:`pyspark.sql.functions.udf` or :meth:`pyspark.sql.functions.pandas_udf`
a Python function, or a user-defined function. The user-defined function can
be either row-at-a-time or vectorized. See :meth:`pyspark.sql.functions.udf` and
:meth:`pyspark.sql.functions.pandas_udf`.
returnType : :class:`pyspark.sql.types.DataType` or str, optional
the return type of the registered user-defined function. The value can
be either a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.
`returnType` can be optionally specified when `f` is a Python function but not
when `f` is a user-defined function. Please see the examples below.
Returns
-------
function
a user-defined function
Notes
-----
To register a nondeterministic Python function, users need to first build
a nondeterministic user-defined function for the Python function and then register it
as a SQL function.
Examples
--------
1. When `f` is a Python function:
`returnType` defaults to string type and can be optionally specified. The produced
object must match the specified type. In this case, this API works as if
`register(name, f, returnType=StringType())`.
>>> strlen = spark.udf.register("stringLengthString", lambda x: len(x))
>>> spark.sql("SELECT stringLengthString('test')").collect()
[Row(stringLengthString(test)='4')]
>>> spark.sql("SELECT 'foo' AS text").select(strlen("text")).collect()
[Row(stringLengthString(text)='3')]
>>> from pyspark.sql.types import IntegerType
>>> _ = spark.udf.register("stringLengthInt", lambda x: len(x), IntegerType())
>>> spark.sql("SELECT stringLengthInt('test')").collect()
[Row(stringLengthInt(test)=4)]
>>> from pyspark.sql.types import IntegerType
>>> _ = spark.udf.register("stringLengthInt", lambda x: len(x), IntegerType())
>>> spark.sql("SELECT stringLengthInt('test')").collect()
[Row(stringLengthInt(test)=4)]
2. When `f` is a user-defined function (from Spark 2.3.0):
Spark uses the return type of the given user-defined function as the return type of
the registered user-defined function. `returnType` should not be specified.
In this case, this API works as if `register(name, f)`.
>>> from pyspark.sql.types import IntegerType
>>> from pyspark.sql.functions import udf
>>> slen = udf(lambda s: len(s), IntegerType())
>>> _ = spark.udf.register("slen", slen)
>>> spark.sql("SELECT slen('test')").collect()
[Row(slen(test)=4)]
>>> import random
>>> from pyspark.sql.functions import udf
>>> from pyspark.sql.types import IntegerType
>>> random_udf = udf(lambda: random.randint(0, 100), IntegerType()).asNondeterministic()
>>> new_random_udf = spark.udf.register("random_udf", random_udf)
>>> spark.sql("SELECT random_udf()").collect() # doctest: +SKIP
[Row(random_udf()=82)]
>>> import pandas as pd # doctest: +SKIP
>>> from pyspark.sql.functions import pandas_udf
>>> @pandas_udf("integer") # doctest: +SKIP
... def add_one(s: pd.Series) -> pd.Series:
... return s + 1
...
>>> _ = spark.udf.register("add_one", add_one) # doctest: +SKIP
>>> spark.sql("SELECT add_one(id) FROM range(3)").collect() # doctest: +SKIP
[Row(add_one(id)=1), Row(add_one(id)=2), Row(add_one(id)=3)]
>>> @pandas_udf("integer") # doctest: +SKIP
... def sum_udf(v: pd.Series) -> int:
... return v.sum()
...
>>> _ = spark.udf.register("sum_udf", sum_udf) # doctest: +SKIP
>>> q = "SELECT sum_udf(v1) FROM VALUES (3, 0), (2, 0), (1, 1) tbl(v1, v2) GROUP BY v2"
>>> spark.sql(q).collect() # doctest: +SKIP
[Row(sum_udf(v1)=1), Row(sum_udf(v1)=5)]
"""
# This is to check whether the input function is from a user-defined function or
# Python function.
if hasattr(f, "asNondeterministic"):
if returnType is not None:
raise TypeError(
"Invalid return type: data type can not be specified when f is"
"a user-defined function, but got %s." % returnType
)
f = cast("UserDefinedFunctionLike", f)
if f.evalType not in [
PythonEvalType.SQL_BATCHED_UDF,
PythonEvalType.SQL_SCALAR_PANDAS_UDF,
PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF,
PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF,
]:
raise ValueError(
"Invalid f: f must be SQL_BATCHED_UDF, SQL_SCALAR_PANDAS_UDF, "
"SQL_SCALAR_PANDAS_ITER_UDF or SQL_GROUPED_AGG_PANDAS_UDF."
)
register_udf = _create_udf(
f.func,
returnType=f.returnType,
name=name,
evalType=f.evalType,
deterministic=f.deterministic,
)._unwrapped # type: ignore[attr-defined]
return_udf = f
else:
if returnType is None:
returnType = StringType()
return_udf = _create_udf(
f, returnType=returnType, evalType=PythonEvalType.SQL_BATCHED_UDF, name=name
)
register_udf = return_udf._unwrapped # type: ignore[attr-defined]
self.sparkSession._jsparkSession.udf().registerPython(name, register_udf._judf)
return return_udf
def registerJavaFunction(
self,
name: str,
javaClassName: str,
returnType: Optional["DataTypeOrString"] = None,
) -> None:
"""Register a Java user-defined function as a SQL function.
In addition to a name and the function itself, the return type can be optionally specified.
When the return type is not specified we would infer it via reflection.
.. versionadded:: 2.3.0
Parameters
----------
name : str
name of the user-defined function
javaClassName : str
fully qualified name of java class
returnType : :class:`pyspark.sql.types.DataType` or str, optional
the return type of the registered Java function. The value can be either
a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string.
Examples
--------
>>> from pyspark.sql.types import IntegerType
>>> spark.udf.registerJavaFunction(
... "javaStringLength", "test.org.apache.spark.sql.JavaStringLength", IntegerType())
... # doctest: +SKIP
>>> spark.sql("SELECT javaStringLength('test')").collect() # doctest: +SKIP
[Row(javaStringLength(test)=4)]
>>> spark.udf.registerJavaFunction(
... "javaStringLength2", "test.org.apache.spark.sql.JavaStringLength")
... # doctest: +SKIP
>>> spark.sql("SELECT javaStringLength2('test')").collect() # doctest: +SKIP
[Row(javaStringLength2(test)=4)]
>>> spark.udf.registerJavaFunction(
... "javaStringLength3", "test.org.apache.spark.sql.JavaStringLength", "integer")
... # doctest: +SKIP
>>> spark.sql("SELECT javaStringLength3('test')").collect() # doctest: +SKIP
[Row(javaStringLength3(test)=4)]
"""
jdt = None
if returnType is not None:
if not isinstance(returnType, DataType):
returnType = _parse_datatype_string(returnType)
returnType = cast(DataType, returnType)
jdt = self.sparkSession._jsparkSession.parseDataType(returnType.json())
self.sparkSession._jsparkSession.udf().registerJava(name, javaClassName, jdt)
def registerJavaUDAF(self, name: str, javaClassName: str) -> None:
"""Register a Java user-defined aggregate function as a SQL function.
.. versionadded:: 2.3.0
name : str
name of the user-defined aggregate function
javaClassName : str
fully qualified name of java class
Examples
--------
>>> spark.udf.registerJavaUDAF("javaUDAF", "test.org.apache.spark.sql.MyDoubleAvg")
... # doctest: +SKIP
>>> df = spark.createDataFrame([(1, "a"),(2, "b"), (3, "a")],["id", "name"])
>>> df.createOrReplaceTempView("df")
>>> q = "SELECT name, javaUDAF(id) as avg from df group by name order by name desc"
>>> spark.sql(q).collect() # doctest: +SKIP
[Row(name='b', avg=102.0), Row(name='a', avg=102.0)]
"""
self.sparkSession._jsparkSession.udf().registerJavaUDAF(name, javaClassName)
def _test() -> None:
import doctest
from pyspark.sql import SparkSession
import pyspark.sql.udf
globs = pyspark.sql.udf.__dict__.copy()
spark = SparkSession.builder.master("local[4]").appName("sql.udf tests").getOrCreate()
globs["spark"] = spark
(failure_count, test_count) = doctest.testmod(
pyspark.sql.udf, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE
)
spark.stop()
if failure_count:
sys.exit(-1)
if __name__ == "__main__":
_test()
| nchammas/spark | python/pyspark/sql/udf.py | Python | apache-2.0 | 21,985 |
""" config.py """
import os
from flask import Flask
from peewee import MySQLDatabase, SqliteDatabase
#-------------------------------------------------------------------------------
# Environment
#-------------------------------------------------------------------------------
DB = 'idreamoftoast'
ENV = os.environ.get('TOAST_PRODUCTION', None)
HOST = os.environ.get('TOAST_HOST', None)
USER = os.environ.get('TOAST_USER', None)
PASSWD = os.environ.get('TOAST_PASSWD', None)
LOG_PATH = os.environ.get('TOAST_LOG_PATH', './')
#-------------------------------------------------------------------------------
# Config Methods
#-------------------------------------------------------------------------------
def get_app():
app = None
# If env is set, we are in production!
if ENV:
app = Flask(__name__)
import logging
file_handler = logging.FileHandler(LOG_PATH + 'flask.log')
file_handler.setLevel(logging.WARNING)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]'
))
app.logger.addHandler(file_handler)
else:
# Development settings here!
app = Flask(__name__, static_folder='public', static_url_path='')
@app.route("/")
def root():
return app.send_static_file('index.html')
return app
def get_database():
db = None
# If env is set, we are in production!
if ENV:
# Production settings here!
if not (HOST or USER or PASSWD):
import sys
print('Environment variables NOT set!')
sys.exit()
db = MySQLDatabase(DB, host=HOST, user=USER, passwd=PASSWD)
else:
# Development settings here!
db = SqliteDatabase('toast.db')#, threadlocals=True)
return db
| whiskeylover/idreamoftoast | toast/config.py | Python | apache-2.0 | 1,878 |
# Copyright 2010 OpenStack Foundation
# Copyright 2012 University Of Minho
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from collections import deque
from collections import OrderedDict
import contextlib
import copy
import datetime
import errno
import glob
import os
import random
import re
import shutil
import signal
import threading
import time
import uuid
import eventlet
from eventlet import greenthread
import fixtures
from lxml import etree
import mock
from mox3 import mox
from os_brick.initiator import connector
import os_vif
from oslo_concurrency import lockutils
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_service import loopingcall
from oslo_utils import encodeutils
from oslo_utils import fileutils
from oslo_utils import fixture as utils_fixture
from oslo_utils import importutils
from oslo_utils import units
from oslo_utils import uuidutils
from oslo_utils import versionutils
import six
from six.moves import builtins
from six.moves import range
from nova.api.metadata import base as instance_metadata
from nova.compute import arch
from nova.compute import cpumodel
from nova.compute import manager
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import vm_mode
from nova.compute import vm_states
import nova.conf
from nova import context
from nova import db
from nova import exception
from nova.network import model as network_model
from nova import objects
from nova.objects import block_device as block_device_obj
from nova.objects import fields
from nova.objects import migrate_data as migrate_data_obj
from nova.objects import virtual_interface as obj_vif
from nova.pci import manager as pci_manager
from nova.pci import utils as pci_utils
from nova import test
from nova.tests.unit import fake_block_device
from nova.tests.unit import fake_instance
from nova.tests.unit import fake_network
import nova.tests.unit.image.fake
from nova.tests.unit import matchers
from nova.tests.unit.objects import test_pci_device
from nova.tests.unit.objects import test_vcpu_model
from nova.tests.unit.virt.libvirt import fake_imagebackend
from nova.tests.unit.virt.libvirt import fake_libvirt_utils
from nova.tests.unit.virt.libvirt import fakelibvirt
from nova.tests import uuidsentinel as uuids
from nova import utils
from nova import version
from nova.virt import block_device as driver_block_device
from nova.virt.disk import api as disk_api
from nova.virt import driver
from nova.virt import fake
from nova.virt import firewall as base_firewall
from nova.virt import hardware
from nova.virt.image import model as imgmodel
from nova.virt import images
from nova.virt.libvirt import blockinfo
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import driver as libvirt_driver
from nova.virt.libvirt import firewall
from nova.virt.libvirt import guest as libvirt_guest
from nova.virt.libvirt import host
from nova.virt.libvirt import imagebackend
from nova.virt.libvirt import imagecache
from nova.virt.libvirt import migration as libvirt_migrate
from nova.virt.libvirt.storage import dmcrypt
from nova.virt.libvirt.storage import lvm
from nova.virt.libvirt.storage import rbd_utils
from nova.virt.libvirt import utils as libvirt_utils
from nova.virt.libvirt.volume import volume as volume_drivers
libvirt_driver.libvirt = fakelibvirt
host.libvirt = fakelibvirt
libvirt_guest.libvirt = fakelibvirt
libvirt_migrate.libvirt = fakelibvirt
CONF = nova.conf.CONF
_fake_network_info = fake_network.fake_get_instance_nw_info
_fake_NodeDevXml = \
{"pci_0000_04_00_3": """
<device>
<name>pci_0000_04_00_3</name>
<parent>pci_0000_00_01_1</parent>
<driver>
<name>igb</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>4</bus>
<slot>0</slot>
<function>3</function>
<product id='0x1521'>I350 Gigabit Network Connection</product>
<vendor id='0x8086'>Intel Corporation</vendor>
<capability type='virt_functions'>
<address domain='0x0000' bus='0x04' slot='0x10' function='0x3'/>
<address domain='0x0000' bus='0x04' slot='0x10' function='0x7'/>
<address domain='0x0000' bus='0x04' slot='0x11' function='0x3'/>
<address domain='0x0000' bus='0x04' slot='0x11' function='0x7'/>
</capability>
</capability>
</device>""",
"pci_0000_04_10_7": """
<device>
<name>pci_0000_04_10_7</name>
<parent>pci_0000_00_01_1</parent>
<driver>
<name>igbvf</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>4</bus>
<slot>16</slot>
<function>7</function>
<product id='0x1520'>I350 Ethernet Controller Virtual Function
</product>
<vendor id='0x8086'>Intel Corporation</vendor>
<capability type='phys_function'>
<address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/>
</capability>
<capability type='virt_functions'>
</capability>
</capability>
</device>""",
"pci_0000_04_11_7": """
<device>
<name>pci_0000_04_11_7</name>
<parent>pci_0000_00_01_1</parent>
<driver>
<name>igbvf</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>4</bus>
<slot>17</slot>
<function>7</function>
<product id='0x1520'>I350 Ethernet Controller Virtual Function
</product>
<vendor id='0x8086'>Intel Corporation</vendor>
<numa node='0'/>
<capability type='phys_function'>
<address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/>
</capability>
<capability type='virt_functions'>
</capability>
</capability>
</device>""",
"pci_0000_04_00_1": """
<device>
<name>pci_0000_04_00_1</name>
<path>/sys/devices/pci0000:00/0000:00:02.0/0000:04:00.1</path>
<parent>pci_0000_00_02_0</parent>
<driver>
<name>mlx5_core</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>4</bus>
<slot>0</slot>
<function>1</function>
<product id='0x1013'>MT27700 Family [ConnectX-4]</product>
<vendor id='0x15b3'>Mellanox Technologies</vendor>
<iommuGroup number='15'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
</iommuGroup>
<numa node='0'/>
<pci-express>
<link validity='cap' port='0' speed='8' width='16'/>
<link validity='sta' speed='8' width='16'/>
</pci-express>
</capability>
</device>""",
# libvirt >= 1.3.0 nodedev-dumpxml
"pci_0000_03_00_0": """
<device>
<name>pci_0000_03_00_0</name>
<path>/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.0</path>
<parent>pci_0000_00_02_0</parent>
<driver>
<name>mlx5_core</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>3</bus>
<slot>0</slot>
<function>0</function>
<product id='0x1013'>MT27700 Family [ConnectX-4]</product>
<vendor id='0x15b3'>Mellanox Technologies</vendor>
<capability type='virt_functions' maxCount='16'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x2'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x3'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x4'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x5'/>
</capability>
<iommuGroup number='15'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
</iommuGroup>
<numa node='0'/>
<pci-express>
<link validity='cap' port='0' speed='8' width='16'/>
<link validity='sta' speed='8' width='16'/>
</pci-express>
</capability>
</device>""",
"pci_0000_03_00_1": """
<device>
<name>pci_0000_03_00_1</name>
<path>/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.1</path>
<parent>pci_0000_00_02_0</parent>
<driver>
<name>mlx5_core</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>3</bus>
<slot>0</slot>
<function>1</function>
<product id='0x1013'>MT27700 Family [ConnectX-4]</product>
<vendor id='0x15b3'>Mellanox Technologies</vendor>
<capability type='virt_functions' maxCount='16'/>
<iommuGroup number='15'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
</iommuGroup>
<numa node='0'/>
<pci-express>
<link validity='cap' port='0' speed='8' width='16'/>
<link validity='sta' speed='8' width='16'/>
</pci-express>
</capability>
</device>""",
}
_fake_cpu_info = {
"arch": "test_arch",
"model": "test_model",
"vendor": "test_vendor",
"topology": {
"sockets": 1,
"cores": 8,
"threads": 16
},
"features": ["feature1", "feature2"]
}
eph_default_ext = utils.get_hash_str(disk_api._DEFAULT_FILE_SYSTEM)[:7]
def eph_name(size):
return ('ephemeral_%(size)s_%(ext)s' %
{'size': size, 'ext': eph_default_ext})
def fake_disk_info_byname(instance, type='qcow2'):
"""Return instance_disk_info corresponding accurately to the properties of
the given Instance object. The info is returned as an OrderedDict of
name->disk_info for each disk.
:param instance: The instance we're generating fake disk_info for.
:param type: libvirt's disk type.
:return: disk_info
:rtype: OrderedDict
"""
instance_dir = os.path.join(CONF.instances_path, instance.uuid)
def instance_path(name):
return os.path.join(instance_dir, name)
disk_info = OrderedDict()
# root disk
if instance.image_ref is not None:
cache_name = imagecache.get_cache_fname(instance.image_ref)
disk_info['disk'] = {
'type': type,
'path': instance_path('disk'),
'virt_disk_size': instance.flavor.root_gb * units.Gi,
'backing_file': cache_name,
'disk_size': instance.flavor.root_gb * units.Gi,
'over_committed_disk_size': 0}
swap_mb = instance.flavor.swap
if swap_mb > 0:
disk_info['disk.swap'] = {
'type': type,
'path': instance_path('disk.swap'),
'virt_disk_size': swap_mb * units.Mi,
'backing_file': 'swap_%s' % swap_mb,
'disk_size': swap_mb * units.Mi,
'over_committed_disk_size': 0}
eph_gb = instance.flavor.ephemeral_gb
if eph_gb > 0:
disk_info['disk.local'] = {
'type': type,
'path': instance_path('disk.local'),
'virt_disk_size': eph_gb * units.Gi,
'backing_file': eph_name(eph_gb),
'disk_size': eph_gb * units.Gi,
'over_committed_disk_size': 0}
if instance.config_drive:
disk_info['disk.config'] = {
'type': 'raw',
'path': instance_path('disk.config'),
'virt_disk_size': 1024,
'backing_file': '',
'disk_size': 1024,
'over_committed_disk_size': 0}
return disk_info
def fake_disk_info_json(instance, type='qcow2'):
"""Return fake instance_disk_info corresponding accurately to the
properties of the given Instance object.
:param instance: The instance we're generating fake disk_info for.
:param type: libvirt's disk type.
:return: JSON representation of instance_disk_info for all disks.
:rtype: str
"""
disk_info = fake_disk_info_byname(instance, type)
return jsonutils.dumps(disk_info.values())
def _concurrency(signal, wait, done, target, is_block_dev=False):
signal.send()
wait.wait()
done.send()
class FakeVirtDomain(object):
def __init__(self, fake_xml=None, uuidstr=None, id=None, name=None):
if uuidstr is None:
uuidstr = str(uuid.uuid4())
self.uuidstr = uuidstr
self.id = id
self.domname = name
self._info = [power_state.RUNNING, 2048 * units.Mi, 1234 * units.Mi,
None, None]
if fake_xml:
self._fake_dom_xml = fake_xml
else:
self._fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
</devices>
</domain>
"""
def name(self):
if self.domname is None:
return "fake-domain %s" % self
else:
return self.domname
def ID(self):
return self.id
def info(self):
return self._info
def create(self):
pass
def managedSave(self, *args):
pass
def createWithFlags(self, launch_flags):
pass
def XMLDesc(self, flags):
return self._fake_dom_xml
def UUIDString(self):
return self.uuidstr
def attachDeviceFlags(self, xml, flags):
pass
def attachDevice(self, xml):
pass
def detachDeviceFlags(self, xml, flags):
pass
def snapshotCreateXML(self, xml, flags):
pass
def blockCommit(self, disk, base, top, bandwidth=0, flags=0):
pass
def blockRebase(self, disk, base, bandwidth=0, flags=0):
pass
def blockJobInfo(self, path, flags):
pass
def resume(self):
pass
def destroy(self):
pass
def fsFreeze(self, disks=None, flags=0):
pass
def fsThaw(self, disks=None, flags=0):
pass
def isActive(self):
return True
class CacheConcurrencyTestCase(test.NoDBTestCase):
def setUp(self):
super(CacheConcurrencyTestCase, self).setUp()
self.flags(instances_path=self.useFixture(fixtures.TempDir()).path)
# utils.synchronized() will create the lock_path for us if it
# doesn't already exist. It will also delete it when it's done,
# which can cause race conditions with the multiple threads we
# use for tests. So, create the path here so utils.synchronized()
# won't delete it out from under one of the threads.
self.lock_path = os.path.join(CONF.instances_path, 'locks')
fileutils.ensure_tree(self.lock_path)
def fake_exists(fname):
basedir = os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name)
if fname == basedir or fname == self.lock_path:
return True
return False
def fake_execute(*args, **kwargs):
pass
def fake_extend(image, size, use_cow=False):
pass
self.stub_out('os.path.exists', fake_exists)
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(imagebackend.disk, 'extend', fake_extend)
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def _fake_instance(self, uuid):
return objects.Instance(id=1, uuid=uuid)
def test_same_fname_concurrency(self):
# Ensures that the same fname cache runs at a sequentially.
uuid = uuidutils.generate_uuid()
backend = imagebackend.Backend(False)
wait1 = eventlet.event.Event()
done1 = eventlet.event.Event()
sig1 = eventlet.event.Event()
thr1 = eventlet.spawn(backend.image(self._fake_instance(uuid),
'name').cache,
_concurrency, 'fname', None,
signal=sig1, wait=wait1, done=done1)
eventlet.sleep(0)
# Thread 1 should run before thread 2.
sig1.wait()
wait2 = eventlet.event.Event()
done2 = eventlet.event.Event()
sig2 = eventlet.event.Event()
thr2 = eventlet.spawn(backend.image(self._fake_instance(uuid),
'name').cache,
_concurrency, 'fname', None,
signal=sig2, wait=wait2, done=done2)
wait2.send()
eventlet.sleep(0)
try:
self.assertFalse(done2.ready())
finally:
wait1.send()
done1.wait()
eventlet.sleep(0)
self.assertTrue(done2.ready())
# Wait on greenthreads to assert they didn't raise exceptions
# during execution
thr1.wait()
thr2.wait()
def test_different_fname_concurrency(self):
# Ensures that two different fname caches are concurrent.
uuid = uuidutils.generate_uuid()
backend = imagebackend.Backend(False)
wait1 = eventlet.event.Event()
done1 = eventlet.event.Event()
sig1 = eventlet.event.Event()
thr1 = eventlet.spawn(backend.image(self._fake_instance(uuid),
'name').cache,
_concurrency, 'fname2', None,
signal=sig1, wait=wait1, done=done1)
eventlet.sleep(0)
# Thread 1 should run before thread 2.
sig1.wait()
wait2 = eventlet.event.Event()
done2 = eventlet.event.Event()
sig2 = eventlet.event.Event()
thr2 = eventlet.spawn(backend.image(self._fake_instance(uuid),
'name').cache,
_concurrency, 'fname1', None,
signal=sig2, wait=wait2, done=done2)
eventlet.sleep(0)
# Wait for thread 2 to start.
sig2.wait()
wait2.send()
tries = 0
while not done2.ready() and tries < 10:
eventlet.sleep(0)
tries += 1
try:
self.assertTrue(done2.ready())
finally:
wait1.send()
eventlet.sleep(0)
# Wait on greenthreads to assert they didn't raise exceptions
# during execution
thr1.wait()
thr2.wait()
class FakeVolumeDriver(object):
def __init__(self, *args, **kwargs):
pass
def attach_volume(self, *args):
pass
def detach_volume(self, *args):
pass
def get_xml(self, *args):
return ""
def get_config(self, *args):
"""Connect the volume to a fake device."""
conf = vconfig.LibvirtConfigGuestDisk()
conf.source_type = "network"
conf.source_protocol = "fake"
conf.source_name = "fake"
conf.target_dev = "fake"
conf.target_bus = "fake"
return conf
def connect_volume(self, *args):
"""Connect the volume to a fake device."""
pass
class FakeConfigGuestDisk(object):
def __init__(self, *args, **kwargs):
self.source_type = None
self.driver_cache = None
class FakeConfigGuest(object):
def __init__(self, *args, **kwargs):
self.driver_cache = None
class FakeNodeDevice(object):
def __init__(self, fakexml):
self.xml = fakexml
def XMLDesc(self, flags):
return self.xml
def _create_test_instance():
flavor = objects.Flavor(memory_mb=2048,
swap=0,
vcpu_weight=None,
root_gb=10,
id=2,
name=u'm1.small',
ephemeral_gb=20,
rxtx_factor=1.0,
flavorid=u'1',
vcpus=2,
extra_specs={})
return {
'id': 1,
'uuid': '32dfcb37-5af1-552b-357c-be8c3aa38310',
'memory_kb': '1024000',
'basepath': '/some/path',
'bridge_name': 'br100',
'display_name': "Acme webserver",
'vcpus': 2,
'project_id': 'fake',
'bridge': 'br101',
'image_ref': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
'root_gb': 10,
'ephemeral_gb': 20,
'instance_type_id': '5', # m1.small
'extra_specs': {},
'system_metadata': {
'image_disk_format': 'raw',
},
'flavor': flavor,
'new_flavor': None,
'old_flavor': None,
'pci_devices': objects.PciDeviceList(),
'numa_topology': None,
'config_drive': None,
'vm_mode': None,
'kernel_id': None,
'ramdisk_id': None,
'os_type': 'linux',
'user_id': '838a72b0-0d54-4827-8fd6-fb1227633ceb',
'ephemeral_key_uuid': None,
'vcpu_model': None,
'host': 'fake-host',
'task_state': None,
}
class LibvirtConnTestCase(test.NoDBTestCase):
REQUIRES_LOCKING = True
_EPHEMERAL_20_DEFAULT = eph_name(20)
def setUp(self):
super(LibvirtConnTestCase, self).setUp()
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.get_admin_context()
temp_dir = self.useFixture(fixtures.TempDir()).path
self.flags(instances_path=temp_dir)
self.flags(snapshots_directory=temp_dir, group='libvirt')
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.libvirt_utils',
fake_libvirt_utils))
self.flags(sysinfo_serial="hardware", group="libvirt")
# normally loaded during nova-compute startup
os_vif.initialize()
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def fake_extend(image, size, use_cow=False):
pass
self.stubs.Set(libvirt_driver.disk_api, 'extend', fake_extend)
self.stubs.Set(imagebackend.Image, 'resolve_driver_format',
imagebackend.Image._get_driver_format)
self.useFixture(fakelibvirt.FakeLibvirtFixture())
self.test_instance = _create_test_instance()
self.test_image_meta = {
"disk_format": "raw",
}
self.image_service = nova.tests.unit.image.fake.stub_out_image_service(
self)
self.device_xml_tmpl = """
<domain type='kvm'>
<devices>
<disk type='block' device='disk'>
<driver name='qemu' type='raw' cache='none'/>
<source dev='{device_path}'/>
<target bus='virtio' dev='vdb'/>
<serial>58a84f6d-3f0c-4e19-a0af-eb657b790657</serial>
<address type='pci' domain='0x0' bus='0x0' slot='0x04' \
function='0x0'/>
</disk>
</devices>
</domain>
"""
def relpath(self, path):
return os.path.relpath(path, CONF.instances_path)
def tearDown(self):
nova.tests.unit.image.fake.FakeImageService_reset()
super(LibvirtConnTestCase, self).tearDown()
def test_driver_capabilities(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertTrue(drvr.capabilities['has_imagecache'],
'Driver capabilities for \'has_imagecache\' '
'is invalid')
self.assertTrue(drvr.capabilities['supports_recreate'],
'Driver capabilities for \'supports_recreate\' '
'is invalid')
self.assertFalse(drvr.capabilities['supports_migrate_to_same_host'],
'Driver capabilities for '
'\'supports_migrate_to_same_host\' is invalid')
self.assertTrue(drvr.capabilities['supports_attach_interface'],
'Driver capabilities for '
'\'supports_attach_interface\' '
'is invalid')
def create_fake_libvirt_mock(self, **kwargs):
"""Defining mocks for LibvirtDriver(libvirt is not used)."""
# A fake libvirt.virConnect
class FakeLibvirtDriver(object):
def defineXML(self, xml):
return FakeVirtDomain()
# Creating mocks
volume_driver = ['iscsi=nova.tests.unit.virt.libvirt.test_driver'
'.FakeVolumeDriver']
fake = FakeLibvirtDriver()
# Customizing above fake if necessary
for key, val in kwargs.items():
fake.__setattr__(key, val)
self.stubs.Set(libvirt_driver.LibvirtDriver, '_conn', fake)
self.stubs.Set(libvirt_driver.LibvirtDriver, '_get_volume_drivers',
lambda x: volume_driver)
self.stubs.Set(host.Host, 'get_connection', lambda x: fake)
def fake_lookup(self, instance_name):
return FakeVirtDomain()
def fake_execute(self, *args, **kwargs):
open(args[-1], "a").close()
def _create_service(self, **kwargs):
service_ref = {'host': kwargs.get('host', 'dummy'),
'disabled': kwargs.get('disabled', False),
'binary': 'nova-compute',
'topic': 'compute',
'report_count': 0}
return objects.Service(**service_ref)
def _get_pause_flag(self, drvr, network_info, power_on=True,
vifs_already_plugged=False):
timeout = CONF.vif_plugging_timeout
events = []
if (drvr._conn_supports_start_paused and
utils.is_neutron() and
not vifs_already_plugged and
power_on and timeout):
events = drvr._get_neutron_events(network_info)
return bool(events)
def test_public_api_signatures(self):
baseinst = driver.ComputeDriver(None)
inst = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertPublicAPISignatures(baseinst, inst)
def test_legacy_block_device_info(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertFalse(drvr.need_legacy_block_device_info)
@mock.patch.object(host.Host, "has_min_version")
def test_min_version_start_ok(self, mock_version):
mock_version.return_value = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
@mock.patch.object(host.Host, "has_min_version")
def test_min_version_start_abort(self, mock_version):
mock_version.return_value = False
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) - 1)
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_next_min_version_deprecation_warning(self, mock_warning,
mock_get_libversion):
# Skip test if there's no currently planned new min version
if (versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) ==
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_VERSION)):
self.skipTest("NEXT_MIN_LIBVIRT_VERSION == MIN_LIBVIRT_VERSION")
# Test that a warning is logged if the libvirt version is less than
# the next required minimum version.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
# assert that the next min version is in a warning message
expected_arg = {'version': versionutils.convert_version_to_str(
versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))}
version_arg_found = False
for call in mock_warning.call_args_list:
if call[0][1] == expected_arg:
version_arg_found = True
break
self.assertTrue(version_arg_found)
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION) - 1)
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_next_min_qemu_version_deprecation_warning(self, mock_warning,
mock_get_libversion):
# Skip test if there's no currently planned new min version
if (versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION) ==
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_VERSION)):
self.skipTest("NEXT_MIN_QEMU_VERSION == MIN_QEMU_VERSION")
# Test that a warning is logged if the libvirt version is less than
# the next required minimum version.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
# assert that the next min version is in a warning message
expected_arg = {'version': versionutils.convert_version_to_str(
versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION))}
version_arg_found = False
for call in mock_warning.call_args_list:
if call[0][1] == expected_arg:
version_arg_found = True
break
self.assertTrue(version_arg_found)
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_next_min_version_ok(self, mock_warning, mock_get_libversion):
# Skip test if there's no currently planned new min version
if (versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) ==
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_VERSION)):
self.skipTest("NEXT_MIN_LIBVIRT_VERSION == MIN_LIBVIRT_VERSION")
# Test that a warning is not logged if the libvirt version is greater
# than or equal to NEXT_MIN_LIBVIRT_VERSION.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
# assert that the next min version is in a warning message
expected_arg = {'version': versionutils.convert_version_to_str(
versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))}
version_arg_found = False
for call in mock_warning.call_args_list:
if call[0][1] == expected_arg:
version_arg_found = True
break
self.assertFalse(version_arg_found)
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION))
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_next_min_qemu_version_ok(self, mock_warning, mock_get_libversion):
# Skip test if there's no currently planned new min version
if (versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION) ==
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_VERSION)):
self.skipTest("NEXT_MIN_QEMU_VERSION == MIN_QEMU_VERSION")
# Test that a warning is not logged if the libvirt version is greater
# than or equal to NEXT_MIN_QEMU_VERSION.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
# assert that the next min version is in a warning message
expected_arg = {'version': versionutils.convert_version_to_str(
versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION))}
version_arg_found = False
for call in mock_warning.call_args_list:
if call[0][1] == expected_arg:
version_arg_found = True
break
self.assertFalse(version_arg_found)
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.PPC64)) - 1)
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.PPC64)))
@mock.patch.object(arch, "from_host", return_value=arch.PPC64)
def test_min_version_ppc_old_libvirt(self, mock_libv, mock_qemu,
mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.PPC64)))
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.PPC64)) - 1)
@mock.patch.object(arch, "from_host", return_value=arch.PPC64)
def test_min_version_ppc_old_qemu(self, mock_libv, mock_qemu,
mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.PPC64)))
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.PPC64)))
@mock.patch.object(arch, "from_host", return_value=arch.PPC64)
def test_min_version_ppc_ok(self, mock_libv, mock_qemu, mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.S390X)) - 1)
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.S390X)))
@mock.patch.object(arch, "from_host", return_value=arch.S390X)
def test_min_version_s390_old_libvirt(self, mock_libv, mock_qemu,
mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.S390X)))
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.S390X)) - 1)
@mock.patch.object(arch, "from_host", return_value=arch.S390X)
def test_min_version_s390_old_qemu(self, mock_libv, mock_qemu,
mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.S390X)))
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.S390X)))
@mock.patch.object(arch, "from_host", return_value=arch.S390X)
def test_min_version_s390_ok(self, mock_libv, mock_qemu, mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
def _do_test_parse_migration_flags(self, lm_expected=None,
bm_expected=None):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr._parse_migration_flags()
if lm_expected is not None:
self.assertEqual(lm_expected, drvr._live_migration_flags)
if bm_expected is not None:
self.assertEqual(bm_expected, drvr._block_migration_flags)
def test_parse_live_migration_flags_default(self):
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE))
def test_parse_live_migration_flags(self):
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE))
def test_parse_block_migration_flags_default(self):
self._do_test_parse_migration_flags(
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_parse_block_migration_flags(self):
self._do_test_parse_migration_flags(
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_parse_migration_flags_p2p_xen(self):
self.flags(virt_type='xen', group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_live_migration_tunnelled_none(self):
self.flags(live_migration_tunnelled=None, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED))
def test_live_migration_tunnelled_true(self):
self.flags(live_migration_tunnelled=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED))
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_live_migration_permit_postcopy_true(self, host):
self.flags(live_migration_permit_post_copy=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY))
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_live_migration_permit_auto_converge_true(self, host):
self.flags(live_migration_permit_auto_converge=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE))
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_live_migration_permit_auto_converge_and_post_copy_true(self,
host):
self.flags(live_migration_permit_auto_converge=True, group='libvirt')
self.flags(live_migration_permit_post_copy=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY))
@mock.patch.object(host.Host, 'has_min_version')
def test_live_migration_auto_converge_and_post_copy_true_old_libvirt(
self, mock_host):
self.flags(live_migration_permit_auto_converge=True, group='libvirt')
self.flags(live_migration_permit_post_copy=True, group='libvirt')
def fake_has_min_version(lv_ver=None, hv_ver=None, hv_type=None):
if (lv_ver == libvirt_driver.MIN_LIBVIRT_POSTCOPY_VERSION and
hv_ver == libvirt_driver.MIN_QEMU_POSTCOPY_VERSION):
return False
return True
mock_host.side_effect = fake_has_min_version
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE))
@mock.patch.object(host.Host, 'has_min_version', return_value=False)
def test_live_migration_permit_postcopy_true_old_libvirt(self, host):
self.flags(live_migration_permit_post_copy=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
@mock.patch.object(host.Host, 'has_min_version', return_value=False)
def test_live_migration_permit_auto_converge_true_old_libvirt(self, host):
self.flags(live_migration_permit_auto_converge=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_live_migration_permit_postcopy_false(self):
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_live_migration_permit_autoconverge_false(self):
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password(self, mock_get_guest, ver, mock_image):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.set_admin_password(instance, "123")
mock_guest.set_user_password.assert_called_once_with("root", "123")
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password_parallels(self, mock_get_guest, ver):
self.flags(virt_type='parallels', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.set_admin_password(instance, "123")
mock_guest.set_user_password.assert_called_once_with("root", "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password_windows(self, mock_get_guest, ver, mock_image):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
instance.os_type = "windows"
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.set_admin_password(instance, "123")
mock_guest.set_user_password.assert_called_once_with(
"Administrator", "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password_image(self, mock_get_guest, ver, mock_image):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes",
"os_admin_user": "foo"
}}
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.set_admin_password(instance, "123")
mock_guest.set_user_password.assert_called_once_with("foo", "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=False)
def test_set_admin_password_bad_version(self, mock_svc, mock_image):
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
for hyp in ('kvm', 'parallels'):
self.flags(virt_type=hyp, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.SetAdminPasswdNotSupported,
drvr.set_admin_password, instance, "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_set_admin_password_bad_hyp(self, mock_svc, mock_image):
self.flags(virt_type='lxc', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.SetAdminPasswdNotSupported,
drvr.set_admin_password, instance, "123")
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_set_admin_password_guest_agent_not_running(self, mock_svc):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.QemuGuestAgentNotEnabled,
drvr.set_admin_password, instance, "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password_error(self, mock_get_guest, ver, mock_image):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_guest.set_user_password.side_effect = (
fakelibvirt.libvirtError("error"))
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.set_admin_password, instance, "123")
@mock.patch.object(objects.Service, 'save')
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_set_host_enabled_with_disable(self, mock_svc, mock_save):
# Tests disabling an enabled host.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
svc = self._create_service(host='fake-mini')
mock_svc.return_value = svc
drvr._set_host_enabled(False)
self.assertTrue(svc.disabled)
mock_save.assert_called_once_with()
@mock.patch.object(objects.Service, 'save')
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_set_host_enabled_with_enable(self, mock_svc, mock_save):
# Tests enabling a disabled host.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
svc = self._create_service(disabled=True, host='fake-mini')
mock_svc.return_value = svc
drvr._set_host_enabled(True)
# since disabled_reason is not set and not prefixed with "AUTO:",
# service should not be enabled.
mock_save.assert_not_called()
self.assertTrue(svc.disabled)
@mock.patch.object(objects.Service, 'save')
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_set_host_enabled_with_enable_state_enabled(self, mock_svc,
mock_save):
# Tests enabling an enabled host.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
svc = self._create_service(disabled=False, host='fake-mini')
mock_svc.return_value = svc
drvr._set_host_enabled(True)
self.assertFalse(svc.disabled)
mock_save.assert_not_called()
@mock.patch.object(objects.Service, 'save')
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_set_host_enabled_with_disable_state_disabled(self, mock_svc,
mock_save):
# Tests disabling a disabled host.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
svc = self._create_service(disabled=True, host='fake-mini')
mock_svc.return_value = svc
drvr._set_host_enabled(False)
mock_save.assert_not_called()
self.assertTrue(svc.disabled)
def test_set_host_enabled_swallows_exceptions(self):
# Tests that set_host_enabled will swallow exceptions coming from the
# db_api code so they don't break anything calling it, e.g. the
# _get_new_connection method.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
with mock.patch.object(db, 'service_get_by_compute_host') as db_mock:
# Make db.service_get_by_compute_host raise NovaException; this
# is more robust than just raising ComputeHostNotFound.
db_mock.side_effect = exception.NovaException
drvr._set_host_enabled(False)
@mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName")
def test_prepare_pci_device(self, mock_lookup):
pci_devices = [dict(hypervisor_name='xxx')]
self.flags(virt_type='xen', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conn = drvr._host.get_connection()
mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn)
drvr._prepare_pci_devices_for_use(pci_devices)
@mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName")
@mock.patch.object(fakelibvirt.virNodeDevice, "dettach")
def test_prepare_pci_device_exception(self, mock_detach, mock_lookup):
pci_devices = [dict(hypervisor_name='xxx',
id='id1',
instance_uuid='uuid')]
self.flags(virt_type='xen', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conn = drvr._host.get_connection()
mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn)
mock_detach.side_effect = fakelibvirt.libvirtError("xxxx")
self.assertRaises(exception.PciDevicePrepareFailed,
drvr._prepare_pci_devices_for_use, pci_devices)
@mock.patch.object(host.Host, "has_min_version", return_value=False)
def test_device_metadata(self, mock_version):
xml = """
<domain>
<name>dummy</name>
<uuid>32dfcb37-5af1-552b-357c-be8c3aa38310</uuid>
<memory>1048576</memory>
<vcpu>1</vcpu>
<os>
<type arch='x86_64' machine='pc-i440fx-2.4'>hvm</type>
</os>
<devices>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/dev/mapper/generic'/>
<target dev='sda' bus='scsi'/>
<address type='drive' controller='0' bus='0' target='0' unit='0'/>
</disk>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/dev/mapper/generic-1'/>
<target dev='hda' bus='ide'/>
<address type='drive' controller='0' bus='1' target='0' unit='0'/>
</disk>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/dev/mapper/generic-2'/>
<target dev='hdb' bus='ide'/>
<address type='drive' controller='0' bus='1' target='1' unit='1'/>
</disk>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/dev/mapper/aa1'/>
<target dev='sdb' bus='usb'/>
</disk>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/var/lib/libvirt/images/centos'/>
<backingStore/>
<target dev='vda' bus='virtio'/>
<boot order='1'/>
<alias name='virtio-disk0'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x09'
function='0x0'/>
</disk>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='none'/>
<source file='/var/lib/libvirt/images/generic.qcow2'/>
<target dev='vdb' bus='virtio'/>
<address type='virtio-mmio'/>
</disk>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2'/>
<source file='/var/lib/libvirt/images/test.qcow2'/>
<backingStore/>
<target dev='vdc' bus='virtio'/>
<alias name='virtio-disk1'/>
<address type='ccw' cssid='0xfe' ssid='0x0' devno='0x0000'/>
</disk>
<interface type='network'>
<mac address='52:54:00:f6:35:8f'/>
<source network='default'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x03'
function='0x0'/>
</interface>
<interface type='network'>
<mac address='51:5a:2c:a4:5e:1b'/>
<source network='default'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x04'
function='0x1'/>
</interface>
<interface type='network'>
<mac address='fa:16:3e:d1:28:e4'/>
<source network='default'/>
<model type='virtio'/>
<address type='virtio-mmio'/>
</interface>
<interface type='network'>
<mac address='52:54:00:14:6f:50'/>
<source network='default' bridge='virbr0'/>
<target dev='vnet0'/>
<model type='virtio'/>
<alias name='net0'/>
<address type='ccw' cssid='0xfe' ssid='0x0' devno='0x0001'/>
</interface>
</devices>
</domain>"""
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
guest = libvirt_guest.Guest(dom)
instance_ref = objects.Instance(**self.test_instance)
bdms = block_device_obj.block_device_make_list_from_dicts(
self.context, [
fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sda', 'tag': "db"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/hda', 'tag': "nfvfunc1"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 3,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sdb', 'tag': "nfvfunc2"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 4,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/hdb'}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 5,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vda', 'tag': "nfvfunc3"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 6,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vdb', 'tag': "nfvfunc4"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 7,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vdc', 'tag': "nfvfunc5"}),
]
)
vif = obj_vif.VirtualInterface(context=self.context)
vif.address = '52:54:00:f6:35:8f'
vif.network_id = 123
vif.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
vif.uuid = '12ec4b21-ef22-6c21-534b-ba3e3ab3a311'
vif.tag = 'mytag1'
vif1 = obj_vif.VirtualInterface(context=self.context)
vif1.address = '51:5a:2c:a4:5e:1b'
vif1.network_id = 123
vif1.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
vif1.uuid = 'abec4b21-ef22-6c21-534b-ba3e3ab3a312'
vif1.tag = None
vif2 = obj_vif.VirtualInterface(context=self.context)
vif2.address = 'fa:16:3e:d1:28:e4'
vif2.network_id = 123
vif2.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
vif2.uuid = '645686e4-7086-4eab-8c2f-c41f017a1b16'
vif2.tag = 'mytag2'
vif3 = obj_vif.VirtualInterface(context=self.context)
vif3.address = '52:54:00:14:6f:50'
vif3.network_id = 123
vif3.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
vif3.uuid = '99cc3604-782d-4a32-a27c-bc33ac56ce86'
vif3.tag = 'mytag3'
vifs = [vif, vif1, vif2, vif3]
with test.nested(
mock.patch('nova.objects.VirtualInterfaceList'
'.get_by_instance_uuid', return_value=vifs),
mock.patch('nova.objects.BlockDeviceMappingList'
'.get_by_instance_uuid', return_value=bdms),
mock.patch('nova.virt.libvirt.host.Host.get_guest',
return_value=guest),
mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc',
return_value=xml)):
metadata_obj = drvr._build_device_metadata(self.context,
instance_ref)
metadata = metadata_obj.devices
self.assertEqual(9, len(metadata))
self.assertIsInstance(metadata[0],
objects.DiskMetadata)
self.assertIsInstance(metadata[0].bus,
objects.SCSIDeviceBus)
self.assertEqual(['db'], metadata[0].tags)
self.assertFalse(metadata[0].bus.obj_attr_is_set('address'))
self.assertEqual(['nfvfunc1'], metadata[1].tags)
self.assertIsInstance(metadata[1],
objects.DiskMetadata)
self.assertIsInstance(metadata[1].bus,
objects.IDEDeviceBus)
self.assertEqual(['nfvfunc1'], metadata[1].tags)
self.assertFalse(metadata[1].bus.obj_attr_is_set('address'))
self.assertIsInstance(metadata[2],
objects.DiskMetadata)
self.assertIsInstance(metadata[2].bus,
objects.USBDeviceBus)
self.assertEqual(['nfvfunc2'], metadata[2].tags)
self.assertFalse(metadata[2].bus.obj_attr_is_set('address'))
self.assertIsInstance(metadata[3],
objects.DiskMetadata)
self.assertIsInstance(metadata[3].bus,
objects.PCIDeviceBus)
self.assertEqual(['nfvfunc3'], metadata[3].tags)
self.assertEqual('0000:00:09.0', metadata[3].bus.address)
self.assertIsInstance(metadata[4],
objects.DiskMetadata)
self.assertEqual(['nfvfunc4'], metadata[4].tags)
self.assertIsInstance(metadata[5],
objects.DiskMetadata)
self.assertEqual(['nfvfunc5'], metadata[5].tags)
self.assertIsInstance(metadata[6],
objects.NetworkInterfaceMetadata)
self.assertIsInstance(metadata[6].bus,
objects.PCIDeviceBus)
self.assertEqual(['mytag1'], metadata[6].tags)
self.assertEqual('0000:00:03.0', metadata[6].bus.address)
self.assertIsInstance(metadata[7],
objects.NetworkInterfaceMetadata)
self.assertEqual(['mytag2'], metadata[7].tags)
self.assertIsInstance(metadata[8],
objects.NetworkInterfaceMetadata)
self.assertEqual(['mytag3'], metadata[8].tags)
@mock.patch.object(host.Host, 'get_connection')
@mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc')
def test_detach_pci_devices(self, mocked_get_xml_desc, mock_conn):
fake_domXML1_with_pci = (
"""<domain> <devices>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='none'/>
<source file='xxx'/>
<target dev='vda' bus='virtio'/>
<alias name='virtio-disk0'/>
<address type='pci' domain='0x0000' bus='0x00'
slot='0x04' function='0x0'/>
</disk>
<hostdev mode="subsystem" type="pci" managed="yes">
<source>
<address function="0x1" slot="0x10" domain="0x0001"
bus="0x04"/>
</source>
</hostdev></devices></domain>""")
fake_domXML1_without_pci = (
"""<domain> <devices>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='none'/>
<source file='xxx'/>
<target dev='vda' bus='virtio'/>
<alias name='virtio-disk0'/>
<address type='pci' domain='0x0001' bus='0x00'
slot='0x04' function='0x0'/>
</disk></devices></domain>""")
pci_device_info = {'compute_node_id': 1,
'instance_uuid': 'uuid',
'address': '0001:04:10.1'}
pci_device = objects.PciDevice(**pci_device_info)
pci_devices = [pci_device]
mocked_get_xml_desc.return_value = fake_domXML1_without_pci
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
dom = fakelibvirt.Domain(
drvr._get_connection(), fake_domXML1_with_pci, False)
guest = libvirt_guest.Guest(dom)
drvr._detach_pci_devices(guest, pci_devices)
@mock.patch.object(host.Host, 'get_connection')
@mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc')
def test_detach_pci_devices_timeout(self, mocked_get_xml_desc, mock_conn):
fake_domXML1_with_pci = (
"""<domain> <devices>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='none'/>
<source file='xxx'/>
<target dev='vda' bus='virtio'/>
<alias name='virtio-disk0'/>
<address type='pci' domain='0x0000' bus='0x00'
slot='0x04' function='0x0'/>
</disk>
<hostdev mode="subsystem" type="pci" managed="yes">
<source>
<address function="0x1" slot="0x10" domain="0x0001"
bus="0x04"/>
</source>
</hostdev></devices></domain>""")
pci_device_info = {'compute_node_id': 1,
'instance_uuid': 'uuid',
'address': '0001:04:10.1'}
pci_device = objects.PciDevice(**pci_device_info)
pci_devices = [pci_device]
mocked_get_xml_desc.return_value = fake_domXML1_with_pci
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
dom = fakelibvirt.Domain(
drvr._get_connection(), fake_domXML1_with_pci, False)
guest = libvirt_guest.Guest(dom)
self.assertRaises(exception.PciDeviceDetachFailed,
drvr._detach_pci_devices, guest, pci_devices)
@mock.patch.object(connector, 'get_connector_properties')
def test_get_connector(self, fake_get_connector):
initiator = 'fake.initiator.iqn'
ip = 'fakeip'
host = 'fakehost'
wwpns = ['100010604b019419']
wwnns = ['200010604b019419']
self.flags(my_ip=ip)
self.flags(host=host)
expected = {
'ip': ip,
'initiator': initiator,
'host': host,
'wwpns': wwpns,
'wwnns': wwnns
}
volume = {
'id': 'fake'
}
# TODO(walter-boring) add the fake in os-brick
fake_get_connector.return_value = expected
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
result = drvr.get_volume_connector(volume)
self.assertThat(expected, matchers.DictMatches(result))
@mock.patch.object(connector, 'get_connector_properties')
def test_get_connector_storage_ip(self, fake_get_connector):
ip = '100.100.100.100'
storage_ip = '101.101.101.101'
self.flags(my_block_storage_ip=storage_ip, my_ip=ip)
volume = {
'id': 'fake'
}
expected = {
'ip': storage_ip
}
# TODO(walter-boring) add the fake in os-brick
fake_get_connector.return_value = expected
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
result = drvr.get_volume_connector(volume)
self.assertEqual(storage_ip, result['ip'])
def test_lifecycle_event_registration(self):
calls = []
def fake_registerErrorHandler(*args, **kwargs):
calls.append('fake_registerErrorHandler')
def fake_get_host_capabilities(**args):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.arch = arch.ARMV7
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
calls.append('fake_get_host_capabilities')
return caps
@mock.patch.object(fakelibvirt, 'registerErrorHandler',
side_effect=fake_registerErrorHandler)
@mock.patch.object(host.Host, "get_capabilities",
side_effect=fake_get_host_capabilities)
def test_init_host(get_host_capabilities, register_error_handler):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("test_host")
test_init_host()
# NOTE(dkliban): Will fail if get_host_capabilities is called before
# registerErrorHandler
self.assertEqual(['fake_registerErrorHandler',
'fake_get_host_capabilities'], calls)
def test_sanitize_log_to_xml(self):
# setup fake data
data = {'auth_password': 'scrubme'}
bdm = [{'connection_info': {'data': data}}]
bdi = {'block_device_mapping': bdm}
# Tests that the parameters to the _get_guest_xml method
# are sanitized for passwords when logged.
def fake_debug(*args, **kwargs):
if 'auth_password' in args[0]:
self.assertNotIn('scrubme', args[0])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conf = mock.Mock()
with test.nested(
mock.patch.object(libvirt_driver.LOG, 'debug',
side_effect=fake_debug),
mock.patch.object(drvr, '_get_guest_config', return_value=conf)
) as (
debug_mock, conf_mock
):
drvr._get_guest_xml(self.context, self.test_instance,
network_info={}, disk_info={},
image_meta={}, block_device_info=bdi)
# we don't care what the log message is, we just want to make sure
# our stub method is called which asserts the password is scrubbed
self.assertTrue(debug_mock.called)
@mock.patch.object(time, "time")
def test_get_guest_config(self, time_mock):
time_mock.return_value = 1234567.89
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
test_instance = copy.deepcopy(self.test_instance)
test_instance["display_name"] = "purple tomatoes"
ctxt = context.RequestContext(project_id=123,
project_name="aubergine",
user_id=456,
user_name="pie")
flavor = objects.Flavor(name='m1.small',
memory_mb=6,
vcpus=28,
root_gb=496,
ephemeral_gb=8128,
swap=33550336,
extra_specs={})
instance_ref = objects.Instance(**test_instance)
instance_ref.flavor = flavor
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info,
context=ctxt)
self.assertEqual(cfg.uuid, instance_ref["uuid"])
self.assertEqual(2, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureAPIC)
self.assertEqual(cfg.memory, 6 * units.Ki)
self.assertEqual(cfg.vcpus, 28)
self.assertEqual(cfg.os_type, vm_mode.HVM)
self.assertEqual(cfg.os_boot_dev, ["hd"])
self.assertIsNone(cfg.os_root)
self.assertEqual(len(cfg.devices), 10)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(len(cfg.metadata), 1)
self.assertIsInstance(cfg.metadata[0],
vconfig.LibvirtConfigGuestMetaNovaInstance)
self.assertEqual(version.version_string_with_package(),
cfg.metadata[0].package)
self.assertEqual("purple tomatoes",
cfg.metadata[0].name)
self.assertEqual(1234567.89,
cfg.metadata[0].creationTime)
self.assertEqual("image",
cfg.metadata[0].roottype)
self.assertEqual(str(instance_ref["image_ref"]),
cfg.metadata[0].rootid)
self.assertIsInstance(cfg.metadata[0].owner,
vconfig.LibvirtConfigGuestMetaNovaOwner)
self.assertEqual(456,
cfg.metadata[0].owner.userid)
self.assertEqual("pie",
cfg.metadata[0].owner.username)
self.assertEqual(123,
cfg.metadata[0].owner.projectid)
self.assertEqual("aubergine",
cfg.metadata[0].owner.projectname)
self.assertIsInstance(cfg.metadata[0].flavor,
vconfig.LibvirtConfigGuestMetaNovaFlavor)
self.assertEqual("m1.small",
cfg.metadata[0].flavor.name)
self.assertEqual(6,
cfg.metadata[0].flavor.memory)
self.assertEqual(28,
cfg.metadata[0].flavor.vcpus)
self.assertEqual(496,
cfg.metadata[0].flavor.disk)
self.assertEqual(8128,
cfg.metadata[0].flavor.ephemeral)
self.assertEqual(33550336,
cfg.metadata[0].flavor.swap)
def test_get_guest_config_lxc(self):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, {'mapping': {}})
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
self.assertEqual(vm_mode.EXE, cfg.os_type)
self.assertEqual("/sbin/init", cfg.os_init_path)
self.assertEqual("console=tty0 console=ttyS0", cfg.os_cmdline)
self.assertIsNone(cfg.os_root)
self.assertEqual(3, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestFilesys)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestConsole)
def test_get_guest_config_lxc_with_id_maps(self):
self.flags(virt_type='lxc', group='libvirt')
self.flags(uid_maps=['0:1000:100'], group='libvirt')
self.flags(gid_maps=['0:1000:100'], group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, {'mapping': {}})
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.vcpus, cfg.vcpus)
self.assertEqual(vm_mode.EXE, cfg.os_type)
self.assertEqual("/sbin/init", cfg.os_init_path)
self.assertEqual("console=tty0 console=ttyS0", cfg.os_cmdline)
self.assertIsNone(cfg.os_root)
self.assertEqual(3, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestFilesys)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestConsole)
self.assertEqual(len(cfg.idmaps), 2)
self.assertIsInstance(cfg.idmaps[0],
vconfig.LibvirtConfigGuestUIDMap)
self.assertIsInstance(cfg.idmaps[1],
vconfig.LibvirtConfigGuestGIDMap)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_fits(self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps)):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_no_fit(self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=4096, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set', return_value=set([3])),
mock.patch.object(random, 'choice')
) as (get_host_cap_mock,
get_vcpu_pin_set_mock, choice_mock):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertFalse(choice_mock.called)
self.assertEqual(set([3]), cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
def _test_get_guest_memory_backing_config(
self, host_topology, inst_topology, numatune):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
with mock.patch.object(
drvr, "_get_host_numa_topology",
return_value=host_topology):
return drvr._get_guest_memory_backing_config(
inst_topology, numatune, {})
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_get_guest_memory_backing_config_large_success(self, mock_version):
host_topology = objects.NUMATopology(
cells=[
objects.NUMACell(
id=3, cpuset=set([1]), memory=1024, mempages=[
objects.NUMAPagesTopology(size_kb=4, total=2000,
used=0),
objects.NUMAPagesTopology(size_kb=2048, total=512,
used=0),
objects.NUMAPagesTopology(size_kb=1048576, total=0,
used=0),
])])
inst_topology = objects.InstanceNUMATopology(cells=[
objects.InstanceNUMACell(
id=3, cpuset=set([0, 1]), memory=1024, pagesize=2048)])
numa_tune = vconfig.LibvirtConfigGuestNUMATune()
numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()]
numa_tune.memnodes[0].cellid = 0
numa_tune.memnodes[0].nodeset = [3]
result = self._test_get_guest_memory_backing_config(
host_topology, inst_topology, numa_tune)
self.assertEqual(1, len(result.hugepages))
self.assertEqual(2048, result.hugepages[0].size_kb)
self.assertEqual([0], result.hugepages[0].nodeset)
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_get_guest_memory_backing_config_smallest(self, mock_version):
host_topology = objects.NUMATopology(
cells=[
objects.NUMACell(
id=3, cpuset=set([1]), memory=1024, mempages=[
objects.NUMAPagesTopology(size_kb=4, total=2000,
used=0),
objects.NUMAPagesTopology(size_kb=2048, total=512,
used=0),
objects.NUMAPagesTopology(size_kb=1048576, total=0,
used=0),
])])
inst_topology = objects.InstanceNUMATopology(cells=[
objects.InstanceNUMACell(
id=3, cpuset=set([0, 1]), memory=1024, pagesize=4)])
numa_tune = vconfig.LibvirtConfigGuestNUMATune()
numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()]
numa_tune.memnodes[0].cellid = 0
numa_tune.memnodes[0].nodeset = [3]
result = self._test_get_guest_memory_backing_config(
host_topology, inst_topology, numa_tune)
self.assertIsNone(result)
def test_get_guest_memory_backing_config_realtime(self):
flavor = {"extra_specs": {
"hw:cpu_realtime": "yes",
"hw:cpu_policy": "dedicated"
}}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
membacking = drvr._get_guest_memory_backing_config(
None, None, flavor)
self.assertTrue(membacking.locked)
self.assertFalse(membacking.sharedpages)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_pci_no_numa_info(
self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
pci_device_info = dict(test_pci_device.fake_db_dev)
pci_device_info.update(compute_node_id=1,
label='fake',
status=fields.PciDeviceStatus.AVAILABLE,
address='0000:00:00.1',
instance_uuid=None,
request_id=None,
extra_info={},
numa_node=None)
pci_device = objects.PciDevice(**pci_device_info)
with test.nested(
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(
host.Host, "get_capabilities", return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set', return_value=set([3])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
mock.patch.object(pci_manager, "get_instance_pci_devs",
return_value=[pci_device])):
cfg = conn._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(set([3]), cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_2pci_no_fit(self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=4096, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
pci_device_info = dict(test_pci_device.fake_db_dev)
pci_device_info.update(compute_node_id=1,
label='fake',
status=fields.PciDeviceStatus.AVAILABLE,
address='0000:00:00.1',
instance_uuid=None,
request_id=None,
extra_info={},
numa_node=1)
pci_device = objects.PciDevice(**pci_device_info)
pci_device_info.update(numa_node=0, address='0000:00:00.2')
pci_device2 = objects.PciDevice(**pci_device_info)
with test.nested(
mock.patch.object(
host.Host, "get_capabilities", return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set', return_value=set([3])),
mock.patch.object(random, 'choice'),
mock.patch.object(pci_manager, "get_instance_pci_devs",
return_value=[pci_device, pci_device2])
) as (get_host_cap_mock,
get_vcpu_pin_set_mock, choice_mock, pci_mock):
cfg = conn._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertFalse(choice_mock.called)
self.assertEqual(set([3]), cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
@mock.patch.object(fakelibvirt.Connection, 'getType')
@mock.patch.object(fakelibvirt.Connection, 'getVersion')
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
@mock.patch.object(host.Host, 'get_capabilities')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_set_host_enabled')
def _test_get_guest_config_numa_unsupported(self, fake_lib_version,
fake_version, fake_type,
fake_arch, exception_class,
pagesize, mock_host,
mock_caps, mock_lib_version,
mock_version, mock_type):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=0, cpuset=set([0]),
memory=1024, pagesize=pagesize)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = fake_arch
caps.host.topology = self._fake_caps_numa_topology()
mock_type.return_value = fake_type
mock_version.return_value = fake_version
mock_lib_version.return_value = fake_lib_version
mock_caps.return_value = caps
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.assertRaises(exception_class,
drvr._get_guest_config,
instance_ref, [],
image_meta, disk_info)
def test_get_guest_config_numa_old_version_libvirt(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) - 1,
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_old_version_libvirt_ppc(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION_PPC) - 1,
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.PPC64LE,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_bad_version_libvirt(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.BAD_LIBVIRT_NUMA_VERSIONS[0]),
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.NUMATopologyUnsupported,
None)
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_has_numa_support_bad_version_libvirt_log(self, mock_warn):
# Tests that a warning is logged once and only once when there is a bad
# BAD_LIBVIRT_NUMA_VERSIONS detected.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertFalse(hasattr(drvr, '_bad_libvirt_numa_version_warn'))
with mock.patch.object(drvr._host, 'has_version', return_value=True):
for i in range(2):
self.assertFalse(drvr._has_numa_support())
self.assertTrue(drvr._bad_libvirt_numa_version_warn)
self.assertEqual(1, mock_warn.call_count)
# assert the version is logged properly
self.assertEqual('1.2.9.2', mock_warn.call_args[0][1])
def test_get_guest_config_numa_old_version_qemu(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION),
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) - 1,
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_other_arch_qemu(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION),
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.S390,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_xen(self):
self.flags(virt_type='xen', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION),
versionutils.convert_version_to_int((4, 5, 0)),
'XEN',
arch.X86_64,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_old_pages_libvirt(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION) - 1,
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.MemoryPagesUnsupported,
2048)
def test_get_guest_config_numa_old_pages_qemu(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION),
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) - 1,
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.NUMATopologyUnsupported,
2048)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_fit_w_cpu_pinset(
self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=1024, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology(kb_mem=4194304)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set', return_value=set([2, 3])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8)))
) as (has_min_version_mock, get_host_cap_mock,
get_vcpu_pin_set_mock, get_online_cpus_mock):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
# NOTE(ndipanov): we make sure that pin_set was taken into account
# when choosing viable cells
self.assertEqual(set([2, 3]), cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_non_numa_host_instance_topo(self, is_able):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=0, cpuset=set([0]), memory=1024),
objects.InstanceNUMACell(
id=1, cpuset=set([2]), memory=1024)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps)):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.numatune)
self.assertIsNotNone(cfg.cpu.numa)
for instance_cell, numa_cfg_cell in zip(
instance_topology.cells, cfg.cpu.numa.cells):
self.assertEqual(instance_cell.id, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_topo(self, is_able):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]), memory=1024, pagesize=None),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]), memory=1024,
pagesize=None)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set',
return_value=set([2, 3, 4, 5])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
# Test that the pinning is correct and limited to allowed only
self.assertEqual(0, cfg.cputune.vcpupin[0].id)
self.assertEqual(set([2, 3]), cfg.cputune.vcpupin[0].cpuset)
self.assertEqual(1, cfg.cputune.vcpupin[1].id)
self.assertEqual(set([2, 3]), cfg.cputune.vcpupin[1].cpuset)
self.assertEqual(2, cfg.cputune.vcpupin[2].id)
self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[2].cpuset)
self.assertEqual(3, cfg.cputune.vcpupin[3].id)
self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[3].cpuset)
self.assertIsNotNone(cfg.cpu.numa)
self.assertIsInstance(cfg.cputune.emulatorpin,
vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
self.assertEqual(set([2, 3, 4, 5]), cfg.cputune.emulatorpin.cpuset)
for instance_cell, numa_cfg_cell, index in zip(
instance_topology.cells,
cfg.cpu.numa.cells,
range(len(instance_topology.cells))):
self.assertEqual(index, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
allnodes = [cell.id for cell in instance_topology.cells]
self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
self.assertEqual("strict", cfg.numatune.memory.mode)
for instance_cell, memnode, index in zip(
instance_topology.cells,
cfg.numatune.memnodes,
range(len(instance_topology.cells))):
self.assertEqual(index, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
def test_get_guest_config_numa_host_instance_topo_reordered(self):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=3, cpuset=set([0, 1]), memory=1024),
objects.InstanceNUMACell(
id=0, cpuset=set([2, 3]), memory=1024)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
# Test that the pinning is correct and limited to allowed only
self.assertEqual(0, cfg.cputune.vcpupin[0].id)
self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[0].cpuset)
self.assertEqual(1, cfg.cputune.vcpupin[1].id)
self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[1].cpuset)
self.assertEqual(2, cfg.cputune.vcpupin[2].id)
self.assertEqual(set([0, 1]), cfg.cputune.vcpupin[2].cpuset)
self.assertEqual(3, cfg.cputune.vcpupin[3].id)
self.assertEqual(set([0, 1]), cfg.cputune.vcpupin[3].cpuset)
self.assertIsNotNone(cfg.cpu.numa)
self.assertIsInstance(cfg.cputune.emulatorpin,
vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
self.assertEqual(set([0, 1, 6, 7]), cfg.cputune.emulatorpin.cpuset)
for index, (instance_cell, numa_cfg_cell) in enumerate(zip(
instance_topology.cells,
cfg.cpu.numa.cells)):
self.assertEqual(index, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
self.assertIsNone(numa_cfg_cell.memAccess)
allnodes = set([cell.id for cell in instance_topology.cells])
self.assertEqual(allnodes, set(cfg.numatune.memory.nodeset))
self.assertEqual("strict", cfg.numatune.memory.mode)
for index, (instance_cell, memnode) in enumerate(zip(
instance_topology.cells,
cfg.numatune.memnodes)):
self.assertEqual(index, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
def test_get_guest_config_numa_host_instance_topo_cpu_pinning(self):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]), memory=1024,
cpu_pinning={0: 24, 1: 25}),
objects.InstanceNUMACell(
id=0, cpuset=set([2, 3]), memory=1024,
cpu_pinning={2: 0, 3: 1})])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology(
sockets_per_cell=4, cores_per_socket=3, threads_per_core=2)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = conn._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
# Test that the pinning is correct and limited to allowed only
self.assertEqual(0, cfg.cputune.vcpupin[0].id)
self.assertEqual(set([24]), cfg.cputune.vcpupin[0].cpuset)
self.assertEqual(1, cfg.cputune.vcpupin[1].id)
self.assertEqual(set([25]), cfg.cputune.vcpupin[1].cpuset)
self.assertEqual(2, cfg.cputune.vcpupin[2].id)
self.assertEqual(set([0]), cfg.cputune.vcpupin[2].cpuset)
self.assertEqual(3, cfg.cputune.vcpupin[3].id)
self.assertEqual(set([1]), cfg.cputune.vcpupin[3].cpuset)
self.assertIsNotNone(cfg.cpu.numa)
# Emulator must be pinned to union of cfg.cputune.vcpupin[*].cpuset
self.assertIsInstance(cfg.cputune.emulatorpin,
vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
self.assertEqual(set([0, 1, 24, 25]),
cfg.cputune.emulatorpin.cpuset)
for i, (instance_cell, numa_cfg_cell) in enumerate(zip(
instance_topology.cells, cfg.cpu.numa.cells)):
self.assertEqual(i, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
self.assertIsNone(numa_cfg_cell.memAccess)
allnodes = set([cell.id for cell in instance_topology.cells])
self.assertEqual(allnodes, set(cfg.numatune.memory.nodeset))
self.assertEqual("strict", cfg.numatune.memory.mode)
for i, (instance_cell, memnode) in enumerate(zip(
instance_topology.cells, cfg.numatune.memnodes)):
self.assertEqual(i, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
def test_get_guest_config_numa_host_mempages_shared(self):
instance_topology = objects.InstanceNUMATopology(
cells=[
objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]),
memory=1024, pagesize=2048),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]),
memory=1024, pagesize=2048)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set',
return_value=set([2, 3, 4, 5])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for instance_cell, numa_cfg_cell, index in zip(
instance_topology.cells,
cfg.cpu.numa.cells,
range(len(instance_topology.cells))):
self.assertEqual(index, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
self.assertEqual("shared", numa_cfg_cell.memAccess)
allnodes = [cell.id for cell in instance_topology.cells]
self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
self.assertEqual("strict", cfg.numatune.memory.mode)
for instance_cell, memnode, index in zip(
instance_topology.cells,
cfg.numatune.memnodes,
range(len(instance_topology.cells))):
self.assertEqual(index, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
self.assertEqual(0, len(cfg.cputune.vcpusched))
self.assertEqual(set([2, 3, 4, 5]), cfg.cputune.emulatorpin.cpuset)
def test_get_guest_config_numa_host_instance_cpu_pinning_realtime(self):
instance_topology = objects.InstanceNUMATopology(
cells=[
objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]),
memory=1024, pagesize=2048),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]),
memory=1024, pagesize=2048)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={
"hw:cpu_realtime": "yes",
"hw:cpu_policy": "dedicated",
"hw:cpu_realtime_mask": "^0-1"
})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set',
return_value=set([2, 3, 4, 5])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for instance_cell, numa_cfg_cell, index in zip(
instance_topology.cells,
cfg.cpu.numa.cells,
range(len(instance_topology.cells))):
self.assertEqual(index, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
self.assertEqual("shared", numa_cfg_cell.memAccess)
allnodes = [cell.id for cell in instance_topology.cells]
self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
self.assertEqual("strict", cfg.numatune.memory.mode)
for instance_cell, memnode, index in zip(
instance_topology.cells,
cfg.numatune.memnodes,
range(len(instance_topology.cells))):
self.assertEqual(index, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
self.assertEqual(1, len(cfg.cputune.vcpusched))
self.assertEqual("fifo", cfg.cputune.vcpusched[0].scheduler)
self.assertEqual(set([2, 3]), cfg.cputune.vcpusched[0].vcpus)
self.assertEqual(set([0, 1]), cfg.cputune.emulatorpin.cpuset)
def test_get_cpu_numa_config_from_instance(self):
topology = objects.InstanceNUMATopology(cells=[
objects.InstanceNUMACell(id=0, cpuset=set([1, 2]), memory=128),
objects.InstanceNUMACell(id=1, cpuset=set([3, 4]), memory=128),
])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conf = drvr._get_cpu_numa_config_from_instance(topology, True)
self.assertIsInstance(conf, vconfig.LibvirtConfigGuestCPUNUMA)
self.assertEqual(0, conf.cells[0].id)
self.assertEqual(set([1, 2]), conf.cells[0].cpus)
self.assertEqual(131072, conf.cells[0].memory)
self.assertEqual("shared", conf.cells[0].memAccess)
self.assertEqual(1, conf.cells[1].id)
self.assertEqual(set([3, 4]), conf.cells[1].cpus)
self.assertEqual(131072, conf.cells[1].memory)
self.assertEqual("shared", conf.cells[1].memAccess)
def test_get_cpu_numa_config_from_instance_none(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conf = drvr._get_cpu_numa_config_from_instance(None, False)
self.assertIsNone(conf)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
return_value=True)
def test_get_memnode_numa_config_from_instance(self, mock_numa):
instance_topology = objects.InstanceNUMATopology(cells=[
objects.InstanceNUMACell(id=0, cpuset=set([1, 2]), memory=128),
objects.InstanceNUMACell(id=1, cpuset=set([3, 4]), memory=128),
objects.InstanceNUMACell(id=16, cpuset=set([5, 6]), memory=128)
])
host_topology = objects.NUMATopology(
cells=[
objects.NUMACell(
id=0, cpuset=set([1, 2]), memory=1024, mempages=[]),
objects.NUMACell(
id=1, cpuset=set([3, 4]), memory=1024, mempages=[]),
objects.NUMACell(
id=16, cpuset=set([5, 6]), memory=1024, mempages=[])])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
with test.nested(
mock.patch.object(drvr, "_get_host_numa_topology",
return_value=host_topology)):
guest_numa_config = drvr._get_guest_numa_config(instance_topology,
flavor={}, allowed_cpus=[1, 2, 3, 4, 5, 6], image_meta={})
self.assertEqual(2, guest_numa_config.numatune.memnodes[2].cellid)
self.assertEqual([16],
guest_numa_config.numatune.memnodes[2].nodeset)
self.assertEqual(set([5, 6]),
guest_numa_config.numaconfig.cells[2].cpus)
@mock.patch.object(host.Host, 'has_version', return_value=True)
def test_has_cpu_policy_support(self, mock_has_version):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.CPUPinningNotSupported,
drvr._has_cpu_policy_support)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
return_value=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_hugepage_support",
return_value=True)
@mock.patch.object(host.Host, "get_capabilities")
def test_does_not_want_hugepages(self, mock_caps, mock_hp, mock_numa):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_topology = objects.InstanceNUMATopology(
cells=[
objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]),
memory=1024, pagesize=4),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]),
memory=1024, pagesize=4)])
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
mock_caps.return_value = caps
host_topology = drvr._get_host_numa_topology()
self.assertFalse(drvr._wants_hugepages(None, None))
self.assertFalse(drvr._wants_hugepages(host_topology, None))
self.assertFalse(drvr._wants_hugepages(None, instance_topology))
self.assertFalse(drvr._wants_hugepages(host_topology,
instance_topology))
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
return_value=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_hugepage_support",
return_value=True)
@mock.patch.object(host.Host, "get_capabilities")
def test_does_want_hugepages(self, mock_caps, mock_hp, mock_numa):
for each_arch in [arch.I686, arch.X86_64, arch.PPC64LE, arch.PPC64]:
self._test_does_want_hugepages(
mock_caps, mock_hp, mock_numa, each_arch)
def _test_does_want_hugepages(self, mock_caps, mock_hp, mock_numa,
architecture):
self.flags(reserved_huge_pages=[
{'node': 0, 'size': 2048, 'count': 128},
{'node': 1, 'size': 2048, 'count': 1},
{'node': 3, 'size': 2048, 'count': 64}])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_topology = objects.InstanceNUMATopology(
cells=[
objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]),
memory=1024, pagesize=2048),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]),
memory=1024, pagesize=2048)])
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = architecture
caps.host.topology = self._fake_caps_numa_topology()
mock_caps.return_value = caps
host_topology = drvr._get_host_numa_topology()
self.assertEqual(128, host_topology.cells[0].mempages[1].reserved)
self.assertEqual(1, host_topology.cells[1].mempages[1].reserved)
self.assertEqual(0, host_topology.cells[2].mempages[1].reserved)
self.assertEqual(64, host_topology.cells[3].mempages[1].reserved)
self.assertTrue(drvr._wants_hugepages(host_topology,
instance_topology))
def test_get_guest_config_clock(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
hpet_map = {
arch.X86_64: True,
arch.I686: True,
arch.PPC: False,
arch.PPC64: False,
arch.ARMV7: False,
arch.AARCH64: False,
}
for guestarch, expect_hpet in hpet_map.items():
with mock.patch.object(libvirt_driver.libvirt_utils,
'get_arch',
return_value=guestarch):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta,
disk_info)
self.assertIsInstance(cfg.clock,
vconfig.LibvirtConfigGuestClock)
self.assertEqual(cfg.clock.offset, "utc")
self.assertIsInstance(cfg.clock.timers[0],
vconfig.LibvirtConfigGuestTimer)
self.assertIsInstance(cfg.clock.timers[1],
vconfig.LibvirtConfigGuestTimer)
self.assertEqual(cfg.clock.timers[0].name, "pit")
self.assertEqual(cfg.clock.timers[0].tickpolicy,
"delay")
self.assertEqual(cfg.clock.timers[1].name, "rtc")
self.assertEqual(cfg.clock.timers[1].tickpolicy,
"catchup")
if expect_hpet:
self.assertEqual(3, len(cfg.clock.timers))
self.assertIsInstance(cfg.clock.timers[2],
vconfig.LibvirtConfigGuestTimer)
self.assertEqual('hpet', cfg.clock.timers[2].name)
self.assertFalse(cfg.clock.timers[2].present)
else:
self.assertEqual(2, len(cfg.clock.timers))
@mock.patch.object(libvirt_utils, 'get_arch')
@mock.patch.object(host.Host, 'has_min_version')
def test_get_guest_config_windows(self, mock_version, mock_get_arch):
mock_version.return_value = False
mock_get_arch.return_value = arch.I686
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref['os_type'] = 'windows'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(cfg.clock,
vconfig.LibvirtConfigGuestClock)
self.assertEqual(cfg.clock.offset, "localtime")
self.assertEqual(3, len(cfg.clock.timers), cfg.clock.timers)
self.assertEqual("pit", cfg.clock.timers[0].name)
self.assertEqual("rtc", cfg.clock.timers[1].name)
self.assertEqual("hpet", cfg.clock.timers[2].name)
self.assertFalse(cfg.clock.timers[2].present)
@mock.patch.object(libvirt_utils, 'get_arch')
@mock.patch.object(host.Host, 'has_min_version')
def test_get_guest_config_windows_timer(self, mock_version, mock_get_arch):
mock_version.return_value = True
mock_get_arch.return_value = arch.I686
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref['os_type'] = 'windows'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(cfg.clock,
vconfig.LibvirtConfigGuestClock)
self.assertEqual(cfg.clock.offset, "localtime")
self.assertEqual(4, len(cfg.clock.timers), cfg.clock.timers)
self.assertEqual("pit", cfg.clock.timers[0].name)
self.assertEqual("rtc", cfg.clock.timers[1].name)
self.assertEqual("hpet", cfg.clock.timers[2].name)
self.assertFalse(cfg.clock.timers[2].present)
self.assertEqual("hypervclock", cfg.clock.timers[3].name)
self.assertTrue(cfg.clock.timers[3].present)
self.assertEqual(3, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureAPIC)
self.assertIsInstance(cfg.features[2],
vconfig.LibvirtConfigGuestFeatureHyperV)
@mock.patch.object(host.Host, 'has_min_version')
def test_get_guest_config_windows_hyperv_feature2(self, mock_version):
mock_version.return_value = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref['os_type'] = 'windows'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(cfg.clock,
vconfig.LibvirtConfigGuestClock)
self.assertEqual(cfg.clock.offset, "localtime")
self.assertEqual(3, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureAPIC)
self.assertIsInstance(cfg.features[2],
vconfig.LibvirtConfigGuestFeatureHyperV)
self.assertTrue(cfg.features[2].relaxed)
self.assertTrue(cfg.features[2].spinlocks)
self.assertEqual(8191, cfg.features[2].spinlock_retries)
self.assertTrue(cfg.features[2].vapic)
def test_get_guest_config_with_two_nics(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 2),
image_meta, disk_info)
self.assertEqual(2, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureAPIC)
self.assertEqual(cfg.memory, instance_ref.flavor.memory_mb * units.Ki)
self.assertEqual(cfg.vcpus, instance_ref.flavor.vcpus)
self.assertEqual(cfg.os_type, vm_mode.HVM)
self.assertEqual(cfg.os_boot_dev, ["hd"])
self.assertIsNone(cfg.os_root)
self.assertEqual(len(cfg.devices), 10)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
def test_get_guest_config_bug_1118829(self):
self.flags(virt_type='uml', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
disk_info = {'disk_bus': 'virtio',
'cdrom_bus': 'ide',
'mapping': {u'vda': {'bus': 'virtio',
'type': 'disk',
'dev': u'vda'},
'root': {'bus': 'virtio',
'type': 'disk',
'dev': 'vda'}}}
# NOTE(jdg): For this specific test leave this blank
# This will exercise the failed code path still,
# and won't require fakes and stubs of the iscsi discovery
block_device_info = {}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
drvr._get_guest_config(instance_ref, [], image_meta, disk_info,
None, block_device_info)
self.assertEqual(instance_ref['root_device_name'], '/dev/vda')
def test_get_guest_config_with_root_device_name(self):
self.flags(virt_type='uml', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
block_device_info = {'root_device_name': '/dev/vdb'}
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
block_device_info)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info,
None, block_device_info)
self.assertEqual(0, len(cfg.features))
self.assertEqual(cfg.memory, instance_ref.flavor.memory_mb * units.Ki)
self.assertEqual(cfg.vcpus, instance_ref.flavor.vcpus)
self.assertEqual(cfg.os_type, "uml")
self.assertEqual(cfg.os_boot_dev, [])
self.assertEqual(cfg.os_root, '/dev/vdb')
self.assertEqual(len(cfg.devices), 3)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestConsole)
def test_has_uefi_support_with_invalid_version(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
with mock.patch.object(drvr._host,
'has_min_version', return_value=False):
self.assertFalse(drvr._has_uefi_support())
def test_has_uefi_support_not_supported_arch(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "alpha"
self.assertFalse(drvr._has_uefi_support())
@mock.patch('os.path.exists', return_value=False)
def test_has_uefi_support_with_no_loader_existed(self, mock_exist):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertFalse(drvr._has_uefi_support())
@mock.patch('os.path.exists', return_value=True)
def test_has_uefi_support(self, mock_has_version):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
with mock.patch.object(drvr._host,
'has_min_version', return_value=True):
self.assertTrue(drvr._has_uefi_support())
def test_get_guest_config_with_uefi(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_firmware_type": "uefi"}})
instance_ref = objects.Instance(**self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with mock.patch.object(drvr, "_has_uefi_support",
return_value=True) as mock_support:
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
mock_support.assert_called_once_with()
self.assertEqual(cfg.os_loader_type, "pflash")
def test_get_guest_config_with_block_device(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
conn_info = {'driver_volume_type': 'fake'}
bdms = block_device_obj.block_device_make_list_from_dicts(
self.context, [
fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vdc'}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vdd'}),
]
)
info = {'block_device_mapping': driver_block_device.convert_volumes(
bdms
)}
info['block_device_mapping'][0]['connection_info'] = conn_info
info['block_device_mapping'][1]['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
info)
with mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'
) as mock_save:
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info,
None, info)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[2].target_dev, 'vdc')
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[3].target_dev, 'vdd')
mock_save.assert_called_with()
def test_get_guest_config_lxc_with_attached_volume(self):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
conn_info = {'driver_volume_type': 'fake'}
bdms = block_device_obj.block_device_make_list_from_dicts(
self.context, [
fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'source_type': 'volume', 'destination_type': 'volume',
'boot_index': 0}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'source_type': 'volume', 'destination_type': 'volume',
}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 3,
'source_type': 'volume', 'destination_type': 'volume',
}),
]
)
info = {'block_device_mapping': driver_block_device.convert_volumes(
bdms
)}
info['block_device_mapping'][0]['connection_info'] = conn_info
info['block_device_mapping'][1]['connection_info'] = conn_info
info['block_device_mapping'][2]['connection_info'] = conn_info
info['block_device_mapping'][0]['mount_device'] = '/dev/vda'
info['block_device_mapping'][1]['mount_device'] = '/dev/vdc'
info['block_device_mapping'][2]['mount_device'] = '/dev/vdd'
with mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'
) as mock_save:
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
info)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info,
None, info)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[1].target_dev, 'vdc')
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[2].target_dev, 'vdd')
mock_save.assert_called_with()
def test_get_guest_config_with_configdrive(self):
# It's necessary to check if the architecture is power, because
# power doesn't have support to ide, and so libvirt translate
# all ide calls to scsi
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
# make configdrive.required_by() return True
instance_ref['config_drive'] = True
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
# The last device is selected for this. on x86 is the last ide
# device (hdd). Since power only support scsi, the last device
# is sdz
expect = {"ppc": "sdz", "ppc64": "sdz",
"ppc64le": "sdz", "aarch64": "sdz"}
disk = expect.get(blockinfo.libvirt_utils.get_arch({}), "hdd")
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[2].target_dev, disk)
def test_get_guest_config_with_virtio_scsi_bus(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_scsi_model": "virtio-scsi"}})
instance_ref = objects.Instance(**self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
[])
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestController)
self.assertEqual(cfg.devices[2].model, 'virtio-scsi')
def test_get_guest_config_with_virtio_scsi_bus_bdm(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_scsi_model": "virtio-scsi"}})
instance_ref = objects.Instance(**self.test_instance)
conn_info = {'driver_volume_type': 'fake'}
bdms = block_device_obj.block_device_make_list_from_dicts(
self.context, [
fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sdc', 'disk_bus': 'scsi'}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sdd', 'disk_bus': 'scsi'}),
]
)
bd_info = {
'block_device_mapping': driver_block_device.convert_volumes(bdms)}
bd_info['block_device_mapping'][0]['connection_info'] = conn_info
bd_info['block_device_mapping'][1]['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
bd_info)
with mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'
) as mock_save:
cfg = drvr._get_guest_config(instance_ref, [], image_meta,
disk_info, [], bd_info)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[2].target_dev, 'sdc')
self.assertEqual(cfg.devices[2].target_bus, 'scsi')
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[3].target_dev, 'sdd')
self.assertEqual(cfg.devices[3].target_bus, 'scsi')
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestController)
self.assertEqual(cfg.devices[4].model, 'virtio-scsi')
mock_save.assert_called_with()
def test_get_guest_config_with_vnc(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='kvm', group='libvirt')
self.flags(pointer_model='ps2mouse')
self.flags(enabled=False, group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 7)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "vnc")
def test_get_guest_config_with_vnc_and_tablet(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=True,
group='libvirt')
self.flags(enabled=False, group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].type, "vnc")
def test_get_guest_config_with_spice_and_tablet(self):
self.flags(enabled=False, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=True,
group='libvirt')
self.flags(enabled=True,
agent_enabled=False,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].type, "spice")
def test_get_guest_config_with_spice_and_agent(self):
self.flags(enabled=False, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=True,
group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestChannel)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].target_name, "com.redhat.spice.0")
self.assertEqual(cfg.devices[5].type, "spice")
self.assertEqual(cfg.devices[6].type, "qxl")
@mock.patch('nova.console.serial.acquire_port')
@mock.patch('nova.virt.hardware.get_number_of_serial_ports',
return_value=1)
@mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',)
def test_create_serial_console_devices_based_on_arch(self, mock_get_arch,
mock_get_port_number,
mock_acquire_port):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
expected = {arch.X86_64: vconfig.LibvirtConfigGuestSerial,
arch.S390: vconfig.LibvirtConfigGuestConsole,
arch.S390X: vconfig.LibvirtConfigGuestConsole}
for guest_arch, device_type in expected.items():
mock_get_arch.return_value = guest_arch
guest = vconfig.LibvirtConfigGuest()
drvr._create_serial_console_devices(guest, instance=None,
flavor={}, image_meta={})
self.assertEqual(1, len(guest.devices))
console_device = guest.devices[0]
self.assertIsInstance(console_device, device_type)
self.assertEqual("tcp", console_device.type)
@mock.patch('nova.virt.hardware.get_number_of_serial_ports',
return_value=4)
@mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',
side_effect=[arch.X86_64, arch.S390, arch.S390X])
def test_create_serial_console_devices_with_limit_exceeded_based_on_arch(
self, mock_get_arch, mock_get_port_number):
self.flags(enabled=True, group='serial_console')
self.flags(virt_type="qemu", group='libvirt')
flavor = 'fake_flavor'
image_meta = objects.ImageMeta()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
guest = vconfig.LibvirtConfigGuest()
self.assertRaises(exception.SerialPortNumberLimitExceeded,
drvr._create_serial_console_devices,
guest, None, flavor, image_meta)
mock_get_arch.assert_called_with(image_meta)
mock_get_port_number.assert_called_with(flavor,
image_meta)
drvr._create_serial_console_devices(guest, None, flavor, image_meta)
mock_get_arch.assert_called_with(image_meta)
mock_get_port_number.assert_called_with(flavor,
image_meta)
drvr._create_serial_console_devices(guest, None, flavor, image_meta)
mock_get_arch.assert_called_with(image_meta)
mock_get_port_number.assert_called_with(flavor,
image_meta)
@mock.patch('nova.console.serial.acquire_port')
def test_get_guest_config_serial_console(self, acquire_port):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
acquire_port.return_value = 11111
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(8, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("tcp", cfg.devices[2].type)
self.assertEqual(11111, cfg.devices[2].listen_port)
def test_get_guest_config_serial_console_through_flavor(self):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw:serial_port_count': 3}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(10, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("tcp", cfg.devices[2].type)
self.assertEqual("tcp", cfg.devices[3].type)
self.assertEqual("tcp", cfg.devices[4].type)
def test_get_guest_config_serial_console_invalid_flavor(self):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw:serial_port_count': "a"}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.assertRaises(
exception.ImageSerialPortNumberInvalid,
drvr._get_guest_config, instance_ref, [],
image_meta, disk_info)
def test_get_guest_config_serial_console_image_and_flavor(self):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_serial_port_count": "3"}})
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw:serial_port_count': 4}
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta,
disk_info)
self.assertEqual(10, len(cfg.devices), cfg.devices)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("tcp", cfg.devices[2].type)
self.assertEqual("tcp", cfg.devices[3].type)
self.assertEqual("tcp", cfg.devices[4].type)
@mock.patch('nova.console.serial.acquire_port')
def test_get_guest_config_serial_console_through_port_rng_exhausted(
self, acquire_port):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
acquire_port.side_effect = exception.SocketPortRangeExhaustedException(
'127.0.0.1')
self.assertRaises(
exception.SocketPortRangeExhaustedException,
drvr._get_guest_config, instance_ref, [],
image_meta, disk_info)
@mock.patch('nova.console.serial.release_port')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info')
@mock.patch.object(host.Host, 'get_guest')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_get_serial_ports_from_guest')
def test_serial_console_release_port(
self, mock_get_serial_ports_from_guest, mock_get_guest,
mock_get_info, mock_release_port):
self.flags(enabled="True", group='serial_console')
guest = libvirt_guest.Guest(FakeVirtDomain())
guest.power_off = mock.Mock()
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.SHUTDOWN)
mock_get_guest.return_value = guest
mock_get_serial_ports_from_guest.return_value = iter([
('127.0.0.1', 10000), ('127.0.0.1', 10001)])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._destroy(objects.Instance(**self.test_instance))
mock_release_port.assert_has_calls(
[mock.call(host='127.0.0.1', port=10000),
mock.call(host='127.0.0.1', port=10001)])
@mock.patch('os.path.getsize', return_value=0) # size doesn't matter
@mock.patch('nova.virt.libvirt.storage.lvm.get_volume_size',
return_value='fake-size')
def test_detach_encrypted_volumes(self, mock_getsize,
mock_get_volume_size):
"""Test that unencrypted volumes are not disconnected with dmcrypt."""
instance = objects.Instance(**self.test_instance)
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<driver name='fake-driver' type='fake-type' />
<source file='filename'/>
<target dev='vdc' bus='virtio'/>
</disk>
<disk type='block' device='disk'>
<driver name='fake-driver' type='fake-type' />
<source dev='/dev/mapper/disk'/>
<target dev='vda'/>
</disk>
<disk type='block' device='disk'>
<driver name='fake-driver' type='fake-type' />
<source dev='/dev/mapper/swap'/>
<target dev='vdb'/>
</disk>
</devices>
</domain>
"""
dom = FakeVirtDomain(fake_xml=xml)
instance.ephemeral_key_uuid = uuids.ephemeral_key_uuid # encrypted
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
@mock.patch.object(dmcrypt, 'delete_volume')
@mock.patch.object(conn._host, 'get_domain', return_value=dom)
def detach_encrypted_volumes(block_device_info, mock_get_domain,
mock_delete_volume):
conn._detach_encrypted_volumes(instance, block_device_info)
mock_get_domain.assert_called_once_with(instance)
self.assertFalse(mock_delete_volume.called)
block_device_info = {'root_device_name': '/dev/vda',
'ephemerals': [],
'block_device_mapping': []}
detach_encrypted_volumes(block_device_info)
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_serial_ports_from_guest(self, mock_get_xml_desc):
i = self._test_get_serial_ports_from_guest(None,
mock_get_xml_desc)
self.assertEqual([
('127.0.0.1', 100),
('127.0.0.1', 101),
('127.0.0.2', 100),
('127.0.0.2', 101)], list(i))
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_serial_ports_from_guest_bind_only(self, mock_get_xml_desc):
i = self._test_get_serial_ports_from_guest('bind',
mock_get_xml_desc)
self.assertEqual([
('127.0.0.1', 101),
('127.0.0.2', 100)], list(i))
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_serial_ports_from_guest_connect_only(self,
mock_get_xml_desc):
i = self._test_get_serial_ports_from_guest('connect',
mock_get_xml_desc)
self.assertEqual([
('127.0.0.1', 100),
('127.0.0.2', 101)], list(i))
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_serial_ports_from_guest_on_s390(self, mock_get_xml_desc):
i = self._test_get_serial_ports_from_guest(None,
mock_get_xml_desc,
'console')
self.assertEqual([
('127.0.0.1', 100),
('127.0.0.1', 101),
('127.0.0.2', 100),
('127.0.0.2', 101)], list(i))
def _test_get_serial_ports_from_guest(self, mode, mock_get_xml_desc,
dev_name='serial'):
xml = """
<domain type='kvm'>
<devices>
<%(dev_name)s type="tcp">
<source host="127.0.0.1" service="100" mode="connect"/>
</%(dev_name)s>
<%(dev_name)s type="tcp">
<source host="127.0.0.1" service="101" mode="bind"/>
</%(dev_name)s>
<%(dev_name)s type="tcp">
<source host="127.0.0.2" service="100" mode="bind"/>
</%(dev_name)s>
<%(dev_name)s type="tcp">
<source host="127.0.0.2" service="101" mode="connect"/>
</%(dev_name)s>
</devices>
</domain>""" % {'dev_name': dev_name}
mock_get_xml_desc.return_value = xml
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
guest = libvirt_guest.Guest(FakeVirtDomain())
return drvr._get_serial_ports_from_guest(guest, mode=mode)
def test_get_guest_config_with_type_xen(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='xen',
use_usb_tablet=False,
group='libvirt')
self.flags(enabled=False,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 6)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestConsole)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[3].type, "vnc")
self.assertEqual(cfg.devices[4].type, "xen")
@mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',
return_value=arch.S390X)
def test_get_guest_config_with_type_kvm_on_s390(self, mock_get_arch):
self.flags(enabled=False, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=False,
group='libvirt')
self._stub_host_capabilities_cpu_arch(arch.S390X)
instance_ref = objects.Instance(**self.test_instance)
cfg = self._get_guest_config_via_fake_api(instance_ref)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
log_file_device = cfg.devices[2]
self.assertIsInstance(log_file_device,
vconfig.LibvirtConfigGuestConsole)
self.assertEqual("sclplm", log_file_device.target_type)
self.assertEqual("file", log_file_device.type)
terminal_device = cfg.devices[3]
self.assertIsInstance(terminal_device,
vconfig.LibvirtConfigGuestConsole)
self.assertEqual("sclp", terminal_device.target_type)
self.assertEqual("pty", terminal_device.type)
self.assertEqual("s390-ccw-virtio", cfg.os_mach_type)
def _stub_host_capabilities_cpu_arch(self, cpu_arch):
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.arch = cpu_arch
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
return caps
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
def _get_guest_config_via_fake_api(self, instance):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
return drvr._get_guest_config(instance, [],
image_meta, disk_info)
def test_get_guest_config_with_type_xen_pae_hvm(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='xen',
use_usb_tablet=False,
group='libvirt')
self.flags(enabled=False,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref['vm_mode'] = vm_mode.HVM
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(cfg.os_type, vm_mode.HVM)
self.assertEqual(cfg.os_loader, CONF.libvirt.xen_hvmloader_path)
self.assertEqual(3, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeaturePAE)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[2],
vconfig.LibvirtConfigGuestFeatureAPIC)
def test_get_guest_config_with_type_xen_pae_pvm(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='xen',
use_usb_tablet=False,
group='libvirt')
self.flags(enabled=False,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(cfg.os_type, vm_mode.XEN)
self.assertEqual(1, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeaturePAE)
def test_get_guest_config_with_vnc_and_spice(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=True,
group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 10)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestChannel)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].target_name, "com.redhat.spice.0")
self.assertEqual(cfg.devices[6].type, "vnc")
self.assertEqual(cfg.devices[7].type, "spice")
def test_get_guest_config_with_watchdog_action_image_meta(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_watchdog_action": "none"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertEqual(len(cfg.devices), 9)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestWatchdog)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("none", cfg.devices[7].action)
def _test_get_guest_usb_tablet(self, vnc_enabled, spice_enabled, os_type,
agent_enabled=False, image_meta=None):
self.flags(enabled=vnc_enabled, group='vnc')
self.flags(enabled=spice_enabled,
agent_enabled=agent_enabled, group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict(image_meta)
return drvr._get_guest_pointer_model(os_type, image_meta)
def test_use_ps2_mouse(self):
self.flags(pointer_model='ps2mouse')
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNone(tablet)
def test_get_guest_usb_tablet_wipe(self):
self.flags(use_usb_tablet=True, group='libvirt')
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(True, False, vm_mode.HVM)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(False, True, vm_mode.HVM)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(False, False, vm_mode.HVM)
self.assertIsNone(tablet)
tablet = self._test_get_guest_usb_tablet(True, True, "foo")
self.assertIsNone(tablet)
tablet = self._test_get_guest_usb_tablet(
False, True, vm_mode.HVM, True)
self.assertIsNone(tablet)
def test_get_guest_usb_tablet_image_meta(self):
self.flags(use_usb_tablet=True, group='libvirt')
image_meta = {"properties": {"hw_pointer_model": "usbtablet"}}
tablet = self._test_get_guest_usb_tablet(
True, True, vm_mode.HVM, image_meta=image_meta)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(
True, False, vm_mode.HVM, image_meta=image_meta)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(
False, True, vm_mode.HVM, image_meta=image_meta)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(
False, False, vm_mode.HVM, image_meta=image_meta)
self.assertIsNone(tablet)
tablet = self._test_get_guest_usb_tablet(
True, True, "foo", image_meta=image_meta)
self.assertIsNone(tablet)
tablet = self._test_get_guest_usb_tablet(
False, True, vm_mode.HVM, True, image_meta=image_meta)
self.assertIsNone(tablet)
def test_get_guest_usb_tablet_image_meta_no_vnc(self):
self.flags(use_usb_tablet=False, group='libvirt')
self.flags(pointer_model=None)
image_meta = {"properties": {"hw_pointer_model": "usbtablet"}}
self.assertRaises(
exception.UnsupportedPointerModelRequested,
self._test_get_guest_usb_tablet,
False, False, vm_mode.HVM, True, image_meta=image_meta)
def test_get_guest_no_pointer_model_usb_tablet_set(self):
self.flags(use_usb_tablet=True, group='libvirt')
self.flags(pointer_model=None)
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNotNone(tablet)
def test_get_guest_no_pointer_model_usb_tablet_not_set(self):
self.flags(use_usb_tablet=False, group='libvirt')
self.flags(pointer_model=None)
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNone(tablet)
def test_get_guest_pointer_model_usb_tablet(self):
self.flags(use_usb_tablet=False, group='libvirt')
self.flags(pointer_model='usbtablet')
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNotNone(tablet)
def test_get_guest_pointer_model_usb_tablet_image(self):
image_meta = {"properties": {"hw_pointer_model": "usbtablet"}}
tablet = self._test_get_guest_usb_tablet(
True, True, vm_mode.HVM, image_meta=image_meta)
self.assertIsNotNone(tablet)
def test_get_guest_pointer_model_usb_tablet_image_no_HVM(self):
self.flags(pointer_model=None)
self.flags(use_usb_tablet=False, group='libvirt')
image_meta = {"properties": {"hw_pointer_model": "usbtablet"}}
self.assertRaises(
exception.UnsupportedPointerModelRequested,
self._test_get_guest_usb_tablet,
True, True, vm_mode.XEN, image_meta=image_meta)
def _test_get_guest_config_with_watchdog_action_flavor(self,
hw_watchdog_action="hw:watchdog_action"):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {hw_watchdog_action: 'none'}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(9, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestWatchdog)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("none", cfg.devices[7].action)
def test_get_guest_config_with_watchdog_action_through_flavor(self):
self._test_get_guest_config_with_watchdog_action_flavor()
# TODO(pkholkin): the test accepting old property name 'hw_watchdog_action'
# should be removed in the next release
def test_get_guest_config_with_watchdog_action_through_flavor_no_scope(
self):
self._test_get_guest_config_with_watchdog_action_flavor(
hw_watchdog_action="hw_watchdog_action")
def test_get_guest_config_with_watchdog_overrides_flavor(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_watchdog_action': 'none'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_watchdog_action": "pause"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(9, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestWatchdog)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("pause", cfg.devices[7].action)
def test_get_guest_config_with_video_driver_image_meta(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_video_model": "vmvga"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[5].type, "vnc")
self.assertEqual(cfg.devices[6].type, "vmvga")
def test_get_guest_config_with_qga_through_image_meta(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_qemu_guest_agent": "yes"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertEqual(len(cfg.devices), 9)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestChannel)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].type, "vnc")
self.assertEqual(cfg.devices[7].type, "unix")
self.assertEqual(cfg.devices[7].target_name, "org.qemu.guest_agent.0")
def test_get_guest_config_with_video_driver_vram(self):
self.flags(enabled=False, group='vnc')
self.flags(virt_type='kvm', group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_video:ram_max_mb': "100"}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_video_model": "qxl",
"hw_video_ram": "64"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestChannel)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[5].type, "spice")
self.assertEqual(cfg.devices[6].type, "qxl")
self.assertEqual(cfg.devices[6].vram, 64 * units.Mi / units.Ki)
@mock.patch('nova.virt.disk.api.teardown_container')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info')
@mock.patch('nova.virt.disk.api.setup_container')
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch.object(fake_libvirt_utils, 'get_instance_path')
def test_unmount_fs_if_error_during_lxc_create_domain(self,
mock_get_inst_path, mock_ensure_tree, mock_setup_container,
mock_get_info, mock_teardown):
"""If we hit an error during a `_create_domain` call to `libvirt+lxc`
we need to ensure the guest FS is unmounted from the host so that any
future `lvremove` calls will work.
"""
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_instance = mock.MagicMock()
mock_get_inst_path.return_value = '/tmp/'
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_image = mock.MagicMock()
mock_image.path = '/tmp/test.img'
drvr.image_backend.image.return_value = mock_image
mock_setup_container.return_value = '/dev/nbd0'
mock_get_info.side_effect = exception.InstanceNotFound(
instance_id='foo')
drvr._conn.defineXML = mock.Mock()
drvr._conn.defineXML.side_effect = ValueError('somethingbad')
with test.nested(
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr, 'firewall_driver'),
mock.patch.object(drvr, 'cleanup')):
self.assertRaises(ValueError,
drvr._create_domain_and_network,
self.context,
'xml',
mock_instance, None, None)
mock_teardown.assert_called_with(container_dir='/tmp/rootfs')
def test_video_driver_flavor_limit_not_set(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_video_model": "qxl",
"hw_video_ram": "64"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with mock.patch.object(objects.Instance, 'save'):
self.assertRaises(exception.RequestedVRamTooHigh,
drvr._get_guest_config,
instance_ref,
[],
image_meta,
disk_info)
def test_video_driver_ram_above_flavor_limit(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
instance_ref = objects.Instance(**self.test_instance)
instance_type = instance_ref.get_flavor()
instance_type.extra_specs = {'hw_video:ram_max_mb': "50"}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_video_model": "qxl",
"hw_video_ram": "64"}})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with mock.patch.object(objects.Instance, 'save'):
self.assertRaises(exception.RequestedVRamTooHigh,
drvr._get_guest_config,
instance_ref,
[],
image_meta,
disk_info)
def test_get_guest_config_without_qga_through_image_meta(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_qemu_guest_agent": "no"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].type, "vnc")
def test_get_guest_config_with_rng_device(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(pointer_model='ps2mouse')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestRng)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[6].model, 'random')
self.assertIsNone(cfg.devices[6].backend)
self.assertIsNone(cfg.devices[6].rate_bytes)
self.assertIsNone(cfg.devices[6].rate_period)
def test_get_guest_config_with_rng_not_allowed(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(pointer_model='ps2mouse')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 7)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigMemoryBalloon)
def test_get_guest_config_with_rng_limits(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(pointer_model='ps2mouse')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True',
'hw_rng:rate_bytes': '1024',
'hw_rng:rate_period': '2'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestRng)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[6].model, 'random')
self.assertIsNone(cfg.devices[6].backend)
self.assertEqual(cfg.devices[6].rate_bytes, 1024)
self.assertEqual(cfg.devices[6].rate_period, 2)
@mock.patch('nova.virt.libvirt.driver.os.path.exists')
def test_get_guest_config_with_rng_backend(self, mock_path):
self.flags(virt_type='kvm',
rng_dev_path='/dev/hw_rng',
group='libvirt')
self.flags(pointer_model='ps2mouse')
mock_path.return_value = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestRng)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[6].model, 'random')
self.assertEqual(cfg.devices[6].backend, '/dev/hw_rng')
self.assertIsNone(cfg.devices[6].rate_bytes)
self.assertIsNone(cfg.devices[6].rate_period)
@mock.patch('nova.virt.libvirt.driver.os.path.exists')
def test_get_guest_config_with_rng_dev_not_present(self, mock_path):
self.flags(virt_type='kvm',
use_usb_tablet=False,
rng_dev_path='/dev/hw_rng',
group='libvirt')
mock_path.return_value = False
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.assertRaises(exception.RngDeviceNotExist,
drvr._get_guest_config,
instance_ref,
[],
image_meta, disk_info)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_guest_cpu_shares_with_multi_vcpu(self, is_able):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.vcpus = 4
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(4096, cfg.cputune.shares)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_with_cpu_quota(self, is_able):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'quota:cpu_shares': '10000',
'quota:cpu_period': '20000'}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(10000, cfg.cputune.shares)
self.assertEqual(20000, cfg.cputune.period)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_with_bogus_cpu_quota(self, is_able):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'quota:cpu_shares': 'fishfood',
'quota:cpu_period': '20000'}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.assertRaises(ValueError,
drvr._get_guest_config,
instance_ref, [], image_meta, disk_info)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=False)
def test_get_update_guest_cputune(self, is_able):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'quota:cpu_shares': '10000',
'quota:cpu_period': '20000'}
self.assertRaises(
exception.UnsupportedHostCPUControlPolicy,
drvr._update_guest_cputune, {}, instance_ref.flavor, "kvm")
def _test_get_guest_config_sysinfo_serial(self, expected_serial):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
cfg = drvr._get_guest_config_sysinfo(instance_ref)
self.assertIsInstance(cfg, vconfig.LibvirtConfigGuestSysinfo)
self.assertEqual(version.vendor_string(),
cfg.system_manufacturer)
self.assertEqual(version.product_string(),
cfg.system_product)
self.assertEqual(version.version_string_with_package(),
cfg.system_version)
self.assertEqual(expected_serial,
cfg.system_serial)
self.assertEqual(instance_ref['uuid'],
cfg.system_uuid)
self.assertEqual("Virtual Machine",
cfg.system_family)
def test_get_guest_config_sysinfo_serial_none(self):
self.flags(sysinfo_serial="none", group="libvirt")
self._test_get_guest_config_sysinfo_serial(None)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_host_sysinfo_serial_hardware")
def test_get_guest_config_sysinfo_serial_hardware(self, mock_uuid):
self.flags(sysinfo_serial="hardware", group="libvirt")
theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc"
mock_uuid.return_value = theuuid
self._test_get_guest_config_sysinfo_serial(theuuid)
@contextlib.contextmanager
def patch_exists(self, result):
real_exists = os.path.exists
def fake_exists(filename):
if filename == "/etc/machine-id":
return result
return real_exists(filename)
with mock.patch.object(os.path, "exists") as mock_exists:
mock_exists.side_effect = fake_exists
yield mock_exists
def test_get_guest_config_sysinfo_serial_os(self):
self.flags(sysinfo_serial="os", group="libvirt")
theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc"
with test.nested(
mock.patch.object(six.moves.builtins, "open",
mock.mock_open(read_data=theuuid)),
self.patch_exists(True)):
self._test_get_guest_config_sysinfo_serial(theuuid)
def test_get_guest_config_sysinfo_serial_os_empty_machine_id(self):
self.flags(sysinfo_serial="os", group="libvirt")
with test.nested(
mock.patch.object(six.moves.builtins, "open",
mock.mock_open(read_data="")),
self.patch_exists(True)):
self.assertRaises(exception.NovaException,
self._test_get_guest_config_sysinfo_serial,
None)
def test_get_guest_config_sysinfo_serial_os_no_machine_id_file(self):
self.flags(sysinfo_serial="os", group="libvirt")
with self.patch_exists(False):
self.assertRaises(exception.NovaException,
self._test_get_guest_config_sysinfo_serial,
None)
def test_get_guest_config_sysinfo_serial_auto_hardware(self):
self.flags(sysinfo_serial="auto", group="libvirt")
real_exists = os.path.exists
with test.nested(
mock.patch.object(os.path, "exists"),
mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_host_sysinfo_serial_hardware")
) as (mock_exists, mock_uuid):
def fake_exists(filename):
if filename == "/etc/machine-id":
return False
return real_exists(filename)
mock_exists.side_effect = fake_exists
theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc"
mock_uuid.return_value = theuuid
self._test_get_guest_config_sysinfo_serial(theuuid)
def test_get_guest_config_sysinfo_serial_auto_os(self):
self.flags(sysinfo_serial="auto", group="libvirt")
real_exists = os.path.exists
real_open = builtins.open
with test.nested(
mock.patch.object(os.path, "exists"),
mock.patch.object(builtins, "open"),
) as (mock_exists, mock_open):
def fake_exists(filename):
if filename == "/etc/machine-id":
return True
return real_exists(filename)
mock_exists.side_effect = fake_exists
theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc"
def fake_open(filename, *args, **kwargs):
if filename == "/etc/machine-id":
h = mock.MagicMock()
h.read.return_value = theuuid
h.__enter__.return_value = h
return h
return real_open(filename, *args, **kwargs)
mock_open.side_effect = fake_open
self._test_get_guest_config_sysinfo_serial(theuuid)
def _create_fake_service_compute(self):
service_info = {
'id': 1729,
'host': 'fake',
'report_count': 0
}
service_ref = objects.Service(**service_info)
compute_info = {
'id': 1729,
'vcpus': 2,
'memory_mb': 1024,
'local_gb': 2048,
'vcpus_used': 0,
'memory_mb_used': 0,
'local_gb_used': 0,
'free_ram_mb': 1024,
'free_disk_gb': 2048,
'hypervisor_type': 'xen',
'hypervisor_version': 1,
'running_vms': 0,
'cpu_info': '',
'current_workload': 0,
'service_id': service_ref['id'],
'host': service_ref['host']
}
compute_ref = objects.ComputeNode(**compute_info)
return (service_ref, compute_ref)
def test_get_guest_config_with_pci_passthrough_kvm(self):
self.flags(virt_type='kvm', group='libvirt')
service_ref, compute_ref = self._create_fake_service_compute()
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
pci_device_info = dict(test_pci_device.fake_db_dev)
pci_device_info.update(compute_node_id=1,
label='fake',
status=fields.PciDeviceStatus.ALLOCATED,
address='0000:00:00.1',
compute_id=compute_ref.id,
instance_uuid=instance.uuid,
request_id=None,
extra_info={})
pci_device = objects.PciDevice(**pci_device_info)
pci_list = objects.PciDeviceList()
pci_list.objects.append(pci_device)
instance.pci_devices = pci_list
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
cfg = drvr._get_guest_config(instance, [],
image_meta, disk_info)
had_pci = 0
# care only about the PCI devices
for dev in cfg.devices:
if type(dev) == vconfig.LibvirtConfigGuestHostdevPCI:
had_pci += 1
self.assertEqual(dev.type, 'pci')
self.assertEqual(dev.managed, 'yes')
self.assertEqual(dev.mode, 'subsystem')
self.assertEqual(dev.domain, "0000")
self.assertEqual(dev.bus, "00")
self.assertEqual(dev.slot, "00")
self.assertEqual(dev.function, "1")
self.assertEqual(had_pci, 1)
def test_get_guest_config_with_pci_passthrough_xen(self):
self.flags(virt_type='xen', group='libvirt')
service_ref, compute_ref = self._create_fake_service_compute()
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
pci_device_info = dict(test_pci_device.fake_db_dev)
pci_device_info.update(compute_node_id=1,
label='fake',
status=fields.PciDeviceStatus.ALLOCATED,
address='0000:00:00.2',
compute_id=compute_ref.id,
instance_uuid=instance.uuid,
request_id=None,
extra_info={})
pci_device = objects.PciDevice(**pci_device_info)
pci_list = objects.PciDeviceList()
pci_list.objects.append(pci_device)
instance.pci_devices = pci_list
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
cfg = drvr._get_guest_config(instance, [],
image_meta, disk_info)
had_pci = 0
# care only about the PCI devices
for dev in cfg.devices:
if type(dev) == vconfig.LibvirtConfigGuestHostdevPCI:
had_pci += 1
self.assertEqual(dev.type, 'pci')
self.assertEqual(dev.managed, 'no')
self.assertEqual(dev.mode, 'subsystem')
self.assertEqual(dev.domain, "0000")
self.assertEqual(dev.bus, "00")
self.assertEqual(dev.slot, "00")
self.assertEqual(dev.function, "2")
self.assertEqual(had_pci, 1)
def test_get_guest_config_os_command_line_through_image_meta(self):
self.flags(virt_type="kvm",
cpu_mode='none',
group='libvirt')
self.test_instance['kernel_id'] = "fake_kernel_id"
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"os_command_line":
"fake_os_command_line"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_cmdline, "fake_os_command_line")
def test_get_guest_config_os_command_line_without_kernel_id(self):
self.flags(virt_type="kvm",
cpu_mode='none',
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"os_command_line":
"fake_os_command_line"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsNone(cfg.os_cmdline)
def test_get_guest_config_os_command_empty(self):
self.flags(virt_type="kvm",
cpu_mode='none',
group='libvirt')
self.test_instance['kernel_id'] = "fake_kernel_id"
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"os_command_line": ""}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
# the instance has 'root=/dev/vda console=tty0 console=ttyS0' set by
# default, so testing an empty string and None value in the
# os_command_line image property must pass
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertNotEqual(cfg.os_cmdline, "")
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_guest_storage_config")
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support")
def test_get_guest_config_armv7(self, mock_numa, mock_storage):
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.arch = arch.ARMV7
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
return caps
self.flags(virt_type="kvm",
group="libvirt")
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_mach_type, "vexpress-a15")
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_guest_storage_config")
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support")
def test_get_guest_config_aarch64(self, mock_numa, mock_storage):
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.arch = arch.AARCH64
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
return caps
self.flags(virt_type="kvm",
group="libvirt")
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_mach_type, "virt")
def test_get_guest_config_machine_type_s390(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigGuestCPU()
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
host_cpu_archs = (arch.S390, arch.S390X)
for host_cpu_arch in host_cpu_archs:
caps.host.cpu.arch = host_cpu_arch
os_mach_type = drvr._get_machine_type(image_meta, caps)
self.assertEqual('s390-ccw-virtio', os_mach_type)
def test_get_guest_config_machine_type_through_image_meta(self):
self.flags(virt_type="kvm",
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_machine_type":
"fake_machine_type"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_mach_type, "fake_machine_type")
def test_get_guest_config_machine_type_from_config(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(hw_machine_type=['x86_64=fake_machine_type'],
group='libvirt')
def fake_getCapabilities():
return """
<capabilities>
<host>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<cpu>
<arch>x86_64</arch>
<model>Penryn</model>
<vendor>Intel</vendor>
<topology sockets='1' cores='2' threads='1'/>
<feature name='xtpr'/>
</cpu>
</host>
</capabilities>
"""
def fake_baselineCPU(cpu, flag):
return """<cpu mode='custom' match='exact'>
<model fallback='allow'>Penryn</model>
<vendor>Intel</vendor>
<feature policy='require' name='xtpr'/>
</cpu>
"""
# Make sure the host arch is mocked as x86_64
self.create_fake_libvirt_mock(getCapabilities=fake_getCapabilities,
baselineCPU=fake_baselineCPU,
getVersion=lambda: 1005001)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_mach_type, "fake_machine_type")
def _test_get_guest_config_ppc64(self, device_index):
"""Test for nova.virt.libvirt.driver.LibvirtDriver._get_guest_config.
"""
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
expected = (arch.PPC64, arch.PPC)
for guestarch in expected:
with mock.patch.object(libvirt_driver.libvirt_utils,
'get_arch',
return_value=guestarch):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta,
disk_info)
self.assertIsInstance(cfg.devices[device_index],
vconfig.LibvirtConfigGuestVideo)
self.assertEqual(cfg.devices[device_index].type, 'vga')
def test_get_guest_config_ppc64_through_image_meta_vnc_enabled(self):
self.flags(enabled=True, group='vnc')
self._test_get_guest_config_ppc64(6)
def test_get_guest_config_ppc64_through_image_meta_spice_enabled(self):
self.flags(enabled=True,
agent_enabled=True,
group='spice')
self._test_get_guest_config_ppc64(8)
def _test_get_guest_config_bootmenu(self, image_meta, extra_specs):
self.flags(virt_type='kvm', group='libvirt')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = extra_specs
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref, image_meta)
conf = conn._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertTrue(conf.os_bootmenu)
def test_get_guest_config_bootmenu_via_image_meta(self):
image_meta = objects.ImageMeta.from_dict(
{"disk_format": "raw",
"properties": {"hw_boot_menu": "True"}})
self._test_get_guest_config_bootmenu(image_meta, {})
def test_get_guest_config_bootmenu_via_extra_specs(self):
image_meta = objects.ImageMeta.from_dict(
self.test_image_meta)
self._test_get_guest_config_bootmenu(image_meta,
{'hw:boot_menu': 'True'})
def test_get_guest_cpu_config_none(self):
self.flags(cpu_mode="none", group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertIsNone(conf.cpu.mode)
self.assertIsNone(conf.cpu.model)
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_config_default_kvm(self):
self.flags(virt_type="kvm",
cpu_mode='none',
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertIsNone(conf.cpu.mode)
self.assertIsNone(conf.cpu.model)
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_config_default_uml(self):
self.flags(virt_type="uml",
cpu_mode='none',
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsNone(conf.cpu)
def test_get_guest_cpu_config_default_lxc(self):
self.flags(virt_type="lxc",
cpu_mode='none',
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsNone(conf.cpu)
def test_get_guest_cpu_config_host_passthrough(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.flags(cpu_mode="host-passthrough", group='libvirt')
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertEqual(conf.cpu.mode, "host-passthrough")
self.assertIsNone(conf.cpu.model)
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_config_host_model(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.flags(cpu_mode="host-model", group='libvirt')
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertEqual(conf.cpu.mode, "host-model")
self.assertIsNone(conf.cpu.model)
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_config_custom(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.flags(cpu_mode="custom",
cpu_model="Penryn",
group='libvirt')
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertEqual(conf.cpu.mode, "custom")
self.assertEqual(conf.cpu.model, "Penryn")
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_topology(self):
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.vcpus = 8
instance_ref.flavor.extra_specs = {'hw:cpu_max_sockets': '4'}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertEqual(conf.cpu.mode, "host-model")
self.assertEqual(conf.cpu.sockets, 4)
self.assertEqual(conf.cpu.cores, 2)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_memory_balloon_config_by_default(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for device in cfg.devices:
if device.root_name == 'memballoon':
self.assertIsInstance(device,
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual('virtio', device.model)
self.assertEqual(10, device.period)
def test_get_guest_memory_balloon_config_disable(self):
self.flags(mem_stats_period_seconds=0, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
no_exist = True
for device in cfg.devices:
if device.root_name == 'memballoon':
no_exist = False
break
self.assertTrue(no_exist)
def test_get_guest_memory_balloon_config_period_value(self):
self.flags(mem_stats_period_seconds=21, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for device in cfg.devices:
if device.root_name == 'memballoon':
self.assertIsInstance(device,
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual('virtio', device.model)
self.assertEqual(21, device.period)
def test_get_guest_memory_balloon_config_qemu(self):
self.flags(virt_type='qemu', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for device in cfg.devices:
if device.root_name == 'memballoon':
self.assertIsInstance(device,
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual('virtio', device.model)
self.assertEqual(10, device.period)
def test_get_guest_memory_balloon_config_xen(self):
self.flags(virt_type='xen', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for device in cfg.devices:
if device.root_name == 'memballoon':
self.assertIsInstance(device,
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual('xen', device.model)
self.assertEqual(10, device.period)
def test_get_guest_memory_balloon_config_lxc(self):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
no_exist = True
for device in cfg.devices:
if device.root_name == 'memballoon':
no_exist = False
break
self.assertTrue(no_exist)
@mock.patch('nova.virt.libvirt.driver.LOG.warning')
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(host.Host, "get_capabilities")
def test_get_supported_perf_events_foo(self, mock_get_caps,
mock_min_version,
mock_warn):
self.flags(enabled_perf_events=['foo'], group='libvirt')
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
mock_get_caps.return_value = caps
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
events = drvr._get_supported_perf_events()
self.assertTrue(mock_warn.called)
self.assertEqual([], events)
@mock.patch.object(host.Host, "get_capabilities")
def _test_get_guest_with_perf(self, caps, events, mock_get_caps):
mock_get_caps.return_value = caps
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host('test_perf')
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(events, cfg.perf_events)
@mock.patch.object(fakelibvirt, 'VIR_PERF_PARAM_CMT', True,
create=True)
@mock.patch.object(fakelibvirt, 'VIR_PERF_PARAM_MBMT', True,
create=True)
@mock.patch.object(fakelibvirt, 'VIR_PERF_PARAM_MBML', True,
create=True)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_get_guest_with_perf_supported(self,
mock_min_version):
self.flags(enabled_perf_events=['cmt', 'mbml', 'mbmt'],
group='libvirt')
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
features = []
for f in ('cmt', 'mbm_local', 'mbm_total'):
feature = vconfig.LibvirtConfigGuestCPUFeature()
feature.name = f
feature.policy = cpumodel.POLICY_REQUIRE
features.append(feature)
caps.host.cpu.features = set(features)
self._test_get_guest_with_perf(caps, ['cmt', 'mbml', 'mbmt'])
@mock.patch.object(host.Host, 'has_min_version')
def test_get_guest_with_perf_libvirt_unsupported(self, mock_min_version):
def fake_has_min_version(lv_ver=None, hv_ver=None, hv_type=None):
if lv_ver == libvirt_driver.MIN_LIBVIRT_PERF_VERSION:
return False
return True
mock_min_version.side_effect = fake_has_min_version
self.flags(enabled_perf_events=['cmt'], group='libvirt')
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
self._test_get_guest_with_perf(caps, [])
@mock.patch.object(fakelibvirt, 'VIR_PERF_PARAM_CMT', True,
create=True)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_get_guest_with_perf_host_unsupported(self,
mock_min_version):
self.flags(enabled_perf_events=['cmt'], group='libvirt')
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
self._test_get_guest_with_perf(caps, [])
def test_xml_and_uri_no_ramdisk_no_kernel(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data,
expect_kernel=False, expect_ramdisk=False)
def test_xml_and_uri_no_ramdisk_no_kernel_xen_hvm(self):
instance_data = dict(self.test_instance)
instance_data.update({'vm_mode': vm_mode.HVM})
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, expect_xen_hvm=True)
def test_xml_and_uri_no_ramdisk_no_kernel_xen_pv(self):
instance_data = dict(self.test_instance)
instance_data.update({'vm_mode': vm_mode.XEN})
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, expect_xen_hvm=False,
xen_only=True)
def test_xml_and_uri_no_ramdisk(self):
instance_data = dict(self.test_instance)
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=True, expect_ramdisk=False)
def test_xml_and_uri_no_kernel(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=False, expect_ramdisk=False)
def test_xml_and_uri(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=True, expect_ramdisk=True)
def test_xml_and_uri_rescue(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=True,
expect_ramdisk=True, rescue=instance_data)
def test_xml_and_uri_rescue_no_kernel_no_ramdisk(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, rescue=instance_data)
def test_xml_and_uri_rescue_no_kernel(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=True, rescue=instance_data)
def test_xml_and_uri_rescue_no_ramdisk(self):
instance_data = dict(self.test_instance)
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=True,
expect_ramdisk=False, rescue=instance_data)
def test_xml_uuid(self):
self._check_xml_and_uuid(self.test_image_meta)
def test_lxc_container_and_uri(self):
instance_data = dict(self.test_instance)
self._check_xml_and_container(instance_data)
def test_xml_disk_prefix(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_prefix(instance_data, None)
def test_xml_user_specified_disk_prefix(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_prefix(instance_data, 'sd')
def test_xml_disk_driver(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_driver(instance_data)
def test_xml_disk_bus_virtio(self):
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self._check_xml_and_disk_bus(image_meta,
None,
(("disk", "virtio", "vda"),))
def test_xml_disk_bus_ide(self):
# It's necessary to check if the architecture is power, because
# power doesn't have support to ide, and so libvirt translate
# all ide calls to scsi
expected = {arch.PPC: ("cdrom", "scsi", "sda"),
arch.PPC64: ("cdrom", "scsi", "sda"),
arch.PPC64LE: ("cdrom", "scsi", "sda"),
arch.AARCH64: ("cdrom", "scsi", "sda")}
expec_val = expected.get(blockinfo.libvirt_utils.get_arch({}),
("cdrom", "ide", "hda"))
image_meta = objects.ImageMeta.from_dict({
"disk_format": "iso"})
self._check_xml_and_disk_bus(image_meta,
None,
(expec_val,))
def test_xml_disk_bus_ide_and_virtio(self):
# It's necessary to check if the architecture is power, because
# power doesn't have support to ide, and so libvirt translate
# all ide calls to scsi
expected = {arch.PPC: ("cdrom", "scsi", "sda"),
arch.PPC64: ("cdrom", "scsi", "sda"),
arch.PPC64LE: ("cdrom", "scsi", "sda"),
arch.AARCH64: ("cdrom", "scsi", "sda")}
swap = {'device_name': '/dev/vdc',
'swap_size': 1}
ephemerals = [{'device_type': 'disk',
'disk_bus': 'virtio',
'device_name': '/dev/vdb',
'size': 1}]
block_device_info = {
'swap': swap,
'ephemerals': ephemerals}
expec_val = expected.get(blockinfo.libvirt_utils.get_arch({}),
("cdrom", "ide", "hda"))
image_meta = objects.ImageMeta.from_dict({
"disk_format": "iso"})
self._check_xml_and_disk_bus(image_meta,
block_device_info,
(expec_val,
("disk", "virtio", "vdb"),
("disk", "virtio", "vdc")))
@mock.patch.object(host.Host, "list_instance_domains")
def test_list_instances(self, mock_list):
vm1 = FakeVirtDomain(id=3, name="instance00000001")
vm2 = FakeVirtDomain(id=17, name="instance00000002")
vm3 = FakeVirtDomain(name="instance00000003")
vm4 = FakeVirtDomain(name="instance00000004")
mock_list.return_value = [vm1, vm2, vm3, vm4]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
names = drvr.list_instances()
self.assertEqual(names[0], vm1.name())
self.assertEqual(names[1], vm2.name())
self.assertEqual(names[2], vm3.name())
self.assertEqual(names[3], vm4.name())
mock_list.assert_called_with(only_guests=True, only_running=False)
@mock.patch.object(host.Host, "list_instance_domains")
def test_list_instance_uuids(self, mock_list):
vm1 = FakeVirtDomain(id=3, name="instance00000001")
vm2 = FakeVirtDomain(id=17, name="instance00000002")
vm3 = FakeVirtDomain(name="instance00000003")
vm4 = FakeVirtDomain(name="instance00000004")
mock_list.return_value = [vm1, vm2, vm3, vm4]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
uuids = drvr.list_instance_uuids()
self.assertEqual(len(uuids), 4)
self.assertEqual(uuids[0], vm1.UUIDString())
self.assertEqual(uuids[1], vm2.UUIDString())
self.assertEqual(uuids[2], vm3.UUIDString())
self.assertEqual(uuids[3], vm4.UUIDString())
mock_list.assert_called_with(only_guests=True, only_running=False)
@mock.patch('nova.virt.libvirt.host.Host.get_online_cpus')
def test_get_host_vcpus(self, get_online_cpus):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.flags(vcpu_pin_set="4-5")
get_online_cpus.return_value = set([4, 5, 6])
expected_vcpus = 2
vcpus = drvr._get_vcpu_total()
self.assertEqual(expected_vcpus, vcpus)
@mock.patch('nova.virt.libvirt.host.Host.get_online_cpus')
def test_get_host_vcpus_out_of_range(self, get_online_cpus):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.flags(vcpu_pin_set="4-6")
get_online_cpus.return_value = set([4, 5])
self.assertRaises(exception.Invalid, drvr._get_vcpu_total)
@mock.patch('nova.virt.libvirt.host.Host.get_online_cpus')
def test_get_host_vcpus_libvirt_error(self, get_online_cpus):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
not_supported_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'this function is not supported by the connection driver:'
' virNodeNumOfDevices',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
self.flags(vcpu_pin_set="4-6")
get_online_cpus.side_effect = not_supported_exc
self.assertRaises(exception.Invalid, drvr._get_vcpu_total)
@mock.patch('nova.virt.libvirt.host.Host.get_online_cpus')
def test_get_host_vcpus_libvirt_error_success(self, get_online_cpus):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
not_supported_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'this function is not supported by the connection driver:'
' virNodeNumOfDevices',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
self.flags(vcpu_pin_set="1")
get_online_cpus.side_effect = not_supported_exc
expected_vcpus = 1
vcpus = drvr._get_vcpu_total()
self.assertEqual(expected_vcpus, vcpus)
@mock.patch('nova.virt.libvirt.host.Host.get_cpu_count')
def test_get_host_vcpus_after_hotplug(self, get_cpu_count):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
get_cpu_count.return_value = 2
expected_vcpus = 2
vcpus = drvr._get_vcpu_total()
self.assertEqual(expected_vcpus, vcpus)
get_cpu_count.return_value = 3
expected_vcpus = 3
vcpus = drvr._get_vcpu_total()
self.assertEqual(expected_vcpus, vcpus)
@mock.patch.object(host.Host, "has_min_version", return_value=True)
def test_quiesce(self, mock_has_min_version):
self.create_fake_libvirt_mock(lookupByName=self.fake_lookup)
with mock.patch.object(FakeVirtDomain, "fsFreeze") as mock_fsfreeze:
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(
{"properties": {"hw_qemu_guest_agent": "yes"}})
self.assertIsNone(drvr.quiesce(self.context, instance, image_meta))
mock_fsfreeze.assert_called_once_with()
def test_quiesce_not_supported(self):
self.create_fake_libvirt_mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
instance = objects.Instance(**self.test_instance)
self.assertRaises(exception.InstanceQuiesceNotSupported,
drvr.quiesce, self.context, instance, None)
@mock.patch.object(host.Host, "has_min_version", return_value=True)
def test_unquiesce(self, mock_has_min_version):
self.create_fake_libvirt_mock(getLibVersion=lambda: 1002005,
lookupByName=self.fake_lookup)
with mock.patch.object(FakeVirtDomain, "fsThaw") as mock_fsthaw:
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(
{"properties": {"hw_qemu_guest_agent": "yes"}})
self.assertIsNone(drvr.unquiesce(self.context, instance,
image_meta))
mock_fsthaw.assert_called_once_with()
def test_create_snapshot_metadata(self):
base = objects.ImageMeta.from_dict(
{'disk_format': 'raw'})
instance_data = {'kernel_id': 'kernel',
'project_id': 'prj_id',
'ramdisk_id': 'ram_id',
'os_type': None}
instance = objects.Instance(**instance_data)
img_fmt = 'raw'
snp_name = 'snapshot_name'
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = drvr._create_snapshot_metadata(base, instance, img_fmt, snp_name)
expected = {'is_public': False,
'status': 'active',
'name': snp_name,
'properties': {
'kernel_id': instance['kernel_id'],
'image_location': 'snapshot',
'image_state': 'available',
'owner_id': instance['project_id'],
'ramdisk_id': instance['ramdisk_id'],
},
'disk_format': img_fmt,
'container_format': 'bare',
}
self.assertEqual(ret, expected)
# simulate an instance with os_type field defined
# disk format equals to ami
# container format not equals to bare
instance['os_type'] = 'linux'
base = objects.ImageMeta.from_dict(
{'disk_format': 'ami',
'container_format': 'test_container'})
expected['properties']['os_type'] = instance['os_type']
expected['disk_format'] = base.disk_format
expected['container_format'] = base.container_format
ret = drvr._create_snapshot_metadata(base, instance, img_fmt, snp_name)
self.assertEqual(ret, expected)
def test_get_volume_driver(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
connection_info = {'driver_volume_type': 'fake',
'data': {'device_path': '/fake',
'access_mode': 'rw'}}
driver = conn._get_volume_driver(connection_info)
result = isinstance(driver, volume_drivers.LibvirtFakeVolumeDriver)
self.assertTrue(result)
def test_get_volume_driver_unknown(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
connection_info = {'driver_volume_type': 'unknown',
'data': {'device_path': '/fake',
'access_mode': 'rw'}}
self.assertRaises(
exception.VolumeDriverNotFound,
conn._get_volume_driver,
connection_info
)
@mock.patch.object(volume_drivers.LibvirtFakeVolumeDriver,
'connect_volume')
@mock.patch.object(volume_drivers.LibvirtFakeVolumeDriver, 'get_config')
def test_get_volume_config(self, get_config, connect_volume):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
connection_info = {'driver_volume_type': 'fake',
'data': {'device_path': '/fake',
'access_mode': 'rw'}}
bdm = {'device_name': 'vdb',
'disk_bus': 'fake-bus',
'device_type': 'fake-type'}
disk_info = {'bus': bdm['disk_bus'], 'type': bdm['device_type'],
'dev': 'vdb'}
mock_config = mock.MagicMock()
get_config.return_value = mock_config
config = drvr._get_volume_config(connection_info, disk_info)
get_config.assert_called_once_with(connection_info, disk_info)
self.assertEqual(mock_config, config)
def test_attach_invalid_volume_type(self):
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
instance = objects.Instance(**self.test_instance)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.VolumeDriverNotFound,
drvr.attach_volume, None,
{"driver_volume_type": "badtype"},
instance,
"/dev/sda")
def test_attach_blockio_invalid_hypervisor(self):
self.flags(virt_type='lxc', group='libvirt')
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
instance = objects.Instance(**self.test_instance)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.InvalidHypervisorType,
drvr.attach_volume, None,
{"driver_volume_type": "fake",
"data": {"logical_block_size": "4096",
"physical_block_size": "4096"}
},
instance,
"/dev/sda")
def _test_check_discard(self, mock_log, driver_discard=None,
bus=None, should_log=False):
mock_config = mock.Mock()
mock_config.driver_discard = driver_discard
mock_config.target_bus = bus
mock_instance = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._check_discard_for_attach_volume(mock_config, mock_instance)
self.assertEqual(should_log, mock_log.called)
@mock.patch('nova.virt.libvirt.driver.LOG.debug')
def test_check_discard_for_attach_volume_no_unmap(self, mock_log):
self._test_check_discard(mock_log, driver_discard=None,
bus='scsi', should_log=False)
@mock.patch('nova.virt.libvirt.driver.LOG.debug')
def test_check_discard_for_attach_volume_blk_controller(self, mock_log):
self._test_check_discard(mock_log, driver_discard='unmap',
bus='virtio', should_log=True)
@mock.patch('nova.virt.libvirt.driver.LOG.debug')
def test_check_discard_for_attach_volume_valid_controller(self, mock_log):
self._test_check_discard(mock_log, driver_discard='unmap',
bus='scsi', should_log=False)
@mock.patch('nova.virt.libvirt.driver.LOG.debug')
def test_check_discard_for_attach_volume_blk_controller_no_unmap(self,
mock_log):
self._test_check_discard(mock_log, driver_discard=None,
bus='virtio', should_log=False)
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch('nova.virt.libvirt.blockinfo.get_info_from_bdm')
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
def test_attach_volume_with_vir_domain_affect_live_flag(self,
mock_get_domain, mock_get_info, get_image):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
image_meta = {}
get_image.return_value = image_meta
mock_dom = mock.MagicMock()
mock_get_domain.return_value = mock_dom
connection_info = {"driver_volume_type": "fake",
"data": {"device_path": "/fake",
"access_mode": "rw"}}
bdm = {'device_name': 'vdb',
'disk_bus': 'fake-bus',
'device_type': 'fake-type'}
disk_info = {'bus': bdm['disk_bus'], 'type': bdm['device_type'],
'dev': 'vdb'}
mock_get_info.return_value = disk_info
mock_conf = mock.MagicMock()
flags = (fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE)
with test.nested(
mock.patch.object(drvr, '_connect_volume'),
mock.patch.object(drvr, '_get_volume_config',
return_value=mock_conf),
mock.patch.object(drvr, '_set_cache_mode'),
mock.patch.object(drvr, '_check_discard_for_attach_volume')
) as (mock_connect_volume, mock_get_volume_config,
mock_set_cache_mode, mock_check_discard):
for state in (power_state.RUNNING, power_state.PAUSED):
mock_dom.info.return_value = [state, 512, 512, 2, 1234, 5678]
drvr.attach_volume(self.context, connection_info, instance,
"/dev/vdb", disk_bus=bdm['disk_bus'],
device_type=bdm['device_type'])
mock_get_domain.assert_called_with(instance)
mock_get_info.assert_called_with(
instance,
CONF.libvirt.virt_type,
test.MatchType(objects.ImageMeta),
bdm)
mock_connect_volume.assert_called_with(
connection_info, disk_info)
mock_get_volume_config.assert_called_with(
connection_info, disk_info)
mock_set_cache_mode.assert_called_with(mock_conf)
mock_dom.attachDeviceFlags.assert_called_with(
mock_conf.to_xml(), flags=flags)
mock_check_discard.assert_called_with(mock_conf, instance)
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
def test_detach_volume_with_vir_domain_affect_live_flag(self,
mock_get_domain):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_xml_with_disk = """<domain>
<devices>
<disk type='file'>
<source file='/path/to/fake-volume'/>
<target dev='vdc' bus='virtio'/>
</disk>
</devices>
</domain>"""
mock_xml_without_disk = """<domain>
<devices>
</devices>
</domain>"""
mock_dom = mock.MagicMock()
# Second time don't return anything about disk vdc so it looks removed
return_list = [mock_xml_with_disk, mock_xml_without_disk]
# Doubling the size of return list because we test with two guest power
# states
mock_dom.XMLDesc.side_effect = return_list + return_list
connection_info = {"driver_volume_type": "fake",
"data": {"device_path": "/fake",
"access_mode": "rw"}}
flags = (fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE)
with mock.patch.object(drvr, '_disconnect_volume') as \
mock_disconnect_volume:
for state in (power_state.RUNNING, power_state.PAUSED):
mock_dom.info.return_value = [state, 512, 512, 2, 1234, 5678]
mock_get_domain.return_value = mock_dom
drvr.detach_volume(connection_info, instance, '/dev/vdc')
mock_get_domain.assert_called_with(instance)
mock_dom.detachDeviceFlags.assert_called_with("""<disk type="file" device="disk">
<source file="/path/to/fake-volume"/>
<target bus="virtio" dev="vdc"/>
</disk>
""", flags=flags)
mock_disconnect_volume.assert_called_with(
connection_info, 'vdc')
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
def test_detach_volume_disk_not_found(self, mock_get_domain):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_xml_without_disk = """<domain>
<devices>
</devices>
</domain>"""
mock_dom = mock.MagicMock(return_value=mock_xml_without_disk)
connection_info = {"driver_volume_type": "fake",
"data": {"device_path": "/fake",
"access_mode": "rw"}}
mock_dom.info.return_value = [power_state.RUNNING, 512, 512, 2, 1234,
5678]
mock_get_domain.return_value = mock_dom
self.assertRaises(exception.DiskNotFound, drvr.detach_volume,
connection_info, instance, '/dev/vdc')
mock_get_domain.assert_called_once_with(instance)
def test_multi_nic(self):
network_info = _fake_network_info(self, 2)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drvr._get_guest_xml(self.context, instance_ref,
network_info, disk_info,
image_meta)
tree = etree.fromstring(xml)
interfaces = tree.findall("./devices/interface")
self.assertEqual(len(interfaces), 2)
self.assertEqual(interfaces[0].get('type'), 'bridge')
def _behave_supports_direct_io(self, raise_open=False, raise_write=False,
exc=ValueError()):
open_behavior = os.open(os.path.join('.', '.directio.test'),
os.O_CREAT | os.O_WRONLY | os.O_DIRECT)
if raise_open:
open_behavior.AndRaise(exc)
else:
open_behavior.AndReturn(3)
write_bahavior = os.write(3, mox.IgnoreArg())
if raise_write:
write_bahavior.AndRaise(exc)
# ensure unlink(filepath) will actually remove the file by deleting
# the remaining link to it in close(fd)
os.close(3)
os.unlink(3)
def test_supports_direct_io(self):
# O_DIRECT is not supported on all Python runtimes, so on platforms
# where it's not supported (e.g. Mac), we can still test the code-path
# by stubbing out the value.
if not hasattr(os, 'O_DIRECT'):
# `mock` seems to have trouble stubbing an attr that doesn't
# originally exist, so falling back to stubbing out the attribute
# directly.
os.O_DIRECT = 16384
self.addCleanup(delattr, os, 'O_DIRECT')
einval = OSError()
einval.errno = errno.EINVAL
self.mox.StubOutWithMock(os, 'open')
self.mox.StubOutWithMock(os, 'write')
self.mox.StubOutWithMock(os, 'close')
self.mox.StubOutWithMock(os, 'unlink')
_supports_direct_io = libvirt_driver.LibvirtDriver._supports_direct_io
self._behave_supports_direct_io()
self._behave_supports_direct_io(raise_write=True)
self._behave_supports_direct_io(raise_open=True)
self._behave_supports_direct_io(raise_write=True, exc=einval)
self._behave_supports_direct_io(raise_open=True, exc=einval)
self.mox.ReplayAll()
self.assertTrue(_supports_direct_io('.'))
self.assertRaises(ValueError, _supports_direct_io, '.')
self.assertRaises(ValueError, _supports_direct_io, '.')
self.assertFalse(_supports_direct_io('.'))
self.assertFalse(_supports_direct_io('.'))
self.mox.VerifyAll()
def _check_xml_and_container(self, instance):
instance_ref = objects.Instance(**instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEqual(drvr._uri(), 'lxc:///')
network_info = _fake_network_info(self, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drvr._get_guest_xml(self.context, instance_ref,
network_info, disk_info,
image_meta)
tree = etree.fromstring(xml)
check = [
(lambda t: t.find('.').get('type'), 'lxc'),
(lambda t: t.find('./os/type').text, 'exe'),
(lambda t: t.find('./devices/filesystem/target').get('dir'), '/')]
for i, (check, expected_result) in enumerate(check):
self.assertEqual(check(tree),
expected_result,
'%s failed common check %d' % (xml, i))
target = tree.find('./devices/filesystem/source').get('dir')
self.assertGreater(len(target), 0)
def _check_xml_and_disk_prefix(self, instance, prefix):
instance_ref = objects.Instance(**instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
def _get_prefix(p, default):
if p:
return p + 'a'
return default
type_disk_map = {
'qemu': [
(lambda t: t.find('.').get('type'), 'qemu'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'vda'))],
'xen': [
(lambda t: t.find('.').get('type'), 'xen'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'xvda'))],
'kvm': [
(lambda t: t.find('.').get('type'), 'kvm'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'vda'))],
'uml': [
(lambda t: t.find('.').get('type'), 'uml'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'ubda'))]
}
for (virt_type, checks) in six.iteritems(type_disk_map):
self.flags(virt_type=virt_type, group='libvirt')
if prefix:
self.flags(disk_prefix=prefix, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
network_info = _fake_network_info(self, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drvr._get_guest_xml(self.context, instance_ref,
network_info, disk_info,
image_meta)
tree = etree.fromstring(xml)
for i, (check, expected_result) in enumerate(checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed check %d' %
(check(tree), expected_result, i))
def _check_xml_and_disk_driver(self, image_meta):
os_open = os.open
directio_supported = True
def os_open_stub(path, flags, *args, **kwargs):
if flags & os.O_DIRECT:
if not directio_supported:
raise OSError(errno.EINVAL,
'%s: %s' % (os.strerror(errno.EINVAL), path))
flags &= ~os.O_DIRECT
return os_open(path, flags, *args, **kwargs)
self.stub_out('os.open', os_open_stub)
@staticmethod
def connection_supports_direct_io_stub(dirpath):
return directio_supported
self.stubs.Set(libvirt_driver.LibvirtDriver,
'_supports_direct_io', connection_supports_direct_io_stub)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
network_info = _fake_network_info(self, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drv._get_guest_xml(self.context, instance_ref,
network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
disks = tree.findall('./devices/disk/driver')
for guest_disk in disks:
self.assertEqual(guest_disk.get("cache"), "none")
directio_supported = False
# The O_DIRECT availability is cached on first use in
# LibvirtDriver, hence we re-create it here
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drv._get_guest_xml(self.context, instance_ref,
network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
disks = tree.findall('./devices/disk/driver')
for guest_disk in disks:
self.assertEqual(guest_disk.get("cache"), "writethrough")
def _check_xml_and_disk_bus(self, image_meta,
block_device_info, wantConfig):
instance_ref = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
block_device_info)
xml = drv._get_guest_xml(self.context, instance_ref,
network_info, disk_info, image_meta,
block_device_info=block_device_info)
tree = etree.fromstring(xml)
got_disks = tree.findall('./devices/disk')
got_disk_targets = tree.findall('./devices/disk/target')
for i in range(len(wantConfig)):
want_device_type = wantConfig[i][0]
want_device_bus = wantConfig[i][1]
want_device_dev = wantConfig[i][2]
got_device_type = got_disks[i].get('device')
got_device_bus = got_disk_targets[i].get('bus')
got_device_dev = got_disk_targets[i].get('dev')
self.assertEqual(got_device_type, want_device_type)
self.assertEqual(got_device_bus, want_device_bus)
self.assertEqual(got_device_dev, want_device_dev)
def _check_xml_and_uuid(self, image_meta):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
network_info = _fake_network_info(self, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drv._get_guest_xml(self.context, instance_ref,
network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
self.assertEqual(tree.find('./uuid').text,
instance_ref['uuid'])
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_host_sysinfo_serial_hardware",)
def _check_xml_and_uri(self, instance, mock_serial,
expect_ramdisk=False, expect_kernel=False,
rescue=None, expect_xen_hvm=False, xen_only=False):
mock_serial.return_value = "cef19ce0-0ca2-11df-855d-b19fbce37686"
instance_ref = objects.Instance(**instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
xen_vm_mode = vm_mode.XEN
if expect_xen_hvm:
xen_vm_mode = vm_mode.HVM
type_uri_map = {'qemu': ('qemu:///system',
[(lambda t: t.find('.').get('type'), 'qemu'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM),
(lambda t: t.find('./devices/emulator'), None)]),
'kvm': ('qemu:///system',
[(lambda t: t.find('.').get('type'), 'kvm'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM),
(lambda t: t.find('./devices/emulator'), None)]),
'uml': ('uml:///system',
[(lambda t: t.find('.').get('type'), 'uml'),
(lambda t: t.find('./os/type').text,
vm_mode.UML)]),
'xen': ('xen:///',
[(lambda t: t.find('.').get('type'), 'xen'),
(lambda t: t.find('./os/type').text,
xen_vm_mode)])}
if expect_xen_hvm or xen_only:
hypervisors_to_check = ['xen']
else:
hypervisors_to_check = ['qemu', 'kvm', 'xen']
for hypervisor_type in hypervisors_to_check:
check_list = type_uri_map[hypervisor_type][1]
if rescue:
suffix = '.rescue'
else:
suffix = ''
if expect_kernel:
check = (lambda t: self.relpath(t.find('./os/kernel').text).
split('/')[1], 'kernel' + suffix)
else:
check = (lambda t: t.find('./os/kernel'), None)
check_list.append(check)
if expect_kernel:
check = (lambda t: "no_timer_check" in t.find('./os/cmdline').
text, hypervisor_type == "qemu")
check_list.append(check)
# Hypervisors that only support vm_mode.HVM and Xen
# should not produce configuration that results in kernel
# arguments
if not expect_kernel and (hypervisor_type in
['qemu', 'kvm', 'xen']):
check = (lambda t: t.find('./os/root'), None)
check_list.append(check)
check = (lambda t: t.find('./os/cmdline'), None)
check_list.append(check)
if expect_ramdisk:
check = (lambda t: self.relpath(t.find('./os/initrd').text).
split('/')[1], 'ramdisk' + suffix)
else:
check = (lambda t: t.find('./os/initrd'), None)
check_list.append(check)
if hypervisor_type in ['qemu', 'kvm']:
xpath = "./sysinfo/system/entry"
check = (lambda t: t.findall(xpath)[0].get("name"),
"manufacturer")
check_list.append(check)
check = (lambda t: t.findall(xpath)[0].text,
version.vendor_string())
check_list.append(check)
check = (lambda t: t.findall(xpath)[1].get("name"),
"product")
check_list.append(check)
check = (lambda t: t.findall(xpath)[1].text,
version.product_string())
check_list.append(check)
check = (lambda t: t.findall(xpath)[2].get("name"),
"version")
check_list.append(check)
# NOTE(sirp): empty strings don't roundtrip in lxml (they are
# converted to None), so we need an `or ''` to correct for that
check = (lambda t: t.findall(xpath)[2].text or '',
version.version_string_with_package())
check_list.append(check)
check = (lambda t: t.findall(xpath)[3].get("name"),
"serial")
check_list.append(check)
check = (lambda t: t.findall(xpath)[3].text,
"cef19ce0-0ca2-11df-855d-b19fbce37686")
check_list.append(check)
check = (lambda t: t.findall(xpath)[4].get("name"),
"uuid")
check_list.append(check)
check = (lambda t: t.findall(xpath)[4].text,
instance['uuid'])
check_list.append(check)
if hypervisor_type in ['qemu', 'kvm']:
check = (lambda t: t.findall('./devices/serial')[0].get(
'type'), 'file')
check_list.append(check)
check = (lambda t: t.findall('./devices/serial')[1].get(
'type'), 'pty')
check_list.append(check)
check = (lambda t: self.relpath(t.findall(
'./devices/serial/source')[0].get('path')).
split('/')[1], 'console.log')
check_list.append(check)
else:
check = (lambda t: t.find('./devices/console').get(
'type'), 'pty')
check_list.append(check)
common_checks = [
(lambda t: t.find('.').tag, 'domain'),
(lambda t: t.find('./memory').text, '2097152')]
if rescue:
common_checks += [
(lambda t: self.relpath(t.findall('./devices/disk/source')[0].
get('file')).split('/')[1], 'disk.rescue'),
(lambda t: self.relpath(t.findall('./devices/disk/source')[1].
get('file')).split('/')[1], 'disk')]
else:
common_checks += [(lambda t: self.relpath(t.findall(
'./devices/disk/source')[0].get('file')).split('/')[1],
'disk')]
common_checks += [(lambda t: self.relpath(t.findall(
'./devices/disk/source')[1].get('file')).split('/')[1],
'disk.local')]
for virt_type in hypervisors_to_check:
expected_uri = type_uri_map[virt_type][0]
checks = type_uri_map[virt_type][1]
self.flags(virt_type=virt_type, group='libvirt')
with mock.patch('nova.virt.libvirt.driver.libvirt') as old_virt:
del old_virt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEqual(drvr._uri(), expected_uri)
network_info = _fake_network_info(self, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
rescue=rescue)
xml = drvr._get_guest_xml(self.context, instance_ref,
network_info, disk_info,
image_meta,
rescue=rescue)
tree = etree.fromstring(xml)
for i, (check, expected_result) in enumerate(checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed check %d' %
(check(tree), expected_result, i))
for i, (check, expected_result) in enumerate(common_checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed common check %d' %
(check(tree), expected_result, i))
filterref = './devices/interface/filterref'
vif = network_info[0]
nic_id = vif['address'].lower().replace(':', '')
fw = firewall.NWFilterFirewall(drvr)
instance_filter_name = fw._instance_filter_name(instance_ref,
nic_id)
self.assertEqual(tree.find(filterref).get('filter'),
instance_filter_name)
# This test is supposed to make sure we don't
# override a specifically set uri
#
# Deliberately not just assigning this string to CONF.connection_uri
# and checking against that later on. This way we make sure the
# implementation doesn't fiddle around with the CONF.
testuri = 'something completely different'
self.flags(connection_uri=testuri, group='libvirt')
for (virt_type, (expected_uri, checks)) in six.iteritems(type_uri_map):
self.flags(virt_type=virt_type, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEqual(drvr._uri(), testuri)
def test_ensure_filtering_rules_for_instance_timeout(self):
# ensure_filtering_fules_for_instance() finishes with timeout.
# Preparing mocks
def fake_none(self, *args):
return
class FakeTime(object):
def __init__(self):
self.counter = 0
def sleep(self, t):
self.counter += t
fake_timer = FakeTime()
def fake_sleep(t):
fake_timer.sleep(t)
# _fake_network_info must be called before create_fake_libvirt_mock(),
# as _fake_network_info calls importutils.import_class() and
# create_fake_libvirt_mock() mocks importutils.import_class().
network_info = _fake_network_info(self, 1)
self.create_fake_libvirt_mock()
instance_ref = objects.Instance(**self.test_instance)
# Start test
self.mox.ReplayAll()
try:
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr.firewall_driver,
'setup_basic_filtering',
fake_none)
self.stubs.Set(drvr.firewall_driver,
'prepare_instance_filter',
fake_none)
self.stubs.Set(drvr.firewall_driver,
'instance_filter_exists',
fake_none)
self.stubs.Set(greenthread,
'sleep',
fake_sleep)
drvr.ensure_filtering_rules_for_instance(instance_ref,
network_info)
except exception.NovaException as e:
msg = ('The firewall filter for %s does not exist' %
instance_ref['name'])
c1 = (0 <= six.text_type(e).find(msg))
self.assertTrue(c1)
self.assertEqual(29, fake_timer.counter, "Didn't wait the expected "
"amount of time")
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_shared_storage_test_file')
@mock.patch.object(fakelibvirt.Connection, 'compareCPU')
def test_check_can_live_migrate_dest_all_pass_with_block_migration(
self, mock_cpu, mock_test_file, mock_svc):
instance_ref = objects.Instance(**self.test_instance)
instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'disk_available_least': 400,
'cpu_info': 'asdf',
}
filename = "file"
# _check_cpu_match
mock_cpu.return_value = 1
# mounted_on_same_shared_storage
mock_test_file.return_value = filename
# No need for the src_compute_info
return_value = drvr.check_can_live_migrate_destination(self.context,
instance_ref, None, compute_info, True)
return_value.is_volume_backed = False
self.assertThat({"filename": "file",
'image_type': 'default',
'disk_available_mb': 409600,
"disk_over_commit": False,
"block_migration": True,
"is_volume_backed": False},
matchers.DictMatches(return_value.to_legacy_dict()))
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_shared_storage_test_file')
@mock.patch.object(fakelibvirt.Connection, 'compareCPU')
def test_check_can_live_migrate_dest_all_pass_no_block_migration(
self, mock_cpu, mock_test_file, mock_svc):
instance_ref = objects.Instance(**self.test_instance)
instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'disk_available_least': 400,
'cpu_info': 'asdf',
}
filename = "file"
# _check_cpu_match
mock_cpu.return_value = 1
# mounted_on_same_shared_storage
mock_test_file.return_value = filename
# No need for the src_compute_info
return_value = drvr.check_can_live_migrate_destination(self.context,
instance_ref, None, compute_info, False)
return_value.is_volume_backed = False
self.assertThat({"filename": "file",
"image_type": 'default',
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 409600,
"is_volume_backed": False},
matchers.DictMatches(return_value.to_legacy_dict()))
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_shared_storage_test_file',
return_value='fake')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_compare_cpu')
def test_check_can_live_migrate_guest_cpu_none_model(
self, mock_cpu, mock_test_file):
# Tests that when instance.vcpu_model.model is None, the host cpu
# model is used for live migration.
instance_ref = objects.Instance(**self.test_instance)
instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel
instance_ref.vcpu_model.model = None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': 'asdf', 'disk_available_least': 1}
result = drvr.check_can_live_migrate_destination(
self.context, instance_ref, compute_info, compute_info)
result.is_volume_backed = False
mock_cpu.assert_called_once_with(None, 'asdf', instance_ref)
expected_result = {"filename": 'fake',
"image_type": CONF.libvirt.images_type,
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 1024,
"is_volume_backed": False}
self.assertEqual(expected_result, result.to_legacy_dict())
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_shared_storage_test_file')
@mock.patch.object(fakelibvirt.Connection, 'compareCPU')
def test_check_can_live_migrate_dest_no_instance_cpu_info(
self, mock_cpu, mock_test_file, mock_svc):
instance_ref = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': jsonutils.dumps({
"vendor": "AMD",
"arch": arch.I686,
"features": ["sse3"],
"model": "Opteron_G3",
"topology": {"cores": 2, "threads": 1, "sockets": 4}
}), 'disk_available_least': 1}
filename = "file"
# _check_cpu_match
mock_cpu.return_value = 1
# mounted_on_same_shared_storage
mock_test_file.return_value = filename
return_value = drvr.check_can_live_migrate_destination(self.context,
instance_ref, compute_info, compute_info, False)
# NOTE(danms): Compute manager would have set this, so set it here
return_value.is_volume_backed = False
self.assertThat({"filename": "file",
"image_type": 'default',
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 1024,
"is_volume_backed": False},
matchers.DictMatches(return_value.to_legacy_dict()))
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(fakelibvirt.Connection, 'compareCPU')
def test_check_can_live_migrate_dest_incompatible_cpu_raises(
self, mock_cpu, mock_svc):
instance_ref = objects.Instance(**self.test_instance)
instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': 'asdf', 'disk_available_least': 1}
mock_cpu.side_effect = exception.InvalidCPUInfo(reason='foo')
self.assertRaises(exception.InvalidCPUInfo,
drvr.check_can_live_migrate_destination,
self.context, instance_ref,
compute_info, compute_info, False)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt, 'config')
def test_compare_cpu_compatible_host_cpu(self, mock_vconfig, mock_compare):
instance = objects.Instance(**self.test_instance)
mock_compare.return_value = 5
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(None, jsonutils.dumps(_fake_cpu_info),
instance)
self.assertIsNone(ret)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt, 'config')
def test_compare_cpu_handles_not_supported_error_gracefully(self,
mock_vconfig,
mock_compare):
instance = objects.Instance(**self.test_instance)
not_supported_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'this function is not supported by the connection driver:'
' virCompareCPU',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
mock_compare.side_effect = not_supported_exc
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(None, jsonutils.dumps(_fake_cpu_info),
instance)
self.assertIsNone(ret)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt.LibvirtDriver,
'_vcpu_model_to_cpu_config')
def test_compare_cpu_compatible_guest_cpu(self, mock_vcpu_to_cpu,
mock_compare):
instance = objects.Instance(**self.test_instance)
mock_compare.return_value = 6
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(jsonutils.dumps(_fake_cpu_info), None,
instance)
self.assertIsNone(ret)
def test_compare_cpu_virt_type_xen(self):
instance = objects.Instance(**self.test_instance)
self.flags(virt_type='xen', group='libvirt')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(None, None, instance)
self.assertIsNone(ret)
def test_compare_cpu_virt_type_qemu(self):
instance = objects.Instance(**self.test_instance)
self.flags(virt_type='qemu', group='libvirt')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(None, None, instance)
self.assertIsNone(ret)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt, 'config')
def test_compare_cpu_invalid_cpuinfo_raises(self, mock_vconfig,
mock_compare):
instance = objects.Instance(**self.test_instance)
mock_compare.return_value = 0
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.InvalidCPUInfo,
conn._compare_cpu, None,
jsonutils.dumps(_fake_cpu_info),
instance)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt, 'config')
def test_compare_cpu_incompatible_cpu_raises(self, mock_vconfig,
mock_compare):
instance = objects.Instance(**self.test_instance)
mock_compare.side_effect = fakelibvirt.libvirtError('cpu')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.MigrationPreCheckError,
conn._compare_cpu, None,
jsonutils.dumps(_fake_cpu_info),
instance)
def test_check_can_live_migrate_dest_cleanup_works_correctly(self):
objects.Instance(**self.test_instance)
dest_check_data = objects.LibvirtLiveMigrateData(
filename="file",
block_migration=True,
disk_over_commit=False,
disk_available_mb=1024)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(drvr, '_cleanup_shared_storage_test_file')
drvr._cleanup_shared_storage_test_file("file")
self.mox.ReplayAll()
drvr.cleanup_live_migration_destination_check(self.context,
dest_check_data)
@mock.patch('os.path.exists', return_value=True)
@mock.patch('os.utime')
def test_check_shared_storage_test_file_exists(self, mock_utime,
mock_path_exists):
tmpfile_path = os.path.join(CONF.instances_path, 'tmp123')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertTrue(drvr._check_shared_storage_test_file(
'tmp123', mock.sentinel.instance))
mock_utime.assert_called_once_with(CONF.instances_path, None)
mock_path_exists.assert_called_once_with(tmpfile_path)
@mock.patch('os.path.exists', return_value=False)
@mock.patch('os.utime')
def test_check_shared_storage_test_file_does_not_exist(self, mock_utime,
mock_path_exists):
tmpfile_path = os.path.join(CONF.instances_path, 'tmp123')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._check_shared_storage_test_file(
'tmp123', mock.sentinel.instance))
mock_utime.assert_called_once_with(CONF.instances_path, None)
mock_path_exists.assert_called_once_with(tmpfile_path)
def _mock_can_live_migrate_source(self, block_migration=False,
is_shared_block_storage=False,
is_shared_instance_path=False,
is_booted_from_volume=False,
disk_available_mb=1024,
block_device_info=None,
block_device_text=None):
instance = objects.Instance(**self.test_instance)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
block_migration=block_migration,
disk_over_commit=False,
disk_available_mb=disk_available_mb)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(drvr, '_is_shared_block_storage')
drvr._is_shared_block_storage(instance, dest_check_data,
block_device_info).AndReturn(is_shared_block_storage)
self.mox.StubOutWithMock(drvr, '_check_shared_storage_test_file')
drvr._check_shared_storage_test_file('file', instance).AndReturn(
is_shared_instance_path)
self.mox.StubOutWithMock(drvr, "get_instance_disk_info")
drvr.get_instance_disk_info(instance,
block_device_info=block_device_info).\
AndReturn(block_device_text)
self.mox.StubOutWithMock(drvr, '_is_booted_from_volume')
drvr._is_booted_from_volume(instance, block_device_text).AndReturn(
is_booted_from_volume)
return (instance, dest_check_data, drvr)
def test_check_can_live_migrate_source_block_migration(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
block_migration=True)
self.mox.StubOutWithMock(drvr, "_assert_dest_node_has_enough_disk")
drvr._assert_dest_node_has_enough_disk(
self.context, instance, dest_check_data.disk_available_mb,
False, None)
self.mox.ReplayAll()
ret = drvr.check_can_live_migrate_source(self.context, instance,
dest_check_data)
self.assertIsInstance(ret, objects.LibvirtLiveMigrateData)
self.assertIn('is_shared_block_storage', ret)
self.assertIn('is_shared_instance_path', ret)
def test_check_can_live_migrate_source_shared_block_storage(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
is_shared_block_storage=True)
self.mox.ReplayAll()
drvr.check_can_live_migrate_source(self.context, instance,
dest_check_data)
def test_check_can_live_migrate_source_shared_instance_path(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
is_shared_instance_path=True)
self.mox.ReplayAll()
drvr.check_can_live_migrate_source(self.context, instance,
dest_check_data)
def test_check_can_live_migrate_source_non_shared_fails(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source()
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
drvr.check_can_live_migrate_source, self.context,
instance, dest_check_data)
def test_check_can_live_migrate_source_shared_block_migration_fails(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
block_migration=True,
is_shared_block_storage=True)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidLocalStorage,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data)
def test_check_can_live_migrate_shared_path_block_migration_fails(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
block_migration=True,
is_shared_instance_path=True)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidLocalStorage,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data, None)
def test_check_can_live_migrate_non_shared_non_block_migration_fails(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source()
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data)
def test_check_can_live_migrate_source_with_dest_not_enough_disk(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
block_migration=True,
disk_available_mb=0)
drvr.get_instance_disk_info(instance,
block_device_info=None).AndReturn(
'[{"virt_disk_size":2}]')
self.mox.ReplayAll()
self.assertRaises(exception.MigrationError,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data)
def test_check_can_live_migrate_source_booted_from_volume(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
is_booted_from_volume=True,
block_device_text='[]')
self.mox.ReplayAll()
drvr.check_can_live_migrate_source(self.context, instance,
dest_check_data)
def test_check_can_live_migrate_source_booted_from_volume_with_swap(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
is_booted_from_volume=True,
block_device_text='[{"path":"disk.swap"}]')
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data)
@mock.patch.object(host.Host, 'has_min_version', return_value=False)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_has_local_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_booted_from_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_shared_block_storage', return_value=False)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_check_shared_storage_test_file', return_value=False)
def test_check_can_live_migrate_source_block_migration_with_bdm_error(
self, mock_check, mock_shared_block, mock_get_bdi,
mock_booted_from_volume, mock_has_local, mock_enough,
mock_min_version):
bdi = {'block_device_mapping': ['bdm']}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
block_migration=True,
disk_over_commit=False,
disk_available_mb=100)
self.assertRaises(exception.MigrationPreCheckError,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data,
block_device_info=bdi)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_has_local_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_booted_from_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_shared_block_storage', return_value=False)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_check_shared_storage_test_file', return_value=False)
def test_check_can_live_migrate_source_bm_with_bdm_tunnelled_error(
self, mock_check, mock_shared_block, mock_get_bdi,
mock_booted_from_volume, mock_has_local, mock_enough,
mock_min_version):
self.flags(live_migration_tunnelled=True,
group='libvirt')
bdi = {'block_device_mapping': ['bdm']}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
block_migration=True,
disk_over_commit=False,
disk_available_mb=100)
drvr._parse_migration_flags()
self.assertRaises(exception.MigrationPreCheckError,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data,
block_device_info=bdi)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_has_local_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_booted_from_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_shared_block_storage')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_check_shared_storage_test_file')
def _test_check_can_live_migrate_source_block_migration_none(
self, block_migrate, is_shared_instance_path, is_share_block,
mock_check, mock_shared_block, mock_get_bdi,
mock_booted_from_volume, mock_has_local, mock_enough, mock_verson):
mock_check.return_value = is_shared_instance_path
mock_shared_block.return_value = is_share_block
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
disk_over_commit=False,
disk_available_mb=100)
dest_check_data_ret = drvr.check_can_live_migrate_source(
self.context, instance, dest_check_data)
self.assertEqual(block_migrate, dest_check_data_ret.block_migration)
def test_check_can_live_migrate_source_block_migration_none_shared1(self):
self._test_check_can_live_migrate_source_block_migration_none(
False,
True,
False)
def test_check_can_live_migrate_source_block_migration_none_shared2(self):
self._test_check_can_live_migrate_source_block_migration_none(
False,
False,
True)
def test_check_can_live_migrate_source_block_migration_none_no_share(self):
self._test_check_can_live_migrate_source_block_migration_none(
True,
False,
False)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_has_local_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_booted_from_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_shared_block_storage')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_check_shared_storage_test_file')
def test_check_can_live_migration_source_disk_over_commit_none(self,
mock_check, mock_shared_block, mock_get_bdi,
mock_booted_from_volume, mock_has_local,
mock_enough, mock_disk_check):
mock_check.return_value = False
mock_shared_block.return_value = False
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
disk_available_mb=100)
drvr.check_can_live_migrate_source(
self.context, instance, dest_check_data)
self.assertFalse(mock_disk_check.called)
def _is_shared_block_storage_test_create_mocks(self, disks):
# Test data
instance_xml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>{}</devices></domain>")
disks_xml = ''
for dsk in disks:
if dsk['type'] is not 'network':
disks_xml = ''.join([disks_xml,
"<disk type='{type}'>"
"<driver name='qemu' type='{driver}'/>"
"<source {source}='{source_path}'/>"
"<target dev='{target_dev}' bus='virtio'/>"
"</disk>".format(**dsk)])
else:
disks_xml = ''.join([disks_xml,
"<disk type='{type}'>"
"<driver name='qemu' type='{driver}'/>"
"<source protocol='{source_proto}'"
"name='{source_image}' >"
"<host name='hostname' port='7000'/>"
"<config file='/path/to/file'/>"
"</source>"
"<target dev='{target_dev}'"
"bus='ide'/>".format(**dsk)])
# Preparing mocks
mock_virDomain = mock.Mock(fakelibvirt.virDomain)
mock_virDomain.XMLDesc = mock.Mock()
mock_virDomain.XMLDesc.return_value = (instance_xml.format(disks_xml))
mock_lookup = mock.Mock()
def mock_lookup_side_effect(name):
return mock_virDomain
mock_lookup.side_effect = mock_lookup_side_effect
mock_getsize = mock.Mock()
mock_getsize.return_value = "10737418240"
return (mock_getsize, mock_lookup)
def test_is_shared_block_storage_rbd(self):
self.flags(images_type='rbd', group='libvirt')
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_instance_disk_info = mock.Mock()
data = objects.LibvirtLiveMigrateData(image_type='rbd')
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertTrue(drvr._is_shared_block_storage(instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
self.assertTrue(drvr._is_storage_shared_with('foo', 'bar'))
def test_is_shared_block_storage_lvm(self):
self.flags(images_type='lvm', group='libvirt')
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
mock_get_instance_disk_info = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
data = objects.LibvirtLiveMigrateData(image_type='lvm',
is_volume_backed=False,
is_shared_instance_path=False)
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_is_shared_block_storage_qcow2(self):
self.flags(images_type='qcow2', group='libvirt')
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
mock_get_instance_disk_info = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
data = objects.LibvirtLiveMigrateData(image_type='qcow2',
is_volume_backed=False,
is_shared_instance_path=False)
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_is_shared_block_storage_rbd_only_source(self):
self.flags(images_type='rbd', group='libvirt')
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
mock_get_instance_disk_info = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
data = objects.LibvirtLiveMigrateData(is_shared_instance_path=False,
is_volume_backed=False)
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_is_shared_block_storage_rbd_only_dest(self):
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
mock_get_instance_disk_info = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
data = objects.LibvirtLiveMigrateData(image_type='rbd',
is_volume_backed=False,
is_shared_instance_path=False)
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_is_shared_block_storage_volume_backed(self):
disks = [{'type': 'block',
'driver': 'raw',
'source': 'dev',
'source_path': '/dev/disk',
'target_dev': 'vda'}]
bdi = {'block_device_mapping': [
{'connection_info': 'info', 'mount_device': '/dev/vda'}]}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
(mock_getsize, mock_lookup) =\
self._is_shared_block_storage_test_create_mocks(disks)
data = objects.LibvirtLiveMigrateData(is_volume_backed=True,
is_shared_instance_path=False)
with mock.patch.object(host.Host, 'get_domain', mock_lookup):
self.assertTrue(drvr._is_shared_block_storage(instance, data,
block_device_info = bdi))
mock_lookup.assert_called_once_with(instance)
def test_is_shared_block_storage_volume_backed_with_disk(self):
disks = [{'type': 'block',
'driver': 'raw',
'source': 'dev',
'source_path': '/dev/disk',
'target_dev': 'vda'},
{'type': 'file',
'driver': 'raw',
'source': 'file',
'source_path': '/instance/disk.local',
'target_dev': 'vdb'}]
bdi = {'block_device_mapping': [
{'connection_info': 'info', 'mount_device': '/dev/vda'}]}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
(mock_getsize, mock_lookup) =\
self._is_shared_block_storage_test_create_mocks(disks)
data = objects.LibvirtLiveMigrateData(is_volume_backed=True,
is_shared_instance_path=False)
with test.nested(
mock.patch.object(os.path, 'getsize', mock_getsize),
mock.patch.object(host.Host, 'get_domain', mock_lookup)):
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info = bdi))
mock_getsize.assert_called_once_with('/instance/disk.local')
mock_lookup.assert_called_once_with(instance)
def test_is_shared_block_storage_nfs(self):
bdi = {'block_device_mapping': []}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_backend = mock.MagicMock()
mock_image_backend.backend.return_value = mock_backend
mock_backend.is_file_in_instance_path.return_value = True
mock_get_instance_disk_info = mock.Mock()
data = objects.LibvirtLiveMigrateData(
is_shared_instance_path=True,
image_type='foo')
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
self.assertTrue(drvr._is_shared_block_storage(
'instance', data, block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_live_migration_update_graphics_xml(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
xml_tmpl = ("<domain type='kvm'>"
"<devices>"
"<graphics type='vnc' listen='{vnc}'>"
"<listen address='{vnc}'/>"
"</graphics>"
"<graphics type='spice' listen='{spice}'>"
"<listen address='{spice}'/>"
"</graphics>"
"</devices>"
"</domain>")
initial_xml = xml_tmpl.format(vnc='1.2.3.4',
spice='5.6.7.8')
target_xml = xml_tmpl.format(vnc='10.0.0.1',
spice='10.0.0.2')
target_xml = etree.tostring(etree.fromstring(target_xml))
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
guest = libvirt_guest.Guest(vdmock)
self.mox.StubOutWithMock(vdmock, "migrateToURI2")
_bandwidth = CONF.libvirt.live_migration_bandwidth
vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE).AndReturn(
initial_xml)
vdmock.migrateToURI2(drvr._live_migration_uri('dest'),
dxml=target_xml,
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError("ERR"))
# start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='10.0.0.1',
graphics_listen_addr_spice='10.0.0.2',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=False)
self.mox.ReplayAll()
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
def test_live_migration_update_volume_xml(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
target_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'cde.67890.opst-lun-Z')
# start test
connection_info = {
u'driver_volume_type': u'iscsi',
u'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'data': {
u'access_mode': u'rw', u'target_discovered': False,
u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
},
}
bdm = objects.LibvirtLiveMigrateBDMInfo(
serial='58a84f6d-3f0c-4e19-a0af-eb657b790657',
bus='virtio', type='disk', dev='vdb',
connection_info=connection_info)
migrate_data = objects.LibvirtLiveMigrateData(
serial_listen_addr='',
target_connect_addr=None,
bdms=[bdm],
block_migration=False)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
test_mock = mock.MagicMock()
guest = libvirt_guest.Guest(test_mock)
with mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info') as \
mget_info,\
mock.patch.object(drvr._host, 'get_domain') as mget_domain,\
mock.patch.object(fakelibvirt.virDomain, 'migrateToURI2'),\
mock.patch.object(
libvirt_migrate, 'get_updated_guest_xml') as mupdate:
mget_info.side_effect = exception.InstanceNotFound(
instance_id='foo')
mget_domain.return_value = test_mock
test_mock.XMLDesc.return_value = target_xml
self.assertFalse(drvr._live_migration_operation(
self.context, instance_ref, 'dest', False,
migrate_data, guest, []))
mupdate.assert_called_once_with(
guest, migrate_data, mock.ANY)
def test_live_migration_with_valid_target_connect_addr(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
target_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'cde.67890.opst-lun-Z')
# start test
connection_info = {
u'driver_volume_type': u'iscsi',
u'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'data': {
u'access_mode': u'rw', u'target_discovered': False,
u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
},
}
bdm = objects.LibvirtLiveMigrateBDMInfo(
serial='58a84f6d-3f0c-4e19-a0af-eb657b790657',
bus='virtio', type='disk', dev='vdb',
connection_info=connection_info)
migrate_data = objects.LibvirtLiveMigrateData(
serial_listen_addr='',
target_connect_addr='127.0.0.2',
bdms=[bdm],
block_migration=False)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
test_mock = mock.MagicMock()
guest = libvirt_guest.Guest(test_mock)
with mock.patch.object(libvirt_migrate,
'get_updated_guest_xml') as mupdate:
test_mock.XMLDesc.return_value = target_xml
drvr._live_migration_operation(self.context, instance_ref,
'dest', False, migrate_data,
guest, [])
test_mock.migrateToURI2.assert_called_once_with(
'qemu+tcp://127.0.0.2/system',
dxml=mupdate(), flags=0, bandwidth=0)
def test_update_volume_xml(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
initial_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'cde.67890.opst-lun-Z')
target_xml = etree.tostring(etree.fromstring(target_xml))
serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657"
bdmi = objects.LibvirtLiveMigrateBDMInfo(serial=serial,
bus='virtio',
type='disk',
dev='vdb')
bdmi.connection_info = {u'driver_volume_type': u'iscsi',
'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'data': {u'access_mode': u'rw', u'target_discovered': False,
u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}}
conf = vconfig.LibvirtConfigGuestDisk()
conf.source_device = bdmi.type
conf.driver_name = "qemu"
conf.driver_format = "raw"
conf.driver_cache = "none"
conf.target_dev = bdmi.dev
conf.target_bus = bdmi.bus
conf.serial = bdmi.connection_info.get('serial')
conf.source_type = "block"
conf.source_path = bdmi.connection_info['data'].get('device_path')
guest = libvirt_guest.Guest(mock.MagicMock())
with test.nested(
mock.patch.object(drvr, '_get_volume_config',
return_value=conf),
mock.patch.object(guest, 'get_xml_desc',
return_value=initial_xml)):
config = libvirt_migrate.get_updated_guest_xml(guest,
objects.LibvirtLiveMigrateData(bdms=[bdmi]),
drvr._get_volume_config)
parser = etree.XMLParser(remove_blank_text=True)
config = etree.fromstring(config, parser)
target_xml = etree.fromstring(target_xml, parser)
self.assertEqual(etree.tostring(target_xml),
etree.tostring(config))
def test_live_migration_uri(self):
hypervisor_uri_map = (
('xen', 'xenmigr://%s/system'),
('kvm', 'qemu+tcp://%s/system'),
('qemu', 'qemu+tcp://%s/system'),
# anything else will return None
('lxc', None),
('parallels', None),
)
dest = 'destination'
for hyperv, uri in hypervisor_uri_map:
self.flags(virt_type=hyperv, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
if uri is not None:
uri = uri % dest
self.assertEqual(uri, drvr._live_migration_uri(dest))
else:
self.assertRaises(exception.LiveMigrationURINotAvailable,
drvr._live_migration_uri,
dest)
def test_live_migration_uri_forced(self):
dest = 'destination'
for hyperv in ('kvm', 'xen'):
self.flags(virt_type=hyperv, group='libvirt')
forced_uri = 'foo://%s/bar'
self.flags(live_migration_uri=forced_uri, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(forced_uri % dest, drvr._live_migration_uri(dest))
def test_update_volume_xml_no_serial(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
xml_tmpl = """
<domain type='kvm'>
<devices>
<disk type='block' device='disk'>
<driver name='qemu' type='raw' cache='none'/>
<source dev='{device_path}'/>
<target bus='virtio' dev='vdb'/>
<serial></serial>
<address type='pci' domain='0x0' bus='0x0' slot='0x04' \
function='0x0'/>
</disk>
</devices>
</domain>
"""
initial_xml = xml_tmpl.format(device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = xml_tmpl.format(device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = etree.tostring(etree.fromstring(target_xml))
serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657"
connection_info = {
u'driver_volume_type': u'iscsi',
'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'data': {
u'access_mode': u'rw', u'target_discovered': False,
u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
},
}
bdmi = objects.LibvirtLiveMigrateBDMInfo(serial=serial,
bus='virtio',
dev='vdb',
type='disk')
bdmi.connection_info = connection_info
conf = vconfig.LibvirtConfigGuestDisk()
conf.source_device = bdmi.type
conf.driver_name = "qemu"
conf.driver_format = "raw"
conf.driver_cache = "none"
conf.target_dev = bdmi.dev
conf.target_bus = bdmi.bus
conf.serial = bdmi.connection_info.get('serial')
conf.source_type = "block"
conf.source_path = bdmi.connection_info['data'].get('device_path')
guest = libvirt_guest.Guest(mock.MagicMock())
with test.nested(
mock.patch.object(drvr, '_get_volume_config',
return_value=conf),
mock.patch.object(guest, 'get_xml_desc',
return_value=initial_xml)):
config = libvirt_migrate.get_updated_guest_xml(guest,
objects.LibvirtLiveMigrateData(bdms=[bdmi]),
drvr._get_volume_config)
self.assertEqual(target_xml, config)
def test_update_volume_xml_no_connection_info(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
initial_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = etree.tostring(etree.fromstring(target_xml))
serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657"
bdmi = objects.LibvirtLiveMigrateBDMInfo(serial=serial,
dev='vdb',
type='disk',
bus='scsi',
format='qcow')
bdmi.connection_info = {}
conf = vconfig.LibvirtConfigGuestDisk()
guest = libvirt_guest.Guest(mock.MagicMock())
with test.nested(
mock.patch.object(drvr, '_get_volume_config',
return_value=conf),
mock.patch.object(guest, 'get_xml_desc',
return_value=initial_xml)):
config = libvirt_migrate.get_updated_guest_xml(
guest,
objects.LibvirtLiveMigrateData(bdms=[bdmi]),
drvr._get_volume_config)
self.assertEqual(target_xml, config)
@mock.patch.object(fakelibvirt.virDomain, "migrateToURI2")
@mock.patch.object(fakelibvirt.virDomain, "XMLDesc")
def test_live_migration_update_serial_console_xml(self, mock_xml,
mock_migrate):
self.compute = importutils.import_object(CONF.compute_manager)
instance_ref = self.test_instance
xml_tmpl = ("<domain type='kvm'>"
"<devices>"
"<console type='tcp'>"
"<source mode='bind' host='{addr}' service='10000'/>"
"</console>"
"</devices>"
"</domain>")
initial_xml = xml_tmpl.format(addr='9.0.0.1')
target_xml = xml_tmpl.format(addr='9.0.0.12')
target_xml = etree.tostring(etree.fromstring(target_xml))
# Preparing mocks
mock_xml.return_value = initial_xml
mock_migrate.side_effect = fakelibvirt.libvirtError("ERR")
# start test
bandwidth = CONF.libvirt.live_migration_bandwidth
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='10.0.0.1',
graphics_listen_addr_spice='10.0.0.2',
serial_listen_addr='9.0.0.12',
target_connect_addr=None,
bdms=[],
block_migration=False)
dom = fakelibvirt.virDomain
guest = libvirt_guest.Guest(dom)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
mock_xml.assert_called_once_with(
flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE)
mock_migrate.assert_called_once_with(
drvr._live_migration_uri('dest'),
dxml=target_xml, flags=mock.ANY, bandwidth=bandwidth)
@mock.patch.object(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None,
create=True)
def test_live_migration_fails_with_serial_console_without_migratable(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_ref = self.test_instance
CONF.set_override("enabled", True, "serial_console")
dom = fakelibvirt.virDomain
migrate_data = objects.LibvirtLiveMigrateData(
serial_listen_addr='', target_connect_addr=None,
block_migration=False)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.MigrationError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, dom, [])
@mock.patch.object(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None,
create=True)
def test_live_migration_uses_migrateToURI_without_migratable_flag(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
guest = libvirt_guest.Guest(vdmock)
self.mox.StubOutWithMock(vdmock, "migrateToURI")
_bandwidth = CONF.libvirt.live_migration_bandwidth
vdmock.migrateToURI(drvr._live_migration_uri('dest'),
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError("ERR"))
# start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='0.0.0.0',
graphics_listen_addr_spice='0.0.0.0',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=False)
self.mox.ReplayAll()
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
def test_live_migration_uses_migrateToURI_without_dest_listen_addrs(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
guest = libvirt_guest.Guest(vdmock)
self.mox.StubOutWithMock(vdmock, "migrateToURI")
_bandwidth = CONF.libvirt.live_migration_bandwidth
vdmock.migrateToURI(drvr._live_migration_uri('dest'),
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError("ERR"))
# start test
migrate_data = objects.LibvirtLiveMigrateData(
serial_listen_addr='',
target_connect_addr=None,
bdms=[],
block_migration=False)
self.mox.ReplayAll()
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(fakelibvirt.virDomain, "migrateToURI3")
@mock.patch('nova.virt.libvirt.migration.get_updated_guest_xml',
return_value='')
@mock.patch('nova.virt.libvirt.guest.Guest.get_xml_desc',
return_value='<xml></xml>')
def test_live_migration_uses_migrateToURI3(
self, mock_old_xml, mock_new_xml, mock_migrateToURI3,
mock_min_version):
# Preparing mocks
disk_paths = ['vda', 'vdb']
params = {
'migrate_disks': ['vda', 'vdb'],
'bandwidth': CONF.libvirt.live_migration_bandwidth,
'destination_xml': '',
}
mock_migrateToURI3.side_effect = fakelibvirt.libvirtError("ERR")
# Start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='0.0.0.0',
graphics_listen_addr_spice='0.0.0.0',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=False)
dom = fakelibvirt.virDomain
guest = libvirt_guest.Guest(dom)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance, 'dest',
False, migrate_data, guest, disk_paths)
mock_migrateToURI3.assert_called_once_with(
drvr._live_migration_uri('dest'),
params=params, flags=0)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(fakelibvirt.virDomain, "migrateToURI3")
@mock.patch('nova.virt.libvirt.migration.get_updated_guest_xml',
return_value='')
@mock.patch('nova.virt.libvirt.guest.Guest.get_xml_desc', return_value='')
def test_block_live_migration_tunnelled_migrateToURI3(
self, mock_old_xml, mock_new_xml,
mock_migrateToURI3, mock_min_version):
self.flags(live_migration_tunnelled=True, group='libvirt')
# Preparing mocks
disk_paths = []
params = {
'bandwidth': CONF.libvirt.live_migration_bandwidth,
'destination_xml': '',
}
# Start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='0.0.0.0',
graphics_listen_addr_spice='0.0.0.0',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=True)
dom = fakelibvirt.virDomain
guest = libvirt_guest.Guest(dom)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._parse_migration_flags()
instance = objects.Instance(**self.test_instance)
drvr._live_migration_operation(self.context, instance, 'dest',
True, migrate_data, guest, disk_paths)
mock_migrateToURI3.assert_called_once_with(
drvr._live_migration_uri('dest'),
params=params, flags=151)
@mock.patch.object(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None,
create=True)
def test_live_migration_fails_without_migratable_flag_or_0_addr(self):
self.flags(enabled=True, vncserver_listen='1.2.3.4', group='vnc')
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "migrateToURI")
# start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='1.2.3.4',
graphics_listen_addr_spice='1.2.3.4',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
block_migration=False)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.MigrationError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, vdmock, [])
def test_live_migration_raises_exception(self):
# Confirms recover method is called when exceptions are raised.
# Preparing data
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
guest = libvirt_guest.Guest(vdmock)
self.mox.StubOutWithMock(vdmock, "migrateToURI2")
_bandwidth = CONF.libvirt.live_migration_bandwidth
if getattr(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None) is None:
vdmock.migrateToURI(drvr._live_migration_uri('dest'),
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError('ERR'))
else:
vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE
).AndReturn(FakeVirtDomain().XMLDesc(flags=0))
vdmock.migrateToURI2(drvr._live_migration_uri('dest'),
dxml=mox.IgnoreArg(),
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError('ERR'))
# start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='127.0.0.1',
graphics_listen_addr_spice='127.0.0.1',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=False)
self.mox.ReplayAll()
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
self.assertEqual(vm_states.ACTIVE, instance_ref.vm_state)
self.assertEqual(power_state.RUNNING, instance_ref.power_state)
@mock.patch('shutil.rmtree')
@mock.patch('os.path.exists', return_value=True)
@mock.patch('nova.virt.libvirt.utils.get_instance_path_at_destination')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.destroy')
def test_rollback_live_migration_at_dest_not_shared(self, mock_destroy,
mock_get_instance_path,
mock_exist,
mock_shutil
):
# destroy method may raise InstanceTerminationFailure or
# InstancePowerOffFailure, here use their base class Invalid.
mock_destroy.side_effect = exception.Invalid(reason='just test')
fake_instance_path = os.path.join(cfg.CONF.instances_path,
'/fake_instance_uuid')
mock_get_instance_path.return_value = fake_instance_path
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
migrate_data = objects.LibvirtLiveMigrateData(
is_shared_instance_path=False,
instance_relative_path=False)
self.assertRaises(exception.Invalid,
drvr.rollback_live_migration_at_destination,
"context", "instance", [], None, True, migrate_data)
mock_exist.assert_called_once_with(fake_instance_path)
mock_shutil.assert_called_once_with(fake_instance_path)
@mock.patch('shutil.rmtree')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path_at_destination')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.destroy')
def test_rollback_live_migration_at_dest_shared(self, mock_destroy,
mock_get_instance_path,
mock_exist,
mock_shutil
):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
migrate_data = objects.LibvirtLiveMigrateData(
is_shared_instance_path=True,
instance_relative_path=False)
drvr.rollback_live_migration_at_destination("context", "instance", [],
None, True, migrate_data)
mock_destroy.assert_called_once_with("context", "instance", [],
None, True, migrate_data)
self.assertFalse(mock_get_instance_path.called)
self.assertFalse(mock_exist.called)
self.assertFalse(mock_shutil.called)
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(host.Host, "has_min_version", return_value=False)
@mock.patch.object(fakelibvirt.Domain, "XMLDesc")
def test_live_migration_copy_disk_paths(self, mock_xml, mock_version,
mock_conn):
xml = """
<domain>
<name>dummy</name>
<uuid>d4e13113-918e-42fe-9fc9-861693ffd432</uuid>
<devices>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.root"/>
<target dev="vda"/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.shared"/>
<target dev="vdb"/>
<shareable/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.config"/>
<target dev="vdc"/>
<readonly/>
</disk>
<disk type="block">
<source dev="/dev/mapper/somevol"/>
<target dev="vdd"/>
</disk>
<disk type="network">
<source protocol="https" name="url_path">
<host name="hostname" port="443"/>
</source>
</disk>
</devices>
</domain>"""
mock_xml.return_value = xml
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
guest = libvirt_guest.Guest(dom)
paths = drvr._live_migration_copy_disk_paths(None, None, guest)
self.assertEqual((["/var/lib/nova/instance/123/disk.root",
"/dev/mapper/somevol"], ['vda', 'vdd']), paths)
@mock.patch.object(fakelibvirt.Domain, "XMLDesc")
def test_live_migration_copy_disk_paths_tunnelled(self, mock_xml):
self.flags(live_migration_tunnelled=True, group='libvirt')
xml = """
<domain>
<name>dummy</name>
<uuid>d4e13113-918e-42fe-9fc9-861693ffd432</uuid>
<devices>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.root"/>
<target dev="vda"/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.shared"/>
<target dev="vdb"/>
<shareable/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.config"/>
<target dev="vdc"/>
<readonly/>
</disk>
<disk type="block">
<source dev="/dev/mapper/somevol"/>
<target dev="vdd"/>
</disk>
<disk type="network">
<source protocol="https" name="url_path">
<host name="hostname" port="443"/>
</source>
</disk>
</devices>
</domain>"""
mock_xml.return_value = xml
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._parse_migration_flags()
dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
guest = libvirt_guest.Guest(dom)
paths = drvr._live_migration_copy_disk_paths(None, None, guest)
self.assertEqual((["/var/lib/nova/instance/123/disk.root",
"/dev/mapper/somevol"], ['vda', 'vdd']), paths)
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(host.Host, "has_min_version", return_value=True)
@mock.patch('nova.virt.driver.get_block_device_info')
@mock.patch('nova.objects.BlockDeviceMappingList.get_by_instance_uuid')
@mock.patch.object(fakelibvirt.Domain, "XMLDesc")
def test_live_migration_copy_disk_paths_selective_block_migration(
self, mock_xml, mock_get_instance,
mock_block_device_info, mock_version, mock_conn):
xml = """
<domain>
<name>dummy</name>
<uuid>d4e13113-918e-42fe-9fc9-861693ffd432</uuid>
<devices>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.root"/>
<target dev="vda"/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.shared"/>
<target dev="vdb"/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.config"/>
<target dev="vdc"/>
</disk>
<disk type="block">
<source dev="/dev/mapper/somevol"/>
<target dev="vdd"/>
</disk>
<disk type="network">
<source protocol="https" name="url_path">
<host name="hostname" port="443"/>
</source>
</disk>
</devices>
</domain>"""
mock_xml.return_value = xml
instance = objects.Instance(**self.test_instance)
instance.root_device_name = '/dev/vda'
block_device_info = {
'swap': {
'disk_bus': u'virtio',
'swap_size': 10,
'device_name': u'/dev/vdc'
},
'root_device_name': u'/dev/vda',
'ephemerals': [{
'guest_format': u'ext3',
'device_name': u'/dev/vdb',
'disk_bus': u'virtio',
'device_type': u'disk',
'size': 1
}],
'block_device_mapping': [{
'guest_format': None,
'boot_index': None,
'mount_device': u'/dev/vdd',
'connection_info': {
u'driver_volume_type': u'iscsi',
'serial': u'147df29f-aec2-4851-b3fe-f68dad151834',
u'data': {
u'access_mode': u'rw',
u'target_discovered': False,
u'encrypted': False,
u'qos_specs': None,
u'target_iqn': u'iqn.2010-10.org.openstack:'
u'volume-147df29f-aec2-4851-b3fe-'
u'f68dad151834',
u'target_portal': u'10.102.44.141:3260', u'volume_id':
u'147df29f-aec2-4851-b3fe-f68dad151834',
u'target_lun': 1,
u'auth_password': u'cXELT66FngwzTwpf',
u'auth_username': u'QbQQjj445uWgeQkFKcVw',
u'auth_method': u'CHAP'
}
},
'disk_bus': None,
'device_type': None,
'delete_on_termination': False
}]
}
mock_block_device_info.return_value = block_device_info
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
guest = libvirt_guest.Guest(dom)
return_value = drvr._live_migration_copy_disk_paths(self.context,
instance,
guest)
expected = (['/var/lib/nova/instance/123/disk.root',
'/var/lib/nova/instance/123/disk.shared',
'/var/lib/nova/instance/123/disk.config'],
['vda', 'vdb', 'vdc'])
self.assertEqual(expected, return_value)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_live_migration_copy_disk_paths")
def test_live_migration_data_gb_plain(self, mock_paths):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
data_gb = drvr._live_migration_data_gb(instance, [])
self.assertEqual(2, data_gb)
self.assertEqual(0, mock_paths.call_count)
def test_live_migration_data_gb_block(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
def fake_stat(path):
class StatResult(object):
def __init__(self, size):
self._size = size
@property
def st_size(self):
return self._size
if path == "/var/lib/nova/instance/123/disk.root":
return StatResult(10 * units.Gi)
elif path == "/dev/mapper/somevol":
return StatResult(1.5 * units.Gi)
else:
raise Exception("Should not be reached")
disk_paths = ["/var/lib/nova/instance/123/disk.root",
"/dev/mapper/somevol"]
with mock.patch.object(os, "stat") as mock_stat:
mock_stat.side_effect = fake_stat
data_gb = drvr._live_migration_data_gb(instance, disk_paths)
# Expecting 2 GB for RAM, plus 10 GB for disk.root
# and 1.5 GB rounded to 2 GB for somevol, so 14 GB
self.assertEqual(14, data_gb)
EXPECT_SUCCESS = 1
EXPECT_FAILURE = 2
EXPECT_ABORT = 3
@mock.patch.object(libvirt_guest.Guest, "migrate_start_postcopy")
@mock.patch.object(time, "time")
@mock.patch.object(time, "sleep",
side_effect=lambda x: eventlet.sleep(0))
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(libvirt_guest.Guest, "get_job_info")
@mock.patch.object(objects.Instance, "save")
@mock.patch.object(objects.Migration, "save")
@mock.patch.object(fakelibvirt.Connection, "_mark_running")
@mock.patch.object(fakelibvirt.virDomain, "abortJob")
@mock.patch.object(libvirt_guest.Guest, "pause")
def _test_live_migration_monitoring(self,
job_info_records,
time_records,
expect_result,
mock_pause,
mock_abort,
mock_running,
mock_save,
mock_mig_save,
mock_job_info,
mock_conn,
mock_sleep,
mock_time,
mock_postcopy_switch,
current_mig_status=None,
expected_mig_status=None,
scheduled_action=None,
scheduled_action_executed=False,
block_migration=False,
expected_switch=False):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
drvr.active_migrations[instance.uuid] = deque()
dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", True)
guest = libvirt_guest.Guest(dom)
finish_event = eventlet.event.Event()
def fake_job_info():
while True:
self.assertGreater(len(job_info_records), 0)
rec = job_info_records.pop(0)
if type(rec) == str:
if rec == "thread-finish":
finish_event.send()
elif rec == "domain-stop":
dom.destroy()
elif rec == "force_complete":
drvr.active_migrations[instance.uuid].append(
"force-complete")
else:
if len(time_records) > 0:
time_records.pop(0)
return rec
return rec
def fake_time():
if len(time_records) > 0:
return time_records[0]
else:
return int(
datetime.datetime(2001, 1, 20, 20, 1, 0)
.strftime('%s'))
mock_job_info.side_effect = fake_job_info
mock_time.side_effect = fake_time
dest = mock.sentinel.migrate_dest
migration = objects.Migration(context=self.context, id=1)
migrate_data = objects.LibvirtLiveMigrateData(
migration=migration, block_migration=block_migration)
if current_mig_status:
migrate_data.migration.status = current_mig_status
else:
migrate_data.migration.status = "unset"
migrate_data.migration.save()
fake_post_method = mock.MagicMock()
fake_recover_method = mock.MagicMock()
drvr._live_migration_monitor(self.context, instance,
guest, dest,
fake_post_method,
fake_recover_method,
False,
migrate_data,
finish_event,
[])
if scheduled_action_executed:
if scheduled_action == 'pause':
self.assertTrue(mock_pause.called)
if scheduled_action == 'postcopy_switch':
self.assertTrue(mock_postcopy_switch.called)
else:
if scheduled_action == 'pause':
self.assertFalse(mock_pause.called)
if scheduled_action == 'postcopy_switch':
self.assertFalse(mock_postcopy_switch.called)
mock_mig_save.assert_called_with()
if expect_result == self.EXPECT_SUCCESS:
self.assertFalse(fake_recover_method.called,
'Recover method called when success expected')
self.assertFalse(mock_abort.called,
'abortJob not called when success expected')
if expected_switch:
self.assertTrue(mock_postcopy_switch.called)
fake_post_method.assert_called_once_with(
self.context, instance, dest, False, migrate_data)
else:
if expect_result == self.EXPECT_ABORT:
self.assertTrue(mock_abort.called,
'abortJob called when abort expected')
else:
self.assertFalse(mock_abort.called,
'abortJob not called when failure expected')
self.assertFalse(fake_post_method.called,
'Post method called when success not expected')
if expected_mig_status:
fake_recover_method.assert_called_once_with(
self.context, instance, dest, False, migrate_data,
migration_status=expected_mig_status)
else:
fake_recover_method.assert_called_once_with(
self.context, instance, dest, False, migrate_data)
self.assertNotIn(instance.uuid, drvr.active_migrations)
def test_live_migration_monitor_success(self):
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS)
def test_live_migration_handle_pause_normal(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in between VIR_DOMAIN_JOB_UNBOUNDED
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="running",
scheduled_action="pause",
scheduled_action_executed=True)
def test_live_migration_handle_pause_on_start(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in case of job type VIR_DOMAIN_JOB_NONE and finish_event is
# not ready yet
domain_info_records = [
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="preparing",
scheduled_action="pause",
scheduled_action_executed=True)
def test_live_migration_handle_pause_on_finish(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in case of job type VIR_DOMAIN_JOB_NONE and finish_event is
# ready
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="completed",
scheduled_action="pause",
scheduled_action_executed=False)
def test_live_migration_handle_pause_on_cancel(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in case of job type VIR_DOMAIN_JOB_CANCELLED
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
current_mig_status="cancelled",
expected_mig_status='cancelled',
scheduled_action="pause",
scheduled_action_executed=False)
def test_live_migration_handle_pause_on_failure(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in case of job type VIR_DOMAIN_JOB_FAILED
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_FAILED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
scheduled_action="pause",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_normal(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# switch scheduled in between VIR_DOMAIN_JOB_UNBOUNDED
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="running",
scheduled_action="postcopy_switch",
scheduled_action_executed=True)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_start(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# switch scheduled in case of job type VIR_DOMAIN_JOB_NONE and
# finish_event is not ready yet
mock_postcopy_enabled.return_value = True
domain_info_records = [
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="preparing",
scheduled_action="postcopy_switch",
scheduled_action_executed=True)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_finish(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# switch scheduled in case of job type VIR_DOMAIN_JOB_NONE and
# finish_event is ready
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="completed",
scheduled_action="postcopy_switch",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_cancel(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# scheduled in case of job type VIR_DOMAIN_JOB_CANCELLED
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
current_mig_status="cancelled",
expected_mig_status='cancelled',
scheduled_action="postcopy_switch",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_pause_on_postcopy(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and pause
# scheduled after migration switched to postcopy
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="running (post-copy)",
scheduled_action="pause",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_postcopy(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and pause
# scheduled after migration switched to postcopy
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="running (post-copy)",
scheduled_action="postcopy_switch",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_failure(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# scheduled in case of job type VIR_DOMAIN_JOB_FAILED
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_FAILED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
scheduled_action="postcopy_switch",
scheduled_action_executed=False)
def test_live_migration_monitor_success_race(self):
# A normalish sequence but we're too slow to see the
# completed job state
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS)
def test_live_migration_monitor_failed(self):
# A failed sequence where we see all the expected events
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_FAILED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE)
def test_live_migration_monitor_failed_race(self):
# A failed sequence where we are too slow to see the
# failed event
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE)
def test_live_migration_monitor_cancelled(self):
# A cancelled sequence where we see all the events
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
expected_mig_status='cancelled')
@mock.patch.object(fakelibvirt.virDomain, "migrateSetMaxDowntime")
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_migration_downtime_steps")
def test_live_migration_monitor_downtime(self, mock_downtime_steps,
mock_set_downtime):
self.flags(live_migration_completion_timeout=1000000,
live_migration_progress_timeout=1000000,
group='libvirt')
# We've setup 4 fake downtime steps - first value is the
# time delay, second is the downtime value
downtime_steps = [
(90, 10),
(180, 50),
(270, 200),
(500, 300),
]
mock_downtime_steps.return_value = downtime_steps
# Each one of these fake times is used for time.time()
# when a new domain_info_records entry is consumed.
# Times are chosen so that only the first 3 downtime
# steps are needed.
fake_times = [0, 1, 30, 95, 150, 200, 300]
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records,
fake_times, self.EXPECT_SUCCESS)
mock_set_downtime.assert_has_calls([mock.call(10),
mock.call(50),
mock.call(200)])
def test_live_migration_monitor_completion(self):
self.flags(live_migration_completion_timeout=100,
live_migration_progress_timeout=1000000,
group='libvirt')
# Each one of these fake times is used for time.time()
# when a new domain_info_records entry is consumed.
fake_times = [0, 40, 80, 120, 160, 200, 240, 280, 320]
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records,
fake_times, self.EXPECT_ABORT,
expected_mig_status='cancelled')
def test_live_migration_monitor_progress(self):
self.flags(live_migration_completion_timeout=1000000,
live_migration_progress_timeout=150,
group='libvirt')
# Each one of these fake times is used for time.time()
# when a new domain_info_records entry is consumed.
fake_times = [0, 40, 80, 120, 160, 200, 240, 280, 320]
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records,
fake_times, self.EXPECT_ABORT,
expected_mig_status='cancelled')
def test_live_migration_monitor_progress_zero_data_remaining(self):
self.flags(live_migration_completion_timeout=1000000,
live_migration_progress_timeout=150,
group='libvirt')
# Each one of these fake times is used for time.time()
# when a new domain_info_records entry is consumed.
fake_times = [0, 40, 80, 120, 160, 200, 240, 280, 320]
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=0),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=70),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=50),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=30),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=10),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=0),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_FAILED),
]
self._test_live_migration_monitoring(domain_info_records,
fake_times, self.EXPECT_FAILURE)
def test_live_migration_downtime_steps(self):
self.flags(live_migration_downtime=400, group='libvirt')
self.flags(live_migration_downtime_steps=10, group='libvirt')
self.flags(live_migration_downtime_delay=30, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
steps = drvr._migration_downtime_steps(3.0)
self.assertEqual([
(0, 37),
(90, 38),
(180, 39),
(270, 42),
(360, 46),
(450, 55),
(540, 70),
(630, 98),
(720, 148),
(810, 238),
(900, 400),
], list(steps))
@mock.patch('nova.virt.libvirt.migration.should_switch_to_postcopy')
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_monitor_postcopy_switch(self,
mock_postcopy_enabled, mock_should_switch):
# A normal sequence where migration is switched to postcopy mode
mock_postcopy_enabled.return_value = True
switch_values = [False, False, True]
mock_should_switch.return_value = switch_values
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
expected_switch=True)
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(utils, "spawn")
@mock.patch.object(libvirt_driver.LibvirtDriver, "_live_migration_monitor")
@mock.patch.object(host.Host, "get_guest")
@mock.patch.object(fakelibvirt.Connection, "_mark_running")
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_live_migration_copy_disk_paths")
def test_live_migration_main(self, mock_copy_disk_path, mock_running,
mock_guest, mock_monitor, mock_thread,
mock_conn):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
dom = fakelibvirt.Domain(drvr._get_connection(),
"<domain><name>demo</name></domain>", True)
guest = libvirt_guest.Guest(dom)
migrate_data = objects.LibvirtLiveMigrateData(block_migration=True)
disks_to_copy = (['/some/path/one', '/test/path/two'],
['vda', 'vdb'])
mock_copy_disk_path.return_value = disks_to_copy
mock_guest.return_value = guest
def fake_post():
pass
def fake_recover():
pass
drvr._live_migration(self.context, instance, "fakehost",
fake_post, fake_recover, True,
migrate_data)
mock_copy_disk_path.assert_called_once_with(self.context, instance,
guest)
class AnyEventletEvent(object):
def __eq__(self, other):
return type(other) == eventlet.event.Event
mock_thread.assert_called_once_with(
drvr._live_migration_operation,
self.context, instance, "fakehost", True,
migrate_data, guest, disks_to_copy[1])
mock_monitor.assert_called_once_with(
self.context, instance, guest, "fakehost",
fake_post, fake_recover, True,
migrate_data, AnyEventletEvent(), disks_to_copy[0])
def _do_test_create_images_and_backing(self, disk_type):
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(drvr, '_fetch_instance_kernel_ramdisk')
self.mox.StubOutWithMock(libvirt_driver.libvirt_utils, 'create_image')
disk_info = {'path': 'foo', 'type': disk_type,
'disk_size': 1 * 1024 ** 3,
'virt_disk_size': 20 * 1024 ** 3,
'backing_file': None}
libvirt_driver.libvirt_utils.create_image(
disk_info['type'], mox.IgnoreArg(), disk_info['virt_disk_size'])
drvr._fetch_instance_kernel_ramdisk(self.context, instance,
fallback_from_host=None)
self.mox.ReplayAll()
self.stub_out('os.path.exists', lambda *args: False)
drvr._create_images_and_backing(self.context, instance,
"/fake/instance/dir", [disk_info])
def test_create_images_and_backing_qcow2(self):
self._do_test_create_images_and_backing('qcow2')
def test_create_images_and_backing_raw(self):
self._do_test_create_images_and_backing('raw')
def test_create_images_and_backing_images_not_exist_no_fallback(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.test_instance.update({'user_id': 'fake-user',
'os_type': None,
'project_id': 'fake-project'})
instance = objects.Instance(**self.test_instance)
backing_file = imagecache.get_cache_fname(instance.image_ref)
disk_info = [
{u'backing_file': backing_file,
u'disk_size': 10747904,
u'path': u'disk_path',
u'type': u'qcow2',
u'virt_disk_size': 25165824}]
with mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image',
side_effect=exception.ImageNotFound(
image_id="fake_id")):
self.assertRaises(exception.ImageNotFound,
conn._create_images_and_backing,
self.context, instance,
"/fake/instance/dir", disk_info)
def test_create_images_and_backing_images_not_exist_fallback(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
base_dir = os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name)
self.test_instance.update({'user_id': 'fake-user',
'os_type': None,
'kernel_id': uuids.kernel_id,
'ramdisk_id': uuids.ramdisk_id,
'project_id': 'fake-project'})
instance = objects.Instance(**self.test_instance)
backing_file = imagecache.get_cache_fname(instance.image_ref)
disk_info = [
{u'backing_file': backing_file,
u'disk_size': 10747904,
u'path': u'disk_path',
u'type': u'qcow2',
u'virt_disk_size': 25165824}]
with test.nested(
mock.patch.object(libvirt_driver.libvirt_utils, 'copy_image'),
mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image',
side_effect=exception.ImageNotFound(
image_id=uuids.fake_id)),
) as (copy_image_mock, fetch_image_mock):
conn._create_images_and_backing(self.context, instance,
"/fake/instance/dir", disk_info,
fallback_from_host="fake_host")
backfile_path = os.path.join(base_dir, backing_file)
kernel_path = os.path.join(CONF.instances_path,
self.test_instance['uuid'],
'kernel')
ramdisk_path = os.path.join(CONF.instances_path,
self.test_instance['uuid'],
'ramdisk')
copy_image_mock.assert_has_calls([
mock.call(dest=backfile_path, src=backfile_path,
host='fake_host', receive=True),
mock.call(dest=kernel_path, src=kernel_path,
host='fake_host', receive=True),
mock.call(dest=ramdisk_path, src=ramdisk_path,
host='fake_host', receive=True)
])
fetch_image_mock.assert_has_calls([
mock.call(context=self.context,
target=backfile_path,
image_id=self.test_instance['image_ref']),
mock.call(self.context, kernel_path, instance.kernel_id),
mock.call(self.context, ramdisk_path, instance.ramdisk_id)
])
@mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image')
def test_create_images_and_backing_images_exist(self, mock_fetch_image):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.test_instance.update({'user_id': 'fake-user',
'os_type': None,
'kernel_id': 'fake_kernel_id',
'ramdisk_id': 'fake_ramdisk_id',
'project_id': 'fake-project'})
instance = objects.Instance(**self.test_instance)
disk_info = [
{u'backing_file': imagecache.get_cache_fname(instance.image_ref),
u'disk_size': 10747904,
u'path': u'disk_path',
u'type': u'qcow2',
u'virt_disk_size': 25165824}]
with test.nested(
mock.patch.object(imagebackend.Image, 'get_disk_size'),
mock.patch.object(os.path, 'exists', return_value=True)
):
conn._create_images_and_backing(self.context, instance,
'/fake/instance/dir', disk_info)
self.assertFalse(mock_fetch_image.called)
def test_create_images_and_backing_ephemeral_gets_created(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
base_dir = os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name)
instance = objects.Instance(**self.test_instance)
disk_info_byname = fake_disk_info_byname(instance)
disk_info_byname['disk.local']['backing_file'] = 'ephemeral_foo'
disk_info_byname['disk.local']['virt_disk_size'] = 1 * units.Gi
disk_info = disk_info_byname.values()
with test.nested(
mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image'),
mock.patch.object(drvr, '_create_ephemeral'),
mock.patch.object(imagebackend.Image, 'verify_base_size'),
mock.patch.object(imagebackend.Image, 'get_disk_size')
) as (fetch_image_mock, create_ephemeral_mock, verify_base_size_mock,
disk_size_mock):
drvr._create_images_and_backing(self.context, instance,
CONF.instances_path, disk_info)
self.assertEqual(len(create_ephemeral_mock.call_args_list), 1)
root_backing, ephemeral_backing = [
os.path.join(base_dir, name)
for name in (disk_info_byname['disk']['backing_file'],
'ephemeral_foo')
]
m_args, m_kwargs = create_ephemeral_mock.call_args_list[0]
self.assertEqual(ephemeral_backing, m_kwargs['target'])
self.assertEqual(len(fetch_image_mock.call_args_list), 1)
m_args, m_kwargs = fetch_image_mock.call_args_list[0]
self.assertEqual(root_backing, m_kwargs['target'])
verify_base_size_mock.assert_has_calls([
mock.call(root_backing, instance.flavor.root_gb * units.Gi),
mock.call(ephemeral_backing, 1 * units.Gi)
])
def test_create_images_and_backing_disk_info_none(self):
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_backend = self.useFixture(fake_imagebackend.ImageBackendFixture())
drvr._create_images_and_backing(self.context, instance,
"/fake/instance/dir", None)
# Assert that we did nothing
self.assertEqual({}, fake_backend.created_disks)
def _generate_target_ret(self, target_connect_addr=None):
target_ret = {
'graphics_listen_addrs': {'spice': '127.0.0.1', 'vnc': '127.0.0.1'},
'target_connect_addr': target_connect_addr,
'serial_listen_addr': '127.0.0.1',
'volume': {
'12345': {'connection_info': {u'data': {'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'},
'serial': '12345'},
'disk_info': {'bus': 'scsi',
'dev': 'sda',
'type': 'disk'}},
'67890': {'connection_info': {u'data': {'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'},
'serial': '67890'},
'disk_info': {'bus': 'scsi',
'dev': 'sdb',
'type': 'disk'}}}}
return target_ret
def test_pre_live_migration_works_correctly_mocked(self):
self._test_pre_live_migration_works_correctly_mocked()
def test_pre_live_migration_with_transport_ip(self):
self.flags(live_migration_inbound_addr='127.0.0.2',
group='libvirt')
target_ret = self._generate_target_ret('127.0.0.2')
self._test_pre_live_migration_works_correctly_mocked(target_ret)
def _test_pre_live_migration_works_correctly_mocked(self,
target_ret=None):
# Creating testdata
vol = {'block_device_mapping': [
{'connection_info': {'serial': '12345', u'data':
{'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'}},
'mount_device': '/dev/sda'},
{'connection_info': {'serial': '67890', u'data':
{'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}},
'mount_device': '/dev/sdb'}]}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
class FakeNetworkInfo(object):
def fixed_ips(self):
return ["test_ip_addr"]
def fake_none(*args, **kwargs):
return
self.stubs.Set(drvr, '_create_images_and_backing', fake_none)
instance = objects.Instance(**self.test_instance)
c = context.get_admin_context()
nw_info = FakeNetworkInfo()
# Creating mocks
self.mox.StubOutWithMock(driver, "block_device_info_get_mapping")
driver.block_device_info_get_mapping(vol
).AndReturn(vol['block_device_mapping'])
self.mox.StubOutWithMock(drvr, "_connect_volume")
for v in vol['block_device_mapping']:
disk_info = {
'bus': "scsi",
'dev': v['mount_device'].rpartition("/")[2],
'type': "disk"
}
drvr._connect_volume(v['connection_info'],
disk_info)
self.mox.StubOutWithMock(drvr, 'plug_vifs')
drvr.plug_vifs(mox.IsA(instance), nw_info)
self.mox.ReplayAll()
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
block_migration=False,
instance_relative_path='foo',
is_shared_block_storage=False,
is_shared_instance_path=False,
)
result = drvr.pre_live_migration(
c, instance, vol, nw_info, None,
migrate_data=migrate_data)
if not target_ret:
target_ret = self._generate_target_ret()
self.assertEqual(
result.to_legacy_dict(
pre_migration_result=True)['pre_live_migration_result'],
target_ret)
@mock.patch.object(os, 'mkdir')
@mock.patch('nova.virt.libvirt.utils.get_instance_path_at_destination')
@mock.patch('nova.virt.libvirt.driver.remotefs.'
'RemoteFilesystem.copy_file')
@mock.patch('nova.virt.driver.block_device_info_get_mapping')
@mock.patch('nova.virt.configdrive.required_by', return_value=True)
def test_pre_live_migration_block_with_config_drive_success(
self, mock_required_by, block_device_info_get_mapping,
mock_copy_file, mock_get_instance_path, mock_mkdir):
self.flags(config_drive_format='iso9660')
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
fake_instance_path = os.path.join(cfg.CONF.instances_path,
'/fake_instance_uuid')
mock_get_instance_path.return_value = fake_instance_path
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
migrate_data = objects.LibvirtLiveMigrateData()
migrate_data.is_shared_instance_path = False
migrate_data.is_shared_block_storage = False
migrate_data.block_migration = True
migrate_data.instance_relative_path = 'foo'
src = "%s:%s/disk.config" % (instance.host, fake_instance_path)
result = drvr.pre_live_migration(
self.context, instance, vol, [], None, migrate_data)
block_device_info_get_mapping.assert_called_once_with(
{'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}
]}
)
mock_copy_file.assert_called_once_with(src, fake_instance_path)
migrate_data.graphics_listen_addrs_vnc = '127.0.0.1'
migrate_data.graphics_listen_addrs_spice = '127.0.0.1'
migrate_data.serial_listen_addr = '127.0.0.1'
self.assertEqual(migrate_data, result)
@mock.patch('nova.virt.driver.block_device_info_get_mapping',
return_value=())
def test_pre_live_migration_block_with_config_drive_mocked_with_vfat(
self, block_device_info_get_mapping):
self.flags(config_drive_format='vfat')
# Creating testdata
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
instance.config_drive = 'True'
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_instance_path=False,
is_shared_block_storage=False,
block_migration=False,
instance_relative_path='foo',
)
res_data = drvr.pre_live_migration(
self.context, instance, vol, [], None, migrate_data)
res_data = res_data.to_legacy_dict(pre_migration_result=True)
block_device_info_get_mapping.assert_called_once_with(
{'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}
]}
)
self.assertEqual({'graphics_listen_addrs': {'spice': '127.0.0.1',
'vnc': '127.0.0.1'},
'target_connect_addr': None,
'serial_listen_addr': '127.0.0.1',
'volume': {}}, res_data['pre_live_migration_result'])
def test_pre_live_migration_vol_backed_works_correctly_mocked(self):
# Creating testdata, using temp dir.
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
vol = {'block_device_mapping': [
{'connection_info': {'serial': '12345', u'data':
{'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'}},
'mount_device': '/dev/sda'},
{'connection_info': {'serial': '67890', u'data':
{'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}},
'mount_device': '/dev/sdb'}]}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
def fake_none(*args, **kwargs):
return
self.stubs.Set(drvr, '_create_images_and_backing', fake_none)
class FakeNetworkInfo(object):
def fixed_ips(self):
return ["test_ip_addr"]
inst_ref = objects.Instance(**self.test_instance)
c = context.get_admin_context()
nw_info = FakeNetworkInfo()
# Creating mocks
self.mox.StubOutWithMock(drvr, "_connect_volume")
for v in vol['block_device_mapping']:
disk_info = {
'bus': "scsi",
'dev': v['mount_device'].rpartition("/")[2],
'type': "disk"
}
drvr._connect_volume(v['connection_info'],
disk_info)
self.mox.StubOutWithMock(drvr, 'plug_vifs')
drvr.plug_vifs(mox.IsA(inst_ref), nw_info)
self.mox.ReplayAll()
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_instance_path=False,
is_shared_block_storage=False,
is_volume_backed=True,
block_migration=False,
instance_relative_path=inst_ref['name'],
disk_over_commit=False,
disk_available_mb=123,
image_type='qcow2',
filename='foo',
)
ret = drvr.pre_live_migration(c, inst_ref, vol, nw_info, None,
migrate_data)
target_ret = {
'graphics_listen_addrs': {'spice': '127.0.0.1',
'vnc': '127.0.0.1'},
'target_connect_addr': None,
'serial_listen_addr': '127.0.0.1',
'volume': {
'12345': {'connection_info': {u'data': {'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'},
'serial': '12345'},
'disk_info': {'bus': 'scsi',
'dev': 'sda',
'type': 'disk'}},
'67890': {'connection_info': {u'data': {'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'},
'serial': '67890'},
'disk_info': {'bus': 'scsi',
'dev': 'sdb',
'type': 'disk'}}}}
self.assertEqual(
ret.to_legacy_dict(True)['pre_live_migration_result'],
target_ret)
self.assertTrue(os.path.exists('%s/%s/' % (tmpdir,
inst_ref['name'])))
def test_pre_live_migration_plug_vifs_retry_fails(self):
self.flags(live_migration_retry_count=3)
instance = objects.Instance(**self.test_instance)
def fake_plug_vifs(instance, network_info):
raise processutils.ProcessExecutionError()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(eventlet.greenthread, 'sleep',
lambda x: eventlet.sleep(0))
disk_info_json = jsonutils.dumps({})
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=True,
is_shared_instance_path=True,
block_migration=False,
)
self.assertRaises(processutils.ProcessExecutionError,
drvr.pre_live_migration,
self.context, instance, block_device_info=None,
network_info=[], disk_info=disk_info_json,
migrate_data=migrate_data)
def test_pre_live_migration_plug_vifs_retry_works(self):
self.flags(live_migration_retry_count=3)
called = {'count': 0}
instance = objects.Instance(**self.test_instance)
def fake_plug_vifs(instance, network_info):
called['count'] += 1
if called['count'] < CONF.live_migration_retry_count:
raise processutils.ProcessExecutionError()
else:
return
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(eventlet.greenthread, 'sleep',
lambda x: eventlet.sleep(0))
disk_info_json = jsonutils.dumps({})
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=True,
is_shared_instance_path=True,
block_migration=False,
)
drvr.pre_live_migration(self.context, instance, block_device_info=None,
network_info=[], disk_info=disk_info_json,
migrate_data=migrate_data)
def test_pre_live_migration_image_not_created_with_shared_storage(self):
migrate_data_set = [{'is_shared_block_storage': False,
'is_shared_instance_path': True,
'is_volume_backed': False,
'filename': 'foo',
'instance_relative_path': 'bar',
'disk_over_commit': False,
'disk_available_mb': 123,
'image_type': 'qcow2',
'block_migration': False},
{'is_shared_block_storage': True,
'is_shared_instance_path': True,
'is_volume_backed': False,
'filename': 'foo',
'instance_relative_path': 'bar',
'disk_over_commit': False,
'disk_available_mb': 123,
'image_type': 'qcow2',
'block_migration': False},
{'is_shared_block_storage': False,
'is_shared_instance_path': True,
'is_volume_backed': False,
'filename': 'foo',
'instance_relative_path': 'bar',
'disk_over_commit': False,
'disk_available_mb': 123,
'image_type': 'qcow2',
'block_migration': True}]
def _to_obj(d):
return migrate_data_obj.LibvirtLiveMigrateData(**d)
migrate_data_set = map(_to_obj, migrate_data_set)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
# creating mocks
with test.nested(
mock.patch.object(drvr,
'_create_images_and_backing'),
mock.patch.object(drvr,
'ensure_filtering_rules_for_instance'),
mock.patch.object(drvr, 'plug_vifs'),
) as (
create_image_mock,
rules_mock,
plug_mock,
):
disk_info_json = jsonutils.dumps({})
for migrate_data in migrate_data_set:
res = drvr.pre_live_migration(self.context, instance,
block_device_info=None,
network_info=[],
disk_info=disk_info_json,
migrate_data=migrate_data)
self.assertFalse(create_image_mock.called)
self.assertIsInstance(res,
objects.LibvirtLiveMigrateData)
def test_pre_live_migration_with_not_shared_instance_path(self):
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=False,
is_shared_instance_path=False,
block_migration=False,
instance_relative_path='foo',
)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
def check_instance_dir(context, instance,
instance_dir, disk_info,
fallback_from_host=False):
self.assertTrue(instance_dir)
# creating mocks
with test.nested(
mock.patch.object(drvr,
'_create_images_and_backing',
side_effect=check_instance_dir),
mock.patch.object(drvr,
'ensure_filtering_rules_for_instance'),
mock.patch.object(drvr, 'plug_vifs'),
) as (
create_image_mock,
rules_mock,
plug_mock,
):
disk_info_json = jsonutils.dumps({})
res = drvr.pre_live_migration(self.context, instance,
block_device_info=None,
network_info=[],
disk_info=disk_info_json,
migrate_data=migrate_data)
create_image_mock.assert_has_calls(
[mock.call(self.context, instance, mock.ANY, {},
fallback_from_host=instance.host)])
self.assertIsInstance(res, objects.LibvirtLiveMigrateData)
def test_pre_live_migration_recreate_disk_info(self):
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=False,
is_shared_instance_path=False,
block_migration=True,
instance_relative_path='/some/path/',
)
disk_info = [{'disk_size': 5368709120, 'type': 'raw',
'virt_disk_size': 5368709120,
'path': '/some/path/disk',
'backing_file': '', 'over_committed_disk_size': 0},
{'disk_size': 1073741824, 'type': 'raw',
'virt_disk_size': 1073741824,
'path': '/some/path/disk.eph0',
'backing_file': '', 'over_committed_disk_size': 0}]
image_disk_info = {'/some/path/disk': 'raw',
'/some/path/disk.eph0': 'raw'}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
instance_path = os.path.dirname(disk_info[0]['path'])
disk_info_path = os.path.join(instance_path, 'disk.info')
with test.nested(
mock.patch.object(os, 'mkdir'),
mock.patch.object(fake_libvirt_utils, 'write_to_file'),
mock.patch.object(drvr, '_create_images_and_backing')
) as (
mkdir, write_to_file, create_images_and_backing
):
drvr.pre_live_migration(self.context, instance,
block_device_info=None,
network_info=[],
disk_info=jsonutils.dumps(disk_info),
migrate_data=migrate_data)
write_to_file.assert_called_with(disk_info_path,
jsonutils.dumps(image_disk_info))
def test_pre_live_migration_with_perf_events(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._supported_perf_events = ['cmt']
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=False,
is_shared_instance_path=False,
block_migration=False,
instance_relative_path='foo',
)
instance = objects.Instance(**self.test_instance)
res = drvr.pre_live_migration(self.context, instance,
block_device_info=None,
network_info=[],
disk_info=None,
migrate_data=migrate_data)
self.assertEqual(['cmt'], res.supported_perf_events)
def test_get_instance_disk_info_works_correctly(self):
# Test data
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance.name:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi
fake_libvirt_utils.disk_sizes['/test/disk.local'] = 20 * units.Gi
fake_libvirt_utils.disk_backing_files['/test/disk.local'] = 'file'
self.mox.StubOutWithMock(os.path, "getsize")
os.path.getsize('/test/disk').AndReturn((10737418240))
os.path.getsize('/test/disk.local').AndReturn((3328599655))
ret = ("image: /test/disk\n"
"file format: raw\n"
"virtual size: 20G (21474836480 bytes)\n"
"disk size: 3.1G\n"
"cluster_size: 2097152\n"
"backing file: /test/dummy (actual path: /backing/file)\n")
self.mox.StubOutWithMock(os.path, "exists")
os.path.exists('/test/disk.local').AndReturn(True)
self.mox.StubOutWithMock(utils, "execute")
utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
'/test/disk.local', prlimit = images.QEMU_IMG_LIMITS,
).AndReturn((ret, ''))
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = drvr.get_instance_disk_info(instance)
info = jsonutils.loads(info)
self.assertEqual(info[0]['type'], 'raw')
self.assertEqual(info[0]['path'], '/test/disk')
self.assertEqual(info[0]['disk_size'], 10737418240)
self.assertEqual(info[0]['backing_file'], "")
self.assertEqual(info[0]['over_committed_disk_size'], 0)
self.assertEqual(info[1]['type'], 'qcow2')
self.assertEqual(info[1]['path'], '/test/disk.local')
self.assertEqual(info[1]['virt_disk_size'], 21474836480)
self.assertEqual(info[1]['backing_file'], "file")
self.assertEqual(info[1]['over_committed_disk_size'], 18146236825)
def test_post_live_migration(self):
vol = {'block_device_mapping': [
{'connection_info': {
'data': {'multipath_id': 'dummy1'},
'serial': 'fake_serial1'},
'mount_device': '/dev/sda',
},
{'connection_info': {
'data': {},
'serial': 'fake_serial2'},
'mount_device': '/dev/sdb', }]}
def fake_initialize_connection(context, volume_id, connector):
return {'data': {}}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_connector = {'host': 'fake'}
inst_ref = {'id': 'foo'}
cntx = context.get_admin_context()
# Set up the mock expectations
with test.nested(
mock.patch.object(driver, 'block_device_info_get_mapping',
return_value=vol['block_device_mapping']),
mock.patch.object(drvr, "get_volume_connector",
return_value=fake_connector),
mock.patch.object(drvr._volume_api, "initialize_connection",
side_effect=fake_initialize_connection),
mock.patch.object(drvr, '_disconnect_volume')
) as (block_device_info_get_mapping, get_volume_connector,
initialize_connection, _disconnect_volume):
drvr.post_live_migration(cntx, inst_ref, vol)
block_device_info_get_mapping.assert_has_calls([
mock.call(vol)])
get_volume_connector.assert_has_calls([
mock.call(inst_ref)])
_disconnect_volume.assert_has_calls([
mock.call({'data': {'multipath_id': 'dummy1'}}, 'sda'),
mock.call({'data': {}}, 'sdb')])
def test_get_instance_disk_info_excludes_volumes(self):
# Test data
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/fake/path/to/volume1'/>"
"<target dev='vdc' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/fake/path/to/volume2'/>"
"<target dev='vdd' bus='virtio'/></disk>"
"</devices></domain>")
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance.name:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi
fake_libvirt_utils.disk_sizes['/test/disk.local'] = 20 * units.Gi
fake_libvirt_utils.disk_backing_files['/test/disk.local'] = 'file'
self.mox.StubOutWithMock(os.path, "getsize")
os.path.getsize('/test/disk').AndReturn((10737418240))
os.path.getsize('/test/disk.local').AndReturn((3328599655))
ret = ("image: /test/disk\n"
"file format: raw\n"
"virtual size: 20G (21474836480 bytes)\n"
"disk size: 3.1G\n"
"cluster_size: 2097152\n"
"backing file: /test/dummy (actual path: /backing/file)\n")
self.mox.StubOutWithMock(os.path, "exists")
os.path.exists('/test/disk.local').AndReturn(True)
self.mox.StubOutWithMock(utils, "execute")
utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
'/test/disk.local', prlimit = images.QEMU_IMG_LIMITS,
).AndReturn((ret, ''))
self.mox.ReplayAll()
conn_info = {'driver_volume_type': 'fake'}
info = {'block_device_mapping': [
{'connection_info': conn_info, 'mount_device': '/dev/vdc'},
{'connection_info': conn_info, 'mount_device': '/dev/vdd'}]}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = drvr.get_instance_disk_info(instance,
block_device_info=info)
info = jsonutils.loads(info)
self.assertEqual(info[0]['type'], 'raw')
self.assertEqual(info[0]['path'], '/test/disk')
self.assertEqual(info[0]['disk_size'], 10737418240)
self.assertEqual(info[0]['backing_file'], "")
self.assertEqual(info[0]['over_committed_disk_size'], 0)
self.assertEqual(info[1]['type'], 'qcow2')
self.assertEqual(info[1]['path'], '/test/disk.local')
self.assertEqual(info[1]['virt_disk_size'], 21474836480)
self.assertEqual(info[1]['backing_file'], "file")
self.assertEqual(info[1]['over_committed_disk_size'], 18146236825)
def test_get_instance_disk_info_no_bdinfo_passed(self):
# NOTE(ndipanov): _get_disk_overcomitted_size_total calls this method
# without access to Nova's block device information. We want to make
# sure that we guess volumes mostly correctly in that case as well
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='block'><driver name='qemu' type='raw'/>"
"<source file='/fake/path/to/volume1'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance.name:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi
self.mox.StubOutWithMock(os.path, "getsize")
os.path.getsize('/test/disk').AndReturn((10737418240))
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = drvr.get_instance_disk_info(instance)
info = jsonutils.loads(info)
self.assertEqual(1, len(info))
self.assertEqual(info[0]['type'], 'raw')
self.assertEqual(info[0]['path'], '/test/disk')
self.assertEqual(info[0]['disk_size'], 10737418240)
self.assertEqual(info[0]['backing_file'], "")
self.assertEqual(info[0]['over_committed_disk_size'], 0)
def test_spawn_with_network_info(self):
# Preparing mocks
def fake_none(*args, **kwargs):
return
def fake_getLibVersion():
return fakelibvirt.FAKE_LIBVIRT_VERSION
def fake_getCapabilities():
return """
<capabilities>
<host>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<cpu>
<arch>x86_64</arch>
<model>Penryn</model>
<vendor>Intel</vendor>
<topology sockets='1' cores='2' threads='1'/>
<feature name='xtpr'/>
</cpu>
</host>
</capabilities>
"""
def fake_baselineCPU(cpu, flag):
return """<cpu mode='custom' match='exact'>
<model fallback='allow'>Penryn</model>
<vendor>Intel</vendor>
<feature policy='require' name='xtpr'/>
</cpu>
"""
# _fake_network_info must be called before create_fake_libvirt_mock(),
# as _fake_network_info calls importutils.import_class() and
# create_fake_libvirt_mock() mocks importutils.import_class().
network_info = _fake_network_info(self, 1)
self.create_fake_libvirt_mock(getLibVersion=fake_getLibVersion,
getCapabilities=fake_getCapabilities,
getVersion=lambda: 1005001,
baselineCPU=fake_baselineCPU)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456 # we send an int to test sha1 call
instance = objects.Instance(**instance_ref)
instance.config_drive = ''
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver,
'_build_device_metadata')
libvirt_driver.LibvirtDriver._build_device_metadata(self.context,
instance)
# Mock out the get_info method of the LibvirtDriver so that the polling
# in the spawn method of the LibvirtDriver returns immediately
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'get_info')
libvirt_driver.LibvirtDriver.get_info(instance
).AndReturn(hardware.InstanceInfo(state=power_state.RUNNING))
# Start test
self.mox.ReplayAll()
with mock.patch('nova.virt.libvirt.driver.libvirt') as old_virt:
del old_virt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr.firewall_driver,
'setup_basic_filtering',
fake_none)
self.stubs.Set(drvr.firewall_driver,
'prepare_instance_filter',
fake_none)
self.stubs.Set(imagebackend.Image,
'cache',
fake_none)
drvr.spawn(self.context, instance, image_meta, [], 'herp',
network_info=network_info)
path = os.path.join(CONF.instances_path, instance['name'])
if os.path.isdir(path):
shutil.rmtree(path)
path = os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name)
if os.path.isdir(path):
shutil.rmtree(os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name))
# Methods called directly by spawn()
@mock.patch.object(libvirt_driver.LibvirtDriver, '_get_guest_xml')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_domain_and_network')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info')
# Methods called by _create_configdrive via post_xml_callback
@mock.patch('nova.virt.configdrive.ConfigDriveBuilder._make_iso9660')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_build_device_metadata')
@mock.patch.object(instance_metadata, 'InstanceMetadata')
def test_spawn_with_config_drive(self, mock_instance_metadata,
mock_build_device_metadata,
mock_mkisofs, mock_get_info,
mock_create_domain_and_network,
mock_get_guest_xml):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
instance.config_drive = 'True'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
instance_info = hardware.InstanceInfo(state=power_state.RUNNING)
mock_build_device_metadata.return_value = None
def fake_create_domain_and_network(
context, xml, instance, network_info, disk_info,
block_device_info=None, power_on=True, reboot=False,
vifs_already_plugged=False, post_xml_callback=None):
# The config disk should be created by this callback, so we need
# to execute it.
post_xml_callback()
fake_backend = self.useFixture(
fake_imagebackend.ImageBackendFixture(exists=lambda _: False))
mock_get_info.return_value = instance_info
mock_create_domain_and_network.side_effect = \
fake_create_domain_and_network
drvr.spawn(self.context, instance,
image_meta, [], None)
# We should have imported 'disk.config'
config_disk = fake_backend.disks['disk.config']
config_disk.import_file.assert_called_once_with(instance, mock.ANY,
'disk.config')
def test_spawn_without_image_meta(self):
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = objects.Instance(**instance_ref)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
fake_backend = self.useFixture(fake_imagebackend.ImageBackendFixture())
drvr.spawn(self.context, instance, image_meta, [], None)
# We should have created a root disk and an ephemeral disk
self.assertEqual(['disk', 'disk.local'],
sorted(fake_backend.created_disks.keys()))
def test_spawn_from_volume_calls_cache(self):
self.cache_called_for_disk = False
def fake_none(*args, **kwargs):
return
def fake_cache(*args, **kwargs):
if kwargs.get('image_id') == 'my_fake_image':
self.cache_called_for_disk = True
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(imagebackend.Image, 'cache', fake_cache)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
block_device_info = {'root_device_name': '/dev/vda',
'block_device_mapping': [
{'mount_device': 'vda',
'boot_index': 0}
]
}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
# Volume-backed instance created without image
instance_ref = self.test_instance
instance_ref['image_ref'] = ''
instance_ref['root_device_name'] = '/dev/vda'
instance_ref['uuid'] = uuidutils.generate_uuid()
instance = objects.Instance(**instance_ref)
drvr.spawn(self.context, instance,
image_meta, [], None,
block_device_info=block_device_info)
self.assertFalse(self.cache_called_for_disk)
# Booted from volume but with placeholder image
instance_ref = self.test_instance
instance_ref['image_ref'] = 'my_fake_image'
instance_ref['root_device_name'] = '/dev/vda'
instance_ref['uuid'] = uuidutils.generate_uuid()
instance = objects.Instance(**instance_ref)
drvr.spawn(self.context, instance,
image_meta, [], None,
block_device_info=block_device_info)
self.assertFalse(self.cache_called_for_disk)
# Booted from an image
instance_ref['image_ref'] = 'my_fake_image'
instance_ref['uuid'] = uuidutils.generate_uuid()
instance = objects.Instance(**instance_ref)
drvr.spawn(self.context, instance,
image_meta, [], None)
self.assertTrue(self.cache_called_for_disk)
def test_start_lxc_from_volume(self):
self.flags(virt_type="lxc",
group='libvirt')
def check_setup_container(image, container_dir=None):
self.assertIsInstance(image, imgmodel.LocalBlockImage)
self.assertEqual(image.path, '/dev/path/to/dev')
return '/dev/nbd1'
bdm = {
'guest_format': None,
'boot_index': 0,
'mount_device': '/dev/sda',
'connection_info': {
'driver_volume_type': 'iscsi',
'serial': 'afc1',
'data': {
'access_mode': 'rw',
'target_discovered': False,
'encrypted': False,
'qos_specs': None,
'target_iqn': 'iqn: volume-afc1',
'target_portal': 'ip: 3260',
'volume_id': 'afc1',
'target_lun': 1,
'auth_password': 'uj',
'auth_username': '47',
'auth_method': 'CHAP'
}
},
'disk_bus': 'scsi',
'device_type': 'disk',
'delete_on_termination': False
}
def _connect_volume_side_effect(connection_info, disk_info):
bdm['connection_info']['data']['device_path'] = '/dev/path/to/dev'
def _get(key, opt=None):
return bdm.get(key, opt)
def getitem(key):
return bdm[key]
def setitem(key, val):
bdm[key] = val
bdm_mock = mock.MagicMock()
bdm_mock.__getitem__.side_effect = getitem
bdm_mock.__setitem__.side_effect = setitem
bdm_mock.get = _get
disk_mock = mock.MagicMock()
disk_mock.source_path = '/dev/path/to/dev'
block_device_info = {'block_device_mapping': [bdm_mock],
'root_device_name': '/dev/sda'}
# Volume-backed instance created without image
instance_ref = self.test_instance
instance_ref['image_ref'] = ''
instance_ref['root_device_name'] = '/dev/sda'
instance_ref['ephemeral_gb'] = 0
instance_ref['uuid'] = uuidutils.generate_uuid()
inst_obj = objects.Instance(**instance_ref)
image_meta = objects.ImageMeta.from_dict({})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter'),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, '_connect_volume',
side_effect=_connect_volume_side_effect),
mock.patch.object(drvr, '_get_volume_config',
return_value=disk_mock),
mock.patch.object(drvr, 'get_info',
return_value=hardware.InstanceInfo(
state=power_state.RUNNING)),
mock.patch('nova.virt.disk.api.setup_container',
side_effect=check_setup_container),
mock.patch('nova.virt.disk.api.teardown_container'),
mock.patch.object(objects.Instance, 'save')):
drvr.spawn(self.context, inst_obj, image_meta, [], None,
network_info=[],
block_device_info=block_device_info)
self.assertEqual('/dev/nbd1',
inst_obj.system_metadata.get(
'rootfs_device_name'))
def test_spawn_with_pci_devices(self):
def fake_none(*args, **kwargs):
return None
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
class FakeLibvirtPciDevice(object):
def dettach(self):
return None
def reset(self):
return None
def fake_node_device_lookup_by_name(address):
pattern = ("pci_%(hex)s{4}_%(hex)s{2}_%(hex)s{2}_%(oct)s{1}"
% dict(hex='[\da-f]', oct='[0-8]'))
pattern = re.compile(pattern)
if pattern.match(address) is None:
raise fakelibvirt.libvirtError()
return FakeLibvirtPciDevice()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
mock_connection = mock.MagicMock(
nodeDeviceLookupByName=fake_node_device_lookup_by_name)
instance_ref = self.test_instance
instance_ref['image_ref'] = 'my_fake_image'
instance = objects.Instance(**instance_ref)
instance['pci_devices'] = objects.PciDeviceList(
objects=[objects.PciDevice(address='0000:00:00.0')])
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.useFixture(fake_imagebackend.ImageBackendFixture())
with mock.patch.object(drvr, '_get_connection',
return_value=mock_connection):
drvr.spawn(self.context, instance, image_meta, [], None)
def _test_create_image_plain(self, os_type='', filename='', mkfs=False):
gotFiles = []
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = objects.Instance(**instance_ref)
instance['os_type'] = os_type
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
if mkfs:
self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND',
{os_type: 'mkfs.ext4 --label %(fs_label)s %(target)s'})
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
self.useFixture(
fake_imagebackend.ImageBackendFixture(got_files=gotFiles))
drvr._create_image(self.context, instance, disk_info['mapping'])
drvr._get_guest_xml(self.context, instance, None,
disk_info, image_meta)
wantFiles = [
{'filename': '356a192b7913b04c54574d18c28d46e6395428ab',
'size': 10 * units.Gi},
{'filename': filename,
'size': 20 * units.Gi},
]
self.assertEqual(gotFiles, wantFiles)
def test_create_image_plain_os_type_blank(self):
self._test_create_image_plain(os_type='',
filename=self._EPHEMERAL_20_DEFAULT,
mkfs=False)
def test_create_image_plain_os_type_none(self):
self._test_create_image_plain(os_type=None,
filename=self._EPHEMERAL_20_DEFAULT,
mkfs=False)
def test_create_image_plain_os_type_set_no_fs(self):
self._test_create_image_plain(os_type='test',
filename=self._EPHEMERAL_20_DEFAULT,
mkfs=False)
def test_create_image_plain_os_type_set_with_fs(self):
ephemeral_file_name = ('ephemeral_20_%s' % utils.get_hash_str(
'mkfs.ext4 --label %(fs_label)s %(target)s')[:7])
self._test_create_image_plain(os_type='test',
filename=ephemeral_file_name,
mkfs=True)
def test_create_image_initrd(self):
kernel_id = uuids.kernel_id
ramdisk_id = uuids.ramdisk_id
kernel_fname = imagecache.get_cache_fname(kernel_id)
ramdisk_fname = imagecache.get_cache_fname(ramdisk_id)
filename = self._EPHEMERAL_20_DEFAULT
gotFiles = []
instance_ref = self.test_instance
instance_ref['image_ref'] = uuids.instance_id
instance_ref['kernel_id'] = uuids.kernel_id
instance_ref['ramdisk_id'] = uuids.ramdisk_id
instance_ref['os_type'] = 'test'
instance = objects.Instance(**instance_ref)
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_backend = self.useFixture(
fake_imagebackend.ImageBackendFixture(got_files=gotFiles))
with test.nested(
mock.patch.object(driver, '_get_guest_xml'),
mock.patch.object(driver, '_create_domain_and_network'),
mock.patch.object(driver, 'get_info',
return_value=[hardware.InstanceInfo(state=power_state.RUNNING)])
):
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
driver._create_image(self.context, instance, disk_info['mapping'])
# Assert that kernel and ramdisk were fetched with fetch_raw_image
# and no size
for name, disk in six.iteritems(fake_backend.disks):
cache = disk.cache
if name in ('kernel', 'ramdisk'):
cache.assert_called_once_with(
context=self.context, filename=mock.ANY, image_id=mock.ANY,
fetch_func=fake_libvirt_utils.fetch_raw_image)
wantFiles = [
{'filename': kernel_fname,
'size': None},
{'filename': ramdisk_fname,
'size': None},
{'filename': imagecache.get_cache_fname(uuids.instance_id),
'size': 10 * units.Gi},
{'filename': filename,
'size': 20 * units.Gi},
]
self.assertEqual(wantFiles, gotFiles)
def _create_image_helper(self, callback, exists=None, suffix='',
test_create_configdrive=False):
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
# NOTE(mikal): use this callback to tweak the instance to match
# what you're trying to test
callback(instance_ref)
instance = objects.Instance(**instance_ref)
# Turn on some swap to exercise that codepath in _create_image
instance.flavor.swap = 500
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
self.stubs.Set(instance_metadata, 'InstanceMetadata', fake_none)
self.stubs.Set(nova.virt.configdrive.ConfigDriveBuilder,
'make_drive', fake_none)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
gotFiles = []
imported_files = []
self.useFixture(fake_imagebackend.ImageBackendFixture(
got_files=gotFiles, imported_files=imported_files, exists=exists))
if test_create_configdrive:
drvr._create_configdrive(self.context, instance)
else:
drvr._create_image(self.context, instance, disk_info['mapping'],
suffix=suffix)
drvr._get_guest_xml(self.context, instance, None,
disk_info, image_meta)
return gotFiles, imported_files
def test_create_image_with_swap(self):
def enable_swap(instance_ref):
# Turn on some swap to exercise that codepath in _create_image
instance_ref['system_metadata']['instance_type_swap'] = 500
gotFiles, _ = self._create_image_helper(enable_swap)
wantFiles = [
{'filename': '356a192b7913b04c54574d18c28d46e6395428ab',
'size': 10 * units.Gi},
{'filename': self._EPHEMERAL_20_DEFAULT,
'size': 20 * units.Gi},
{'filename': 'swap_500',
'size': 500 * units.Mi},
]
self.assertEqual(gotFiles, wantFiles)
@mock.patch(
'nova.virt.libvirt.driver.LibvirtDriver._build_device_metadata',
return_value=None)
def test_create_configdrive(self, mock_save):
def enable_configdrive(instance_ref):
instance_ref['config_drive'] = 'true'
# Ensure that we create a config drive and then import it into the
# image backend store
_, imported_files = self._create_image_helper(
enable_configdrive, exists=lambda name: False,
test_create_configdrive=True)
self.assertTrue(imported_files[0][0].endswith('/disk.config'))
self.assertEqual('disk.config', imported_files[0][1])
@mock.patch.object(nova.virt.libvirt.imagebackend.Image, 'cache',
side_effect=exception.ImageNotFound(image_id='fake-id'))
def test_create_image_not_exist_no_fallback(self, mock_cache):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
self.assertRaises(exception.ImageNotFound,
drvr._create_image,
self.context, instance, disk_info['mapping'])
@mock.patch.object(nova.virt.libvirt.imagebackend.Image, 'cache')
def test_create_image_not_exist_fallback(self, mock_cache):
def side_effect(fetch_func, filename, size=None, *args, **kwargs):
def second_call(fetch_func, filename, size=None, *args, **kwargs):
# call copy_from_host ourselves because we mocked image.cache()
fetch_func('fake-target')
# further calls have no side effect
mock_cache.side_effect = None
mock_cache.side_effect = second_call
# raise an error only the first call
raise exception.ImageNotFound(image_id='fake-id')
mock_cache.side_effect = side_effect
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
with mock.patch.object(libvirt_driver.libvirt_utils,
'copy_image') as mock_copy:
drvr._create_image(self.context, instance, disk_info['mapping'],
fallback_from_host='fake-source-host')
mock_copy.assert_called_once_with(src='fake-target',
dest='fake-target',
host='fake-source-host',
receive=True)
@mock.patch.object(nova.virt.libvirt.imagebackend.Image, 'cache')
def test_create_image_resize_snap_backend(self, mock_cache):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
instance.task_state = task_states.RESIZE_FINISH
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
fake_backend = self.useFixture(fake_imagebackend.ImageBackendFixture())
drvr._create_image(self.context, instance, disk_info['mapping'])
# Assert we called create_snap on the root disk
fake_backend.disks['disk'].create_snap.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME)
@mock.patch.object(utils, 'execute')
def test_create_ephemeral_specified_fs(self, mock_exec):
self.flags(default_ephemeral_format='ext3')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True, specified_fs='ext4')
mock_exec.assert_called_once_with('mkfs', '-t', 'ext4', '-F', '-L',
'myVol', '/dev/something',
run_as_root=True)
def test_create_ephemeral_specified_fs_not_valid(self):
CONF.set_override('default_ephemeral_format', 'ext4')
ephemerals = [{'device_type': 'disk',
'disk_bus': 'virtio',
'device_name': '/dev/vdb',
'guest_format': 'dummy',
'size': 1}]
block_device_info = {
'ephemerals': ephemerals}
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = objects.Instance(**instance_ref)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
image_meta = objects.ImageMeta.from_dict({'disk_format': 'raw'})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
disk_info['mapping'].pop('disk.local')
with test.nested(
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr, 'get_info'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(imagebackend.Image, 'verify_base_size'),
mock.patch.object(imagebackend.Image, 'get_disk_size')):
self.assertRaises(exception.InvalidBDMFormat, drvr._create_image,
context, instance, disk_info['mapping'],
block_device_info=block_device_info)
def test_create_ephemeral_default(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkfs', '-t', 'ext4', '-F', '-L', 'myVol',
'/dev/something', run_as_root=True)
self.mox.ReplayAll()
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True)
def test_create_ephemeral_with_conf(self):
CONF.set_override('default_ephemeral_format', 'ext4')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkfs', '-t', 'ext4', '-F', '-L', 'myVol',
'/dev/something', run_as_root=True)
self.mox.ReplayAll()
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True)
def test_create_ephemeral_with_arbitrary(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND',
{'linux': 'mkfs.ext4 --label %(fs_label)s %(target)s'})
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkfs.ext4', '--label', 'myVol', '/dev/something',
run_as_root=True)
self.mox.ReplayAll()
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True)
def test_create_ephemeral_with_ext3(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND',
{'linux': 'mkfs.ext3 --label %(fs_label)s %(target)s'})
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkfs.ext3', '--label', 'myVol', '/dev/something',
run_as_root=True)
self.mox.ReplayAll()
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True)
def test_create_swap_default(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkswap', '/dev/something', run_as_root=False)
self.mox.ReplayAll()
drvr._create_swap('/dev/something', 1)
def test_get_console_output_file(self):
fake_libvirt_utils.files['console.log'] = '01234567890'
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = objects.Instance(**instance_ref)
console_dir = (os.path.join(tmpdir, instance['name']))
console_log = '%s/console.log' % (console_dir)
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='file'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % console_log
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
try:
prev_max = libvirt_driver.MAX_CONSOLE_BYTES
libvirt_driver.MAX_CONSOLE_BYTES = 5
with mock.patch('os.path.exists', return_value=True):
output = drvr.get_console_output(self.context, instance)
finally:
libvirt_driver.MAX_CONSOLE_BYTES = prev_max
self.assertEqual('67890', output)
def test_get_console_output_file_missing(self):
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = objects.Instance(**instance_ref)
console_log = os.path.join(tmpdir, instance['name'],
'non-existent.log')
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='file'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % console_log
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch('os.path.exists', return_value=False):
output = drvr.get_console_output(self.context, instance)
self.assertEqual('', output)
def test_get_console_output_pty(self):
fake_libvirt_utils.files['pty'] = '01234567890'
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = objects.Instance(**instance_ref)
console_dir = (os.path.join(tmpdir, instance['name']))
pty_file = '%s/fake_pty' % (console_dir)
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='pty'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % pty_file
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
def _fake_flush(self, fake_pty):
return 'foo'
def _fake_append_to_file(self, data, fpath):
return 'pty'
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
libvirt_driver.LibvirtDriver._flush_libvirt_console = _fake_flush
libvirt_driver.LibvirtDriver._append_to_file = _fake_append_to_file
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
try:
prev_max = libvirt_driver.MAX_CONSOLE_BYTES
libvirt_driver.MAX_CONSOLE_BYTES = 5
output = drvr.get_console_output(self.context, instance)
finally:
libvirt_driver.MAX_CONSOLE_BYTES = prev_max
self.assertEqual('67890', output)
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_console_output_not_available(self, mock_get_xml, get_domain):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='foo'>
<source path='srcpath'/>
<target port='0'/>
</console>
</devices>
</domain>
"""
mock_get_xml.return_value = xml
get_domain.return_value = mock.MagicMock()
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.ConsoleNotAvailable,
drvr.get_console_output, self.context, instance)
def test_get_host_ip_addr(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ip = drvr.get_host_ip_addr()
self.assertEqual(ip, CONF.my_ip)
@mock.patch.object(libvirt_driver.LOG, 'warning')
@mock.patch('nova.compute.utils.get_machine_ips')
def test_get_host_ip_addr_failure(self, mock_ips, mock_log):
mock_ips.return_value = ['8.8.8.8', '75.75.75.75']
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.get_host_ip_addr()
mock_log.assert_called_once_with(u'my_ip address (%(my_ip)s) was '
u'not found on any of the '
u'interfaces: %(ifaces)s',
{'ifaces': '8.8.8.8, 75.75.75.75',
'my_ip': mock.ANY})
def test_conn_event_handler(self):
self.mox.UnsetStubs()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
service_mock = mock.MagicMock()
service_mock.disabled.return_value = False
with test.nested(
mock.patch.object(drvr._host, "_connect",
side_effect=fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
"Failed to connect to host",
error_code=
fakelibvirt.VIR_ERR_INTERNAL_ERROR)),
mock.patch.object(drvr._host, "_init_events",
return_value=None),
mock.patch.object(objects.Service, "get_by_compute_host",
return_value=service_mock)):
# verify that the driver registers for the close callback
# and re-connects after receiving the callback
self.assertRaises(exception.HypervisorUnavailable,
drvr.init_host,
"wibble")
self.assertTrue(service_mock.disabled)
def test_command_with_broken_connection(self):
self.mox.UnsetStubs()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
service_mock = mock.MagicMock()
service_mock.disabled.return_value = False
with test.nested(
mock.patch.object(drvr._host, "_connect",
side_effect=fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
"Failed to connect to host",
error_code=
fakelibvirt.VIR_ERR_INTERNAL_ERROR)),
mock.patch.object(drvr._host, "_init_events",
return_value=None),
mock.patch.object(host.Host, "has_min_version",
return_value=True),
mock.patch.object(drvr, "_do_quality_warnings",
return_value=None),
mock.patch.object(objects.Service, "get_by_compute_host",
return_value=service_mock),
mock.patch.object(host.Host, "get_capabilities")):
drvr.init_host("wibble")
self.assertRaises(exception.HypervisorUnavailable,
drvr.get_num_instances)
self.assertTrue(service_mock.disabled)
def test_service_resume_after_broken_connection(self):
self.mox.UnsetStubs()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
service_mock = mock.MagicMock()
service_mock.disabled.return_value = True
with test.nested(
mock.patch.object(drvr._host, "_connect",
return_value=mock.MagicMock()),
mock.patch.object(drvr._host, "_init_events",
return_value=None),
mock.patch.object(host.Host, "has_min_version",
return_value=True),
mock.patch.object(drvr, "_do_quality_warnings",
return_value=None),
mock.patch.object(objects.Service, "get_by_compute_host",
return_value=service_mock),
mock.patch.object(host.Host, "get_capabilities")):
drvr.init_host("wibble")
drvr.get_num_instances()
self.assertTrue(not service_mock.disabled and
service_mock.disabled_reason is None)
@mock.patch.object(objects.Instance, 'save')
def test_immediate_delete(self, mock_save):
def fake_get_domain(instance):
raise exception.InstanceNotFound(instance_id=instance.uuid)
def fake_delete_instance_files(instance):
pass
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, 'delete_instance_files',
fake_delete_instance_files)
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, {})
mock_save.assert_called_once_with()
@mock.patch.object(objects.Instance, 'get_by_uuid')
@mock.patch.object(objects.Instance, 'obj_load_attr', autospec=True)
@mock.patch.object(objects.Instance, 'save', autospec=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, '_destroy')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'delete_instance_files')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_disconnect_volume')
@mock.patch.object(driver, 'block_device_info_get_mapping')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_undefine_domain')
def _test_destroy_removes_disk(self, mock_undefine_domain, mock_mapping,
mock_disconnect_volume,
mock_delete_instance_files, mock_destroy,
mock_inst_save, mock_inst_obj_load_attr,
mock_get_by_uuid, volume_fail=False):
instance = objects.Instance(self.context, **self.test_instance)
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
mock_mapping.return_value = vol['block_device_mapping']
mock_delete_instance_files.return_value = True
mock_get_by_uuid.return_value = instance
if volume_fail:
mock_disconnect_volume.return_value = (
exception.VolumeNotFound('vol'))
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.destroy(self.context, instance, [], vol)
def test_destroy_removes_disk(self):
self._test_destroy_removes_disk(volume_fail=False)
def test_destroy_removes_disk_volume_fails(self):
self._test_destroy_removes_disk(volume_fail=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, 'unplug_vifs')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_destroy')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_undefine_domain')
def test_destroy_not_removes_disk(self, mock_undefine_domain, mock_destroy,
mock_unplug_vifs):
instance = fake_instance.fake_instance_obj(
None, name='instancename', id=1,
uuid='875a8070-d0b9-4949-8b31-104d125c9a64')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.destroy(self.context, instance, [], None, False)
@mock.patch.object(libvirt_driver.LibvirtDriver, 'cleanup')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_teardown_container')
@mock.patch.object(host.Host, 'get_domain')
def test_destroy_lxc_calls_teardown_container(self, mock_get_domain,
mock_teardown_container,
mock_cleanup):
self.flags(virt_type='lxc', group='libvirt')
fake_domain = FakeVirtDomain()
def destroy_side_effect(*args, **kwargs):
fake_domain._info[0] = power_state.SHUTDOWN
with mock.patch.object(fake_domain, 'destroy',
side_effect=destroy_side_effect) as mock_domain_destroy:
mock_get_domain.return_value = fake_domain
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
network_info = []
drvr.destroy(self.context, instance, network_info, None, False)
mock_get_domain.assert_has_calls([mock.call(instance),
mock.call(instance)])
mock_domain_destroy.assert_called_once_with()
mock_teardown_container.assert_called_once_with(instance)
mock_cleanup.assert_called_once_with(self.context, instance,
network_info, None, False,
None)
@mock.patch.object(libvirt_driver.LibvirtDriver, 'cleanup')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_teardown_container')
@mock.patch.object(host.Host, 'get_domain')
def test_destroy_lxc_calls_teardown_container_when_no_domain(self,
mock_get_domain, mock_teardown_container, mock_cleanup):
self.flags(virt_type='lxc', group='libvirt')
instance = objects.Instance(**self.test_instance)
inf_exception = exception.InstanceNotFound(instance_id=instance.uuid)
mock_get_domain.side_effect = inf_exception
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
network_info = []
drvr.destroy(self.context, instance, network_info, None, False)
mock_get_domain.assert_has_calls([mock.call(instance),
mock.call(instance)])
mock_teardown_container.assert_called_once_with(instance)
mock_cleanup.assert_called_once_with(self.context, instance,
network_info, None, False,
None)
def test_reboot_different_ids(self):
class FakeLoopingCall(object):
def start(self, *a, **k):
return self
def wait(self):
return None
self.flags(wait_soft_reboot_seconds=1, group='libvirt')
info_tuple = ('fake', 'fake', 'fake', 'also_fake')
self.reboot_create_called = False
# Mock domain
mock_domain = self.mox.CreateMock(fakelibvirt.virDomain)
mock_domain.info().AndReturn(
(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple)
mock_domain.ID().AndReturn('some_fake_id')
mock_domain.ID().AndReturn('some_fake_id')
mock_domain.shutdown()
mock_domain.info().AndReturn(
(libvirt_guest.VIR_DOMAIN_CRASHED,) + info_tuple)
mock_domain.ID().AndReturn('some_other_fake_id')
mock_domain.ID().AndReturn('some_other_fake_id')
self.mox.ReplayAll()
def fake_get_domain(instance):
return mock_domain
def fake_create_domain(**kwargs):
self.reboot_create_called = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, '_create_domain', fake_create_domain)
self.stubs.Set(loopingcall, 'FixedIntervalLoopingCall',
lambda *a, **k: FakeLoopingCall())
self.stubs.Set(pci_manager, 'get_instance_pci_devs', lambda *a: [])
drvr.reboot(None, instance, [], 'SOFT')
self.assertTrue(self.reboot_create_called)
@mock.patch.object(pci_manager, 'get_instance_pci_devs')
@mock.patch.object(loopingcall, 'FixedIntervalLoopingCall')
@mock.patch.object(greenthread, 'sleep')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot')
@mock.patch.object(host.Host, 'get_domain')
def test_reboot_same_ids(self, mock_get_domain, mock_hard_reboot,
mock_sleep, mock_loopingcall,
mock_get_instance_pci_devs):
class FakeLoopingCall(object):
def start(self, *a, **k):
return self
def wait(self):
return None
self.flags(wait_soft_reboot_seconds=1, group='libvirt')
info_tuple = ('fake', 'fake', 'fake', 'also_fake')
self.reboot_hard_reboot_called = False
# Mock domain
mock_domain = mock.Mock(fakelibvirt.virDomain)
return_values = [(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple,
(libvirt_guest.VIR_DOMAIN_CRASHED,) + info_tuple]
mock_domain.info.side_effect = return_values
mock_domain.ID.return_value = 'some_fake_id'
mock_domain.shutdown.side_effect = mock.Mock()
def fake_hard_reboot(*args, **kwargs):
self.reboot_hard_reboot_called = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_get_domain.return_value = mock_domain
mock_hard_reboot.side_effect = fake_hard_reboot
mock_loopingcall.return_value = FakeLoopingCall()
mock_get_instance_pci_devs.return_value = []
drvr.reboot(None, instance, [], 'SOFT')
self.assertTrue(self.reboot_hard_reboot_called)
@mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot')
@mock.patch.object(host.Host, 'get_domain')
def test_soft_reboot_libvirt_exception(self, mock_get_domain,
mock_hard_reboot):
# Tests that a hard reboot is performed when a soft reboot results
# in raising a libvirtError.
info_tuple = ('fake', 'fake', 'fake', 'also_fake')
# setup mocks
mock_virDomain = mock.Mock(fakelibvirt.virDomain)
mock_virDomain.info.return_value = (
(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple)
mock_virDomain.ID.return_value = 'some_fake_id'
mock_virDomain.shutdown.side_effect = fakelibvirt.libvirtError('Err')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
context = None
instance = objects.Instance(**self.test_instance)
network_info = []
mock_get_domain.return_value = mock_virDomain
drvr.reboot(context, instance, network_info, 'SOFT')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot')
@mock.patch.object(host.Host, 'get_domain')
def _test_resume_state_on_host_boot_with_state(self, state,
mock_get_domain,
mock_hard_reboot):
mock_virDomain = mock.Mock(fakelibvirt.virDomain)
mock_virDomain.info.return_value = ([state, None, None, None, None])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_domain.return_value = mock_virDomain
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
drvr.resume_state_on_host_boot(self.context, instance, network_info,
block_device_info=None)
ignored_states = (power_state.RUNNING,
power_state.SUSPENDED,
power_state.NOSTATE,
power_state.PAUSED)
self.assertEqual(mock_hard_reboot.called, state not in ignored_states)
def test_resume_state_on_host_boot_with_running_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.RUNNING)
def test_resume_state_on_host_boot_with_suspended_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.SUSPENDED)
def test_resume_state_on_host_boot_with_paused_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.PAUSED)
def test_resume_state_on_host_boot_with_nostate(self):
self._test_resume_state_on_host_boot_with_state(power_state.NOSTATE)
def test_resume_state_on_host_boot_with_shutdown_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.RUNNING)
def test_resume_state_on_host_boot_with_crashed_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.CRASHED)
@mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot')
@mock.patch.object(host.Host, 'get_domain')
def test_resume_state_on_host_boot_with_instance_not_found_on_driver(
self, mock_get_domain, mock_hard_reboot):
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_domain.side_effect = exception.InstanceNotFound(
instance_id='fake')
drvr.resume_state_on_host_boot(self.context, instance, network_info=[],
block_device_info=None)
mock_hard_reboot.assert_called_once_with(self.context,
instance, [], None)
@mock.patch('nova.virt.libvirt.LibvirtDriver._undefine_domain')
@mock.patch('nova.virt.libvirt.LibvirtDriver.get_info')
@mock.patch('nova.virt.libvirt.LibvirtDriver._create_domain_and_network')
@mock.patch('nova.virt.libvirt.LibvirtDriver._create_images_and_backing')
@mock.patch('nova.virt.libvirt.LibvirtDriver._get_guest_xml')
@mock.patch('nova.virt.libvirt.LibvirtDriver._get_instance_disk_info')
@mock.patch('nova.virt.libvirt.blockinfo.get_disk_info')
@mock.patch('nova.virt.libvirt.LibvirtDriver._destroy')
def test_hard_reboot(self, mock_destroy, mock_get_disk_info,
mock_get_instance_disk_info, mock_get_guest_xml,
mock_create_images_and_backing,
mock_create_domain_and_network, mock_get_info,
mock_undefine):
self.context.auth_token = True # any non-None value will suffice
instance = objects.Instance(**self.test_instance)
instance_path = libvirt_utils.get_instance_path(instance)
network_info = _fake_network_info(self, 1)
block_device_info = None
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
return_values = [hardware.InstanceInfo(state=power_state.SHUTDOWN),
hardware.InstanceInfo(state=power_state.RUNNING)]
mock_get_info.side_effect = return_values
backing_disk_info = [{"virt_disk_size": 2}]
mock_get_disk_info.return_value = mock.sentinel.disk_info
mock_get_guest_xml.return_value = dummyxml
mock_get_instance_disk_info.return_value = backing_disk_info
drvr._hard_reboot(self.context, instance, network_info,
block_device_info)
mock_destroy.assert_called_once_with(instance)
mock_undefine.assert_called_once_with(instance)
# make sure that _create_images_and_backing is passed the disk_info
# returned from _get_instance_disk_info and not the one that is in
# scope from blockinfo.get_disk_info
mock_create_images_and_backing.assert_called_once_with(self.context,
instance, instance_path, backing_disk_info)
# make sure that _create_domain_and_network is passed the disk_info
# returned from blockinfo.get_disk_info and not the one that's
# returned from _get_instance_disk_info
mock_create_domain_and_network.assert_called_once_with(self.context,
dummyxml, instance, network_info, mock.sentinel.disk_info,
block_device_info=block_device_info,
reboot=True, vifs_already_plugged=True)
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall')
@mock.patch('nova.pci.manager.get_instance_pci_devs')
@mock.patch('nova.virt.libvirt.LibvirtDriver._prepare_pci_devices_for_use')
@mock.patch('nova.virt.libvirt.LibvirtDriver._create_domain_and_network')
@mock.patch('nova.virt.libvirt.LibvirtDriver._create_images_and_backing')
@mock.patch('nova.virt.libvirt.LibvirtDriver._get_instance_disk_info')
@mock.patch('nova.virt.libvirt.utils.write_to_file')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
@mock.patch('nova.virt.libvirt.LibvirtDriver._get_guest_config')
@mock.patch('nova.virt.libvirt.blockinfo.get_disk_info')
@mock.patch('nova.virt.libvirt.LibvirtDriver._destroy')
def test_hard_reboot_does_not_call_glance_show(self,
mock_destroy, mock_get_disk_info, mock_get_guest_config,
mock_get_instance_path, mock_write_to_file,
mock_get_instance_disk_info, mock_create_images_and_backing,
mock_create_domand_and_network, mock_prepare_pci_devices_for_use,
mock_get_instance_pci_devs, mock_looping_call, mock_ensure_tree):
"""For a hard reboot, we shouldn't need an additional call to glance
to get the image metadata.
This is important for automatically spinning up instances on a
host-reboot, since we won't have a user request context that'll allow
the Glance request to go through. We have to rely on the cached image
metadata, instead.
https://bugs.launchpad.net/nova/+bug/1339386
"""
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
network_info = mock.MagicMock()
block_device_info = mock.MagicMock()
mock_get_disk_info.return_value = {}
mock_get_guest_config.return_value = mock.MagicMock()
mock_get_instance_path.return_value = '/foo'
mock_looping_call.return_value = mock.MagicMock()
drvr._image_api = mock.MagicMock()
drvr._hard_reboot(self.context, instance, network_info,
block_device_info)
self.assertFalse(drvr._image_api.get.called)
mock_ensure_tree.assert_called_once_with('/foo')
def test_suspend(self):
guest = libvirt_guest.Guest(FakeVirtDomain(id=1))
dom = guest._domain
instance = objects.Instance(**self.test_instance)
instance.ephemeral_key_uuid = None
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
@mock.patch.object(dmcrypt, 'delete_volume')
@mock.patch.object(conn, '_get_instance_disk_info', return_value=[])
@mock.patch.object(conn, '_detach_sriov_ports')
@mock.patch.object(conn, '_detach_pci_devices')
@mock.patch.object(pci_manager, 'get_instance_pci_devs',
return_value='pci devs')
@mock.patch.object(conn._host, 'get_guest', return_value=guest)
def suspend(mock_get_guest, mock_get_instance_pci_devs,
mock_detach_pci_devices, mock_detach_sriov_ports,
mock_get_instance_disk_info, mock_delete_volume):
mock_managedSave = mock.Mock()
dom.managedSave = mock_managedSave
conn.suspend(self.context, instance)
mock_managedSave.assert_called_once_with(0)
self.assertFalse(mock_get_instance_disk_info.called)
mock_delete_volume.assert_has_calls([mock.call(disk['path'])
for disk in mock_get_instance_disk_info.return_value], False)
suspend()
@mock.patch.object(time, 'sleep')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_create_domain')
@mock.patch.object(host.Host, 'get_domain')
def _test_clean_shutdown(self, mock_get_domain, mock_create_domain,
mock_sleep, seconds_to_shutdown,
timeout, retry_interval,
shutdown_attempts, succeeds):
info_tuple = ('fake', 'fake', 'fake', 'also_fake')
shutdown_count = []
# Mock domain
mock_domain = mock.Mock(fakelibvirt.virDomain)
return_infos = [(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple]
return_shutdowns = [shutdown_count.append("shutdown")]
retry_countdown = retry_interval
for x in range(min(seconds_to_shutdown, timeout)):
return_infos.append(
(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple)
if retry_countdown == 0:
return_shutdowns.append(shutdown_count.append("shutdown"))
retry_countdown = retry_interval
else:
retry_countdown -= 1
if seconds_to_shutdown < timeout:
return_infos.append(
(libvirt_guest.VIR_DOMAIN_SHUTDOWN,) + info_tuple)
mock_domain.info.side_effect = return_infos
mock_domain.shutdown.side_effect = return_shutdowns
def fake_create_domain(**kwargs):
self.reboot_create_called = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_get_domain.return_value = mock_domain
mock_create_domain.side_effect = fake_create_domain
result = drvr._clean_shutdown(instance, timeout, retry_interval)
self.assertEqual(succeeds, result)
self.assertEqual(shutdown_attempts, len(shutdown_count))
def test_clean_shutdown_first_time(self):
self._test_clean_shutdown(seconds_to_shutdown=2,
timeout=5,
retry_interval=3,
shutdown_attempts=1,
succeeds=True)
def test_clean_shutdown_with_retry(self):
self._test_clean_shutdown(seconds_to_shutdown=4,
timeout=5,
retry_interval=3,
shutdown_attempts=2,
succeeds=True)
def test_clean_shutdown_failure(self):
self._test_clean_shutdown(seconds_to_shutdown=6,
timeout=5,
retry_interval=3,
shutdown_attempts=2,
succeeds=False)
def test_clean_shutdown_no_wait(self):
self._test_clean_shutdown(seconds_to_shutdown=6,
timeout=0,
retry_interval=3,
shutdown_attempts=1,
succeeds=False)
@mock.patch.object(FakeVirtDomain, 'attachDeviceFlags')
@mock.patch.object(FakeVirtDomain, 'ID', return_value=1)
@mock.patch.object(utils, 'get_image_from_system_metadata',
return_value=None)
def test_attach_sriov_ports(self,
mock_get_image_metadata,
mock_ID,
mock_attachDevice):
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT
guest = libvirt_guest.Guest(FakeVirtDomain())
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._attach_sriov_ports(self.context, instance, guest, network_info)
mock_get_image_metadata.assert_called_once_with(
instance.system_metadata)
self.assertTrue(mock_attachDevice.called)
@mock.patch.object(FakeVirtDomain, 'attachDeviceFlags')
@mock.patch.object(FakeVirtDomain, 'ID', return_value=1)
@mock.patch.object(utils, 'get_image_from_system_metadata',
return_value=None)
def test_attach_sriov_direct_physical_ports(self,
mock_get_image_metadata,
mock_ID,
mock_attachDevice):
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT_PHYSICAL
guest = libvirt_guest.Guest(FakeVirtDomain())
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._attach_sriov_ports(self.context, instance, guest, network_info)
mock_get_image_metadata.assert_called_once_with(
instance.system_metadata)
self.assertTrue(mock_attachDevice.called)
@mock.patch.object(FakeVirtDomain, 'attachDeviceFlags')
@mock.patch.object(FakeVirtDomain, 'ID', return_value=1)
@mock.patch.object(utils, 'get_image_from_system_metadata',
return_value=None)
def test_attach_sriov_ports_with_info_cache(self,
mock_get_image_metadata,
mock_ID,
mock_attachDevice):
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT
instance.info_cache = objects.InstanceInfoCache(
network_info=network_info)
guest = libvirt_guest.Guest(FakeVirtDomain())
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._attach_sriov_ports(self.context, instance, guest, None)
mock_get_image_metadata.assert_called_once_with(
instance.system_metadata)
self.assertTrue(mock_attachDevice.called)
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def _test_detach_sriov_ports(self,
mock_has_min_version, vif_type):
instance = objects.Instance(**self.test_instance)
expeted_pci_slot = "0000:00:00.0"
network_info = _fake_network_info(self, 1)
network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT
# some more adjustments for the fake network_info so that
# the correct get_config function will be executed (vif's
# get_config_hw_veb - which is according to the real SRIOV vif)
# and most importantly the pci_slot which is translated to
# cfg.source_dev, then to PciDevice.address and sent to
# _detach_pci_devices
network_info[0]['profile'] = dict(pci_slot=expeted_pci_slot)
network_info[0]['type'] = vif_type
network_info[0]['details'] = dict(vlan="2145")
instance.info_cache = objects.InstanceInfoCache(
network_info=network_info)
# fill the pci_devices of the instance so that
# pci_manager.get_instance_pci_devs will not return an empty list
# which will eventually fail the assertion for detachDeviceFlags
expected_pci_device_obj = (
objects.PciDevice(address=expeted_pci_slot, request_id=None))
instance.pci_devices = objects.PciDeviceList()
instance.pci_devices.objects = [expected_pci_device_obj]
domain = FakeVirtDomain()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
guest = libvirt_guest.Guest(domain)
with mock.patch.object(drvr, '_detach_pci_devices') as mock_detach_pci:
drvr._detach_sriov_ports(self.context, instance, guest)
mock_detach_pci.assert_called_once_with(
guest, [expected_pci_device_obj])
def test_detach_sriov_ports_interface_interface_hostdev(self):
# Note: test detach_sriov_ports method for vif with config
# LibvirtConfigGuestInterface
self._test_detach_sriov_ports(vif_type="hw_veb")
def test_detach_sriov_ports_interface_pci_hostdev(self):
# Note: test detach_sriov_ports method for vif with config
# LibvirtConfigGuestHostdevPCI
self._test_detach_sriov_ports(vif_type="ib_hostdev")
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(FakeVirtDomain, 'detachDeviceFlags')
def test_detach_duplicate_mac_sriov_ports(self,
mock_detachDeviceFlags,
mock_has_min_version):
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 2)
for network_info_inst in network_info:
network_info_inst['vnic_type'] = network_model.VNIC_TYPE_DIRECT
network_info_inst['type'] = "hw_veb"
network_info_inst['details'] = dict(vlan="2145")
network_info_inst['address'] = "fa:16:3e:96:2a:48"
network_info[0]['profile'] = dict(pci_slot="0000:00:00.0")
network_info[1]['profile'] = dict(pci_slot="0000:00:00.1")
instance.info_cache = objects.InstanceInfoCache(
network_info=network_info)
# fill the pci_devices of the instance so that
# pci_manager.get_instance_pci_devs will not return an empty list
# which will eventually fail the assertion for detachDeviceFlags
instance.pci_devices = objects.PciDeviceList()
instance.pci_devices.objects = [
objects.PciDevice(address='0000:00:00.0', request_id=None),
objects.PciDevice(address='0000:00:00.1', request_id=None)
]
domain = FakeVirtDomain()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
guest = libvirt_guest.Guest(domain)
drvr._detach_sriov_ports(self.context, instance, guest)
expected_xml = [
('<hostdev mode="subsystem" type="pci" managed="yes">\n'
' <source>\n'
' <address bus="0x00" domain="0x0000" \
function="0x0" slot="0x00"/>\n'
' </source>\n'
'</hostdev>\n'),
('<hostdev mode="subsystem" type="pci" managed="yes">\n'
' <source>\n'
' <address bus="0x00" domain="0x0000" \
function="0x1" slot="0x00"/>\n'
' </source>\n'
'</hostdev>\n')
]
mock_detachDeviceFlags.has_calls([
mock.call(expected_xml[0], flags=1),
mock.call(expected_xml[1], flags=1)
])
def test_resume(self):
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
block_device_info = None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
guest = libvirt_guest.Guest('fake_dom')
with test.nested(
mock.patch.object(drvr, '_get_existing_domain_xml',
return_value=dummyxml),
mock.patch.object(drvr, '_create_domain_and_network',
return_value=guest),
mock.patch.object(drvr, '_attach_pci_devices'),
mock.patch.object(pci_manager, 'get_instance_pci_devs',
return_value='fake_pci_devs'),
mock.patch.object(utils, 'get_image_from_system_metadata'),
mock.patch.object(blockinfo, 'get_disk_info'),
) as (_get_existing_domain_xml, _create_domain_and_network,
_attach_pci_devices, get_instance_pci_devs, get_image_metadata,
get_disk_info):
get_image_metadata.return_value = {'bar': 234}
disk_info = {'foo': 123}
get_disk_info.return_value = disk_info
drvr.resume(self.context, instance, network_info,
block_device_info)
_get_existing_domain_xml.assert_has_calls([mock.call(instance,
network_info, block_device_info)])
_create_domain_and_network.assert_has_calls([mock.call(
self.context, dummyxml,
instance, network_info, disk_info,
block_device_info=block_device_info,
vifs_already_plugged=True)])
_attach_pci_devices.assert_has_calls([mock.call(guest,
'fake_pci_devs')])
@mock.patch.object(host.Host, 'get_domain')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'delete_instance_files')
@mock.patch.object(objects.Instance, 'save')
def test_destroy_undefines(self, mock_save, mock_delete_instance_files,
mock_get_info, mock_get_domain):
dom_mock = mock.MagicMock()
dom_mock.undefineFlags.return_value = 1
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_domain.return_value = dom_mock
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.SHUTDOWN, id=-1)
mock_delete_instance_files.return_value = None
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, [])
mock_save.assert_called_once_with()
@mock.patch.object(rbd_utils, 'RBDDriver')
def test_cleanup_rbd(self, mock_driver):
driver = mock_driver.return_value
driver.cleanup_volumes = mock.Mock()
fake_instance = {'uuid': '875a8070-d0b9-4949-8b31-104d125c9a64'}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr._cleanup_rbd(fake_instance)
driver.cleanup_volumes.assert_called_once_with(fake_instance)
@mock.patch.object(objects.Instance, 'save')
def test_destroy_undefines_no_undefine_flags(self, mock_save):
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(fakelibvirt.libvirtError('Err'))
mock.ID().AndReturn(123)
mock.undefine()
self.mox.ReplayAll()
def fake_get_domain(instance):
return mock
def fake_get_info(instance_name):
return hardware.InstanceInfo(state=power_state.SHUTDOWN, id=-1)
def fake_delete_instance_files(instance):
return None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, 'get_info', fake_get_info)
self.stubs.Set(drvr, 'delete_instance_files',
fake_delete_instance_files)
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, [])
mock_save.assert_called_once_with()
@mock.patch.object(objects.Instance, 'save')
def test_destroy_undefines_no_attribute_with_managed_save(self, mock_save):
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(AttributeError())
mock.hasManagedSaveImage(0).AndReturn(True)
mock.managedSaveRemove(0)
mock.undefine()
self.mox.ReplayAll()
def fake_get_domain(instance):
return mock
def fake_get_info(instance_name):
return hardware.InstanceInfo(state=power_state.SHUTDOWN, id=-1)
def fake_delete_instance_files(instance):
return None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, 'get_info', fake_get_info)
self.stubs.Set(drvr, 'delete_instance_files',
fake_delete_instance_files)
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, [])
mock_save.assert_called_once_with()
@mock.patch.object(objects.Instance, 'save')
def test_destroy_undefines_no_attribute_no_managed_save(self, mock_save):
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(AttributeError())
mock.hasManagedSaveImage(0).AndRaise(AttributeError())
mock.undefine()
self.mox.ReplayAll()
def fake_get_domain(self, instance):
return mock
def fake_get_info(instance_name):
return hardware.InstanceInfo(state=power_state.SHUTDOWN)
def fake_delete_instance_files(instance):
return None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(host.Host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, 'get_info', fake_get_info)
self.stubs.Set(drvr, 'delete_instance_files',
fake_delete_instance_files)
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, [])
mock_save.assert_called_once_with()
def test_destroy_timed_out(self):
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy().AndRaise(fakelibvirt.libvirtError("timed out"))
self.mox.ReplayAll()
def fake_get_domain(self, instance):
return mock
def fake_get_error_code(self):
return fakelibvirt.VIR_ERR_OPERATION_TIMEOUT
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(host.Host, 'get_domain', fake_get_domain)
self.stubs.Set(fakelibvirt.libvirtError, 'get_error_code',
fake_get_error_code)
instance = objects.Instance(**self.test_instance)
self.assertRaises(exception.InstancePowerOffFailure,
drvr.destroy, self.context, instance, [])
def test_private_destroy_not_found(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
"No such domain",
error_code=fakelibvirt.VIR_ERR_NO_DOMAIN)
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy().AndRaise(ex)
mock.info().AndRaise(ex)
mock.UUIDString()
self.mox.ReplayAll()
def fake_get_domain(instance):
return mock
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
instance = objects.Instance(**self.test_instance)
# NOTE(vish): verifies destroy doesn't raise if the instance disappears
drvr._destroy(instance)
def test_private_destroy_lxc_processes_refused_to_die(self):
self.flags(virt_type='lxc', group='libvirt')
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError, "",
error_message="internal error: Some processes refused to die",
error_code=fakelibvirt.VIR_ERR_INTERNAL_ERROR)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(conn._host, 'get_domain') as mock_get_domain, \
mock.patch.object(conn, 'get_info') as mock_get_info:
mock_domain = mock.MagicMock()
mock_domain.ID.return_value = 1
mock_get_domain.return_value = mock_domain
mock_domain.destroy.side_effect = ex
mock_info = mock.MagicMock()
mock_info.id = 1
mock_info.state = power_state.SHUTDOWN
mock_get_info.return_value = mock_info
instance = objects.Instance(**self.test_instance)
conn._destroy(instance)
def test_private_destroy_processes_refused_to_die_still_raises(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError, "",
error_message="internal error: Some processes refused to die",
error_code=fakelibvirt.VIR_ERR_INTERNAL_ERROR)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(conn._host, 'get_domain') as mock_get_domain:
mock_domain = mock.MagicMock()
mock_domain.ID.return_value = 1
mock_get_domain.return_value = mock_domain
mock_domain.destroy.side_effect = ex
instance = objects.Instance(**self.test_instance)
self.assertRaises(fakelibvirt.libvirtError, conn._destroy,
instance)
def test_private_destroy_ebusy_timeout(self):
# Tests that _destroy will retry 3 times to destroy the guest when an
# EBUSY is raised, but eventually times out and raises the libvirtError
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
("Failed to terminate process 26425 with SIGKILL: "
"Device or resource busy"),
error_code=fakelibvirt.VIR_ERR_SYSTEM_ERROR,
int1=errno.EBUSY)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.poweroff = mock.Mock(side_effect=ex)
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(drvr._host, 'get_guest',
return_value=mock_guest):
self.assertRaises(fakelibvirt.libvirtError, drvr._destroy,
instance)
self.assertEqual(3, mock_guest.poweroff.call_count)
def test_private_destroy_ebusy_multiple_attempt_ok(self):
# Tests that the _destroy attempt loop is broken when EBUSY is no
# longer raised.
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
("Failed to terminate process 26425 with SIGKILL: "
"Device or resource busy"),
error_code=fakelibvirt.VIR_ERR_SYSTEM_ERROR,
int1=errno.EBUSY)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.poweroff = mock.Mock(side_effect=[ex, None])
inst_info = hardware.InstanceInfo(power_state.SHUTDOWN, id=1)
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(drvr._host, 'get_guest',
return_value=mock_guest):
with mock.patch.object(drvr, 'get_info', return_value=inst_info):
drvr._destroy(instance)
self.assertEqual(2, mock_guest.poweroff.call_count)
def test_undefine_domain_with_not_found_instance(self):
def fake_get_domain(self, instance):
raise exception.InstanceNotFound(instance_id=instance.uuid)
self.stubs.Set(host.Host, 'get_domain', fake_get_domain)
self.mox.StubOutWithMock(fakelibvirt.libvirtError, "get_error_code")
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
# NOTE(wenjianhn): verifies undefine doesn't raise if the
# instance disappears
drvr._undefine_domain(instance)
@mock.patch.object(host.Host, "list_instance_domains")
@mock.patch.object(objects.BlockDeviceMappingList, "bdms_by_instance_uuid")
@mock.patch.object(objects.InstanceList, "get_by_filters")
def test_disk_over_committed_size_total(self, mock_get, mock_bdms,
mock_list):
# Ensure destroy calls managedSaveRemove for saved instance.
class DiagFakeDomain(object):
def __init__(self, name):
self._name = name
self._uuid = str(uuid.uuid4())
def ID(self):
return 1
def name(self):
return self._name
def UUIDString(self):
return self._uuid
def XMLDesc(self, flags):
return "<domain/>"
instance_domains = [
DiagFakeDomain("instance0000001"),
DiagFakeDomain("instance0000002")]
mock_list.return_value = instance_domains
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_disks = {'instance0000001':
[{'type': 'qcow2', 'path': '/somepath/disk1',
'virt_disk_size': '10737418240',
'backing_file': '/somepath/disk1',
'disk_size': '83886080',
'over_committed_disk_size': '10653532160'}],
'instance0000002':
[{'type': 'raw', 'path': '/somepath/disk2',
'virt_disk_size': '0',
'backing_file': '/somepath/disk2',
'disk_size': '10737418240',
'over_committed_disk_size': '0'}]}
def get_info(instance_name, xml, **kwargs):
return fake_disks.get(instance_name)
instance_uuids = [dom.UUIDString() for dom in instance_domains]
instances = [objects.Instance(
uuid=instance_uuids[0],
root_device_name='/dev/vda'),
objects.Instance(
uuid=instance_uuids[1],
root_device_name='/dev/vdb')
]
mock_get.return_value = instances
with mock.patch.object(drvr,
"_get_instance_disk_info") as mock_info:
mock_info.side_effect = get_info
result = drvr._get_disk_over_committed_size_total()
self.assertEqual(result, 10653532160)
mock_list.assert_called_once_with()
self.assertEqual(2, mock_info.call_count)
filters = {'uuid': instance_uuids}
mock_get.assert_called_once_with(mock.ANY, filters, use_slave=True)
mock_bdms.assert_called_with(mock.ANY, instance_uuids)
@mock.patch.object(host.Host, "list_instance_domains")
@mock.patch.object(objects.BlockDeviceMappingList, "bdms_by_instance_uuid")
@mock.patch.object(objects.InstanceList, "get_by_filters")
def test_disk_over_committed_size_total_eperm(self, mock_get, mock_bdms,
mock_list):
# Ensure destroy calls managedSaveRemove for saved instance.
class DiagFakeDomain(object):
def __init__(self, name):
self._name = name
self._uuid = str(uuid.uuid4())
def ID(self):
return 1
def name(self):
return self._name
def UUIDString(self):
return self._uuid
def XMLDesc(self, flags):
return "<domain/>"
instance_domains = [
DiagFakeDomain("instance0000001"),
DiagFakeDomain("instance0000002"),
DiagFakeDomain("instance0000003"),
DiagFakeDomain("instance0000004")]
mock_list.return_value = instance_domains
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_disks = {'instance0000001':
[{'type': 'qcow2', 'path': '/somepath/disk1',
'virt_disk_size': '10737418240',
'backing_file': '/somepath/disk1',
'disk_size': '83886080',
'over_committed_disk_size': '10653532160'}],
'instance0000002':
[{'type': 'raw', 'path': '/somepath/disk2',
'virt_disk_size': '0',
'backing_file': '/somepath/disk2',
'disk_size': '10737418240',
'over_committed_disk_size': '21474836480'}],
'instance0000003':
[{'type': 'raw', 'path': '/somepath/disk3',
'virt_disk_size': '0',
'backing_file': '/somepath/disk3',
'disk_size': '21474836480',
'over_committed_disk_size': '32212254720'}],
'instance0000004':
[{'type': 'raw', 'path': '/somepath/disk4',
'virt_disk_size': '0',
'backing_file': '/somepath/disk4',
'disk_size': '32212254720',
'over_committed_disk_size': '42949672960'}]}
def side_effect(name, dom, block_device_info):
if name == 'instance0000001':
self.assertEqual('/dev/vda',
block_device_info['root_device_name'])
raise OSError(errno.ENOENT, 'No such file or directory')
if name == 'instance0000002':
self.assertEqual('/dev/vdb',
block_device_info['root_device_name'])
raise OSError(errno.ESTALE, 'Stale NFS file handle')
if name == 'instance0000003':
self.assertEqual('/dev/vdc',
block_device_info['root_device_name'])
raise OSError(errno.EACCES, 'Permission denied')
if name == 'instance0000004':
self.assertEqual('/dev/vdd',
block_device_info['root_device_name'])
return fake_disks.get(name)
get_disk_info = mock.Mock()
get_disk_info.side_effect = side_effect
drvr._get_instance_disk_info = get_disk_info
instance_uuids = [dom.UUIDString() for dom in instance_domains]
instances = [objects.Instance(
uuid=instance_uuids[0],
root_device_name='/dev/vda'),
objects.Instance(
uuid=instance_uuids[1],
root_device_name='/dev/vdb'),
objects.Instance(
uuid=instance_uuids[2],
root_device_name='/dev/vdc'),
objects.Instance(
uuid=instance_uuids[3],
root_device_name='/dev/vdd')
]
mock_get.return_value = instances
result = drvr._get_disk_over_committed_size_total()
self.assertEqual(42949672960, result)
mock_list.assert_called_once_with()
self.assertEqual(4, get_disk_info.call_count)
filters = {'uuid': instance_uuids}
mock_get.assert_called_once_with(mock.ANY, filters, use_slave=True)
mock_bdms.assert_called_with(mock.ANY, instance_uuids)
@mock.patch.object(host.Host, "list_instance_domains",
return_value=[mock.MagicMock(name='foo')])
@mock.patch.object(libvirt_driver.LibvirtDriver, "_get_instance_disk_info",
side_effect=exception.VolumeBDMPathNotFound(path='bar'))
@mock.patch.object(objects.BlockDeviceMappingList, "bdms_by_instance_uuid")
@mock.patch.object(objects.InstanceList, "get_by_filters")
def test_disk_over_committed_size_total_bdm_not_found(self,
mock_get,
mock_bdms,
mock_get_disk_info,
mock_list_domains):
# Tests that we handle VolumeBDMPathNotFound gracefully.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(0, drvr._get_disk_over_committed_size_total())
def test_cpu_info(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigCPU()
cpu.model = "Opteron_G4"
cpu.vendor = "AMD"
cpu.arch = arch.X86_64
cpu.cells = 1
cpu.cores = 2
cpu.threads = 1
cpu.sockets = 4
cpu.add_feature(vconfig.LibvirtConfigCPUFeature("extapic"))
cpu.add_feature(vconfig.LibvirtConfigCPUFeature("3dnow"))
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
guest = vconfig.LibvirtConfigGuest()
guest.ostype = vm_mode.HVM
guest.arch = arch.X86_64
guest.domtype = ["kvm"]
caps.guests.append(guest)
guest = vconfig.LibvirtConfigGuest()
guest.ostype = vm_mode.HVM
guest.arch = arch.I686
guest.domtype = ["kvm"]
caps.guests.append(guest)
return caps
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
want = {"vendor": "AMD",
"features": set(["extapic", "3dnow"]),
"model": "Opteron_G4",
"arch": arch.X86_64,
"topology": {"cells": 1, "cores": 2, "threads": 1,
"sockets": 4}}
got = drvr._get_cpu_info()
self.assertEqual(want, got)
def test_get_pcidev_info(self):
def fake_nodeDeviceLookupByName(self, name):
return FakeNodeDevice(_fake_NodeDevXml[name])
self.mox.StubOutWithMock(host.Host, 'device_lookup_by_name')
host.Host.device_lookup_by_name = fake_nodeDeviceLookupByName
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(
fakelibvirt.Connection, 'getLibVersion') as mock_lib_version:
mock_lib_version.return_value = (
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION) - 1)
actualvf = drvr._get_pcidev_info("pci_0000_04_00_3")
expect_vf = {
"dev_id": "pci_0000_04_00_3",
"address": "0000:04:00.3",
"product_id": '1521',
"numa_node": None,
"vendor_id": '8086',
"label": 'label_8086_1521',
"dev_type": fields.PciDeviceType.SRIOV_PF,
}
self.assertEqual(expect_vf, actualvf)
actualvf = drvr._get_pcidev_info("pci_0000_04_10_7")
expect_vf = {
"dev_id": "pci_0000_04_10_7",
"address": "0000:04:10.7",
"product_id": '1520',
"numa_node": None,
"vendor_id": '8086',
"label": 'label_8086_1520',
"dev_type": fields.PciDeviceType.SRIOV_VF,
"parent_addr": '0000:04:00.3',
}
self.assertEqual(expect_vf, actualvf)
actualvf = drvr._get_pcidev_info("pci_0000_04_11_7")
expect_vf = {
"dev_id": "pci_0000_04_11_7",
"address": "0000:04:11.7",
"product_id": '1520',
"vendor_id": '8086',
"numa_node": 0,
"label": 'label_8086_1520',
"dev_type": fields.PciDeviceType.SRIOV_VF,
"parent_addr": '0000:04:00.3',
}
self.assertEqual(expect_vf, actualvf)
with mock.patch.object(
pci_utils, 'is_physical_function', return_value=True):
actualvf = drvr._get_pcidev_info("pci_0000_04_00_1")
expect_vf = {
"dev_id": "pci_0000_04_00_1",
"address": "0000:04:00.1",
"product_id": '1013',
"numa_node": 0,
"vendor_id": '15b3',
"label": 'label_15b3_1013',
"dev_type": fields.PciDeviceType.SRIOV_PF,
}
self.assertEqual(expect_vf, actualvf)
with mock.patch.object(
pci_utils, 'is_physical_function', return_value=False):
actualvf = drvr._get_pcidev_info("pci_0000_04_00_1")
expect_vf = {
"dev_id": "pci_0000_04_00_1",
"address": "0000:04:00.1",
"product_id": '1013',
"numa_node": 0,
"vendor_id": '15b3',
"label": 'label_15b3_1013',
"dev_type": fields.PciDeviceType.STANDARD,
}
self.assertEqual(expect_vf, actualvf)
with mock.patch.object(
fakelibvirt.Connection, 'getLibVersion') as mock_lib_version:
mock_lib_version.return_value = (
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION))
actualvf = drvr._get_pcidev_info("pci_0000_03_00_0")
expect_vf = {
"dev_id": "pci_0000_03_00_0",
"address": "0000:03:00.0",
"product_id": '1013',
"numa_node": 0,
"vendor_id": '15b3',
"label": 'label_15b3_1013',
"dev_type": fields.PciDeviceType.SRIOV_PF,
}
self.assertEqual(expect_vf, actualvf)
actualvf = drvr._get_pcidev_info("pci_0000_03_00_1")
expect_vf = {
"dev_id": "pci_0000_03_00_1",
"address": "0000:03:00.1",
"product_id": '1013',
"numa_node": 0,
"vendor_id": '15b3',
"label": 'label_15b3_1013',
"dev_type": fields.PciDeviceType.SRIOV_PF,
}
self.assertEqual(expect_vf, actualvf)
def test_list_devices_not_supported(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Handle just the NO_SUPPORT error
not_supported_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'this function is not supported by the connection driver:'
' virNodeNumOfDevices',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
with mock.patch.object(drvr._conn, 'listDevices',
side_effect=not_supported_exc):
self.assertEqual('[]', drvr._get_pci_passthrough_devices())
# We cache not supported status to avoid emitting too many logging
# messages. Clear this value to test the other exception case.
del drvr._list_devices_supported
# Other errors should not be caught
other_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'other exc',
error_code=fakelibvirt.VIR_ERR_NO_DOMAIN)
with mock.patch.object(drvr._conn, 'listDevices',
side_effect=other_exc):
self.assertRaises(fakelibvirt.libvirtError,
drvr._get_pci_passthrough_devices)
def test_get_pci_passthrough_devices(self):
def fakelistDevices(caps, fakeargs=0):
return ['pci_0000_04_00_3', 'pci_0000_04_10_7',
'pci_0000_04_11_7']
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.listDevices = fakelistDevices
def fake_nodeDeviceLookupByName(self, name):
return FakeNodeDevice(_fake_NodeDevXml[name])
self.mox.StubOutWithMock(host.Host, 'device_lookup_by_name')
host.Host.device_lookup_by_name = fake_nodeDeviceLookupByName
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actjson = drvr._get_pci_passthrough_devices()
expectvfs = [
{
"dev_id": "pci_0000_04_00_3",
"address": "0000:04:00.3",
"product_id": '1521',
"vendor_id": '8086',
"dev_type": fields.PciDeviceType.SRIOV_PF,
"phys_function": None,
"numa_node": None},
{
"dev_id": "pci_0000_04_10_7",
"domain": 0,
"address": "0000:04:10.7",
"product_id": '1520',
"vendor_id": '8086',
"numa_node": None,
"dev_type": fields.PciDeviceType.SRIOV_VF,
"phys_function": [('0x0000', '0x04', '0x00', '0x3')]},
{
"dev_id": "pci_0000_04_11_7",
"domain": 0,
"address": "0000:04:11.7",
"product_id": '1520',
"vendor_id": '8086',
"numa_node": 0,
"dev_type": fields.PciDeviceType.SRIOV_VF,
"phys_function": [('0x0000', '0x04', '0x00', '0x3')],
}
]
actualvfs = jsonutils.loads(actjson)
for dev in range(len(actualvfs)):
for key in actualvfs[dev].keys():
if key not in ['phys_function', 'virt_functions', 'label']:
self.assertEqual(expectvfs[dev][key], actualvfs[dev][key])
def _fake_caps_numa_topology(self,
cells_per_host=4,
sockets_per_cell=1,
cores_per_socket=1,
threads_per_core=2,
kb_mem=1048576):
# Generate mempages list per cell
cell_mempages = list()
for cellid in range(cells_per_host):
mempages_0 = vconfig.LibvirtConfigCapsNUMAPages()
mempages_0.size = 4
mempages_0.total = 1024 * cellid
mempages_1 = vconfig.LibvirtConfigCapsNUMAPages()
mempages_1.size = 2048
mempages_1.total = 0 + cellid
cell_mempages.append([mempages_0, mempages_1])
topology = fakelibvirt.HostInfo._gen_numa_topology(cells_per_host,
sockets_per_cell,
cores_per_socket,
threads_per_core,
kb_mem=kb_mem,
numa_mempages_list=cell_mempages)
return topology
def _test_get_host_numa_topology(self, mempages):
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = arch.X86_64
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
expected_topo_dict = {'cells': [
{'cpus': '0,1', 'cpu_usage': 0,
'mem': {'total': 256, 'used': 0},
'id': 0},
{'cpus': '3', 'cpu_usage': 0,
'mem': {'total': 256, 'used': 0},
'id': 1},
{'cpus': '', 'cpu_usage': 0,
'mem': {'total': 256, 'used': 0},
'id': 2},
{'cpus': '', 'cpu_usage': 0,
'mem': {'total': 256, 'used': 0},
'id': 3}]}
with test.nested(
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set',
return_value=set([0, 1, 3, 4, 5])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set([0, 1, 2, 3, 6])),
):
got_topo = drvr._get_host_numa_topology()
got_topo_dict = got_topo._to_dict()
self.assertThat(
expected_topo_dict, matchers.DictMatches(got_topo_dict))
if mempages:
# cells 0
self.assertEqual(4, got_topo.cells[0].mempages[0].size_kb)
self.assertEqual(0, got_topo.cells[0].mempages[0].total)
self.assertEqual(2048, got_topo.cells[0].mempages[1].size_kb)
self.assertEqual(0, got_topo.cells[0].mempages[1].total)
# cells 1
self.assertEqual(4, got_topo.cells[1].mempages[0].size_kb)
self.assertEqual(1024, got_topo.cells[1].mempages[0].total)
self.assertEqual(2048, got_topo.cells[1].mempages[1].size_kb)
self.assertEqual(1, got_topo.cells[1].mempages[1].total)
else:
self.assertEqual([], got_topo.cells[0].mempages)
self.assertEqual([], got_topo.cells[1].mempages)
self.assertEqual(expected_topo_dict, got_topo_dict)
self.assertEqual(set([]), got_topo.cells[0].pinned_cpus)
self.assertEqual(set([]), got_topo.cells[1].pinned_cpus)
self.assertEqual(set([]), got_topo.cells[2].pinned_cpus)
self.assertEqual(set([]), got_topo.cells[3].pinned_cpus)
self.assertEqual([set([0, 1])], got_topo.cells[0].siblings)
self.assertEqual([], got_topo.cells[1].siblings)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_get_host_numa_topology(self, mock_version):
self._test_get_host_numa_topology(mempages=True)
@mock.patch.object(fakelibvirt.Connection, 'getType')
@mock.patch.object(fakelibvirt.Connection, 'getVersion')
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
def test_get_host_numa_topology_no_mempages(self, mock_lib_version,
mock_version, mock_type):
self.flags(virt_type='kvm', group='libvirt')
mock_lib_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION) - 1
mock_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION)
mock_type.return_value = host.HV_DRIVER_QEMU
self._test_get_host_numa_topology(mempages=False)
def test_get_host_numa_topology_empty(self):
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = arch.X86_64
caps.host.topology = None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(host.Host, 'has_min_version', return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps)
) as (has_min_version, get_caps):
self.assertIsNone(drvr._get_host_numa_topology())
self.assertEqual(2, get_caps.call_count)
@mock.patch.object(fakelibvirt.Connection, 'getType')
@mock.patch.object(fakelibvirt.Connection, 'getVersion')
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
def test_get_host_numa_topology_old_version(self, mock_lib_version,
mock_version, mock_type):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_lib_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) - 1
mock_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION)
mock_type.return_value = host.HV_DRIVER_QEMU
self.assertIsNone(drvr._get_host_numa_topology())
@mock.patch.object(fakelibvirt.Connection, 'getType')
@mock.patch.object(fakelibvirt.Connection, 'getVersion')
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
def test_get_host_numa_topology_xen(self, mock_lib_version,
mock_version, mock_type):
self.flags(virt_type='xen', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_lib_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION)
mock_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION)
mock_type.return_value = host.HV_DRIVER_XEN
self.assertIsNone(drvr._get_host_numa_topology())
def test_diagnostic_vcpus_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
raise fakelibvirt.libvirtError('vcpus missing')
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
def test_diagnostic_blockstats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
raise fakelibvirt.libvirtError('blockStats missing')
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
def test_diagnostic_interfacestats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
raise fakelibvirt.libvirtError('interfaceStat missing')
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
def test_diagnostic_memorystats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
raise fakelibvirt.libvirtError('memoryStats missing')
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
def test_diagnostic_full(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
@mock.patch.object(host.Host, 'get_domain')
def test_diagnostic_full_with_multiple_interfaces(self, mock_get_domain):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
<interface type="bridge">
<mac address="53:55:00:a5:39:39"/>
<model type="virtio"/>
<target dev="br0"/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self):
return DiagFakeDomain()
mock_get_domain.side_effect = fake_get_domain
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
'br0_rx': 4408,
'br0_rx_drop': 0,
'br0_rx_errors': 0,
'br0_rx_packets': 82,
'br0_tx': 0,
'br0_tx_drop': 0,
'br0_tx_errors': 0,
'br0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0},
{'mac_address': '53:55:00:a5:39:39',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10.,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
@mock.patch.object(host.Host, "list_instance_domains")
def test_failing_vcpu_count(self, mock_list):
"""Domain can fail to return the vcpu description in case it's
just starting up or shutting down. Make sure None is handled
gracefully.
"""
class DiagFakeDomain(object):
def __init__(self, vcpus):
self._vcpus = vcpus
def vcpus(self):
if self._vcpus is None:
raise fakelibvirt.libvirtError("fake-error")
else:
return ([[1, 2, 3, 4]] * self._vcpus, [True] * self._vcpus)
def ID(self):
return 1
def name(self):
return "instance000001"
def UUIDString(self):
return "19479fee-07a5-49bb-9138-d3738280d63c"
mock_list.return_value = [
DiagFakeDomain(None), DiagFakeDomain(5)]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(5, drvr._get_vcpu_used())
mock_list.assert_called_with(only_guests=True, only_running=True)
@mock.patch.object(host.Host, "list_instance_domains")
def test_failing_vcpu_count_none(self, mock_list):
"""Domain will return zero if the current number of vcpus used
is None. This is in case of VM state starting up or shutting
down. None type returned is counted as zero.
"""
class DiagFakeDomain(object):
def __init__(self):
pass
def vcpus(self):
return None
def ID(self):
return 1
def name(self):
return "instance000001"
mock_list.return_value = [DiagFakeDomain()]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(0, drvr._get_vcpu_used())
mock_list.assert_called_with(only_guests=True, only_running=True)
def test_get_instance_capabilities(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
def get_host_capabilities_stub(self):
caps = vconfig.LibvirtConfigCaps()
guest = vconfig.LibvirtConfigGuest()
guest.ostype = 'hvm'
guest.arch = arch.X86_64
guest.domtype = ['kvm', 'qemu']
caps.guests.append(guest)
guest = vconfig.LibvirtConfigGuest()
guest.ostype = 'hvm'
guest.arch = arch.I686
guest.domtype = ['kvm']
caps.guests.append(guest)
return caps
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
want = [(arch.X86_64, 'kvm', 'hvm'),
(arch.X86_64, 'qemu', 'hvm'),
(arch.I686, 'kvm', 'hvm')]
got = drvr._get_instance_capabilities()
self.assertEqual(want, got)
def test_set_cache_mode(self):
self.flags(disk_cachemodes=['file=directsync'], group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuestDisk()
fake_conf.source_type = 'file'
drvr._set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, 'directsync')
def test_set_cache_mode_invalid_mode(self):
self.flags(disk_cachemodes=['file=FAKE'], group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuestDisk()
fake_conf.source_type = 'file'
drvr._set_cache_mode(fake_conf)
self.assertIsNone(fake_conf.driver_cache)
def test_set_cache_mode_invalid_object(self):
self.flags(disk_cachemodes=['file=directsync'], group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuest()
fake_conf.driver_cache = 'fake'
drvr._set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, 'fake')
@mock.patch('os.unlink')
@mock.patch.object(os.path, 'exists')
def _test_shared_storage_detection(self, is_same,
mock_exists, mock_unlink):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.get_host_ip_addr = mock.MagicMock(return_value='bar')
mock_exists.return_value = is_same
with test.nested(
mock.patch.object(drvr._remotefs, 'create_file'),
mock.patch.object(drvr._remotefs, 'remove_file')
) as (mock_rem_fs_create, mock_rem_fs_remove):
result = drvr._is_storage_shared_with('host', '/path')
mock_rem_fs_create.assert_any_call('host', mock.ANY)
create_args, create_kwargs = mock_rem_fs_create.call_args
self.assertTrue(create_args[1].startswith('/path'))
if is_same:
mock_unlink.assert_called_once_with(mock.ANY)
else:
mock_rem_fs_remove.assert_called_with('host', mock.ANY)
remove_args, remove_kwargs = mock_rem_fs_remove.call_args
self.assertTrue(remove_args[1].startswith('/path'))
return result
def test_shared_storage_detection_same_host(self):
self.assertTrue(self._test_shared_storage_detection(True))
def test_shared_storage_detection_different_host(self):
self.assertFalse(self._test_shared_storage_detection(False))
def test_shared_storage_detection_easy(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.mox.StubOutWithMock(drvr, 'get_host_ip_addr')
self.mox.StubOutWithMock(utils, 'execute')
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(os, 'unlink')
drvr.get_host_ip_addr().AndReturn('foo')
self.mox.ReplayAll()
self.assertTrue(drvr._is_storage_shared_with('foo', '/path'))
def test_store_pid_remove_pid(self):
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
popen = mock.Mock(pid=3)
drvr.job_tracker.add_job(instance, popen.pid)
self.assertIn(3, drvr.job_tracker.jobs[instance.uuid])
drvr.job_tracker.remove_job(instance, popen.pid)
self.assertNotIn(instance.uuid, drvr.job_tracker.jobs)
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
def test_get_domain_info_with_more_return(self, mock_get_domain):
instance = objects.Instance(**self.test_instance)
dom_mock = mock.MagicMock()
dom_mock.info.return_value = [
1, 2048, 737, 8, 12345, 888888
]
dom_mock.ID.return_value = mock.sentinel.instance_id
mock_get_domain.return_value = dom_mock
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = drvr.get_info(instance)
self.assertEqual(1, info.state)
self.assertEqual(2048, info.max_mem_kb)
self.assertEqual(737, info.mem_kb)
self.assertEqual(8, info.num_cpu)
self.assertEqual(12345, info.cpu_time_ns)
self.assertEqual(mock.sentinel.instance_id, info.id)
dom_mock.info.assert_called_once_with()
dom_mock.ID.assert_called_once_with()
mock_get_domain.assert_called_once_with(instance)
def test_create_domain(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_domain = mock.MagicMock()
guest = drvr._create_domain(domain=mock_domain)
self.assertEqual(mock_domain, guest._domain)
mock_domain.createWithFlags.assert_has_calls([mock.call(0)])
@mock.patch('nova.virt.disk.api.clean_lxc_namespace')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info')
@mock.patch('nova.virt.disk.api.setup_container')
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch.object(fake_libvirt_utils, 'get_instance_path')
def test_create_domain_lxc(self, mock_get_inst_path, mock_ensure_tree,
mock_setup_container, mock_get_info, mock_clean):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_instance = mock.MagicMock()
inst_sys_meta = dict()
mock_instance.system_metadata = inst_sys_meta
mock_get_inst_path.return_value = '/tmp/'
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_image = mock.MagicMock()
mock_image.path = '/tmp/test.img'
drvr.image_backend.image.return_value = mock_image
mock_setup_container.return_value = '/dev/nbd0'
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.RUNNING)
with test.nested(
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')):
drvr._create_domain_and_network(self.context, 'xml',
mock_instance, [], None)
self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name'])
self.assertFalse(mock_instance.called)
mock_get_inst_path.assert_has_calls([mock.call(mock_instance)])
mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')])
drvr.image_backend.image.assert_has_calls([mock.call(mock_instance,
'disk')])
setup_container_call = mock.call(
mock_image.get_model(),
container_dir='/tmp/rootfs')
mock_setup_container.assert_has_calls([setup_container_call])
mock_get_info.assert_has_calls([mock.call(mock_instance)])
mock_clean.assert_has_calls([mock.call(container_dir='/tmp/rootfs')])
@mock.patch('nova.virt.disk.api.clean_lxc_namespace')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info')
@mock.patch.object(fake_libvirt_utils, 'chown_for_id_maps')
@mock.patch('nova.virt.disk.api.setup_container')
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch.object(fake_libvirt_utils, 'get_instance_path')
def test_create_domain_lxc_id_maps(self, mock_get_inst_path,
mock_ensure_tree, mock_setup_container,
mock_chown, mock_get_info, mock_clean):
self.flags(virt_type='lxc', uid_maps=["0:1000:100"],
gid_maps=["0:1000:100"], group='libvirt')
def chown_side_effect(path, id_maps):
self.assertEqual('/tmp/rootfs', path)
self.assertIsInstance(id_maps[0], vconfig.LibvirtConfigGuestUIDMap)
self.assertEqual(0, id_maps[0].start)
self.assertEqual(1000, id_maps[0].target)
self.assertEqual(100, id_maps[0].count)
self.assertIsInstance(id_maps[1], vconfig.LibvirtConfigGuestGIDMap)
self.assertEqual(0, id_maps[1].start)
self.assertEqual(1000, id_maps[1].target)
self.assertEqual(100, id_maps[1].count)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_instance = mock.MagicMock()
inst_sys_meta = dict()
mock_instance.system_metadata = inst_sys_meta
mock_get_inst_path.return_value = '/tmp/'
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_image = mock.MagicMock()
mock_image.path = '/tmp/test.img'
drvr.image_backend.image.return_value = mock_image
mock_setup_container.return_value = '/dev/nbd0'
mock_chown.side_effect = chown_side_effect
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.RUNNING)
with test.nested(
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')
) as (
mock_is_booted_from_volume, mock_create_domain, mock_plug_vifs,
mock_setup_basic_filtering, mock_prepare_instance_filter,
mock_apply_instance_filter
):
drvr._create_domain_and_network(self.context, 'xml',
mock_instance, [], None)
self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name'])
self.assertFalse(mock_instance.called)
mock_get_inst_path.assert_has_calls([mock.call(mock_instance)])
mock_is_booted_from_volume.assert_called_once_with(mock_instance, {})
mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')])
drvr.image_backend.image.assert_has_calls([mock.call(mock_instance,
'disk')])
setup_container_call = mock.call(
mock_image.get_model(),
container_dir='/tmp/rootfs')
mock_setup_container.assert_has_calls([setup_container_call])
mock_get_info.assert_has_calls([mock.call(mock_instance)])
mock_clean.assert_has_calls([mock.call(container_dir='/tmp/rootfs')])
@mock.patch('nova.virt.disk.api.teardown_container')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info')
@mock.patch('nova.virt.disk.api.setup_container')
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch.object(fake_libvirt_utils, 'get_instance_path')
def test_create_domain_lxc_not_running(self, mock_get_inst_path,
mock_ensure_tree,
mock_setup_container,
mock_get_info, mock_teardown):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_instance = mock.MagicMock()
inst_sys_meta = dict()
mock_instance.system_metadata = inst_sys_meta
mock_get_inst_path.return_value = '/tmp/'
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_image = mock.MagicMock()
mock_image.path = '/tmp/test.img'
drvr.image_backend.image.return_value = mock_image
mock_setup_container.return_value = '/dev/nbd0'
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.SHUTDOWN)
with test.nested(
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')):
drvr._create_domain_and_network(self.context, 'xml',
mock_instance, [], None)
self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name'])
self.assertFalse(mock_instance.called)
mock_get_inst_path.assert_has_calls([mock.call(mock_instance)])
mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')])
drvr.image_backend.image.assert_has_calls([mock.call(mock_instance,
'disk')])
setup_container_call = mock.call(
mock_image.get_model(),
container_dir='/tmp/rootfs')
mock_setup_container.assert_has_calls([setup_container_call])
mock_get_info.assert_has_calls([mock.call(mock_instance)])
teardown_call = mock.call(container_dir='/tmp/rootfs')
mock_teardown.assert_has_calls([teardown_call])
def test_create_domain_define_xml_fails(self):
"""Tests that the xml is logged when defining the domain fails."""
fake_xml = "<test>this is a test</test>"
def fake_defineXML(xml):
self.assertEqual(fake_xml, xml)
raise fakelibvirt.libvirtError('virDomainDefineXML() failed')
def fake_safe_decode(text, *args, **kwargs):
return text + 'safe decoded'
self.log_error_called = False
def fake_error(msg, *args, **kwargs):
self.log_error_called = True
self.assertIn(fake_xml, msg % args)
self.assertIn('safe decoded', msg % args)
self.stubs.Set(encodeutils, 'safe_decode', fake_safe_decode)
self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error)
self.create_fake_libvirt_mock(defineXML=fake_defineXML)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(fakelibvirt.libvirtError, drvr._create_domain,
fake_xml)
self.assertTrue(self.log_error_called)
def test_create_domain_with_flags_fails(self):
"""Tests that the xml is logged when creating the domain with flags
fails
"""
fake_xml = "<test>this is a test</test>"
fake_domain = FakeVirtDomain(fake_xml)
def fake_createWithFlags(launch_flags):
raise fakelibvirt.libvirtError('virDomainCreateWithFlags() failed')
self.log_error_called = False
def fake_error(msg, *args, **kwargs):
self.log_error_called = True
self.assertIn(fake_xml, msg % args)
self.stubs.Set(fake_domain, 'createWithFlags', fake_createWithFlags)
self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error)
self.create_fake_libvirt_mock()
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(fakelibvirt.libvirtError, drvr._create_domain,
domain=fake_domain)
self.assertTrue(self.log_error_called)
def test_create_domain_enable_hairpin_fails(self):
"""Tests that the xml is logged when enabling hairpin mode for the
domain fails.
"""
fake_xml = "<test>this is a test</test>"
fake_domain = FakeVirtDomain(fake_xml)
def fake_execute(*args, **kwargs):
raise processutils.ProcessExecutionError('error')
def fake_get_interfaces(*args):
return ["dev"]
self.log_error_called = False
def fake_error(msg, *args, **kwargs):
self.log_error_called = True
self.assertIn(fake_xml, msg % args)
self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error)
self.create_fake_libvirt_mock()
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.stubs.Set(nova.utils, 'execute', fake_execute)
self.stubs.Set(
nova.virt.libvirt.guest.Guest, 'get_interfaces',
fake_get_interfaces)
self.assertRaises(processutils.ProcessExecutionError,
drvr._create_domain,
domain=fake_domain,
power_on=False)
self.assertTrue(self.log_error_called)
def test_get_vnc_console(self):
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<graphics type='vnc' port='5900'/>"
"</devices></domain>")
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
vnc_dict = drvr.get_vnc_console(self.context, instance)
self.assertEqual(vnc_dict.port, '5900')
def test_get_vnc_console_unavailable(self):
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices></devices></domain>")
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.ConsoleTypeUnavailable,
drvr.get_vnc_console, self.context, instance)
def test_get_spice_console(self):
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<graphics type='spice' port='5950'/>"
"</devices></domain>")
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
spice_dict = drvr.get_spice_console(self.context, instance)
self.assertEqual(spice_dict.port, '5950')
def test_get_spice_console_unavailable(self):
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices></devices></domain>")
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.ConsoleTypeUnavailable,
drvr.get_spice_console, self.context, instance)
def test_detach_volume_with_instance_not_found(self):
# Test that detach_volume() method does not raise exception,
# if the instance does not exist.
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(host.Host, 'get_domain',
side_effect=exception.InstanceNotFound(
instance_id=instance.uuid)),
mock.patch.object(drvr, '_disconnect_volume')
) as (_get_domain, _disconnect_volume):
connection_info = {'driver_volume_type': 'fake'}
drvr.detach_volume(connection_info, instance, '/dev/sda')
_get_domain.assert_called_once_with(instance)
_disconnect_volume.assert_called_once_with(connection_info,
'sda')
def _test_attach_detach_interface_get_config(self, method_name):
"""Tests that the get_config() method is properly called in
attach_interface() and detach_interface().
method_name: either \"attach_interface\" or \"detach_interface\"
depending on the method to test.
"""
self.stubs.Set(host.Host, "get_domain", lambda a, b: FakeVirtDomain())
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_image_meta = objects.ImageMeta.from_dict(
{'id': instance['image_ref']})
if method_name == "attach_interface":
self.mox.StubOutWithMock(drvr.firewall_driver,
'setup_basic_filtering')
drvr.firewall_driver.setup_basic_filtering(instance, network_info)
expected = drvr.vif_driver.get_config(instance, network_info[0],
fake_image_meta,
instance.get_flavor(),
CONF.libvirt.virt_type,
drvr._host)
self.mox.StubOutWithMock(drvr.vif_driver, 'get_config')
drvr.vif_driver.get_config(instance, network_info[0],
mox.IsA(objects.ImageMeta),
mox.IsA(objects.Flavor),
CONF.libvirt.virt_type,
drvr._host).\
AndReturn(expected)
self.mox.ReplayAll()
if method_name == "attach_interface":
drvr.attach_interface(instance, fake_image_meta,
network_info[0])
elif method_name == "detach_interface":
drvr.detach_interface(instance, network_info[0])
else:
raise ValueError("Unhandled method %s" % method_name)
@mock.patch.object(lockutils, "external_lock")
def test_attach_interface_get_config(self, mock_lock):
"""Tests that the get_config() method is properly called in
attach_interface().
"""
mock_lock.return_value = threading.Semaphore()
self._test_attach_detach_interface_get_config("attach_interface")
def test_detach_interface_get_config(self):
"""Tests that the get_config() method is properly called in
detach_interface().
"""
self._test_attach_detach_interface_get_config("detach_interface")
def test_default_root_device_name(self):
instance = {'uuid': 'fake_instance'}
image_meta = objects.ImageMeta.from_dict({'id': uuids.image_id})
root_bdm = {'source_type': 'image',
'destination_type': 'volume',
'image_id': 'fake_id'}
self.flags(virt_type='qemu', group='libvirt')
self.mox.StubOutWithMock(blockinfo, 'get_disk_bus_for_device_type')
self.mox.StubOutWithMock(blockinfo, 'get_root_info')
blockinfo.get_disk_bus_for_device_type(instance,
'qemu',
image_meta,
'disk').InAnyOrder().\
AndReturn('virtio')
blockinfo.get_disk_bus_for_device_type(instance,
'qemu',
image_meta,
'cdrom').InAnyOrder().\
AndReturn('ide')
blockinfo.get_root_info(instance, 'qemu',
image_meta, root_bdm,
'virtio', 'ide').AndReturn({'dev': 'vda'})
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(drvr.default_root_device_name(instance, image_meta,
root_bdm), '/dev/vda')
@mock.patch.object(objects.BlockDeviceMapping, "save")
def test_default_device_names_for_instance(self, save_mock):
instance = objects.Instance(**self.test_instance)
instance.root_device_name = '/dev/vda'
ephemerals = [objects.BlockDeviceMapping(
**fake_block_device.AnonFakeDbBlockDeviceDict(
{'device_name': 'vdb',
'source_type': 'blank',
'volume_size': 2,
'destination_type': 'local'}))]
swap = [objects.BlockDeviceMapping(
**fake_block_device.AnonFakeDbBlockDeviceDict(
{'device_name': 'vdg',
'source_type': 'blank',
'volume_size': 512,
'guest_format': 'swap',
'destination_type': 'local'}))]
block_device_mapping = [
objects.BlockDeviceMapping(
**fake_block_device.AnonFakeDbBlockDeviceDict(
{'source_type': 'volume',
'destination_type': 'volume',
'volume_id': 'fake-image-id',
'device_name': '/dev/vdxx',
'disk_bus': 'scsi'}))]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.default_device_names_for_instance(instance,
instance.root_device_name,
ephemerals, swap,
block_device_mapping)
# Ephemeral device name was correct so no changes
self.assertEqual('/dev/vdb', ephemerals[0].device_name)
# Swap device name was incorrect so it was changed
self.assertEqual('/dev/vdc', swap[0].device_name)
# Volume device name was changed too, taking the bus into account
self.assertEqual('/dev/sda', block_device_mapping[0].device_name)
self.assertEqual(3, save_mock.call_count)
def _test_get_device_name_for_instance(self, new_bdm, expected_dev):
instance = objects.Instance(**self.test_instance)
instance.root_device_name = '/dev/vda'
instance.ephemeral_gb = 0
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
got_dev = drvr.get_device_name_for_instance(
instance, [], new_bdm)
self.assertEqual(expected_dev, got_dev)
def test_get_device_name_for_instance_simple(self):
new_bdm = objects.BlockDeviceMapping(
context=context,
source_type='volume', destination_type='volume',
boot_index=-1, volume_id='fake-id',
device_name=None, guest_format=None,
disk_bus=None, device_type=None)
self._test_get_device_name_for_instance(new_bdm, '/dev/vdb')
def test_get_device_name_for_instance_suggested(self):
new_bdm = objects.BlockDeviceMapping(
context=context,
source_type='volume', destination_type='volume',
boot_index=-1, volume_id='fake-id',
device_name='/dev/vdg', guest_format=None,
disk_bus=None, device_type=None)
self._test_get_device_name_for_instance(new_bdm, '/dev/vdb')
def test_get_device_name_for_instance_bus(self):
new_bdm = objects.BlockDeviceMapping(
context=context,
source_type='volume', destination_type='volume',
boot_index=-1, volume_id='fake-id',
device_name=None, guest_format=None,
disk_bus='scsi', device_type=None)
self._test_get_device_name_for_instance(new_bdm, '/dev/sda')
def test_get_device_name_for_instance_device_type(self):
new_bdm = objects.BlockDeviceMapping(
context=context,
source_type='volume', destination_type='volume',
boot_index=-1, volume_id='fake-id',
device_name=None, guest_format=None,
disk_bus=None, device_type='floppy')
self._test_get_device_name_for_instance(new_bdm, '/dev/fda')
def test_is_supported_fs_format(self):
supported_fs = [disk_api.FS_FORMAT_EXT2, disk_api.FS_FORMAT_EXT3,
disk_api.FS_FORMAT_EXT4, disk_api.FS_FORMAT_XFS]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
for fs in supported_fs:
self.assertTrue(drvr.is_supported_fs_format(fs))
supported_fs = ['', 'dummy']
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
for fs in supported_fs:
self.assertFalse(drvr.is_supported_fs_format(fs))
def test_post_live_migration_at_destination_with_block_device_info(self):
# Preparing mocks
mock_domain = self.mox.CreateMock(fakelibvirt.virDomain)
self.resultXML = None
def fake_getLibVersion():
return fakelibvirt.FAKE_LIBVIRT_VERSION
def fake_getCapabilities():
return """
<capabilities>
<host>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<cpu>
<arch>x86_64</arch>
<model>Penryn</model>
<vendor>Intel</vendor>
<topology sockets='1' cores='2' threads='1'/>
<feature name='xtpr'/>
</cpu>
</host>
</capabilities>
"""
def fake_to_xml(context, instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None, write_to_disk=False):
if image_meta is None:
image_meta = objects.ImageMeta.from_dict({})
conf = drvr._get_guest_config(instance, network_info, image_meta,
disk_info, rescue, block_device_info)
self.resultXML = conf.to_xml()
return self.resultXML
def fake_get_domain(instance):
return mock_domain
def fake_baselineCPU(cpu, flag):
return """<cpu mode='custom' match='exact'>
<model fallback='allow'>Westmere</model>
<vendor>Intel</vendor>
<feature policy='require' name='aes'/>
</cpu>
"""
network_info = _fake_network_info(self, 1)
self.create_fake_libvirt_mock(getLibVersion=fake_getLibVersion,
getCapabilities=fake_getCapabilities,
getVersion=lambda: 1005001,
listDefinedDomains=lambda: [],
numOfDomains=lambda: 0,
baselineCPU=fake_baselineCPU)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456 # we send an int to test sha1 call
instance = objects.Instance(**instance_ref)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr,
'_get_guest_xml',
fake_to_xml)
self.stubs.Set(host.Host,
'get_domain',
fake_get_domain)
bdm = objects.BlockDeviceMapping(
self.context,
**fake_block_device.FakeDbBlockDeviceDict(
{'id': 1, 'guest_format': None,
'boot_index': 0,
'source_type': 'volume',
'destination_type': 'volume',
'device_name': '/dev/vda',
'disk_bus': 'virtio',
'device_type': 'disk',
'delete_on_termination': False}))
block_device_info = {'block_device_mapping':
driver_block_device.convert_volumes([bdm])}
block_device_info['block_device_mapping'][0]['connection_info'] = (
{'driver_volume_type': 'iscsi'})
with test.nested(
mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'),
mock.patch.object(objects.Instance, 'save')
) as (mock_volume_save, mock_instance_save):
drvr.post_live_migration_at_destination(
self.context, instance, network_info, True,
block_device_info=block_device_info)
self.assertIn('fake', self.resultXML)
mock_volume_save.assert_called_once_with()
def test_create_propagates_exceptions(self):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(id=1, uuid=uuids.instance,
image_ref='my_fake_image')
with test.nested(
mock.patch.object(drvr, '_create_domain_setup_lxc'),
mock.patch.object(drvr, '_create_domain_cleanup_lxc'),
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr, 'firewall_driver'),
mock.patch.object(drvr, '_create_domain',
side_effect=exception.NovaException),
mock.patch.object(drvr, 'cleanup')):
self.assertRaises(exception.NovaException,
drvr._create_domain_and_network,
self.context,
'xml',
instance, None, None)
def test_create_without_pause(self):
self.flags(virt_type='lxc', group='libvirt')
@contextlib.contextmanager
def fake_lxc_disk_handler(*args, **kwargs):
yield
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
with test.nested(
mock.patch.object(drvr, '_lxc_disk_handler',
side_effect=fake_lxc_disk_handler),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr, 'firewall_driver'),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, 'cleanup')) as (
_handler, cleanup, firewall_driver, create, plug_vifs):
domain = drvr._create_domain_and_network(self.context, 'xml',
instance, None, None)
self.assertEqual(0, create.call_args_list[0][1]['pause'])
self.assertEqual(0, domain.resume.call_count)
def _test_create_with_network_events(self, neutron_failure=None,
power_on=True):
generated_events = []
def wait_timeout():
event = mock.MagicMock()
if neutron_failure == 'timeout':
raise eventlet.timeout.Timeout()
elif neutron_failure == 'error':
event.status = 'failed'
else:
event.status = 'completed'
return event
def fake_prepare(instance, event_name):
m = mock.MagicMock()
m.instance = instance
m.event_name = event_name
m.wait.side_effect = wait_timeout
generated_events.append(m)
return m
virtapi = manager.ComputeVirtAPI(mock.MagicMock())
prepare = virtapi._compute.instance_events.prepare_for_instance_event
prepare.side_effect = fake_prepare
drvr = libvirt_driver.LibvirtDriver(virtapi, False)
instance = objects.Instance(**self.test_instance)
vifs = [{'id': 'vif1', 'active': False},
{'id': 'vif2', 'active': False}]
@mock.patch.object(drvr, 'plug_vifs')
@mock.patch.object(drvr, 'firewall_driver')
@mock.patch.object(drvr, '_create_domain')
@mock.patch.object(drvr, 'cleanup')
def test_create(cleanup, create, fw_driver, plug_vifs):
domain = drvr._create_domain_and_network(self.context, 'xml',
instance, vifs, None,
power_on=power_on)
plug_vifs.assert_called_with(instance, vifs)
pause = self._get_pause_flag(drvr, vifs, power_on=power_on)
self.assertEqual(pause,
create.call_args_list[0][1]['pause'])
if pause:
domain.resume.assert_called_once_with()
if neutron_failure and CONF.vif_plugging_is_fatal:
cleanup.assert_called_once_with(self.context,
instance, network_info=vifs,
block_device_info=None)
test_create()
if utils.is_neutron() and CONF.vif_plugging_timeout and power_on:
prepare.assert_has_calls([
mock.call(instance, 'network-vif-plugged-vif1'),
mock.call(instance, 'network-vif-plugged-vif2')])
for event in generated_events:
if neutron_failure and generated_events.index(event) != 0:
self.assertEqual(0, event.call_count)
elif (neutron_failure == 'error' and
not CONF.vif_plugging_is_fatal):
event.wait.assert_called_once_with()
else:
self.assertEqual(0, prepare.call_count)
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron(self, is_neutron):
self._test_create_with_network_events()
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_power_off(self,
is_neutron):
# Tests that we don't wait for events if we don't start the instance.
self._test_create_with_network_events(power_on=False)
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_nowait(self, is_neutron):
self.flags(vif_plugging_timeout=0)
self._test_create_with_network_events()
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_failed_nonfatal_timeout(
self, is_neutron):
self.flags(vif_plugging_is_fatal=False)
self._test_create_with_network_events(neutron_failure='timeout')
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_failed_fatal_timeout(
self, is_neutron):
self.assertRaises(exception.VirtualInterfaceCreateException,
self._test_create_with_network_events,
neutron_failure='timeout')
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_failed_nonfatal_error(
self, is_neutron):
self.flags(vif_plugging_is_fatal=False)
self._test_create_with_network_events(neutron_failure='error')
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_failed_fatal_error(
self, is_neutron):
self.assertRaises(exception.VirtualInterfaceCreateException,
self._test_create_with_network_events,
neutron_failure='error')
@mock.patch('nova.utils.is_neutron', return_value=False)
def test_create_with_network_events_non_neutron(self, is_neutron):
self._test_create_with_network_events()
@mock.patch('nova.volume.encryptors.get_encryption_metadata')
@mock.patch('nova.virt.libvirt.blockinfo.get_info_from_bdm')
def test_create_with_bdm(self, get_info_from_bdm, get_encryption_metadata):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_dom = mock.MagicMock()
mock_encryption_meta = mock.MagicMock()
get_encryption_metadata.return_value = mock_encryption_meta
fake_xml = """
<domain>
<name>instance-00000001</name>
<memory>1048576</memory>
<vcpu>1</vcpu>
<devices>
<disk type='file' device='disk'>
<driver name='qemu' type='raw' cache='none'/>
<source file='/path/fake-volume1'/>
<target dev='vda' bus='virtio'/>
</disk>
</devices>
</domain>
"""
fake_volume_id = "fake-volume-id"
connection_info = {"driver_volume_type": "fake",
"data": {"access_mode": "rw",
"volume_id": fake_volume_id}}
def fake_getitem(*args, **kwargs):
fake_bdm = {'connection_info': connection_info,
'mount_device': '/dev/vda'}
return fake_bdm.get(args[0])
mock_volume = mock.MagicMock()
mock_volume.__getitem__.side_effect = fake_getitem
block_device_info = {'block_device_mapping': [mock_volume]}
network_info = [network_model.VIF(id='1'),
network_model.VIF(id='2', active=True)]
with test.nested(
mock.patch.object(drvr, '_get_volume_encryptor'),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver,
'prepare_instance_filter'),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter'),
) as (get_volume_encryptor, plug_vifs, setup_basic_filtering,
prepare_instance_filter, create_domain, apply_instance_filter):
create_domain.return_value = libvirt_guest.Guest(mock_dom)
guest = drvr._create_domain_and_network(
self.context, fake_xml, instance, network_info, None,
block_device_info=block_device_info)
get_encryption_metadata.assert_called_once_with(self.context,
drvr._volume_api, fake_volume_id, connection_info)
get_volume_encryptor.assert_called_once_with(connection_info,
mock_encryption_meta)
plug_vifs.assert_called_once_with(instance, network_info)
setup_basic_filtering.assert_called_once_with(instance,
network_info)
prepare_instance_filter.assert_called_once_with(instance,
network_info)
pause = self._get_pause_flag(drvr, network_info)
create_domain.assert_called_once_with(
fake_xml, pause=pause, power_on=True, post_xml_callback=None)
self.assertEqual(mock_dom, guest._domain)
def test_get_guest_storage_config(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
test_instance = copy.deepcopy(self.test_instance)
test_instance["default_swap_device"] = None
instance = objects.Instance(**test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = instance.get_flavor()
conn_info = {'driver_volume_type': 'fake', 'data': {}}
bdm = objects.BlockDeviceMapping(
self.context,
**fake_block_device.FakeDbBlockDeviceDict({
'id': 1,
'source_type': 'volume',
'destination_type': 'volume',
'device_name': '/dev/vdc'}))
bdi = {'block_device_mapping':
driver_block_device.convert_volumes([bdm])}
bdm = bdi['block_device_mapping'][0]
bdm['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta,
bdi)
mock_conf = mock.MagicMock(source_path='fake')
with test.nested(
mock.patch.object(driver_block_device.DriverVolumeBlockDevice,
'save'),
mock.patch.object(drvr, '_connect_volume'),
mock.patch.object(drvr, '_get_volume_config',
return_value=mock_conf),
mock.patch.object(drvr, '_set_cache_mode')
) as (volume_save, connect_volume, get_volume_config, set_cache_mode):
devices = drvr._get_guest_storage_config(instance, image_meta,
disk_info, False, bdi, flavor, "hvm")
self.assertEqual(3, len(devices))
self.assertEqual('/dev/vdb', instance.default_ephemeral_device)
self.assertIsNone(instance.default_swap_device)
connect_volume.assert_called_with(bdm['connection_info'],
{'bus': 'virtio', 'type': 'disk', 'dev': 'vdc'})
get_volume_config.assert_called_with(bdm['connection_info'],
{'bus': 'virtio', 'type': 'disk', 'dev': 'vdc'})
volume_save.assert_called_once_with()
self.assertEqual(3, set_cache_mode.call_count)
def test_get_neutron_events(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
network_info = [network_model.VIF(id='1'),
network_model.VIF(id='2', active=True)]
events = drvr._get_neutron_events(network_info)
self.assertEqual([('network-vif-plugged', '1')], events)
def test_unplug_vifs_ignores_errors(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
with mock.patch.object(drvr, 'vif_driver') as vif_driver:
vif_driver.unplug.side_effect = exception.AgentError(
method='unplug')
drvr._unplug_vifs('inst', [1], ignore_errors=True)
vif_driver.unplug.assert_called_once_with('inst', 1)
def test_unplug_vifs_reports_errors(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
with mock.patch.object(drvr, 'vif_driver') as vif_driver:
vif_driver.unplug.side_effect = exception.AgentError(
method='unplug')
self.assertRaises(exception.AgentError,
drvr.unplug_vifs, 'inst', [1])
vif_driver.unplug.assert_called_once_with('inst', 1)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._unplug_vifs')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain')
def test_cleanup_pass_with_no_mount_device(self, undefine, unplug):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
drvr.firewall_driver = mock.Mock()
drvr._disconnect_volume = mock.Mock()
fake_inst = {'name': 'foo'}
fake_bdms = [{'connection_info': 'foo',
'mount_device': None}]
with mock.patch('nova.virt.driver'
'.block_device_info_get_mapping',
return_value=fake_bdms):
drvr.cleanup('ctxt', fake_inst, 'netinfo', destroy_disks=False)
self.assertTrue(drvr._disconnect_volume.called)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._unplug_vifs')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain')
def test_cleanup_wants_vif_errors_ignored(self, undefine, unplug):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
fake_inst = {'name': 'foo'}
with mock.patch.object(drvr._conn, 'lookupByName') as lookup:
lookup.return_value = fake_inst
# NOTE(danms): Make unplug cause us to bail early, since
# we only care about how it was called
unplug.side_effect = test.TestingException
self.assertRaises(test.TestingException,
drvr.cleanup, 'ctxt', fake_inst, 'netinfo')
unplug.assert_called_once_with(fake_inst, 'netinfo', True)
@mock.patch.object(libvirt_driver.LibvirtDriver, 'unfilter_instance')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'delete_instance_files',
return_value=True)
@mock.patch.object(objects.Instance, 'save')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_undefine_domain')
def test_cleanup_migrate_data_shared_block_storage(self,
_undefine_domain,
save,
delete_instance_files,
unfilter_instance):
# Tests the cleanup method when migrate_data has
# is_shared_block_storage=True and destroy_disks=False.
instance = objects.Instance(self.context, **self.test_instance)
migrate_data = objects.LibvirtLiveMigrateData(
is_shared_block_storage=True)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
drvr.cleanup(
self.context, instance, network_info={}, destroy_disks=False,
migrate_data=migrate_data, destroy_vifs=False)
delete_instance_files.assert_called_once_with(instance)
self.assertEqual(1, int(instance.system_metadata['clean_attempts']))
self.assertTrue(instance.cleaned)
save.assert_called_once_with()
def test_swap_volume(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
mock_dom = mock.MagicMock()
guest = libvirt_guest.Guest(mock_dom)
with mock.patch.object(drvr._conn, 'defineXML',
create=True) as mock_define:
xmldoc = "<domain/>"
srcfile = "/first/path"
dstfile = "/second/path"
mock_dom.XMLDesc.return_value = xmldoc
mock_dom.isPersistent.return_value = True
mock_dom.blockJobInfo.return_value = {
'type': 0,
'bandwidth': 0,
'cur': 100,
'end': 100
}
drvr._swap_volume(guest, srcfile, dstfile, 1)
mock_dom.XMLDesc.assert_called_once_with(
flags=(fakelibvirt.VIR_DOMAIN_XML_INACTIVE |
fakelibvirt.VIR_DOMAIN_XML_SECURE))
mock_dom.blockRebase.assert_called_once_with(
srcfile, dstfile, 0, flags=(
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_COPY |
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT))
mock_dom.blockResize.assert_called_once_with(
srcfile, 1 * units.Gi / units.Ki)
mock_define.assert_called_once_with(xmldoc)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._disconnect_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._swap_volume')
@mock.patch('nova.objects.block_device.BlockDeviceMapping.'
'get_by_volume_and_instance')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._get_volume_config')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._connect_volume')
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def _test_swap_volume_driver_bdm_save(self, get_guest,
connect_volume, get_volume_config,
get_by_volume_and_instance,
swap_volume,
disconnect_volume,
volume_save,
source_type):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
instance = objects.Instance(**self.test_instance)
old_connection_info = {'driver_volume_type': 'fake',
'serial': 'old-volume-id',
'data': {'device_path': '/fake-old-volume',
'access_mode': 'rw'}}
new_connection_info = {'driver_volume_type': 'fake',
'serial': 'new-volume-id',
'data': {'device_path': '/fake-new-volume',
'access_mode': 'rw'}}
mock_dom = mock.MagicMock()
guest = libvirt_guest.Guest(mock_dom)
mock_dom.XMLDesc.return_value = """<domain>
<devices>
<disk type='file'>
<source file='/fake-old-volume'/>
<target dev='vdb' bus='virtio'/>
</disk>
</devices>
</domain>
"""
mock_dom.name.return_value = 'inst'
mock_dom.UUIDString.return_value = 'uuid'
get_guest.return_value = guest
disk_info = {'bus': 'virtio', 'type': 'disk', 'dev': 'vdb'}
get_volume_config.return_value = mock.MagicMock(
source_path='/fake-new-volume')
bdm = objects.BlockDeviceMapping(self.context,
**fake_block_device.FakeDbBlockDeviceDict(
{'id': 2, 'instance_uuid': uuids.instance,
'device_name': '/dev/vdb',
'source_type': source_type,
'destination_type': 'volume',
'volume_id': 'fake-volume-id-2',
'boot_index': 0}))
get_by_volume_and_instance.return_value = bdm
conn.swap_volume(old_connection_info, new_connection_info, instance,
'/dev/vdb', 1)
get_guest.assert_called_once_with(instance)
connect_volume.assert_called_once_with(new_connection_info, disk_info)
swap_volume.assert_called_once_with(guest, 'vdb',
'/fake-new-volume', 1)
disconnect_volume.assert_called_once_with(old_connection_info, 'vdb')
volume_save.assert_called_once_with()
@mock.patch('nova.virt.block_device.DriverVolumeBlockDevice.save')
def test_swap_volume_driver_bdm_save_source_is_volume(self, volume_save):
self._test_swap_volume_driver_bdm_save(volume_save=volume_save,
source_type='volume')
@mock.patch('nova.virt.block_device.DriverImageBlockDevice.save')
def test_swap_volume_driver_bdm_save_source_is_image(self, volume_save):
self._test_swap_volume_driver_bdm_save(volume_save=volume_save,
source_type='image')
@mock.patch('nova.virt.block_device.DriverSnapshotBlockDevice.save')
def test_swap_volume_driver_bdm_save_source_is_snapshot(self, volume_save):
self._test_swap_volume_driver_bdm_save(volume_save=volume_save,
source_type='snapshot')
def _test_live_snapshot(self, can_quiesce=False, require_quiesce=False):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
mock_dom = mock.MagicMock()
test_image_meta = self.test_image_meta.copy()
if require_quiesce:
test_image_meta = {'properties': {'os_require_quiesce': 'yes'}}
with test.nested(
mock.patch.object(drvr._conn, 'defineXML', create=True),
mock.patch.object(fake_libvirt_utils, 'get_disk_size'),
mock.patch.object(fake_libvirt_utils, 'get_disk_backing_file'),
mock.patch.object(fake_libvirt_utils, 'create_cow_image'),
mock.patch.object(fake_libvirt_utils, 'chown'),
mock.patch.object(fake_libvirt_utils, 'extract_snapshot'),
mock.patch.object(drvr, '_set_quiesced')
) as (mock_define, mock_size, mock_backing, mock_create_cow,
mock_chown, mock_snapshot, mock_quiesce):
xmldoc = "<domain/>"
srcfile = "/first/path"
dstfile = "/second/path"
bckfile = "/other/path"
dltfile = dstfile + ".delta"
mock_dom.XMLDesc.return_value = xmldoc
mock_dom.isPersistent.return_value = True
mock_size.return_value = 1004009
mock_backing.return_value = bckfile
guest = libvirt_guest.Guest(mock_dom)
if not can_quiesce:
mock_quiesce.side_effect = (
exception.InstanceQuiesceNotSupported(
instance_id=self.test_instance['id'], reason='test'))
image_meta = objects.ImageMeta.from_dict(test_image_meta)
drvr._live_snapshot(self.context, self.test_instance, guest,
srcfile, dstfile, "qcow2", "qcow2", image_meta)
mock_dom.XMLDesc.assert_called_once_with(flags=(
fakelibvirt.VIR_DOMAIN_XML_INACTIVE |
fakelibvirt.VIR_DOMAIN_XML_SECURE))
mock_dom.blockRebase.assert_called_once_with(
srcfile, dltfile, 0, flags=(
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_COPY |
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT |
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_SHALLOW))
mock_size.assert_called_once_with(srcfile, format="qcow2")
mock_backing.assert_called_once_with(srcfile, basename=False,
format="qcow2")
mock_create_cow.assert_called_once_with(bckfile, dltfile, 1004009)
mock_chown.assert_called_once_with(dltfile, os.getuid())
mock_snapshot.assert_called_once_with(dltfile, "qcow2",
dstfile, "qcow2")
mock_define.assert_called_once_with(xmldoc)
mock_quiesce.assert_any_call(mock.ANY, self.test_instance,
mock.ANY, True)
if can_quiesce:
mock_quiesce.assert_any_call(mock.ANY, self.test_instance,
mock.ANY, False)
def test_live_snapshot(self):
self._test_live_snapshot()
def test_live_snapshot_with_quiesce(self):
self._test_live_snapshot(can_quiesce=True)
def test_live_snapshot_with_require_quiesce(self):
self._test_live_snapshot(can_quiesce=True, require_quiesce=True)
def test_live_snapshot_with_require_quiesce_fails(self):
self.assertRaises(exception.InstanceQuiesceNotSupported,
self._test_live_snapshot,
can_quiesce=False, require_quiesce=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_live_migration")
def test_live_migration_hostname_valid(self, mock_lm):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.live_migration(self.context, self.test_instance,
"host1.example.com",
lambda x: x,
lambda x: x)
self.assertEqual(1, mock_lm.call_count)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_live_migration")
@mock.patch.object(fake_libvirt_utils, "is_valid_hostname")
def test_live_migration_hostname_invalid(self, mock_hostname, mock_lm):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_hostname.return_value = False
self.assertRaises(exception.InvalidHostname,
drvr.live_migration,
self.context, self.test_instance,
"foo/?com=/bin/sh",
lambda x: x,
lambda x: x)
def test_live_migration_force_complete(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = fake_instance.fake_instance_obj(
None, name='instancename', id=1,
uuid='c83a75d4-4d53-4be5-9a40-04d9c0389ff8')
drvr.active_migrations[instance.uuid] = deque()
drvr.live_migration_force_complete(instance)
self.assertEqual(
1, drvr.active_migrations[instance.uuid].count("force-complete"))
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(fakelibvirt.virDomain, "abortJob")
def test_live_migration_abort(self, mock_abort, mock_conn):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", False)
guest = libvirt_guest.Guest(dom)
with mock.patch.object(nova.virt.libvirt.host.Host, 'get_guest',
return_value=guest):
drvr.live_migration_abort(self.test_instance)
self.assertTrue(mock_abort.called)
@mock.patch('os.path.exists', return_value=True)
@mock.patch('tempfile.mkstemp')
@mock.patch('os.close', return_value=None)
def test_check_instance_shared_storage_local_raw(self,
mock_close,
mock_mkstemp,
mock_exists):
instance_uuid = str(uuid.uuid4())
self.flags(images_type='raw', group='libvirt')
self.flags(instances_path='/tmp')
mock_mkstemp.return_value = (-1,
'/tmp/{0}/file'.format(instance_uuid))
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
temp_file = driver.check_instance_shared_storage_local(self.context,
instance)
self.assertEqual('/tmp/{0}/file'.format(instance_uuid),
temp_file['filename'])
def test_check_instance_shared_storage_local_rbd(self):
self.flags(images_type='rbd', group='libvirt')
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
self.assertIsNone(driver.
check_instance_shared_storage_local(self.context,
instance))
def test_version_to_string(self):
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
string_ver = driver._version_to_string((4, 33, 173))
self.assertEqual("4.33.173", string_ver)
def test_parallels_min_version_fail(self):
self.flags(virt_type='parallels', group='libvirt')
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(driver._conn, 'getLibVersion',
return_value=1002011):
self.assertRaises(exception.NovaException,
driver.init_host, 'wibble')
def test_parallels_min_version_ok(self):
self.flags(virt_type='parallels', group='libvirt')
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(driver._conn, 'getLibVersion',
return_value=1002012):
driver.init_host('wibble')
def test_get_guest_config_parallels_vm(self):
self.flags(virt_type='parallels', group='libvirt')
self.flags(images_type='ploop', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual("parallels", cfg.virt_type)
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
self.assertEqual(vm_mode.HVM, cfg.os_type)
self.assertIsNone(cfg.os_root)
self.assertEqual(6, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[0].driver_format, "ploop")
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
def test_get_guest_config_parallels_ct_rescue(self):
self._test_get_guest_config_parallels_ct(rescue=True)
def test_get_guest_config_parallels_ct(self):
self._test_get_guest_config_parallels_ct(rescue=False)
def _test_get_guest_config_parallels_ct(self, rescue=False):
self.flags(virt_type='parallels', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
ct_instance = self.test_instance.copy()
ct_instance["vm_mode"] = vm_mode.EXE
instance_ref = objects.Instance(**ct_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
if rescue:
rescue_data = ct_instance
else:
rescue_data = None
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, {'mapping': {'disk': {}}},
rescue_data)
self.assertEqual("parallels", cfg.virt_type)
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
self.assertEqual(vm_mode.EXE, cfg.os_type)
self.assertEqual("/sbin/init", cfg.os_init_path)
self.assertIsNone(cfg.os_root)
if rescue:
self.assertEqual(5, len(cfg.devices))
else:
self.assertEqual(4, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestFilesys)
device_index = 0
fs = cfg.devices[device_index]
self.assertEqual(fs.source_type, "file")
self.assertEqual(fs.driver_type, "ploop")
self.assertEqual(fs.target_dir, "/")
if rescue:
device_index = 1
fs = cfg.devices[device_index]
self.assertEqual(fs.source_type, "file")
self.assertEqual(fs.driver_type, "ploop")
self.assertEqual(fs.target_dir, "/mnt/rescue")
self.assertIsInstance(cfg.devices[device_index + 1],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[device_index + 2],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[device_index + 3],
vconfig.LibvirtConfigGuestVideo)
def _test_get_guest_config_parallels_volume(self, vmmode, devices):
self.flags(virt_type='parallels', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
ct_instance = self.test_instance.copy()
ct_instance["vm_mode"] = vmmode
instance_ref = objects.Instance(**ct_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
conn_info = {'driver_volume_type': 'fake'}
bdm = objects.BlockDeviceMapping(
self.context,
**fake_block_device.FakeDbBlockDeviceDict(
{'id': 0,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sda'}))
info = {'block_device_mapping': driver_block_device.convert_volumes(
[bdm])}
info['block_device_mapping'][0]['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
info)
with mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'
) as mock_save:
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info, None, info)
mock_save.assert_called_once_with()
self.assertEqual("parallels", cfg.virt_type)
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
self.assertEqual(vmmode, cfg.os_type)
self.assertIsNone(cfg.os_root)
self.assertEqual(devices, len(cfg.devices))
disk_found = False
for dev in cfg.devices:
result = isinstance(dev, vconfig.LibvirtConfigGuestFilesys)
self.assertFalse(result)
if (isinstance(dev, vconfig.LibvirtConfigGuestDisk) and
(dev.source_path is None or
'disk.local' not in dev.source_path)):
self.assertEqual("disk", dev.source_device)
self.assertEqual("sda", dev.target_dev)
disk_found = True
self.assertTrue(disk_found)
def test_get_guest_config_parallels_volume(self):
self._test_get_guest_config_parallels_volume(vm_mode.EXE, 4)
self._test_get_guest_config_parallels_volume(vm_mode.HVM, 6)
def test_get_guest_disk_config_rbd_older_config_drive_fall_back(self):
# New config drives are stored in rbd but existing instances have
# config drives in the old location under the instances path.
# Test that the driver falls back to 'flat' for config drive if it
# doesn't exist in rbd.
self.flags(images_type='rbd', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
mock_rbd_image = mock.Mock()
mock_flat_image = mock.Mock()
mock_flat_image.libvirt_info.return_value = mock.sentinel.diskconfig
drvr.image_backend.image.side_effect = [mock_rbd_image,
mock_flat_image]
mock_rbd_image.exists.return_value = False
instance = objects.Instance()
disk_mapping = {'disk.config': {'bus': 'ide',
'dev': 'hdd',
'type': 'file'}}
flavor = objects.Flavor(extra_specs={})
diskconfig = drvr._get_guest_disk_config(
instance, 'disk.config', disk_mapping, flavor,
drvr._get_disk_config_image_type())
self.assertEqual(2, drvr.image_backend.image.call_count)
call1 = mock.call(instance, 'disk.config', 'rbd')
call2 = mock.call(instance, 'disk.config', 'flat')
drvr.image_backend.image.assert_has_calls([call1, call2])
self.assertEqual(mock.sentinel.diskconfig, diskconfig)
def _test_prepare_domain_for_snapshot(self, live_snapshot, state):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance_ref = objects.Instance(**self.test_instance)
with mock.patch.object(drvr, "suspend") as mock_suspend:
drvr._prepare_domain_for_snapshot(
self.context, live_snapshot, state, instance_ref)
return mock_suspend.called
def test_prepare_domain_for_snapshot(self):
# Ensure that suspend() is only called on RUNNING or PAUSED instances
for test_power_state in power_state.STATE_MAP.keys():
if test_power_state in (power_state.RUNNING, power_state.PAUSED):
self.assertTrue(self._test_prepare_domain_for_snapshot(
False, test_power_state))
else:
self.assertFalse(self._test_prepare_domain_for_snapshot(
False, test_power_state))
def test_prepare_domain_for_snapshot_lxc(self):
self.flags(virt_type='lxc', group='libvirt')
# Ensure that suspend() is never called with LXC
for test_power_state in power_state.STATE_MAP.keys():
self.assertFalse(self._test_prepare_domain_for_snapshot(
False, test_power_state))
def test_prepare_domain_for_snapshot_live_snapshots(self):
# Ensure that suspend() is never called for live snapshots
for test_power_state in power_state.STATE_MAP.keys():
self.assertFalse(self._test_prepare_domain_for_snapshot(
True, test_power_state))
@mock.patch('os.walk')
@mock.patch('os.path.exists')
@mock.patch('os.path.getsize')
@mock.patch('os.path.isdir')
@mock.patch('nova.utils.execute')
@mock.patch.object(host.Host, "get_domain")
def test_get_instance_disk_info_parallels_ct(self, mock_get_domain,
mock_execute,
mock_isdir,
mock_getsize,
mock_exists,
mock_walk):
dummyxml = ("<domain type='parallels'><name>instance-0000000a</name>"
"<os><type>exe</type></os>"
"<devices>"
"<filesystem type='file'>"
"<driver format='ploop' type='ploop'/>"
"<source file='/test/disk'/>"
"<target dir='/'/></filesystem>"
"</devices></domain>")
ret = ("image: /test/disk/root.hds\n"
"file format: parallels\n"
"virtual size: 20G (21474836480 bytes)\n"
"disk size: 789M\n")
self.flags(virt_type='parallels', group='libvirt')
instance = objects.Instance(**self.test_instance)
instance.vm_mode = vm_mode.EXE
fake_dom = FakeVirtDomain(fake_xml=dummyxml)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_domain.return_value = fake_dom
mock_walk.return_value = [('/test/disk', [],
['DiskDescriptor.xml', 'root.hds'])]
def getsize_sideeffect(*args, **kwargs):
if args[0] == '/test/disk/DiskDescriptor.xml':
return 790
if args[0] == '/test/disk/root.hds':
return 827326464
mock_getsize.side_effect = getsize_sideeffect
mock_exists.return_value = True
mock_isdir.return_value = True
mock_execute.return_value = (ret, '')
info = drvr.get_instance_disk_info(instance)
info = jsonutils.loads(info)
self.assertEqual(info[0]['type'], 'ploop')
self.assertEqual(info[0]['path'], '/test/disk')
self.assertEqual(info[0]['disk_size'], 827327254)
self.assertEqual(info[0]['over_committed_disk_size'], 20647509226)
self.assertEqual(info[0]['virt_disk_size'], 21474836480)
class HostStateTestCase(test.NoDBTestCase):
cpu_info = {"vendor": "Intel", "model": "pentium", "arch": "i686",
"features": ["ssse3", "monitor", "pni", "sse2", "sse",
"fxsr", "clflush", "pse36", "pat", "cmov", "mca", "pge",
"mtrr", "sep", "apic"],
"topology": {"cores": "1", "threads": "1", "sockets": "1"}}
instance_caps = [(arch.X86_64, "kvm", "hvm"),
(arch.I686, "kvm", "hvm")]
pci_devices = [{
"dev_id": "pci_0000_04_00_3",
"address": "0000:04:10.3",
"product_id": '1521',
"vendor_id": '8086',
"dev_type": fields.PciDeviceType.SRIOV_PF,
"phys_function": None}]
numa_topology = objects.NUMATopology(
cells=[objects.NUMACell(
id=1, cpuset=set([1, 2]), memory=1024,
cpu_usage=0, memory_usage=0,
mempages=[], siblings=[],
pinned_cpus=set([])),
objects.NUMACell(
id=2, cpuset=set([3, 4]), memory=1024,
cpu_usage=0, memory_usage=0,
mempages=[], siblings=[],
pinned_cpus=set([]))])
class FakeConnection(libvirt_driver.LibvirtDriver):
"""Fake connection object."""
def __init__(self):
super(HostStateTestCase.FakeConnection,
self).__init__(fake.FakeVirtAPI(), True)
self._host = host.Host("qemu:///system")
def _get_memory_mb_total():
return 497
def _get_memory_mb_used():
return 88
self._host.get_memory_mb_total = _get_memory_mb_total
self._host.get_memory_mb_used = _get_memory_mb_used
def _get_vcpu_total(self):
return 1
def _get_vcpu_used(self):
return 0
def _get_cpu_info(self):
return HostStateTestCase.cpu_info
def _get_disk_over_committed_size_total(self):
return 0
def _get_local_gb_info(self):
return {'total': 100, 'used': 20, 'free': 80}
def get_host_uptime(self):
return ('10:01:16 up 1:36, 6 users, '
'load average: 0.21, 0.16, 0.19')
def _get_disk_available_least(self):
return 13091
def _get_instance_capabilities(self):
return HostStateTestCase.instance_caps
def _get_pci_passthrough_devices(self):
return jsonutils.dumps(HostStateTestCase.pci_devices)
def _get_host_numa_topology(self):
return HostStateTestCase.numa_topology
@mock.patch.object(fakelibvirt, "openAuth")
def test_update_status(self, mock_open):
mock_open.return_value = fakelibvirt.Connection("qemu:///system")
drvr = HostStateTestCase.FakeConnection()
stats = drvr.get_available_resource("compute1")
self.assertEqual(stats["vcpus"], 1)
self.assertEqual(stats["memory_mb"], 497)
self.assertEqual(stats["local_gb"], 100)
self.assertEqual(stats["vcpus_used"], 0)
self.assertEqual(stats["memory_mb_used"], 88)
self.assertEqual(stats["local_gb_used"], 20)
self.assertEqual(stats["hypervisor_type"], 'QEMU')
self.assertEqual(stats["hypervisor_version"],
fakelibvirt.FAKE_QEMU_VERSION)
self.assertEqual(stats["hypervisor_hostname"], 'compute1')
cpu_info = jsonutils.loads(stats["cpu_info"])
self.assertEqual(cpu_info,
{"vendor": "Intel", "model": "pentium",
"arch": arch.I686,
"features": ["ssse3", "monitor", "pni", "sse2", "sse",
"fxsr", "clflush", "pse36", "pat", "cmov",
"mca", "pge", "mtrr", "sep", "apic"],
"topology": {"cores": "1", "threads": "1", "sockets": "1"}
})
self.assertEqual(stats["disk_available_least"], 80)
self.assertEqual(jsonutils.loads(stats["pci_passthrough_devices"]),
HostStateTestCase.pci_devices)
self.assertThat(objects.NUMATopology.obj_from_db_obj(
stats['numa_topology'])._to_dict(),
matchers.DictMatches(
HostStateTestCase.numa_topology._to_dict()))
class LibvirtDriverTestCase(test.NoDBTestCase):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver."""
def setUp(self):
super(LibvirtDriverTestCase, self).setUp()
os_vif.initialize()
self.drvr = libvirt_driver.LibvirtDriver(
fake.FakeVirtAPI(), read_only=True)
self.context = context.get_admin_context()
self.test_image_meta = {
"disk_format": "raw",
}
def _create_instance(self, params=None):
"""Create a test instance."""
if not params:
params = {}
flavor = objects.Flavor(memory_mb=512,
swap=0,
vcpu_weight=None,
root_gb=10,
id=2,
name=u'm1.tiny',
ephemeral_gb=20,
rxtx_factor=1.0,
flavorid=u'1',
vcpus=1,
extra_specs={})
flavor.update(params.pop('flavor', {}))
inst = {}
inst['id'] = 1
inst['uuid'] = '52d3b512-1152-431f-a8f7-28f0288a622b'
inst['os_type'] = 'linux'
inst['image_ref'] = uuids.fake_image_ref
inst['reservation_id'] = 'r-fakeres'
inst['user_id'] = 'fake'
inst['project_id'] = 'fake'
inst['instance_type_id'] = 2
inst['ami_launch_index'] = 0
inst['host'] = 'host1'
inst['root_gb'] = flavor.root_gb
inst['ephemeral_gb'] = flavor.ephemeral_gb
inst['config_drive'] = True
inst['kernel_id'] = 2
inst['ramdisk_id'] = 3
inst['key_data'] = 'ABCDEFG'
inst['system_metadata'] = {}
inst['metadata'] = {}
inst['task_state'] = None
inst.update(params)
instance = fake_instance.fake_instance_obj(
self.context, expected_attrs=['metadata', 'system_metadata',
'pci_devices'],
flavor=flavor, **inst)
# Attributes which we need to be set so they don't touch the db,
# but it's not worth the effort to fake properly
for field in ['numa_topology', 'vcpu_model']:
setattr(instance, field, None)
return instance
def test_migrate_disk_and_power_off_exception(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off.
"""
self.counter = 0
self.checked_shared_storage = False
def fake_get_instance_disk_info(instance,
block_device_info=None):
return '[]'
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
def fake_execute(*args, **kwargs):
self.counter += 1
if self.counter == 1:
assert False, "intentional failure"
def fake_os_path_exists(path):
return True
def fake_is_storage_shared(dest, inst_base):
self.checked_shared_storage = True
return False
self.stubs.Set(self.drvr, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.drvr, '_destroy', fake_destroy)
self.stubs.Set(self.drvr, 'get_host_ip_addr',
fake_get_host_ip_addr)
self.stubs.Set(self.drvr, '_is_storage_shared_with',
fake_is_storage_shared)
self.stubs.Set(utils, 'execute', fake_execute)
self.stub_out('os.path.exists', fake_os_path_exists)
ins_ref = self._create_instance()
flavor = {'root_gb': 10, 'ephemeral_gb': 20}
flavor_obj = objects.Flavor(**flavor)
self.assertRaises(AssertionError,
self.drvr.migrate_disk_and_power_off,
context.get_admin_context(), ins_ref, '10.0.0.2',
flavor_obj, None)
def _test_migrate_disk_and_power_off(self, flavor_obj,
block_device_info=None,
params_for_instance=None):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off.
"""
instance = self._create_instance(params=params_for_instance)
disk_info = fake_disk_info_json(instance)
def fake_get_instance_disk_info(instance,
block_device_info=None):
return disk_info
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
def fake_execute(*args, **kwargs):
pass
def fake_copy_image(src, dest, host=None, receive=False,
on_execute=None, on_completion=None,
compression=True):
self.assertIsNotNone(on_execute)
self.assertIsNotNone(on_completion)
self.stubs.Set(self.drvr, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.drvr, '_destroy', fake_destroy)
self.stubs.Set(self.drvr, 'get_host_ip_addr',
fake_get_host_ip_addr)
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(libvirt_utils, 'copy_image', fake_copy_image)
# dest is different host case
out = self.drvr.migrate_disk_and_power_off(
context.get_admin_context(), instance, '10.0.0.2',
flavor_obj, None, block_device_info=block_device_info)
self.assertEqual(out, disk_info)
# dest is same host case
out = self.drvr.migrate_disk_and_power_off(
context.get_admin_context(), instance, '10.0.0.1',
flavor_obj, None, block_device_info=block_device_info)
self.assertEqual(out, disk_info)
def test_migrate_disk_and_power_off(self):
flavor = {'root_gb': 10, 'ephemeral_gb': 20}
flavor_obj = objects.Flavor(**flavor)
self._test_migrate_disk_and_power_off(flavor_obj)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._disconnect_volume')
def test_migrate_disk_and_power_off_boot_from_volume(self,
disconnect_volume):
info = {'block_device_mapping': [{'boot_index': None,
'mount_device': '/dev/vdd',
'connection_info': None},
{'boot_index': 0,
'mount_device': '/dev/vda',
'connection_info': None}]}
flavor = {'root_gb': 1, 'ephemeral_gb': 0}
flavor_obj = objects.Flavor(**flavor)
# Note(Mike_D): The size of instance's ephemeral_gb is 0 gb.
self._test_migrate_disk_and_power_off(
flavor_obj, block_device_info=info,
params_for_instance={'image_ref': None,
'flavor': {'root_gb': 1,
'ephemeral_gb': 0}})
disconnect_volume.assert_called_with(
info['block_device_mapping'][1]['connection_info'], 'vda')
@mock.patch('nova.utils.execute')
@mock.patch('nova.virt.libvirt.utils.copy_image')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._destroy')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_host_ip_addr')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
def test_migrate_disk_and_power_off_swap(self, mock_get_disk_info,
get_host_ip_addr,
mock_destroy,
mock_copy_image,
mock_execute):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off.
"""
self.copy_or_move_swap_called = False
# Original instance config
instance = self._create_instance({'flavor': {'root_gb': 10,
'ephemeral_gb': 0}})
disk_info = fake_disk_info_json(instance)
mock_get_disk_info.return_value = disk_info
get_host_ip_addr.return_value = '10.0.0.1'
def fake_copy_image(*args, **kwargs):
# disk.swap should not be touched since it is skipped over
if '/test/disk.swap' in list(args):
self.copy_or_move_swap_called = True
def fake_execute(*args, **kwargs):
# disk.swap should not be touched since it is skipped over
if set(['mv', '/test/disk.swap']).issubset(list(args)):
self.copy_or_move_swap_called = True
mock_copy_image.side_effect = fake_copy_image
mock_execute.side_effect = fake_execute
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Re-size fake instance to 20G root and 1024M swap disk
flavor = {'root_gb': 20, 'ephemeral_gb': 0, 'swap': 1024}
flavor_obj = objects.Flavor(**flavor)
# Destination is same host
out = drvr.migrate_disk_and_power_off(context.get_admin_context(),
instance, '10.0.0.1',
flavor_obj, None)
mock_get_disk_info.assert_called_once_with(instance,
block_device_info=None)
self.assertTrue(get_host_ip_addr.called)
mock_destroy.assert_called_once_with(instance)
self.assertFalse(self.copy_or_move_swap_called)
self.assertEqual(disk_info, out)
def _test_migrate_disk_and_power_off_resize_check(self, expected_exc):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtConnection
.migrate_disk_and_power_off.
"""
instance = self._create_instance()
disk_info = fake_disk_info_json(instance)
def fake_get_instance_disk_info(instance, xml=None,
block_device_info=None):
return disk_info
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
self.stubs.Set(self.drvr, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.drvr, '_destroy', fake_destroy)
self.stubs.Set(self.drvr, 'get_host_ip_addr',
fake_get_host_ip_addr)
flavor = {'root_gb': 10, 'ephemeral_gb': 20}
flavor_obj = objects.Flavor(**flavor)
# Migration is not implemented for LVM backed instances
self.assertRaises(expected_exc,
self.drvr.migrate_disk_and_power_off,
None, instance, '10.0.0.1', flavor_obj, None)
@mock.patch('nova.utils.execute')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._destroy')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'._is_storage_shared_with')
def _test_migrate_disk_and_power_off_backing_file(self,
shared_storage,
mock_is_shared_storage,
mock_get_disk_info,
mock_destroy,
mock_execute):
self.convert_file_called = False
flavor = {'root_gb': 20, 'ephemeral_gb': 30, 'swap': 0}
flavor_obj = objects.Flavor(**flavor)
disk_info = [{'type': 'qcow2', 'path': '/test/disk',
'virt_disk_size': '10737418240',
'backing_file': '/base/disk',
'disk_size': '83886080'}]
disk_info_text = jsonutils.dumps(disk_info)
mock_get_disk_info.return_value = disk_info_text
mock_is_shared_storage.return_value = shared_storage
def fake_execute(*args, **kwargs):
self.assertNotEqual(args[0:2], ['qemu-img', 'convert'])
mock_execute.side_effect = fake_execute
instance = self._create_instance()
out = self.drvr.migrate_disk_and_power_off(
context.get_admin_context(), instance, '10.0.0.2',
flavor_obj, None)
self.assertTrue(mock_is_shared_storage.called)
mock_destroy.assert_called_once_with(instance)
self.assertEqual(out, disk_info_text)
def test_migrate_disk_and_power_off_shared_storage(self):
self._test_migrate_disk_and_power_off_backing_file(True)
def test_migrate_disk_and_power_off_non_shared_storage(self):
self._test_migrate_disk_and_power_off_backing_file(False)
def test_migrate_disk_and_power_off_lvm(self):
self.flags(images_type='lvm', group='libvirt')
def fake_execute(*args, **kwargs):
pass
self.stubs.Set(utils, 'execute', fake_execute)
expected_exc = exception.InstanceFaultRollback
self._test_migrate_disk_and_power_off_resize_check(expected_exc)
def test_migrate_disk_and_power_off_resize_cannot_ssh(self):
def fake_execute(*args, **kwargs):
raise processutils.ProcessExecutionError()
def fake_is_storage_shared(dest, inst_base):
self.checked_shared_storage = True
return False
self.stubs.Set(self.drvr, '_is_storage_shared_with',
fake_is_storage_shared)
self.stubs.Set(utils, 'execute', fake_execute)
expected_exc = exception.InstanceFaultRollback
self._test_migrate_disk_and_power_off_resize_check(expected_exc)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
def test_migrate_disk_and_power_off_resize_error(self, mock_get_disk_info):
instance = self._create_instance()
flavor = {'root_gb': 5, 'ephemeral_gb': 10}
flavor_obj = objects.Flavor(**flavor)
mock_get_disk_info.return_value = fake_disk_info_json(instance)
self.assertRaises(
exception.InstanceFaultRollback,
self.drvr.migrate_disk_and_power_off,
'ctx', instance, '10.0.0.1', flavor_obj, None)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
def test_migrate_disk_and_power_off_resize_error_default_ephemeral(
self, mock_get_disk_info):
# Note(Mike_D): The size of this instance's ephemeral_gb is 20 gb.
instance = self._create_instance()
flavor = {'root_gb': 10, 'ephemeral_gb': 0}
flavor_obj = objects.Flavor(**flavor)
mock_get_disk_info.return_value = fake_disk_info_json(instance)
self.assertRaises(exception.InstanceFaultRollback,
self.drvr.migrate_disk_and_power_off,
'ctx', instance, '10.0.0.1', flavor_obj, None)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
@mock.patch('nova.virt.driver.block_device_info_get_ephemerals')
def test_migrate_disk_and_power_off_resize_error_eph(self, mock_get,
mock_get_disk_info):
mappings = [
{
'device_name': '/dev/sdb4',
'source_type': 'blank',
'destination_type': 'local',
'device_type': 'disk',
'guest_format': 'swap',
'boot_index': -1,
'volume_size': 1
},
{
'device_name': '/dev/sda1',
'source_type': 'volume',
'destination_type': 'volume',
'device_type': 'disk',
'volume_id': 1,
'guest_format': None,
'boot_index': 1,
'volume_size': 6
},
{
'device_name': '/dev/sda2',
'source_type': 'snapshot',
'destination_type': 'volume',
'snapshot_id': 1,
'device_type': 'disk',
'guest_format': None,
'boot_index': 0,
'volume_size': 4
},
{
'device_name': '/dev/sda3',
'source_type': 'blank',
'destination_type': 'local',
'device_type': 'disk',
'guest_format': None,
'boot_index': -1,
'volume_size': 3
}
]
mock_get.return_value = mappings
instance = self._create_instance()
# Old flavor, eph is 20, real disk is 3, target is 2, fail
flavor = {'root_gb': 10, 'ephemeral_gb': 2}
flavor_obj = objects.Flavor(**flavor)
mock_get_disk_info.return_value = fake_disk_info_json(instance)
self.assertRaises(
exception.InstanceFaultRollback,
self.drvr.migrate_disk_and_power_off,
'ctx', instance, '10.0.0.1', flavor_obj, None)
# Old flavor, eph is 20, real disk is 3, target is 4
flavor = {'root_gb': 10, 'ephemeral_gb': 4}
flavor_obj = objects.Flavor(**flavor)
self._test_migrate_disk_and_power_off(flavor_obj)
@mock.patch('nova.utils.execute')
@mock.patch('nova.virt.libvirt.utils.copy_image')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._destroy')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'._is_storage_shared_with')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
def test_migrate_disk_and_power_off_resize_copy_disk_info(self,
mock_disk_info,
mock_shared,
mock_path,
mock_destroy,
mock_copy,
mock_execuate):
instance = self._create_instance()
disk_info = fake_disk_info_json(instance)
disk_info_text = jsonutils.loads(disk_info)
instance_base = os.path.dirname(disk_info_text[0]['path'])
flavor = {'root_gb': 10, 'ephemeral_gb': 25}
flavor_obj = objects.Flavor(**flavor)
mock_disk_info.return_value = disk_info
mock_path.return_value = instance_base
mock_shared.return_value = False
src_disk_info_path = os.path.join(instance_base + '_resize',
'disk.info')
with mock.patch.object(os.path, 'exists', autospec=True) \
as mock_exists:
# disk.info exists on the source
mock_exists.side_effect = \
lambda path: path == src_disk_info_path
self.drvr.migrate_disk_and_power_off(context.get_admin_context(),
instance, mock.sentinel,
flavor_obj, None)
self.assertTrue(mock_exists.called)
dst_disk_info_path = os.path.join(instance_base, 'disk.info')
mock_copy.assert_any_call(src_disk_info_path, dst_disk_info_path,
host=mock.sentinel, on_execute=mock.ANY,
on_completion=mock.ANY)
def test_wait_for_running(self):
def fake_get_info(instance):
if instance['name'] == "not_found":
raise exception.InstanceNotFound(instance_id=instance['uuid'])
elif instance['name'] == "running":
return hardware.InstanceInfo(state=power_state.RUNNING)
else:
return hardware.InstanceInfo(state=power_state.SHUTDOWN)
self.stubs.Set(self.drvr, 'get_info',
fake_get_info)
# instance not found case
self.assertRaises(exception.InstanceNotFound,
self.drvr._wait_for_running,
{'name': 'not_found',
'uuid': 'not_found_uuid'})
# instance is running case
self.assertRaises(loopingcall.LoopingCallDone,
self.drvr._wait_for_running,
{'name': 'running',
'uuid': 'running_uuid'})
# else case
self.drvr._wait_for_running({'name': 'else',
'uuid': 'other_uuid'})
def test_disk_size_from_instance_disk_info(self):
flavor_data = {'root_gb': 10, 'ephemeral_gb': 20, 'swap_gb': 30}
inst = objects.Instance(flavor=objects.Flavor(**flavor_data))
self.assertEqual(10 * units.Gi,
self.drvr._disk_size_from_instance(inst, 'disk'))
self.assertEqual(20 * units.Gi,
self.drvr._disk_size_from_instance(inst,
'disk.local'))
self.assertEqual(0,
self.drvr._disk_size_from_instance(inst, 'disk.swap'))
@mock.patch('nova.utils.execute')
def test_disk_raw_to_qcow2(self, mock_execute):
path = '/test/disk'
_path_qcow = path + '_qcow'
self.drvr._disk_raw_to_qcow2(path)
mock_execute.assert_has_calls([
mock.call('qemu-img', 'convert', '-f', 'raw',
'-O', 'qcow2', path, _path_qcow),
mock.call('mv', _path_qcow, path)])
@mock.patch('nova.utils.execute')
def test_disk_qcow2_to_raw(self, mock_execute):
path = '/test/disk'
_path_raw = path + '_raw'
self.drvr._disk_qcow2_to_raw(path)
mock_execute.assert_has_calls([
mock.call('qemu-img', 'convert', '-f', 'qcow2',
'-O', 'raw', path, _path_raw),
mock.call('mv', _path_raw, path)])
@mock.patch('nova.virt.disk.api.extend')
def test_disk_resize_raw(self, mock_extend):
image = imgmodel.LocalFileImage("/test/disk",
imgmodel.FORMAT_RAW)
self.drvr._disk_resize(image, 50)
mock_extend.assert_called_once_with(image, 50)
@mock.patch('nova.virt.disk.api.can_resize_image')
@mock.patch('nova.virt.disk.api.is_image_extendable')
@mock.patch('nova.virt.disk.api.extend')
def test_disk_resize_qcow2(
self, mock_extend, mock_can_resize, mock_is_image_extendable):
with test.nested(
mock.patch.object(
self.drvr, '_disk_qcow2_to_raw'),
mock.patch.object(
self.drvr, '_disk_raw_to_qcow2'))\
as (mock_disk_qcow2_to_raw, mock_disk_raw_to_qcow2):
mock_can_resize.return_value = True
mock_is_image_extendable.return_value = True
imageqcow2 = imgmodel.LocalFileImage("/test/disk",
imgmodel.FORMAT_QCOW2)
imageraw = imgmodel.LocalFileImage("/test/disk",
imgmodel.FORMAT_RAW)
self.drvr._disk_resize(imageqcow2, 50)
mock_disk_qcow2_to_raw.assert_called_once_with(imageqcow2.path)
mock_extend.assert_called_once_with(imageraw, 50)
mock_disk_raw_to_qcow2.assert_called_once_with(imageqcow2.path)
def _test_finish_migration(self, power_on, resize_instance=False):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.finish_migration.
"""
powered_on = power_on
self.fake_create_domain_called = False
self.fake_disk_resize_called = False
create_image_called = [False]
def fake_to_xml(context, instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None, write_to_disk=False):
return ""
def fake_plug_vifs(instance, network_info):
pass
def fake_create_image(context, inst,
disk_mapping, suffix='',
disk_images=None, network_info=None,
block_device_info=None, inject_files=True,
fallback_from_host=None):
self.assertFalse(inject_files)
create_image_called[0] = True
def fake_create_domain_and_network(
context, xml, instance, network_info, disk_info,
block_device_info=None, power_on=True, reboot=False,
vifs_already_plugged=False, post_xml_callback=None):
self.fake_create_domain_called = True
self.assertEqual(powered_on, power_on)
self.assertTrue(vifs_already_plugged)
def fake_enable_hairpin():
pass
def fake_execute(*args, **kwargs):
pass
def fake_get_info(instance):
if powered_on:
return hardware.InstanceInfo(state=power_state.RUNNING)
else:
return hardware.InstanceInfo(state=power_state.SHUTDOWN)
def fake_disk_resize(image, size):
# Assert that _create_image is called before disk resize,
# otherwise we might be trying to resize a disk whose backing
# file hasn't been fetched, yet.
self.assertTrue(create_image_called[0])
self.fake_disk_resize_called = True
self.flags(use_cow_images=True)
self.stubs.Set(self.drvr, '_disk_resize',
fake_disk_resize)
self.stubs.Set(self.drvr, '_get_guest_xml', fake_to_xml)
self.stubs.Set(self.drvr, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(self.drvr, '_create_image',
fake_create_image)
self.stubs.Set(self.drvr, '_create_domain_and_network',
fake_create_domain_and_network)
self.stubs.Set(nova.virt.libvirt.guest.Guest, 'enable_hairpin',
fake_enable_hairpin)
self.stubs.Set(utils, 'execute', fake_execute)
fw = base_firewall.NoopFirewallDriver()
self.stubs.Set(self.drvr, 'firewall_driver', fw)
self.stubs.Set(self.drvr, 'get_info',
fake_get_info)
instance = self._create_instance({'config_drive': str(True)})
migration = objects.Migration()
migration.source_compute = 'fake-source-compute'
migration.dest_compute = 'fake-dest-compute'
migration.source_node = 'fake-source-node'
migration.dest_node = 'fake-dest-node'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
# Source disks are raw to test conversion
disk_info = fake_disk_info_json(instance, type='raw')
with test.nested(
mock.patch.object(self.drvr, '_disk_raw_to_qcow2',
autospec=True),
mock.patch.object(self.drvr, '_ensure_console_log_for_instance')
) as (mock_raw_to_qcow2, mock_ensure_console_log):
self.drvr.finish_migration(
context.get_admin_context(), migration, instance,
disk_info, [], image_meta,
resize_instance, None, power_on)
mock_ensure_console_log.assert_called_once_with(instance)
# Assert that we converted the root and ephemeral disks
instance_path = libvirt_utils.get_instance_path(instance)
convert_calls = [mock.call(os.path.join(instance_path, name))
for name in ('disk', 'disk.local')]
mock_raw_to_qcow2.assert_has_calls(convert_calls, any_order=True)
# Implicitly assert that we did not convert the config disk
self.assertEqual(len(convert_calls), mock_raw_to_qcow2.call_count)
self.assertTrue(self.fake_create_domain_called)
self.assertEqual(
resize_instance, self.fake_disk_resize_called)
def test_finish_migration_resize(self):
self._test_finish_migration(True, resize_instance=True)
def test_finish_migration_power_on(self):
self._test_finish_migration(True)
def test_finish_migration_power_off(self):
self._test_finish_migration(False)
def _test_finish_revert_migration(self, power_on):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.finish_revert_migration.
"""
powered_on = power_on
self.fake_create_domain_called = False
def fake_execute(*args, **kwargs):
pass
def fake_plug_vifs(instance, network_info):
pass
def fake_create_domain(context, xml, instance, network_info,
disk_info, block_device_info=None,
power_on=None,
vifs_already_plugged=None):
self.fake_create_domain_called = True
self.assertEqual(powered_on, power_on)
self.assertTrue(vifs_already_plugged)
return mock.MagicMock()
def fake_enable_hairpin():
pass
def fake_get_info(instance):
if powered_on:
return hardware.InstanceInfo(state=power_state.RUNNING)
else:
return hardware.InstanceInfo(state=power_state.SHUTDOWN)
def fake_to_xml(context, instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None):
return ""
self.stubs.Set(self.drvr, '_get_guest_xml', fake_to_xml)
self.stubs.Set(self.drvr, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(utils, 'execute', fake_execute)
fw = base_firewall.NoopFirewallDriver()
self.stubs.Set(self.drvr, 'firewall_driver', fw)
self.stubs.Set(self.drvr, '_create_domain_and_network',
fake_create_domain)
self.stubs.Set(nova.virt.libvirt.guest.Guest, 'enable_hairpin',
fake_enable_hairpin)
self.stubs.Set(self.drvr, 'get_info',
fake_get_info)
self.stubs.Set(utils, 'get_image_from_system_metadata',
lambda *a: self.test_image_meta)
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
ins_ref = self._create_instance()
os.mkdir(os.path.join(tmpdir, ins_ref['name']))
libvirt_xml_path = os.path.join(tmpdir,
ins_ref['name'],
'libvirt.xml')
f = open(libvirt_xml_path, 'w')
f.close()
self.drvr.finish_revert_migration(
context.get_admin_context(), ins_ref,
[], None, power_on)
self.assertTrue(self.fake_create_domain_called)
def test_finish_revert_migration_power_on(self):
self._test_finish_revert_migration(True)
def test_finish_revert_migration_power_off(self):
self._test_finish_revert_migration(False)
def _test_finish_revert_migration_after_crash(self, backup_made=True,
del_inst_failed=False):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
context = 'fake_context'
ins_ref = self._create_instance()
with test.nested(
mock.patch.object(os.path, 'exists', return_value=backup_made),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(drvr, '_get_guest_xml'),
mock.patch.object(shutil, 'rmtree'),
mock.patch.object(loopingcall, 'FixedIntervalLoopingCall'),
) as (mock_stat, mock_path, mock_exec, mock_cdn, mock_ggx,
mock_rmtree, mock_looping_call):
mock_path.return_value = '/fake/foo'
if del_inst_failed:
mock_rmtree.side_effect = OSError(errno.ENOENT,
'test exception')
drvr.finish_revert_migration(context, ins_ref, [])
if backup_made:
mock_exec.assert_called_once_with('mv', '/fake/foo_resize',
'/fake/foo')
else:
self.assertFalse(mock_exec.called)
def test_finish_revert_migration_after_crash(self):
self._test_finish_revert_migration_after_crash(backup_made=True)
def test_finish_revert_migration_after_crash_before_new(self):
self._test_finish_revert_migration_after_crash(backup_made=True)
def test_finish_revert_migration_after_crash_before_backup(self):
self._test_finish_revert_migration_after_crash(backup_made=False)
def test_finish_revert_migration_after_crash_delete_failed(self):
self._test_finish_revert_migration_after_crash(backup_made=True,
del_inst_failed=True)
def test_finish_revert_migration_preserves_disk_bus(self):
def fake_get_guest_xml(context, instance, network_info, disk_info,
image_meta, block_device_info=None):
self.assertEqual('ide', disk_info['disk_bus'])
image_meta = {"disk_format": "raw",
"properties": {"hw_disk_bus": "ide"}}
instance = self._create_instance()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(drvr, 'image_backend'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(utils, 'get_image_from_system_metadata',
return_value=image_meta),
mock.patch.object(drvr, '_get_guest_xml',
side_effect=fake_get_guest_xml)):
drvr.finish_revert_migration('', instance, None, power_on=False)
def test_finish_revert_migration_snap_backend(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
ins_ref = self._create_instance()
with test.nested(
mock.patch.object(utils, 'get_image_from_system_metadata'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(drvr, '_get_guest_xml')) as (
mock_image, mock_cdn, mock_ggx):
mock_image.return_value = {'disk_format': 'raw'}
drvr.finish_revert_migration('', ins_ref, None, power_on=False)
drvr.image_backend.rollback_to_snap.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME)
drvr.image_backend.remove_snap.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True)
def test_finish_revert_migration_snap_backend_snapshot_not_found(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
ins_ref = self._create_instance()
with test.nested(
mock.patch.object(rbd_utils, 'RBDDriver'),
mock.patch.object(utils, 'get_image_from_system_metadata'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(drvr, '_get_guest_xml')) as (
mock_rbd, mock_image, mock_cdn, mock_ggx):
mock_image.return_value = {'disk_format': 'raw'}
mock_rbd.rollback_to_snap.side_effect = exception.SnapshotNotFound(
snapshot_id='testing')
drvr.finish_revert_migration('', ins_ref, None, power_on=False)
drvr.image_backend.remove_snap.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True)
def test_finish_revert_migration_snap_backend_image_does_not_exist(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
drvr.image_backend.exists.return_value = False
ins_ref = self._create_instance()
with test.nested(
mock.patch.object(rbd_utils, 'RBDDriver'),
mock.patch.object(utils, 'get_image_from_system_metadata'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(drvr, '_get_guest_xml')) as (
mock_rbd, mock_image, mock_cdn, mock_ggx):
mock_image.return_value = {'disk_format': 'raw'}
drvr.finish_revert_migration('', ins_ref, None, power_on=False)
self.assertFalse(drvr.image_backend.rollback_to_snap.called)
self.assertFalse(drvr.image_backend.remove_snap.called)
def test_cleanup_failed_migration(self):
self.mox.StubOutWithMock(shutil, 'rmtree')
shutil.rmtree('/fake/inst')
self.mox.ReplayAll()
self.drvr._cleanup_failed_migration('/fake/inst')
def test_confirm_migration(self):
ins_ref = self._create_instance()
self.mox.StubOutWithMock(self.drvr, "_cleanup_resize")
self.drvr._cleanup_resize(ins_ref,
_fake_network_info(self, 1))
self.mox.ReplayAll()
self.drvr.confirm_migration("migration_ref", ins_ref,
_fake_network_info(self, 1))
def test_cleanup_resize_same_host(self):
CONF.set_override('policy_dirs', [], group='oslo_policy')
ins_ref = self._create_instance({'host': CONF.host})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
with test.nested(
mock.patch.object(os.path, 'exists'),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute')) as (
mock_exists, mock_get_path, mock_exec):
mock_exists.return_value = True
mock_get_path.return_value = '/fake/inst'
drvr._cleanup_resize(ins_ref, _fake_network_info(self, 1))
mock_get_path.assert_called_once_with(ins_ref)
mock_exec.assert_called_once_with('rm', '-rf', '/fake/inst_resize',
delay_on_retry=True, attempts=5)
def test_cleanup_resize_not_same_host(self):
CONF.set_override('policy_dirs', [], group='oslo_policy')
host = 'not' + CONF.host
ins_ref = self._create_instance({'host': host})
fake_net = _fake_network_info(self, 1)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
with test.nested(
mock.patch.object(os.path, 'exists'),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr, '_undefine_domain'),
mock.patch.object(drvr, 'unplug_vifs'),
mock.patch.object(drvr, 'unfilter_instance')
) as (mock_exists, mock_get_path, mock_exec, mock_undef,
mock_unplug, mock_unfilter):
mock_exists.return_value = True
mock_get_path.return_value = '/fake/inst'
drvr._cleanup_resize(ins_ref, fake_net)
mock_get_path.assert_called_once_with(ins_ref)
mock_exec.assert_called_once_with('rm', '-rf', '/fake/inst_resize',
delay_on_retry=True, attempts=5)
mock_undef.assert_called_once_with(ins_ref)
mock_unplug.assert_called_once_with(ins_ref, fake_net)
mock_unfilter.assert_called_once_with(ins_ref, fake_net)
def test_cleanup_resize_snap_backend(self):
CONF.set_override('policy_dirs', [], group='oslo_policy')
ins_ref = self._create_instance({'host': CONF.host})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
with test.nested(
mock.patch.object(os.path, 'exists'),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr.image_backend, 'remove_snap')) as (
mock_exists, mock_get_path, mock_exec, mock_remove):
mock_exists.return_value = True
mock_get_path.return_value = '/fake/inst'
drvr._cleanup_resize(ins_ref, _fake_network_info(self, 1))
mock_get_path.assert_called_once_with(ins_ref)
mock_exec.assert_called_once_with('rm', '-rf', '/fake/inst_resize',
delay_on_retry=True, attempts=5)
mock_remove.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True)
def test_cleanup_resize_snap_backend_image_does_not_exist(self):
CONF.set_override('policy_dirs', [], group='oslo_policy')
ins_ref = self._create_instance({'host': CONF.host})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
drvr.image_backend.exists.return_value = False
with test.nested(
mock.patch.object(os.path, 'exists'),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr.image_backend, 'remove_snap')) as (
mock_exists, mock_get_path, mock_exec, mock_remove):
mock_exists.return_value = True
mock_get_path.return_value = '/fake/inst'
drvr._cleanup_resize(ins_ref, _fake_network_info(self, 1))
mock_get_path.assert_called_once_with(ins_ref)
mock_exec.assert_called_once_with('rm', '-rf', '/fake/inst_resize',
delay_on_retry=True, attempts=5)
self.assertFalse(mock_remove.called)
def test_get_instance_disk_info_exception(self):
instance = self._create_instance()
class FakeExceptionDomain(FakeVirtDomain):
def __init__(self):
super(FakeExceptionDomain, self).__init__()
def XMLDesc(self, flags):
raise fakelibvirt.libvirtError("Libvirt error")
def fake_get_domain(self, instance):
return FakeExceptionDomain()
self.stubs.Set(host.Host, 'get_domain',
fake_get_domain)
self.assertRaises(exception.InstanceNotFound,
self.drvr.get_instance_disk_info,
instance)
@mock.patch('os.path.exists')
@mock.patch.object(lvm, 'list_volumes')
def test_lvm_disks(self, listlvs, exists):
instance = objects.Instance(uuid=uuids.instance, id=1)
self.flags(images_volume_group='vols', group='libvirt')
exists.return_value = True
listlvs.return_value = ['%s_foo' % uuids.instance,
'other-uuid_foo']
disks = self.drvr._lvm_disks(instance)
self.assertEqual(['/dev/vols/%s_foo' % uuids.instance], disks)
def test_is_booted_from_volume(self):
func = libvirt_driver.LibvirtDriver._is_booted_from_volume
instance, disk_mapping = {}, {}
self.assertTrue(func(instance, disk_mapping))
disk_mapping['disk'] = 'map'
self.assertTrue(func(instance, disk_mapping))
instance['image_ref'] = 'uuid'
self.assertFalse(func(instance, disk_mapping))
@mock.patch('nova.virt.libvirt.driver.imagebackend')
@mock.patch(
'nova.virt.libvirt.driver.LibvirtDriver._try_fetch_image_cache')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._inject_data')
@mock.patch('nova.virt.libvirt.driver.imagecache')
def test_data_not_injects_with_configdrive(self, mock_image, mock_inject,
mock_fetch, mock_backend):
self.flags(inject_partition=-1, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# config_drive is True by default, configdrive.required_by()
# returns True
instance_ref = self._create_instance()
disk_images = {'image_id': None}
drvr._create_and_inject_local_root(self.context, instance_ref, False,
'', disk_images, [], None, [], True, None)
self.assertFalse(mock_inject.called)
@mock.patch('nova.virt.netutils.get_injected_network_template')
@mock.patch('nova.virt.disk.api.inject_data')
@mock.patch.object(libvirt_driver.LibvirtDriver, "_conn")
def _test_inject_data(self, driver_params, path, disk_params,
mock_conn, disk_inject_data, inj_network,
called=True):
class ImageBackend(object):
path = '/path'
def get_model(self, connection):
return imgmodel.LocalFileImage(self.path,
imgmodel.FORMAT_RAW)
def fake_inj_network(*args, **kwds):
return args[0] or None
inj_network.side_effect = fake_inj_network
image_backend = ImageBackend()
image_backend.path = path
with mock.patch.object(
self.drvr.image_backend,
'image',
return_value=image_backend):
self.flags(inject_partition=0, group='libvirt')
self.drvr._inject_data(image_backend, **driver_params)
if called:
disk_inject_data.assert_called_once_with(
mock.ANY,
*disk_params,
partition=None, mandatory=('files',))
self.assertEqual(disk_inject_data.called, called)
def _test_inject_data_default_driver_params(self, **params):
return {
'instance': self._create_instance(params=params),
'network_info': None,
'admin_pass': None,
'files': None
}
def test_inject_data_adminpass(self):
self.flags(inject_password=True, group='libvirt')
driver_params = self._test_inject_data_default_driver_params()
driver_params['admin_pass'] = 'foobar'
disk_params = [
None, # key
None, # net
{}, # metadata
'foobar', # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/path", disk_params)
# Test with the configuration setted to false.
self.flags(inject_password=False, group='libvirt')
self._test_inject_data(driver_params, "/path",
disk_params, called=False)
def test_inject_data_key(self):
driver_params = self._test_inject_data_default_driver_params()
driver_params['instance']['key_data'] = 'key-content'
self.flags(inject_key=True, group='libvirt')
disk_params = [
'key-content', # key
None, # net
{}, # metadata
None, # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/path", disk_params)
# Test with the configuration setted to false.
self.flags(inject_key=False, group='libvirt')
self._test_inject_data(driver_params, "/path",
disk_params, called=False)
def test_inject_data_metadata(self):
instance_metadata = {'metadata': {'data': 'foo'}}
driver_params = self._test_inject_data_default_driver_params(
**instance_metadata
)
disk_params = [
None, # key
None, # net
{'data': 'foo'}, # metadata
None, # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/path", disk_params)
def test_inject_data_files(self):
driver_params = self._test_inject_data_default_driver_params()
driver_params['files'] = ['file1', 'file2']
disk_params = [
None, # key
None, # net
{}, # metadata
None, # admin_pass
['file1', 'file2'], # files
]
self._test_inject_data(driver_params, "/path", disk_params)
def test_inject_data_net(self):
driver_params = self._test_inject_data_default_driver_params()
driver_params['network_info'] = {'net': 'eno1'}
disk_params = [
None, # key
{'net': 'eno1'}, # net
{}, # metadata
None, # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/path", disk_params)
def test_inject_not_exist_image(self):
driver_params = self._test_inject_data_default_driver_params()
disk_params = [
'key-content', # key
None, # net
None, # metadata
None, # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/fail/path",
disk_params, called=False)
def _test_attach_detach_interface(self, method, power_state,
expected_flags):
instance = self._create_instance()
network_info = _fake_network_info(self, 1)
domain = FakeVirtDomain()
self.mox.StubOutWithMock(host.Host, 'get_domain')
self.mox.StubOutWithMock(self.drvr.firewall_driver,
'setup_basic_filtering')
self.mox.StubOutWithMock(domain, 'attachDeviceFlags')
self.mox.StubOutWithMock(domain, 'info')
host.Host.get_domain(instance).AndReturn(domain)
if method == 'attach_interface':
self.drvr.firewall_driver.setup_basic_filtering(
instance, [network_info[0]])
fake_image_meta = objects.ImageMeta.from_dict(
{'id': instance.image_ref})
expected = self.drvr.vif_driver.get_config(
instance, network_info[0], fake_image_meta, instance.flavor,
CONF.libvirt.virt_type, self.drvr._host)
self.mox.StubOutWithMock(self.drvr.vif_driver,
'get_config')
self.drvr.vif_driver.get_config(
instance, network_info[0],
mox.IsA(objects.ImageMeta),
mox.IsA(objects.Flavor),
CONF.libvirt.virt_type,
self.drvr._host).AndReturn(expected)
domain.info().AndReturn([power_state, 1, 2, 3, 4])
if method == 'attach_interface':
domain.attachDeviceFlags(expected.to_xml(), flags=expected_flags)
elif method == 'detach_interface':
domain.detachDeviceFlags(expected.to_xml(), expected_flags)
self.mox.ReplayAll()
if method == 'attach_interface':
self.drvr.attach_interface(
instance, fake_image_meta, network_info[0])
elif method == 'detach_interface':
self.drvr.detach_interface(
instance, network_info[0])
self.mox.VerifyAll()
def test_attach_interface_with_running_instance(self):
self._test_attach_detach_interface(
'attach_interface', power_state.RUNNING,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def test_attach_interface_with_pause_instance(self):
self._test_attach_detach_interface(
'attach_interface', power_state.PAUSED,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def test_attach_interface_with_shutdown_instance(self):
self._test_attach_detach_interface(
'attach_interface', power_state.SHUTDOWN,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG))
def test_detach_interface_with_running_instance(self):
self._test_attach_detach_interface(
'detach_interface', power_state.RUNNING,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def test_detach_interface_with_pause_instance(self):
self._test_attach_detach_interface(
'detach_interface', power_state.PAUSED,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def test_detach_interface_with_shutdown_instance(self):
self._test_attach_detach_interface(
'detach_interface', power_state.SHUTDOWN,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG))
@mock.patch('nova.virt.libvirt.driver.LOG')
def test_detach_interface_device_not_found(self, mock_log):
# Asserts that we don't log an error when the interface device is not
# found on the guest after a libvirt error during detach.
instance = self._create_instance()
vif = _fake_network_info(self, 1)[0]
guest = mock.Mock(spec='nova.virt.libvirt.guest.Guest')
guest.get_power_state = mock.Mock()
self.drvr._host.get_guest = mock.Mock(return_value=guest)
self.drvr.vif_driver = mock.Mock()
error = fakelibvirt.libvirtError(
'no matching network device was found')
error.err = (fakelibvirt.VIR_ERR_OPERATION_FAILED,)
guest.detach_device = mock.Mock(side_effect=error)
# mock out that get_interface_by_mac doesn't find the interface
guest.get_interface_by_mac = mock.Mock(return_value=None)
self.drvr.detach_interface(instance, vif)
guest.get_interface_by_mac.assert_called_once_with(vif['address'])
# an error shouldn't be logged, but a warning should be logged
self.assertFalse(mock_log.error.called)
self.assertEqual(1, mock_log.warning.call_count)
self.assertIn('the device is no longer found on the guest',
six.text_type(mock_log.warning.call_args[0]))
@mock.patch('nova.virt.libvirt.utils.write_to_file')
# NOTE(mdbooth): The following 4 mocks are required to execute
# get_guest_xml().
@mock.patch.object(libvirt_driver.LibvirtDriver, '_set_host_enabled')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_build_device_metadata')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_supports_direct_io')
@mock.patch('nova.api.metadata.base.InstanceMetadata')
def _test_rescue(self, instance,
mock_instance_metadata, mock_supports_direct_io,
mock_build_device_metadata, mock_set_host_enabled,
mock_write_to_file,
exists=None):
self.flags(instances_path=self.useFixture(fixtures.TempDir()).path)
mock_build_device_metadata.return_value = None
mock_supports_direct_io.return_value = True
backend = self.useFixture(
fake_imagebackend.ImageBackendFixture(exists=exists))
image_meta = objects.ImageMeta.from_dict(
{'id': uuids.image_id, 'name': 'fake'})
network_info = _fake_network_info(self, 1)
rescue_password = 'fake_password'
domain_xml = [None]
def fake_create_domain(xml=None, domain=None, power_on=True,
pause=False, post_xml_callback=None):
domain_xml[0] = xml
if post_xml_callback is not None:
post_xml_callback()
with mock.patch.object(
self.drvr, '_create_domain',
side_effect=fake_create_domain) as mock_create_domain:
self.drvr.rescue(self.context, instance,
network_info, image_meta, rescue_password)
self.assertTrue(mock_create_domain.called)
return backend, etree.fromstring(domain_xml[0])
def test_rescue(self):
instance = self._create_instance({'config_drive': None})
backend, doc = self._test_rescue(instance)
# Assert that we created the expected set of disks, and no others
self.assertEqual(['disk.rescue', 'kernel.rescue', 'ramdisk.rescue'],
sorted(backend.created_disks.keys()))
disks = backend.disks
kernel_ramdisk = [disks[name + '.rescue']
for name in ('kernel', 'ramdisk')]
# Assert that kernel and ramdisk were both created as raw
for disk in kernel_ramdisk:
self.assertEqual('raw', disk.image_type)
# Assert that the root rescue disk was created as the default type
self.assertIsNone(disks['disk.rescue'].image_type)
# We expect the generated domain to contain disk.rescue and
# disk, in that order
expected_domain_disk_paths = map(
lambda name: disks[name].path, ('disk.rescue', 'disk'))
domain_disk_paths = doc.xpath('devices/disk/source/@file')
self.assertEqual(expected_domain_disk_paths, domain_disk_paths)
# The generated domain xml should contain the rescue kernel
# and ramdisk
expected_kernel_ramdisk_paths = map(
lambda disk: os.path.join(CONF.instances_path, disk.path),
kernel_ramdisk)
kernel_ramdisk_paths = \
doc.xpath('os/*[self::initrd|self::kernel]/text()')
self.assertEqual(expected_kernel_ramdisk_paths,
kernel_ramdisk_paths)
@mock.patch('nova.virt.configdrive.ConfigDriveBuilder._make_iso9660')
def test_rescue_config_drive(self, mock_mkisofs):
instance = self._create_instance({'config_drive': str(True)})
backend, doc = self._test_rescue(
instance, exists=lambda name: name != 'disk.config.rescue')
# Assert that we created the expected set of disks, and no others
self.assertEqual(['disk.config.rescue', 'disk.rescue', 'kernel.rescue',
'ramdisk.rescue'],
sorted(backend.created_disks.keys()))
disks = backend.disks
config_disk = disks['disk.config.rescue']
kernel_ramdisk = [disks[name + '.rescue']
for name in ('kernel', 'ramdisk')]
# Assert that we imported the config disk
self.assertTrue(config_disk.import_file.called)
# Assert that the config disk, kernel and ramdisk were created as raw
for disk in [config_disk] + kernel_ramdisk:
self.assertEqual('raw', disk.image_type)
# Assert that the root rescue disk was created as the default type
self.assertIsNone(disks['disk.rescue'].image_type)
# We expect the generated domain to contain disk.rescue, disk, and
# disk.config.rescue in that order
expected_domain_disk_paths = map(
lambda name: disks[name].path, ('disk.rescue', 'disk',
'disk.config.rescue'))
domain_disk_paths = doc.xpath('devices/disk/source/@file')
self.assertEqual(expected_domain_disk_paths, domain_disk_paths)
# The generated domain xml should contain the rescue kernel
# and ramdisk
expected_kernel_ramdisk_paths = map(
lambda disk: os.path.join(CONF.instances_path, disk.path),
kernel_ramdisk)
kernel_ramdisk_paths = \
doc.xpath('os/*[self::initrd|self::kernel]/text()')
self.assertEqual(expected_kernel_ramdisk_paths,
kernel_ramdisk_paths)
@mock.patch.object(libvirt_utils, 'get_instance_path')
@mock.patch.object(libvirt_utils, 'load_file')
@mock.patch.object(host.Host, "get_domain")
def test_unrescue(self, mock_get_domain, mock_load_file,
mock_get_instance_path):
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='block' device='disk'>"
"<source dev='/dev/some-vg/some-lv'/>"
"<target dev='vda' bus='virtio'/></disk>"
"</devices></domain>")
mock_get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
fake_dom = FakeVirtDomain(fake_xml=dummyxml)
mock_get_domain.return_value = fake_dom
mock_load_file.return_value = "fake_unrescue_xml"
unrescue_xml_path = os.path.join('/path', 'unrescue.xml')
xml_path = os.path.join('/path', 'libvirt.xml')
rescue_file = os.path.join('/path', 'rescue.file')
rescue_dir = os.path.join('/path', 'rescue.dir')
def isdir_sideeffect(*args, **kwargs):
if args[0] == '/path/rescue.file':
return False
if args[0] == '/path/rescue.dir':
return True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(libvirt_utils, 'write_to_file'),
mock.patch.object(drvr, '_destroy'),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(libvirt_utils, 'file_delete'),
mock.patch.object(shutil, 'rmtree'),
mock.patch.object(os.path, "isdir",
side_effect=isdir_sideeffect),
mock.patch.object(drvr, '_lvm_disks',
return_value=['lvm.rescue']),
mock.patch.object(lvm, 'remove_volumes'),
mock.patch.object(glob, 'iglob',
return_value=[rescue_file, rescue_dir])
) as (mock_write, mock_destroy, mock_create, mock_del,
mock_rmtree, mock_isdir, mock_lvm_disks,
mock_remove_volumes, mock_glob):
drvr.unrescue(instance, None)
mock_write.assert_called_once_with(xml_path, "fake_unrescue_xml")
mock_destroy.assert_called_once_with(instance)
mock_create.assert_called_once_with("fake_unrescue_xml",
fake_dom)
self.assertEqual(2, mock_del.call_count)
self.assertEqual(unrescue_xml_path,
mock_del.call_args_list[0][0][0])
self.assertEqual(1, mock_rmtree.call_count)
self.assertEqual(rescue_dir, mock_rmtree.call_args_list[0][0][0])
self.assertEqual(rescue_file, mock_del.call_args_list[1][0][0])
mock_remove_volumes.assert_called_once_with(['lvm.rescue'])
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files(self, get_instance_path, exists, exe,
shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
exe.assert_called_with('mv', '/path', '/path_del')
shutil.assert_called_with('/path_del')
self.assertTrue(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('os.kill')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_kill_running(
self, get_instance_path, kill, exists, exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
self.drvr.job_tracker.jobs[instance.uuid] = [3, 4]
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
exe.assert_called_with('mv', '/path', '/path_del')
kill.assert_has_calls([mock.call(3, signal.SIGKILL), mock.call(3, 0),
mock.call(4, signal.SIGKILL), mock.call(4, 0)])
shutil.assert_called_with('/path_del')
self.assertTrue(result)
self.assertNotIn(instance.uuid, self.drvr.job_tracker.jobs)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_resize(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = [Exception(), None]
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')]
self.assertEqual(expected, exe.mock_calls)
shutil.assert_called_with('/path_del')
self.assertTrue(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_failed(self, get_instance_path, exists, exe,
shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
exists.side_effect = [False, False, True, True]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
exe.assert_called_with('mv', '/path', '/path_del')
shutil.assert_called_with('/path_del')
self.assertFalse(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_mv_failed(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = Exception()
exists.side_effect = [True, True]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')] * 2
self.assertEqual(expected, exe.mock_calls)
self.assertFalse(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_resume(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = Exception()
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')] * 2
self.assertEqual(expected, exe.mock_calls)
self.assertTrue(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_none(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = Exception()
exists.side_effect = [False, False, False, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')] * 2
self.assertEqual(expected, exe.mock_calls)
self.assertEqual(0, len(shutil.mock_calls))
self.assertTrue(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_concurrent(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = [Exception(), Exception(), None]
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')]
expected.append(expected[0])
self.assertEqual(expected, exe.mock_calls)
shutil.assert_called_with('/path_del')
self.assertTrue(result)
def _assert_on_id_map(self, idmap, klass, start, target, count):
self.assertIsInstance(idmap, klass)
self.assertEqual(start, idmap.start)
self.assertEqual(target, idmap.target)
self.assertEqual(count, idmap.count)
def test_get_id_maps(self):
self.flags(virt_type="lxc", group="libvirt")
CONF.libvirt.virt_type = "lxc"
CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"]
CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"]
idmaps = self.drvr._get_guest_idmaps()
self.assertEqual(len(idmaps), 4)
self._assert_on_id_map(idmaps[0],
vconfig.LibvirtConfigGuestUIDMap,
0, 10000, 1)
self._assert_on_id_map(idmaps[1],
vconfig.LibvirtConfigGuestUIDMap,
1, 20000, 10)
self._assert_on_id_map(idmaps[2],
vconfig.LibvirtConfigGuestGIDMap,
0, 10000, 1)
self._assert_on_id_map(idmaps[3],
vconfig.LibvirtConfigGuestGIDMap,
1, 20000, 10)
def test_get_id_maps_not_lxc(self):
CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"]
CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"]
idmaps = self.drvr._get_guest_idmaps()
self.assertEqual(0, len(idmaps))
def test_get_id_maps_only_uid(self):
self.flags(virt_type="lxc", group="libvirt")
CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"]
CONF.libvirt.gid_maps = []
idmaps = self.drvr._get_guest_idmaps()
self.assertEqual(2, len(idmaps))
self._assert_on_id_map(idmaps[0],
vconfig.LibvirtConfigGuestUIDMap,
0, 10000, 1)
self._assert_on_id_map(idmaps[1],
vconfig.LibvirtConfigGuestUIDMap,
1, 20000, 10)
def test_get_id_maps_only_gid(self):
self.flags(virt_type="lxc", group="libvirt")
CONF.libvirt.uid_maps = []
CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"]
idmaps = self.drvr._get_guest_idmaps()
self.assertEqual(2, len(idmaps))
self._assert_on_id_map(idmaps[0],
vconfig.LibvirtConfigGuestGIDMap,
0, 10000, 1)
self._assert_on_id_map(idmaps[1],
vconfig.LibvirtConfigGuestGIDMap,
1, 20000, 10)
def test_instance_on_disk(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(uuid=uuids.instance, id=1)
self.assertFalse(drvr.instance_on_disk(instance))
def test_instance_on_disk_rbd(self):
self.flags(images_type='rbd', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(uuid=uuids.instance, id=1)
self.assertTrue(drvr.instance_on_disk(instance))
def test_get_disk_xml(self):
dom_xml = """
<domain type="kvm">
<devices>
<disk type="file">
<source file="disk1_file"/>
<target dev="vda" bus="virtio"/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
<disk type="block">
<source dev="/path/to/dev/1"/>
<target dev="vdb" bus="virtio" serial="1234"/>
</disk>
</devices>
</domain>
"""
diska_xml = """<disk type="file" device="disk">
<source file="disk1_file"/>
<target bus="virtio" dev="vda"/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>"""
diskb_xml = """<disk type="block" device="disk">
<source dev="/path/to/dev/1"/>
<target bus="virtio" dev="vdb"/>
</disk>"""
dom = mock.MagicMock()
dom.XMLDesc.return_value = dom_xml
guest = libvirt_guest.Guest(dom)
# NOTE(gcb): etree.tostring(node) returns an extra line with
# some white spaces, need to strip it.
actual_diska_xml = guest.get_disk('vda').to_xml()
self.assertEqual(diska_xml.strip(), actual_diska_xml.strip())
actual_diskb_xml = guest.get_disk('vdb').to_xml()
self.assertEqual(diskb_xml.strip(), actual_diskb_xml.strip())
self.assertIsNone(guest.get_disk('vdc'))
def test_vcpu_model_from_config(self):
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
vcpu_model = drv._cpu_config_to_vcpu_model(None, None)
self.assertIsNone(vcpu_model)
cpu = vconfig.LibvirtConfigGuestCPU()
feature1 = vconfig.LibvirtConfigGuestCPUFeature()
feature2 = vconfig.LibvirtConfigGuestCPUFeature()
feature1.name = 'sse'
feature1.policy = cpumodel.POLICY_REQUIRE
feature2.name = 'aes'
feature2.policy = cpumodel.POLICY_REQUIRE
cpu.features = set([feature1, feature2])
cpu.mode = cpumodel.MODE_CUSTOM
cpu.sockets = 1
cpu.cores = 2
cpu.threads = 4
vcpu_model = drv._cpu_config_to_vcpu_model(cpu, None)
self.assertEqual(cpumodel.MATCH_EXACT, vcpu_model.match)
self.assertEqual(cpumodel.MODE_CUSTOM, vcpu_model.mode)
self.assertEqual(4, vcpu_model.topology.threads)
self.assertEqual(set(['sse', 'aes']),
set([f.name for f in vcpu_model.features]))
cpu.mode = cpumodel.MODE_HOST_MODEL
vcpu_model_1 = drv._cpu_config_to_vcpu_model(cpu, vcpu_model)
self.assertEqual(cpumodel.MODE_HOST_MODEL, vcpu_model.mode)
self.assertEqual(vcpu_model, vcpu_model_1)
@mock.patch.object(lvm, 'get_volume_size', return_value=10)
@mock.patch.object(host.Host, "get_guest")
@mock.patch.object(dmcrypt, 'delete_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.unfilter_instance')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain')
@mock.patch.object(objects.Instance, 'save')
def test_cleanup_lvm_encrypted(self, mock_save, mock_undefine_domain,
mock_unfilter, mock_delete_volume,
mock_get_guest, mock_get_size):
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance = objects.Instance(
uuid=uuids.instance, id=1,
ephemeral_key_uuid=uuids.ephemeral_key_uuid)
instance.system_metadata = {}
block_device_info = {'root_device_name': '/dev/vda',
'ephemerals': [],
'block_device_mapping': []}
self.flags(images_type="lvm",
group='libvirt')
dom_xml = """
<domain type="kvm">
<devices>
<disk type="block">
<driver name='qemu' type='raw' cache='none'/>
<source dev="/dev/mapper/fake-dmcrypt"/>
<target dev="vda" bus="virtio" serial="1234"/>
</disk>
</devices>
</domain>
"""
dom = mock.MagicMock()
dom.XMLDesc.return_value = dom_xml
guest = libvirt_guest.Guest(dom)
mock_get_guest.return_value = guest
drv.cleanup(self.context, instance, 'fake_network', destroy_vifs=False,
block_device_info=block_device_info)
mock_delete_volume.assert_called_once_with('/dev/mapper/fake-dmcrypt')
@mock.patch.object(lvm, 'get_volume_size', return_value=10)
@mock.patch.object(host.Host, "get_guest")
@mock.patch.object(dmcrypt, 'delete_volume')
def _test_cleanup_lvm(self, mock_delete_volume, mock_get_guest, mock_size,
encrypted=False):
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance = objects.Instance(
uuid=uuids.instance, id=1,
ephemeral_key_uuid=uuids.ephemeral_key_uuid)
block_device_info = {'root_device_name': '/dev/vda',
'ephemerals': [],
'block_device_mapping': []}
dev_name = 'fake-dmcrypt' if encrypted else 'fake'
dom_xml = """
<domain type="kvm">
<devices>
<disk type="block">
<driver name='qemu' type='raw' cache='none'/>
<source dev="/dev/mapper/%s"/>
<target dev="vda" bus="virtio" serial="1234"/>
</disk>
</devices>
</domain>
""" % dev_name
dom = mock.MagicMock()
dom.XMLDesc.return_value = dom_xml
guest = libvirt_guest.Guest(dom)
mock_get_guest.return_value = guest
drv._cleanup_lvm(instance, block_device_info)
if encrypted:
mock_delete_volume.assert_called_once_with(
'/dev/mapper/fake-dmcrypt')
else:
self.assertFalse(mock_delete_volume.called)
def test_cleanup_lvm(self):
self._test_cleanup_lvm()
def test_cleanup_encrypted_lvm(self):
self._test_cleanup_lvm(encrypted=True)
def test_vcpu_model_to_config(self):
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
feature = objects.VirtCPUFeature(policy=cpumodel.POLICY_REQUIRE,
name='sse')
feature_1 = objects.VirtCPUFeature(policy=cpumodel.POLICY_FORBID,
name='aes')
topo = objects.VirtCPUTopology(sockets=1, cores=2, threads=4)
vcpu_model = objects.VirtCPUModel(mode=cpumodel.MODE_HOST_MODEL,
features=[feature, feature_1],
topology=topo)
cpu = drv._vcpu_model_to_cpu_config(vcpu_model)
self.assertEqual(cpumodel.MODE_HOST_MODEL, cpu.mode)
self.assertEqual(1, cpu.sockets)
self.assertEqual(4, cpu.threads)
self.assertEqual(2, len(cpu.features))
self.assertEqual(set(['sse', 'aes']),
set([f.name for f in cpu.features]))
self.assertEqual(set([cpumodel.POLICY_REQUIRE,
cpumodel.POLICY_FORBID]),
set([f.policy for f in cpu.features]))
def test_trigger_crash_dump(self):
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
instance = objects.Instance(uuid=uuids.instance, id=1)
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.drvr.trigger_crash_dump(instance)
def test_trigger_crash_dump_not_running(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'Requested operation is not valid: domain is not running',
error_code=fakelibvirt.VIR_ERR_OPERATION_INVALID)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.inject_nmi = mock.Mock(side_effect=ex)
instance = objects.Instance(uuid=uuids.instance, id=1)
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.assertRaises(exception.InstanceNotRunning,
self.drvr.trigger_crash_dump, instance)
def test_trigger_crash_dump_not_supported(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.inject_nmi = mock.Mock(side_effect=ex)
instance = objects.Instance(uuid=uuids.instance, id=1)
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.assertRaises(exception.TriggerCrashDumpNotSupported,
self.drvr.trigger_crash_dump, instance)
def test_trigger_crash_dump_unexpected_error(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'UnexpectedError',
error_code=fakelibvirt.VIR_ERR_SYSTEM_ERROR)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.inject_nmi = mock.Mock(side_effect=ex)
instance = objects.Instance(uuid=uuids.instance, id=1)
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.assertRaises(fakelibvirt.libvirtError,
self.drvr.trigger_crash_dump, instance)
class LibvirtVolumeUsageTestCase(test.NoDBTestCase):
"""Test for LibvirtDriver.get_all_volume_usage."""
def setUp(self):
super(LibvirtVolumeUsageTestCase, self).setUp()
self.drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.c = context.get_admin_context()
self.ins_ref = objects.Instance(
id=1729,
uuid='875a8070-d0b9-4949-8b31-104d125c9a64'
)
# verify bootable volume device path also
self.bdms = [{'volume_id': 1,
'device_name': '/dev/vde'},
{'volume_id': 2,
'device_name': 'vda'}]
def test_get_all_volume_usage(self):
def fake_block_stats(instance_name, disk):
return (169, 688640, 0, 0, -1)
self.stubs.Set(self.drvr, 'block_stats', fake_block_stats)
vol_usage = self.drvr.get_all_volume_usage(self.c,
[dict(instance=self.ins_ref, instance_bdms=self.bdms)])
expected_usage = [{'volume': 1,
'instance': self.ins_ref,
'rd_bytes': 688640, 'wr_req': 0,
'rd_req': 169, 'wr_bytes': 0},
{'volume': 2,
'instance': self.ins_ref,
'rd_bytes': 688640, 'wr_req': 0,
'rd_req': 169, 'wr_bytes': 0}]
self.assertEqual(vol_usage, expected_usage)
def test_get_all_volume_usage_device_not_found(self):
def fake_get_domain(self, instance):
raise exception.InstanceNotFound(instance_id="fakedom")
self.stubs.Set(host.Host, 'get_domain', fake_get_domain)
vol_usage = self.drvr.get_all_volume_usage(self.c,
[dict(instance=self.ins_ref, instance_bdms=self.bdms)])
self.assertEqual(vol_usage, [])
class LibvirtNonblockingTestCase(test.NoDBTestCase):
"""Test libvirtd calls are nonblocking."""
def setUp(self):
super(LibvirtNonblockingTestCase, self).setUp()
self.flags(connection_uri="test:///default",
group='libvirt')
def test_connection_to_primitive(self):
# Test bug 962840.
import nova.virt.libvirt.driver as libvirt_driver
drvr = libvirt_driver.LibvirtDriver('')
drvr.set_host_enabled = mock.Mock()
jsonutils.to_primitive(drvr._conn, convert_instances=True)
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_tpool_execute_calls_libvirt(self, mock_svc):
conn = fakelibvirt.virConnect()
conn.is_expected = True
self.mox.StubOutWithMock(eventlet.tpool, 'execute')
eventlet.tpool.execute(
fakelibvirt.openAuth,
'test:///default',
mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(conn)
eventlet.tpool.execute(
conn.domainEventRegisterAny,
None,
fakelibvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
mox.IgnoreArg(),
mox.IgnoreArg())
if hasattr(fakelibvirt.virConnect, 'registerCloseCallback'):
eventlet.tpool.execute(
conn.registerCloseCallback,
mox.IgnoreArg(),
mox.IgnoreArg())
self.mox.ReplayAll()
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
c = driver._get_connection()
self.assertTrue(c.is_expected)
class LibvirtVolumeSnapshotTestCase(test.NoDBTestCase):
"""Tests for libvirtDriver.volume_snapshot_create/delete."""
def setUp(self):
super(LibvirtVolumeSnapshotTestCase, self).setUp()
self.drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.c = context.get_admin_context()
self.flags(instance_name_template='instance-%s')
self.flags(qemu_allowed_storage_drivers=[], group='libvirt')
# creating instance
self.inst = {}
self.inst['uuid'] = uuidutils.generate_uuid()
self.inst['id'] = '1'
# create domain info
self.dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='disk1_file'/>
<target dev='vda' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio' serial='1234'/>
</disk>
</devices>
</domain>"""
# alternate domain info with network-backed snapshot chain
self.dom_netdisk_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='disk1_file'/>
<target dev='vda' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67eaffffff</serial>
</disk>
<disk type='network' device='disk'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/root.img'>
<host name='server1' port='24007'/>
</source>
<backingStore type='network' index='1'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/snap.img'>
<host name='server1' port='24007'/>
</source>
<backingStore type='network' index='2'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/snap-b.img'>
<host name='server1' port='24007'/>
</source>
<backingStore/>
</backingStore>
</backingStore>
<target dev='vdb' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
</devices>
</domain>
"""
# XML with netdisk attached, and 1 snapshot taken
self.dom_netdisk_xml_2 = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='disk1_file'/>
<target dev='vda' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67eaffffff</serial>
</disk>
<disk type='network' device='disk'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/snap.img'>
<host name='server1' port='24007'/>
</source>
<backingStore type='network' index='1'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/root.img'>
<host name='server1' port='24007'/>
</source>
<backingStore/>
</backingStore>
<target dev='vdb' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
</devices>
</domain>
"""
self.create_info = {'type': 'qcow2',
'snapshot_id': '1234-5678',
'new_file': 'new-file'}
self.volume_uuid = '0e38683e-f0af-418f-a3f1-6b67ea0f919d'
self.snapshot_id = '9c3ca9f4-9f4e-4dba-bedd-5c5e4b52b162'
self.delete_info_1 = {'type': 'qcow2',
'file_to_merge': 'snap.img',
'merge_target_file': None}
self.delete_info_2 = {'type': 'qcow2',
'file_to_merge': 'snap.img',
'merge_target_file': 'other-snap.img'}
self.delete_info_3 = {'type': 'qcow2',
'file_to_merge': None,
'merge_target_file': None}
self.delete_info_netdisk = {'type': 'qcow2',
'file_to_merge': 'snap.img',
'merge_target_file': 'root.img'}
self.delete_info_invalid_type = {'type': 'made_up_type',
'file_to_merge': 'some_file',
'merge_target_file':
'some_other_file'}
def tearDown(self):
super(LibvirtVolumeSnapshotTestCase, self).tearDown()
@mock.patch('nova.virt.block_device.DriverVolumeBlockDevice.'
'refresh_connection_info')
@mock.patch('nova.objects.block_device.BlockDeviceMapping.'
'get_by_volume_and_instance')
def test_volume_refresh_connection_info(self,
mock_get_by_volume_and_instance,
mock_refresh_connection_info):
instance = objects.Instance(**self.inst)
fake_bdm = fake_block_device.FakeDbBlockDeviceDict({
'id': 123,
'instance_uuid': uuids.instance,
'device_name': '/dev/sdb',
'source_type': 'volume',
'destination_type': 'volume',
'volume_id': 'fake-volume-id-1',
'connection_info': '{"fake": "connection_info"}'})
fake_bdm = objects.BlockDeviceMapping(self.c, **fake_bdm)
mock_get_by_volume_and_instance.return_value = fake_bdm
self.drvr._volume_refresh_connection_info(self.c, instance,
self.volume_uuid)
mock_get_by_volume_and_instance.assert_called_once_with(
self.c, self.volume_uuid, instance.uuid)
mock_refresh_connection_info.assert_called_once_with(self.c, instance,
self.drvr._volume_api, self.drvr)
def test_volume_snapshot_create(self, quiesce=True):
"""Test snapshot creation with file-based disk."""
self.flags(instance_name_template='instance-%s')
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
instance = objects.Instance(**self.inst)
new_file = 'new-file'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
self.mox.StubOutWithMock(domain, 'snapshotCreateXML')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
snap_xml_src = (
'<domainsnapshot>\n'
' <disks>\n'
' <disk name="disk1_file" snapshot="external" type="file">\n'
' <source file="new-file"/>\n'
' </disk>\n'
' <disk name="vdb" snapshot="no"/>\n'
' </disks>\n'
'</domainsnapshot>\n')
# Older versions of libvirt may be missing these.
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT = 32
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE = 64
snap_flags = (fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT)
snap_flags_q = (snap_flags |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE)
if quiesce:
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags_q)
else:
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags_q).\
AndRaise(fakelibvirt.libvirtError(
'quiescing failed, no qemu-ga'))
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags)
self.mox.ReplayAll()
guest = libvirt_guest.Guest(domain)
self.drvr._volume_snapshot_create(self.c, instance, guest,
self.volume_uuid, new_file)
self.mox.VerifyAll()
def test_volume_snapshot_create_libgfapi(self, quiesce=True):
"""Test snapshot creation with libgfapi network disk."""
self.flags(instance_name_template = 'instance-%s')
self.flags(qemu_allowed_storage_drivers = ['gluster'], group='libvirt')
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='disk1_file'/>
<target dev='vda' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
<disk type='block'>
<source protocol='gluster' name='gluster1/volume-1234'>
<host name='127.3.4.5' port='24007'/>
</source>
<target dev='vdb' bus='virtio' serial='1234'/>
</disk>
</devices>
</domain>"""
instance = objects.Instance(**self.inst)
new_file = 'new-file'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
self.mox.StubOutWithMock(domain, 'snapshotCreateXML')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
snap_xml_src = (
'<domainsnapshot>\n'
' <disks>\n'
' <disk name="disk1_file" snapshot="external" type="file">\n'
' <source file="new-file"/>\n'
' </disk>\n'
' <disk name="vdb" snapshot="no"/>\n'
' </disks>\n'
'</domainsnapshot>\n')
# Older versions of libvirt may be missing these.
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT = 32
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE = 64
snap_flags = (fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT)
snap_flags_q = (snap_flags |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE)
if quiesce:
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags_q)
else:
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags_q).\
AndRaise(fakelibvirt.libvirtError(
'quiescing failed, no qemu-ga'))
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags)
self.mox.ReplayAll()
guest = libvirt_guest.Guest(domain)
self.drvr._volume_snapshot_create(self.c, instance, guest,
self.volume_uuid, new_file)
self.mox.VerifyAll()
def test_volume_snapshot_create_noquiesce(self):
self.test_volume_snapshot_create(quiesce=False)
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_can_quiesce(self, ver):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.inst)
image_meta = objects.ImageMeta.from_dict(
{"properties": {
"hw_qemu_guest_agent": "yes"}})
self.assertIsNone(self.drvr._can_quiesce(instance, image_meta))
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_can_quiesce_bad_hyp(self, ver):
self.flags(virt_type='lxc', group='libvirt')
instance = objects.Instance(**self.inst)
image_meta = objects.ImageMeta.from_dict(
{"properties": {
"hw_qemu_guest_agent": "yes"}})
self.assertRaises(exception.InstanceQuiesceNotSupported,
self.drvr._can_quiesce, instance, image_meta)
@mock.patch.object(host.Host,
'has_min_version', return_value=False)
def test_can_quiesce_bad_ver(self, ver):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.inst)
image_meta = {"properties": {
"hw_qemu_guest_agent": "yes"}}
self.assertRaises(exception.InstanceQuiesceNotSupported,
self.drvr._can_quiesce, instance, image_meta)
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_can_quiesce_agent_not_enable(self, ver):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.inst)
image_meta = objects.ImageMeta.from_dict({})
self.assertRaises(exception.QemuGuestAgentNotEnabled,
self.drvr._can_quiesce, instance, image_meta)
@mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_volume_snapshot_create')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_volume_refresh_connection_info')
def test_volume_snapshot_create_outer_success(self, mock_refresh,
mock_snap_create, mock_loop):
class FakeLoopingCall(object):
def __init__(self, func):
self.func = func
def start(self, *a, **k):
try:
self.func()
except loopingcall.LoopingCallDone:
pass
return self
def wait(self):
return None
mock_loop.side_effect = FakeLoopingCall
instance = objects.Instance(**self.inst)
domain = FakeVirtDomain(fake_xml=self.dom_xml, id=1)
guest = libvirt_guest.Guest(domain)
@mock.patch.object(self.drvr, '_volume_api')
@mock.patch.object(self.drvr._host, 'get_guest')
def _test(mock_get_guest, mock_vol_api):
mock_get_guest.return_value = guest
mock_vol_api.get_snapshot.return_value = {'status': 'available'}
self.drvr.volume_snapshot_create(self.c, instance,
self.volume_uuid,
self.create_info)
mock_get_guest.assert_called_once_with(instance)
mock_snap_create.assert_called_once_with(
self.c, instance, guest, self.volume_uuid,
self.create_info['new_file'])
mock_vol_api.update_snapshot_status.assert_called_once_with(
self.c, self.create_info['snapshot_id'], 'creating')
mock_vol_api.get_snapshot.assert_called_once_with(
self.c, self.create_info['snapshot_id'])
mock_refresh.assert_called_once_with(
self.c, instance, self.volume_uuid)
_test()
def test_volume_snapshot_create_outer_failure(self):
instance = objects.Instance(**self.inst)
domain = FakeVirtDomain(fake_xml=self.dom_xml, id=1)
guest = libvirt_guest.Guest(domain)
self.mox.StubOutWithMock(self.drvr._host, 'get_guest')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_create')
self.drvr._host.get_guest(instance).AndReturn(guest)
self.drvr._volume_snapshot_create(self.c,
instance,
guest,
self.volume_uuid,
self.create_info['new_file']).\
AndRaise(exception.NovaException('oops'))
self.drvr._volume_api.update_snapshot_status(
self.c, self.create_info['snapshot_id'], 'error')
self.mox.ReplayAll()
self.assertRaises(exception.NovaException,
self.drvr.volume_snapshot_create,
self.c,
instance,
self.volume_uuid,
self.create_info)
def test_volume_snapshot_delete_1(self):
"""Deleting newest snapshot -- blockRebase."""
# libvirt lib doesn't have VIR_DOMAIN_BLOCK_REBASE_RELATIVE flag
fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_REBASE_RELATIVE')
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockRebase('vda', 'snap.img', 0, flags=0)
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.mox.VerifyAll()
fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_REBASE_RELATIVE': 8})
def test_volume_snapshot_delete_relative_1(self):
"""Deleting newest snapshot -- blockRebase using relative flag"""
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
guest = libvirt_guest.Guest(domain)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_guest')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_guest(instance).AndReturn(guest)
domain.blockRebase('vda', 'snap.img', 0,
flags=fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE)
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.mox.VerifyAll()
def _setup_block_rebase_domain_and_guest_mocks(self, dom_xml):
mock_domain = mock.Mock(spec=fakelibvirt.virDomain)
mock_domain.XMLDesc.return_value = dom_xml
guest = libvirt_guest.Guest(mock_domain)
exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError, 'virDomainBlockRebase() failed',
error_code=fakelibvirt.VIR_ERR_OPERATION_INVALID)
mock_domain.blockRebase.side_effect = exc
return mock_domain, guest
@mock.patch.object(host.Host, "has_min_version",
mock.Mock(return_value=True))
@mock.patch("nova.virt.libvirt.guest.Guest.is_active",
mock.Mock(return_value=False))
@mock.patch('nova.virt.images.qemu_img_info',
return_value=mock.Mock(file_format="fake_fmt"))
@mock.patch('nova.utils.execute')
def test_volume_snapshot_delete_when_dom_not_running(self, mock_execute,
mock_qemu_img_info):
"""Deleting newest snapshot of a file-based image when the domain is
not running should trigger a blockRebase using qemu-img not libvirt.
In this test, we rebase the image with another image as backing file.
"""
mock_domain, guest = self._setup_block_rebase_domain_and_guest_mocks(
self.dom_xml)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=guest):
self.drvr._volume_snapshot_delete(self.c, instance,
self.volume_uuid, snapshot_id,
self.delete_info_1)
mock_qemu_img_info.assert_called_once_with("snap.img")
mock_execute.assert_called_once_with('qemu-img', 'rebase',
'-b', 'snap.img', '-F',
'fake_fmt', 'disk1_file')
@mock.patch.object(host.Host, "has_min_version",
mock.Mock(return_value=True))
@mock.patch("nova.virt.libvirt.guest.Guest.is_active",
mock.Mock(return_value=False))
@mock.patch('nova.virt.images.qemu_img_info',
return_value=mock.Mock(file_format="fake_fmt"))
@mock.patch('nova.utils.execute')
def test_volume_snapshot_delete_when_dom_not_running_and_no_rebase_base(
self, mock_execute, mock_qemu_img_info):
"""Deleting newest snapshot of a file-based image when the domain is
not running should trigger a blockRebase using qemu-img not libvirt.
In this test, the image is rebased onto no backing file (i.e.
it will exist independently of any backing file)
"""
mock_domain, mock_guest = (
self._setup_block_rebase_domain_and_guest_mocks(self.dom_xml))
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.drvr._volume_snapshot_delete(self.c, instance,
self.volume_uuid, snapshot_id,
self.delete_info_3)
self.assertEqual(0, mock_qemu_img_info.call_count)
mock_execute.assert_called_once_with('qemu-img', 'rebase',
'-b', '', 'disk1_file')
@mock.patch.object(host.Host, "has_min_version",
mock.Mock(return_value=True))
@mock.patch("nova.virt.libvirt.guest.Guest.is_active",
mock.Mock(return_value=False))
def test_volume_snapshot_delete_when_dom_with_nw_disk_not_running(self):
"""Deleting newest snapshot of a network disk when the domain is not
running should raise a NovaException.
"""
mock_domain, mock_guest = (
self._setup_block_rebase_domain_and_guest_mocks(
self.dom_netdisk_xml))
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
ex = self.assertRaises(exception.NovaException,
self.drvr._volume_snapshot_delete,
self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.assertIn('has not been fully tested', six.text_type(ex))
def test_volume_snapshot_delete_2(self):
"""Deleting older snapshot -- blockCommit."""
# libvirt lib doesn't have VIR_DOMAIN_BLOCK_COMMIT_RELATIVE
fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_COMMIT_RELATIVE')
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
self.mox.ReplayAll()
self.assertRaises(exception.Invalid,
self.drvr._volume_snapshot_delete,
self.c,
instance,
self.volume_uuid,
snapshot_id,
self.delete_info_2)
fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_COMMIT_RELATIVE': 4})
def test_volume_snapshot_delete_relative_2(self):
"""Deleting older snapshot -- blockCommit using relative flag"""
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockCommit('vda', 'other-snap.img', 'snap.img', 0,
flags=fakelibvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE)
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_2)
self.mox.VerifyAll()
def test_volume_snapshot_delete_nonrelative_null_base(self):
# Deleting newest and last snapshot of a volume
# with blockRebase. So base of the new image will be null.
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
guest = libvirt_guest.Guest(domain)
with test.nested(
mock.patch.object(domain, 'XMLDesc', return_value=self.dom_xml),
mock.patch.object(self.drvr._host, 'get_guest',
return_value=guest),
mock.patch.object(domain, 'blockRebase'),
mock.patch.object(domain, 'blockJobInfo',
return_value={
'type': 4, # See virDomainBlockJobType enum
'bandwidth': 0,
'cur': 1000,
'end': 1000})
) as (mock_xmldesc, mock_get_guest,
mock_rebase, mock_job_info):
self.drvr._volume_snapshot_delete(self.c, instance,
self.volume_uuid, snapshot_id,
self.delete_info_3)
mock_xmldesc.assert_called_once_with(flags=0)
mock_get_guest.assert_called_once_with(instance)
mock_rebase.assert_called_once_with('vda', None, 0, flags=0)
mock_job_info.assert_called_once_with('vda', flags=0)
def test_volume_snapshot_delete_netdisk_nonrelative_null_base(self):
# Deleting newest and last snapshot of a network attached volume
# with blockRebase. So base of the new image will be null.
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_netdisk_xml_2)
guest = libvirt_guest.Guest(domain)
with test.nested(
mock.patch.object(domain, 'XMLDesc',
return_value=self.dom_netdisk_xml_2),
mock.patch.object(self.drvr._host, 'get_guest',
return_value=guest),
mock.patch.object(domain, 'blockRebase'),
mock.patch.object(domain, 'blockJobInfo',
return_value={
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
) as (mock_xmldesc, mock_get_guest,
mock_rebase, mock_job_info):
self.drvr._volume_snapshot_delete(self.c, instance,
self.volume_uuid, snapshot_id,
self.delete_info_3)
mock_xmldesc.assert_called_once_with(flags=0)
mock_get_guest.assert_called_once_with(instance)
mock_rebase.assert_called_once_with('vdb', None, 0, flags=0)
mock_job_info.assert_called_once_with('vdb', flags=0)
def test_volume_snapshot_delete_outer_success(self):
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_delete')
self.drvr._volume_snapshot_delete(self.c,
instance,
self.volume_uuid,
snapshot_id,
delete_info=self.delete_info_1)
self.drvr._volume_api.update_snapshot_status(
self.c, snapshot_id, 'deleting')
self.mox.StubOutWithMock(self.drvr, '_volume_refresh_connection_info')
self.drvr._volume_refresh_connection_info(self.c, instance,
self.volume_uuid)
self.mox.ReplayAll()
self.drvr.volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id,
self.delete_info_1)
self.mox.VerifyAll()
def test_volume_snapshot_delete_outer_failure(self):
instance = objects.Instance(**self.inst)
snapshot_id = '1234-9876'
FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_delete')
self.drvr._volume_snapshot_delete(self.c,
instance,
self.volume_uuid,
snapshot_id,
delete_info=self.delete_info_1).\
AndRaise(exception.NovaException('oops'))
self.drvr._volume_api.update_snapshot_status(
self.c, snapshot_id, 'error_deleting')
self.mox.ReplayAll()
self.assertRaises(exception.NovaException,
self.drvr.volume_snapshot_delete,
self.c,
instance,
self.volume_uuid,
snapshot_id,
self.delete_info_1)
self.mox.VerifyAll()
def test_volume_snapshot_delete_invalid_type(self):
instance = objects.Instance(**self.inst)
FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.drvr._volume_api.update_snapshot_status(
self.c, self.snapshot_id, 'error_deleting')
self.mox.ReplayAll()
self.assertRaises(exception.NovaException,
self.drvr.volume_snapshot_delete,
self.c,
instance,
self.volume_uuid,
self.snapshot_id,
self.delete_info_invalid_type)
def test_volume_snapshot_delete_netdisk_1(self):
"""Delete newest snapshot -- blockRebase for libgfapi/network disk."""
class FakeNetdiskDomain(FakeVirtDomain):
def __init__(self, *args, **kwargs):
super(FakeNetdiskDomain, self).__init__(*args, **kwargs)
def XMLDesc(self, flags):
return self.dom_netdisk_xml
# libvirt lib doesn't have VIR_DOMAIN_BLOCK_REBASE_RELATIVE
fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_REBASE_RELATIVE')
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockRebase('vdb', 'vdb[1]', 0, flags=0)
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.mox.VerifyAll()
fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_REBASE_RELATIVE': 8})
def test_volume_snapshot_delete_netdisk_relative_1(self):
"""Delete newest snapshot -- blockRebase for libgfapi/network disk."""
class FakeNetdiskDomain(FakeVirtDomain):
def __init__(self, *args, **kwargs):
super(FakeNetdiskDomain, self).__init__(*args, **kwargs)
def XMLDesc(self, flags):
return self.dom_netdisk_xml
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockRebase('vdb', 'vdb[1]', 0,
flags=fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE)
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.mox.VerifyAll()
def test_volume_snapshot_delete_netdisk_2(self):
"""Delete older snapshot -- blockCommit for libgfapi/network disk."""
class FakeNetdiskDomain(FakeVirtDomain):
def __init__(self, *args, **kwargs):
super(FakeNetdiskDomain, self).__init__(*args, **kwargs)
def XMLDesc(self, flags):
return self.dom_netdisk_xml
# libvirt lib doesn't have VIR_DOMAIN_BLOCK_COMMIT_RELATIVE
fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_COMMIT_RELATIVE')
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
self.mox.ReplayAll()
self.assertRaises(exception.Invalid,
self.drvr._volume_snapshot_delete,
self.c,
instance,
self.volume_uuid,
snapshot_id,
self.delete_info_netdisk)
fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_COMMIT_RELATIVE': 4})
def test_volume_snapshot_delete_netdisk_relative_2(self):
"""Delete older snapshot -- blockCommit for libgfapi/network disk."""
class FakeNetdiskDomain(FakeVirtDomain):
def __init__(self, *args, **kwargs):
super(FakeNetdiskDomain, self).__init__(*args, **kwargs)
def XMLDesc(self, flags):
return self.dom_netdisk_xml
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockCommit('vdb', 'vdb[0]', 'vdb[1]', 0,
flags=fakelibvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE)
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id,
self.delete_info_netdisk)
self.mox.VerifyAll()
def _fake_convert_image(source, dest, in_format, out_format,
run_as_root=True):
libvirt_driver.libvirt_utils.files[dest] = ''
class _BaseSnapshotTests(test.NoDBTestCase):
def setUp(self):
super(_BaseSnapshotTests, self).setUp()
self.flags(snapshots_directory='./', group='libvirt')
self.context = context.get_admin_context()
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.libvirt_utils',
fake_libvirt_utils))
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
self.image_service = nova.tests.unit.image.fake.stub_out_image_service(
self)
self.mock_update_task_state = mock.Mock()
test_instance = _create_test_instance()
self.instance_ref = objects.Instance(**test_instance)
self.instance_ref.info_cache = objects.InstanceInfoCache(
network_info=None)
def _assert_snapshot(self, snapshot, disk_format,
expected_properties=None):
self.mock_update_task_state.assert_has_calls([
mock.call(task_state=task_states.IMAGE_PENDING_UPLOAD),
mock.call(task_state=task_states.IMAGE_UPLOADING,
expected_state=task_states.IMAGE_PENDING_UPLOAD)])
props = snapshot['properties']
self.assertEqual(props['image_state'], 'available')
self.assertEqual(snapshot['status'], 'active')
self.assertEqual(snapshot['disk_format'], disk_format)
self.assertEqual(snapshot['name'], 'test-snap')
if expected_properties:
for expected_key, expected_value in \
six.iteritems(expected_properties):
self.assertEqual(expected_value, props[expected_key])
def _create_image(self, extra_properties=None):
properties = {'instance_id': self.instance_ref['id'],
'user_id': str(self.context.user_id)}
if extra_properties:
properties.update(extra_properties)
sent_meta = {'name': 'test-snap',
'is_public': False,
'status': 'creating',
'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = self.image_service.create(self.context, sent_meta)
return recv_meta
@mock.patch.object(host.Host, 'has_min_version')
@mock.patch.object(imagebackend.Image, 'resolve_driver_format')
@mock.patch.object(host.Host, 'get_domain')
def _snapshot(self, image_id, mock_get_domain, mock_resolve, mock_version):
mock_get_domain.return_value = FakeVirtDomain()
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
driver.snapshot(self.context, self.instance_ref, image_id,
self.mock_update_task_state)
snapshot = self.image_service.show(self.context, image_id)
return snapshot
def _test_snapshot(self, disk_format, extra_properties=None):
recv_meta = self._create_image(extra_properties=extra_properties)
snapshot = self._snapshot(recv_meta['id'])
self._assert_snapshot(snapshot, disk_format=disk_format,
expected_properties=extra_properties)
class LibvirtSnapshotTests(_BaseSnapshotTests):
def test_ami(self):
# Assign different image_ref from nova/images/fakes for testing ami
self.instance_ref.image_ref = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77'
self.instance_ref.system_metadata = \
utils.get_system_metadata_from_image(
{'disk_format': 'ami'})
self._test_snapshot(disk_format='ami')
@mock.patch.object(fake_libvirt_utils, 'disk_type', new='raw')
@mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image)
def test_raw(self, mock_convert_image):
self._test_snapshot(disk_format='raw')
def test_qcow2(self):
self._test_snapshot(disk_format='qcow2')
@mock.patch.object(fake_libvirt_utils, 'disk_type', new='ploop')
@mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image)
def test_ploop(self, mock_convert_image):
self._test_snapshot(disk_format='ploop')
def test_no_image_architecture(self):
self.instance_ref.image_ref = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'
self._test_snapshot(disk_format='qcow2')
def test_no_original_image(self):
self.instance_ref.image_ref = '661122aa-1234-dede-fefe-babababababa'
self._test_snapshot(disk_format='qcow2')
def test_snapshot_metadata_image(self):
# Assign an image with an architecture defined (x86_64)
self.instance_ref.image_ref = 'a440c04b-79fa-479c-bed1-0b816eaec379'
extra_properties = {'architecture': 'fake_arch',
'key_a': 'value_a',
'key_b': 'value_b',
'os_type': 'linux'}
self._test_snapshot(disk_format='qcow2',
extra_properties=extra_properties)
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone(self, mock_rbd, mock_driver):
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(return_value=['test-pool', '', ''])
rbd.parse_url = mock.Mock(return_value=['a', 'b', 'c', 'd'])
with mock.patch.object(fake_libvirt_utils, 'find_disk',
return_value=('rbd://some/fake/rbd/image',
'raw')):
with mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd'):
self._test_snapshot(disk_format='raw')
rbd.clone.assert_called_with(mock.ANY, mock.ANY, dest_pool='test-pool')
rbd.flatten.assert_called_with(mock.ANY, pool='test-pool')
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone_graceful_fallback(self, mock_rbd, mock_driver):
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(side_effect=exception.ImageUnacceptable(
image_id='fake_id', reason='rbd testing'))
with test.nested(
mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image),
mock.patch.object(fake_libvirt_utils, 'find_disk',
return_value=('rbd://some/fake/rbd/image',
'raw')),
mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd')):
self._test_snapshot(disk_format='raw')
self.assertFalse(rbd.clone.called)
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone_eperm(self, mock_rbd, mock_driver):
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(return_value=['test-pool', '', ''])
rbd.parse_url = mock.Mock(return_value=['a', 'b', 'c', 'd'])
rbd.clone = mock.Mock(side_effect=exception.Forbidden(
image_id='fake_id', reason='rbd testing'))
with test.nested(
mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image),
mock.patch.object(fake_libvirt_utils, 'find_disk',
return_value=('rbd://some/fake/rbd/image',
'raw')),
mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd')):
self._test_snapshot(disk_format='raw')
# Ensure that the direct_snapshot attempt was cleaned up
rbd.remove_snap.assert_called_with('c', 'd', ignore_errors=False,
pool='b', force=True)
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone_post_process_fails(self, mock_rbd,
mock_driver):
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(return_value=['test-pool', '', ''])
rbd.parse_url = mock.Mock(return_value=['a', 'b', 'c', 'd'])
with test.nested(
mock.patch.object(fake_libvirt_utils, 'find_disk',
return_value=('rbd://some/fake/rbd/image',
'raw')),
mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd'),
mock.patch.object(self.image_service, 'update',
side_effect=test.TestingException)):
self.assertRaises(test.TestingException, self._test_snapshot,
disk_format='raw')
rbd.clone.assert_called_with(mock.ANY, mock.ANY, dest_pool='test-pool')
rbd.flatten.assert_called_with(mock.ANY, pool='test-pool')
# Ensure that the direct_snapshot attempt was cleaned up
rbd.remove_snap.assert_called_with('c', 'd', ignore_errors=True,
pool='b', force=True)
@mock.patch.object(imagebackend.Image, 'direct_snapshot')
@mock.patch.object(imagebackend.Image, 'resolve_driver_format')
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(host.Host, 'get_guest')
def test_raw_with_rbd_clone_is_live_snapshot(self,
mock_get_guest,
mock_version,
mock_resolve,
mock_snapshot):
self.flags(disable_libvirt_livesnapshot=False, group='workarounds')
self.flags(images_type='rbd', group='libvirt')
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_guest._domain = mock.Mock()
mock_get_guest.return_value = mock_guest
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
recv_meta = self._create_image()
with mock.patch.object(driver, "suspend") as mock_suspend:
driver.snapshot(self.context, self.instance_ref, recv_meta['id'],
self.mock_update_task_state)
self.assertFalse(mock_suspend.called)
@mock.patch.object(libvirt_driver.imagebackend.images, 'convert_image',
side_effect=_fake_convert_image)
@mock.patch.object(fake_libvirt_utils, 'find_disk')
@mock.patch.object(imagebackend.Image, 'resolve_driver_format')
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(host.Host, 'get_guest')
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone_failure_does_cold_snapshot(self,
mock_rbd,
mock_driver,
mock_get_guest,
mock_version,
mock_resolve,
mock_find_disk,
mock_convert):
self.flags(disable_libvirt_livesnapshot=False, group='workarounds')
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(side_effect=exception.ImageUnacceptable(
image_id='fake_id', reason='rbd testing'))
mock_find_disk.return_value = ('rbd://some/fake/rbd/image', 'raw')
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_guest.get_power_state.return_value = power_state.RUNNING
mock_guest._domain = mock.Mock()
mock_get_guest.return_value = mock_guest
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
recv_meta = self._create_image()
with mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd'):
with mock.patch.object(driver, "suspend") as mock_suspend:
driver.snapshot(self.context, self.instance_ref,
recv_meta['id'], self.mock_update_task_state)
self.assertTrue(mock_suspend.called)
class LXCSnapshotTests(LibvirtSnapshotTests):
"""Repeat all of the Libvirt snapshot tests, but with LXC enabled"""
def setUp(self):
super(LXCSnapshotTests, self).setUp()
self.flags(virt_type='lxc', group='libvirt')
def test_raw_with_rbd_clone_failure_does_cold_snapshot(self):
self.skipTest("managedSave is not supported with LXC")
class LVMSnapshotTests(_BaseSnapshotTests):
@mock.patch.object(fake_libvirt_utils, 'disk_type', new='lvm')
@mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image)
@mock.patch.object(libvirt_driver.imagebackend.lvm, 'volume_info')
def _test_lvm_snapshot(self, disk_format, mock_volume_info,
mock_convert_image):
self.flags(images_type='lvm',
images_volume_group='nova-vg', group='libvirt')
self._test_snapshot(disk_format=disk_format)
mock_volume_info.assert_has_calls([mock.call('/dev/nova-vg/lv')])
mock_convert_image.assert_called_once_with(
'/dev/nova-vg/lv', mock.ANY, 'raw', disk_format,
run_as_root=True)
def test_raw(self):
self._test_lvm_snapshot('raw')
def test_qcow2(self):
self.flags(snapshot_image_format='qcow2', group='libvirt')
self._test_lvm_snapshot('qcow2')
| cloudbase/nova | nova/tests/unit/virt/libvirt/test_driver.py | Python | apache-2.0 | 828,674 |
from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
from hazelcast.protocol.builtin import CodecUtil
# hex: 0x050F00
_REQUEST_MESSAGE_TYPE = 331520
# hex: 0x050F01
_RESPONSE_MESSAGE_TYPE = 331521
_REQUEST_INDEX_OFFSET = REQUEST_HEADER_SIZE
_REQUEST_INITIAL_FRAME_SIZE = _REQUEST_INDEX_OFFSET + INT_SIZE_IN_BYTES
def encode_request(name, index):
buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)
FixSizedTypesCodec.encode_int(buf, _REQUEST_INDEX_OFFSET, index)
StringCodec.encode(buf, name, True)
return OutboundMessage(buf, True)
def decode_response(msg):
msg.next_frame()
return CodecUtil.decode_nullable(msg, DataCodec.decode)
| hazelcast/hazelcast-python-client | hazelcast/protocol/codec/list_get_codec.py | Python | apache-2.0 | 944 |