text
stringlengths
6
947k
repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
#!/usr/bin/env python3 import asyncio import contextlib import datetime import functools import importlib import itertools import logging import os import sys import traceback import click import discord import config from cogs.utils import db from core import Chiaki, migration # use faster event loop, but fall back to default if on Windows or not installed try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) @contextlib.contextmanager def log(stream=False): logging.getLogger('discord').setLevel(logging.INFO) os.makedirs(os.path.join(os.path.dirname(__file__), 'logs'), exist_ok=True) root = logging.getLogger() root.setLevel(logging.INFO) handler = logging.FileHandler( filename=f'logs/chiaki-{datetime.datetime.now()}.log', encoding='utf-8', mode='w' ) fmt = logging.Formatter('[{asctime}] ({levelname:<7}) {name}: {message}', '%Y-%m-%d %H:%M:%S', style='{') handler.setFormatter(fmt) root.addHandler(handler) if stream: stream_handler = logging.StreamHandler() stream_handler.setFormatter(fmt) root.addHandler(stream_handler) try: yield finally: for hdlr in root.handlers[:]: hdlr.close() root.removeHandler(hdlr) #--------------MAIN--------------- _old_send = discord.abc.Messageable.send async def new_send(self, content=None, *, allow_everyone=False, **kwargs): if content is not None: if not allow_everyone: content = str(content).replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere') return await _old_send(self, content, **kwargs) @click.group(invoke_without_command=True) @click.option('--log-stream', is_flag=True, help='Adds a stderr stream-handler for logging') @click.pass_context def main(ctx, log_stream): if ctx.invoked_subcommand is not None: return # This has to be patched first because Chiaki loads her extensions in # __init__, which means she loads her commands in __init__ from discord.ext import commands old_commands_group = commands.group commands.group = functools.partial(old_commands_group, case_insensitive=True) bot = Chiaki() discord.abc.Messageable.send = new_send with log(log_stream): try: bot.run() finally: discord.abc.Messageable.send = _old_send commands.group = old_commands_group return 69 * bot.reset_requested # ------------- DB-related stuff ------------------ async def _create_pool(): psql = f'postgresql://{config.psql_user}:{config.psql_pass}@{config.psql_host}/{config.psql_db}' return await db.create_pool(psql, command_timeout=60) def _load_modules(extensions): for e in itertools.chain.from_iterable(Chiaki.find_extensions(e) or [e] for e in extensions): try: importlib.import_module(e) except: click.echo(f'Could not load {e}.\n{traceback.format_exc()}', err=True) raise async def _migrate(version='', downgrade=False, verbose=False): # click doesn't like None as a default so we have to settle with an empty string if not version: version = None _load_modules(config.extensions) pool = await _create_pool() async with pool.acquire() as conn: await migration.migrate(version, connection=conn, downgrade=downgrade, verbose=verbose) def _sync_migrate(version, downgrade, verbose): run = asyncio.get_event_loop().run_until_complete run(_migrate(version, downgrade=downgrade, verbose=verbose)) @main.command() @click.option('--version', default='', metavar='[version]', help='Version to migrate to, defaults to latest') @click.option('-v', '--verbose', is_flag=True) def upgrade(version, verbose): """Upgrade the database to a version""" _sync_migrate(version, downgrade=False, verbose=verbose) click.echo('Upgrade successful! <3') @main.command() @click.option('--version', default='', metavar='[version]', help='Version to migrate to, defaults to latest') @click.option('-v', '--verbose', is_flag=True) def downgrade(version, verbose): """Downgrade the database to a version""" _sync_migrate(version, downgrade=True, verbose=verbose) click.echo('Downgrade successful! <3') async def _init(verbose): _load_modules(config.extensions) pool = await _create_pool() async with pool.acquire() as conn: await migration.init(connection=conn, verbose=verbose) @main.command(name='init-db') @click.option('-v', '--verbose', is_flag=True) def init_db(verbose): """Initialize the database""" run = asyncio.get_event_loop().run_until_complete run(_init(verbose)) click.echo('Database initialization successful! <3') if __name__ == '__main__': sys.exit(main())
Ikusaba-san/Chiaki-Nanami
chiaki.py
Python
mit
4,858
0.004529
# -*- coding: utf-8 -*- """ pipya main cli file Copyright (c) 2015 Brunston Poon 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. Full license in LICENCE.txt """ #IMPORT IMPORT IMPORT IMPORT IMPORT IMPORT IMPORT IMPORT IMPORT IMPORT IMPORT #Let's make sure that the user has all the dependencies installed and that #they are running the correct version of Python try: import feedparser except ImportError: print("feedparser is a system-agnostic dependency for RSS support") sys.exit() import sys, os import time import json import webbrowser import helper as h import fetch as fetch toggle = True version = sys.version_info[0] if version != 3: print(""" Please upgrade to Python3, preferably 3.4.* or greater, before continuing""") toggle = False sys.exit() if os.name == "nt": try: from colorama import init init() except ImportError: print("colorama is a windows dependency for ANSI colors support") sys.exit() def main(): wapi, user, citystr,newslink = h.kernfig() h.welcome(user) while True: wapi, user, citystr,newslink = h.kernfig() print(h.ask()) uin = str.lower(input(">")) if "fetch" in uin: fetch.main(uin) elif "visit" in uin: for itemToVisit in h.giveComputerIndex(uin): newsfeed = h.grab(newslink) webbrowser.open(newsfeed.entries[itemToVisit-1].link) elif "set" in uin: if "name" in uin: name = input("What would you like me to call you? ") h.cfgwriter("settings.cfg",0,name) if "city" in uin: city = input(""" Changing weather location? Where to? Must be in Wunderground form. """) h.cfgwriter("settings.cfg",1,city) elif "name" and "pronounce" in uin: print(h.pipya()+"My name is pronounced Pip-pah. The y is silent :).") elif "name" and ("how" or "where") and "get" in uin: print(h.pipya()+"""\ My name started as pypa, for "python personal assistant". It morphed to pipya for pronounceability. Thanks for asking!""") elif "what" and "can" and "do" in uin: h.capabilities() elif "who" and "are" and ("you" or "pipya") in uin: print(h.pipya()+""" I am Pipya, a personal assistant written in python3. My creator is brupoon. He intended for me to be a jack-of-all-trades personal assistant operated by a cli. I am a sexless, genderless entity, though my name is similar to the human feminine "Pippa". """) elif uin in ["quit", "goodbye", "exit"]: print("Goodbye, {0}! 'Till next time.".format(user)) sys.exit() elif uin in ["jellyfish"]: h.jellyfish() else: print("Pipya: Sorry, {0}, I didn't quite catch that.".format(user)) if (__name__ == '__main__') and (toggle==True): main()
brupoon/pipya
pipya.py
Python
gpl-3.0
3,093
0.005496
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Octofiles documentation build configuration file, created by # sphinx-quickstart on Thu Mar 10 14:51:08 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinxcontrib.httpdomain' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Octofiles' copyright = '2016, Hackultura' author = 'Hackultura' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0.0' # The full version, including alpha/beta/rc tags. release = '1.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'pt_BR' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'Octofilesdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'Octofiles.tex', 'Octofiles Documentation', 'Hackultura', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'octofiles', 'Octofiles Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Octofiles', 'Octofiles Documentation', author, 'Octofiles', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. #epub_basename = project # The HTML theme for the epub output. Since the default themes are not # optimized for small screen space, using the same theme for HTML and epub # output is usually not wise. This defaults to 'epub', a theme designed to save # visual space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files that should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the Pillow. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True
hackultura/octofiles
docs/source/conf.py
Python
gpl-3.0
11,319
0.006538
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask from config import * # create the app app = Flask(__name__) # Load default config and override config from config file app.config.from_object('config')
n8foo/cigarbox
app.py
Python
apache-2.0
223
0.004484
# -*- coding: utf-8 -*- ############################################################################### # # GetLoginProfile # Retrieves the user name and password create date for the specified user. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo 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. # # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class GetLoginProfile(Choreography): def __init__(self, temboo_session): """ Create a new instance of the GetLoginProfile Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(GetLoginProfile, self).__init__(temboo_session, '/Library/Amazon/IAM/GetLoginProfile') def new_input_set(self): return GetLoginProfileInputSet() def _make_result_set(self, result, path): return GetLoginProfileResultSet(result, path) def _make_execution(self, session, exec_id, path): return GetLoginProfileChoreographyExecution(session, exec_id, path) class GetLoginProfileInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the GetLoginProfile Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AWSAccessKeyId(self, value): """ Set the value of the AWSAccessKeyId input for this Choreo. ((required, string) The Access Key ID provided by Amazon Web Services.) """ super(GetLoginProfileInputSet, self)._set_input('AWSAccessKeyId', value) def set_AWSSecretKeyId(self, value): """ Set the value of the AWSSecretKeyId input for this Choreo. ((required, string) The Secret Key ID provided by Amazon Web Services.) """ super(GetLoginProfileInputSet, self)._set_input('AWSSecretKeyId', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are "xml" (the default) and "json".) """ super(GetLoginProfileInputSet, self)._set_input('ResponseFormat', value) def set_UserName(self, value): """ Set the value of the UserName input for this Choreo. ((required, string) Name of the user whose login profile you want to retrieve.) """ super(GetLoginProfileInputSet, self)._set_input('UserName', value) class GetLoginProfileResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the GetLoginProfile Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Amazon.) """ return self._output.get('Response', None) class GetLoginProfileChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return GetLoginProfileResultSet(response, path)
jordanemedlock/psychtruths
temboo/core/Library/Amazon/IAM/GetLoginProfile.py
Python
apache-2.0
3,876
0.005418
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Craig J. Anderson # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # $Id$ """ Provide the SubstKeywords class that will replace keywords in a passed string with information about the person/marriage/spouse. For sample: foo = SubstKeywords(database, person_handle) print foo.replace_and_clean(['$n was born on $b.']) Will return a value such as: Mary Smith was born on 3/28/1923. """ from __future__ import print_function #------------------------------------------------------------------------ # # Gramps modules # #------------------------------------------------------------------------ from gramps.gen.display.name import displayer as name_displayer from gramps.gen.datehandler import displayer from gramps.gen.lib import EventType from gramps.gen.utils.db import get_birth_or_fallback, get_death_or_fallback from gramps.gen.constfunc import STRTYPE, cuni #------------------------------------------------------------------------ # # Local constants # #------------------------------------------------------------------------ class TextTypes(): """Four enumerations that are used to for the four main parts of a string. and used for states. Separator is not used in states. text -> remove or display remove -> display """ separator, text, remove, display = list(range(4)) TXT = TextTypes() #------------------------------------------------------------------------ # # Formatting classes # #------------------------------------------------------------------------ class GenericFormat(object): """A Generic parsing class. Will be subclassed by specific format strings """ def __init__(self, string_in): self.string_in = string_in def _default_format(self, item): """ The default format if there is no format string """ pass def is_blank(self, item): """ if the information is not known (item is None), remove the format string information from the input string if any. """ if item is None: self.string_in.remove_start_end("(", ")") return True return False def generic_format(self, item, code, uppr, function): """the main parsing engine. Needed are the following: the input string code - List of one character (string) codes (all lowercase) uppr - list of one character (string) codes that can be uppercased each needs to have a lowercase equivalent in code function - list of functions. there is a one to one relationship with character codes and functions. """ if self.string_in.this != "(": return self._default_format(item) self.string_in.step() main = VarString() separator = SeparatorParse(self.string_in) #code given in args #function given in args while self.string_in.this and self.string_in.this != ")": #Check to see if _in.this is in code to_upper = False if uppr.find(self.string_in.this) != -1: #and the result should be uppercased. to_upper = True where = code.find(self.string_in.this.lower()) else: where = code.find(self.string_in.this) if where != -1: self.string_in.step() tmp = function[where]() if to_upper: tmp = tmp.upper() if tmp == "" or tmp is None: main.add_remove() elif isinstance(tmp, VarString): #events cause this main.extend(tmp) else: main.add_variable(tmp) elif separator.is_a(): main.add_separator(separator.parse_format()) else: main.add_text(self.string_in.parse_format()) if self.string_in.this == ")": self.string_in.step() return main #------------------------------------------------------------------------ # Name Format strings #------------------------------------------------------------------------ class NameFormat(GenericFormat): """ The name format class. If no format string, the name is displayed as per preference options otherwise, parse through a format string and put the name parts in """ def get_name(self, person): """ A helper method for retrieving the person's name """ if person: return person.get_primary_name() return None def _default_format(self, name): """ display the name as set in preferences """ return name_displayer.sorted_name(name) def parse_format(self, name): """ Parse the name """ if self.is_blank(name): return def common(): """ return the common name of the person """ return (name.get_call_name() or name.get_first_name().split(' ')[0]) code = "tfcnxslg" upper = code.upper() function = [name.get_title, #t name.get_first_name, #f name.get_call_name, #c name.get_nick_name, #n common, #x name.get_suffix, #s name.get_surname, #l name.get_family_nick_name #g ] return self.generic_format(name, code, upper, function) #------------------------------------------------------------------------ # Date Format strings #------------------------------------------------------------------------ class DateFormat(GenericFormat): """ The date format class. If no format string, the date is displayed as per preference options otherwise, parse through a format string and put the date parts in """ def get_date(self, event): """ A helper method for retrieving a date from an event """ if event: return event.get_date_object() return None def _default_format(self, date): return displayer.display(date) def __count_chars(self, char, max_amount): """ count the year/month/day codes """ count = 1 #already have seen/passed one while count < max_amount and self.string_in.this == char: self.string_in.step() count = count +1 return count def parse_format(self, date): """ Parse the name """ if self.is_blank(date): return def year(): """ The year part only """ year = cuni(date.get_year()) count = self.__count_chars("y", 4) if year == "0": return if count == 1: #found 'y' if len(year) == 1: return year elif year[-2] == "0": return year[-1] else: return year[-2:] elif count == 2: #found 'yy' tmp = "0" + year return tmp[-2:] elif count == 3: #found 'yyy' if len(year) > 2: return year else: tmp = "00" + year return tmp[-3:] else: #count == 4 #found 'yyyy' tmp = "000" + year return tmp[-4:] def month(char_found = "m"): """ The month part only """ month = cuni(date.get_month()) count = self.__count_chars(char_found, 4) if month == "0": return if count == 1: return month elif count == 2: #found 'mm' tmp = "0" + month return tmp[-2:] elif count == 3: #found 'mmm' return displayer.short_months[int(month)] else: #found 'mmmm' return displayer.long_months[int(month)] def month_up(): return month("M").upper() def day(): """ The day part only """ day = cuni(date.get_day()) count = self.__count_chars("d", 2) if day == "0": #0 means not defined! return if count == 1: #found 'd' return day else: #found 'dd' tmp = "0" + day return tmp[-2:] def modifier(): #ui_mods taken from date.py def lookup_modifier(self, modifier): ui_mods = ["", _("before"), _("after"), _("about"), "", "", ""] return ui_mods[date.get_modifier()].capitalize() code = "ymdMo" upper = "O" function = [year, month, day, month_up, modifier] return self.generic_format(date, code, upper, function) #------------------------------------------------------------------------ # Place Format strings #------------------------------------------------------------------------ class PlaceFormat(GenericFormat): """ The place format class. If no format string, the place is displayed as per preference options otherwise, parse through a format string and put the place parts in """ def get_place(self, database, event): """ A helper method for retrieving a place from an event """ if event: bplace_handle = event.get_place_handle() if bplace_handle: return database.get_place_from_handle(bplace_handle) return None def _default_format(self, place): return place.get_title() def parse_format(self, place): """ Parse the place """ if self.is_blank(place): return code = "elcuspnitxy" upper = code.upper() function = [place.get_main_location().get_street, place.get_main_location().get_locality, place.get_main_location().get_city, place.get_main_location().get_county, place.get_main_location().get_state, place.get_main_location().get_postal_code, place.get_main_location().get_country, place.get_main_location().get_parish, place.get_title, place.get_longitude, place.get_latitude ] return self.generic_format(place, code, upper, function) #------------------------------------------------------------------------ # Event Format strings #------------------------------------------------------------------------ class EventFormat(GenericFormat): """ The event format class. If no format string, the event description is displayed otherwise, parse through the format string and put in the parts dates and places can have their own format strings """ def __init__(self, database, _in): self.database = database GenericFormat.__init__(self, _in) def _default_format(self, event): if event is None: return else: return event.get_description() def __empty_format(self): """ clear out a sub format string """ self.string_in.remove_start_end("(", ")") return def __empty_attrib(self): """ clear out an attribute name """ self.string_in.remove_start_end("[", "]") return def parse_format(self, event): """ Parse the event format string. let the date or place classes handle any sub-format strings """ if self.is_blank(event): return def format_date(): """ start formatting a date in this event """ date_format = DateFormat(self.string_in) return date_format.parse_format(date_format.get_date(event)) def format_place(): """ start formatting a place in this event """ place_format = PlaceFormat(self.string_in) place = place_format.get_place(self.database, event) return place_format.parse_format(place) def format_attrib(): """ Get the name and then get the attributes value """ #Event's Atribute attrib_parse = AttributeParse(self.string_in) #self.string_in.step() name = attrib_parse.get_name() if name: return attrib_parse.get_attribute(event.get_attribute_list(), name) else: return code = "ndDia" upper = "" function = [event.get_description, format_date, format_place, event.get_gramps_id, format_attrib ] return self.generic_format(event, code, upper, function) def parse_empty(self): """ remove the format string """ code = "dDa" function = [self.__empty_format, self.__empty_format, self.__empty_attrib] return self.generic_format(None, code, "", function) #------------------------------------------------------------------------ # Gallery Format strings #------------------------------------------------------------------------ class GalleryFormat(GenericFormat): """ The gallery format class. If no format string, the photo description is displayed otherwise, parse through the format string and put in the parts dates (no places) can have their own format strings """ def __init__(self, database, _in): self.database = database GenericFormat.__init__(self, _in) def _default_format(self, photo): if photo is None: return else: return photo.get_description() def __empty_format(self): """ clear out a sub format string """ self.string_in.remove_start_end("(", ")") return def __empty_attrib(self): """ clear out an attribute name """ self.string_in.remove_start_end("[", "]") return def parse_format(self, photo): """ Parse the photo format string. let the date or place classes handle any sub-format strings """ if self.is_blank(photo): return def format_date(): """ start formatting a date in this photo """ date_format = DateFormat(self.string_in) return date_format.parse_format(date_format.get_date(photo)) def format_attrib(): """ Get the name and then get the attributes value """ #photo's Atribute attrib_parse = AttributeParse(self.string_in) name = attrib_parse.get_name() if name: return attrib_parse.get_attribute(photo.get_attribute_list(), name) else: return code = "ndia" upper = "" function = [photo.get_description, format_date, photo.get_gramps_id, format_attrib ] return self.generic_format(photo, code, upper, function) def parse_empty(self): """ remove the format string """ code = "da" function = [self.__empty_format, self.__empty_attrib] return self.generic_format(None, code, "", function) #------------------------------------------------------------------------ # # ConsumableString - The Input string class # #------------------------------------------------------------------------ class ConsumableString(object): """ A simple string implementation with extras to help with parsing. This will contain the string to be parsed. or string in. There will only be one of these for each processed line. """ def __init__(self, string): self.__this_string = string self.__setup() def __setup(self): """ update class attributes this and next """ if len(self.__this_string) > 0: self.this = self.__this_string[0] else: self.this = None if len(self.__this_string) > 1: self.next = self.__this_string[1] else: self.next = None def step(self): """ remove the first char from the string """ self.__this_string = self.__this_string[1:] self.__setup() return self.this def step2(self): """ remove the first two chars from the string """ self.__this_string = self.__this_string[2:] self.__setup() return self.this def remove_start_end(self, start, end): """ Removes a start, end block from the string if there """ if self.this == start: self.text_to_next(end) def __get_a_char_of_text(self): """ Removes one char of TEXT from the string and returns it. """ if self.this == "\\": if self.next == None: rtrn = "\\" else: rtrn = self.next self.step2() else: rtrn = self.this self.step() return rtrn def text_to_next(self, char): """ return/remove a format strings from here """ new_str = "" while self.this is not None and self.this != char: new_str += self.__get_a_char_of_text() if self.this == char: self.step() return new_str def is_a(self): return True def parse_format(self): rtrn = self.__get_a_char_of_text() if rtrn: return rtrn return '' #------------------------------------------------------------------------ # # VarString class - The Output string class # #------------------------------------------------------------------------ class VarString(object): """ The current state of the entire string (integer from TextTypes) A list to hold tuple object (integer from TextTypes, string) This will contain the string that will be displayed. or string out. it is used for groups and format strings. """ def __init__(self, start_state = TXT.remove): self.state = start_state #overall state of the string. self._text = [] #list of tuples (TXT.?, string) def __update_state(self, new_status): if new_status > self.state: self.state = new_status def add_text(self, text): self._text.append((TXT.text, text)) def add_variable(self, text): self.state = TXT.display self._text.append((TXT.text, text)) def add_remove(self): self.__update_state(TXT.remove) self._text.append((TXT.remove, "")) def add_separator(self, text): self._text.append((TXT.separator, text)) def get_final(self): #if self.state == TXT.remove: # return (TXT.remove, "") curr_string = "" index = 0 while index < len(self._text): if self._text[index][0] == TXT.text: curr_string += self._text[index][1] index = index + 1 continue #while self._text: if index +1 == len(self._text): if self._text[index][0] == TXT.separator and curr_string != '': curr_string += self._text[index][1] index = index + 1 break #while self._text: type_0_1 = (self._text[index][0], self._text[index+1][0]) #if type_0_1 == (TXT.remove, TXT.remove): # pass if type_0_1 == (TXT.remove, TXT.separator): index = index + 1 #elif type_0_1 == (TXT.remove, TXT.text): # pass elif type_0_1 == (TXT.separator, TXT.remove): index = index + 1 #elif type_0_1 == (TXT.separator, TXT.separator): # pass elif type_0_1 == (TXT.separator, TXT.text): curr_string += self._text[index][1] #else: # print "#oops Should never get here." index = index + 1 #return what we have return (self.state, curr_string) print("===" + str(self.state) + " '" + str(curr_string) + "'") def extend(self, acquisition): """ acquisition is a VarString object Merge the content of acquisition into this place. """ self.__update_state(acquisition.state) if acquisition.state != TXT.display: #The sub {} was TXT.remove. We don't want to simply ignore it. self.add_remove() #add a remove que here to note it. return self._text.extend(acquisition._text) #------------------------------------------------------------------------ # # Parsers # #------------------------------------------------------------------------ #------------------------------------------------------------------------ # SeparatorParse #------------------------------------------------------------------------ class SeparatorParse(object): """ parse out a separator """ def __init__(self, consumer_in): self._in = consumer_in def is_a(self): return self._in.this == "<" def parse_format(self): if not self.is_a(): return """ get the text and return it """ self._in.step() return self._in.text_to_next(">") #------------------------------------------------------------------------ # AttributeParse #------------------------------------------------------------------------ class AttributeParse(object): """ Parse attributes """ def __init__(self, consumer_in): self._in = consumer_in def get_name(self): """ Gets a name inside a [] block """ if self._in.this != "[": return self._in.step() return self._in.text_to_next("]") def get_attribute(self, attrib_list, attrib_name): """ Get an attribute by name """ if attrib_name == "": return for attr in attrib_list: if str(attr.get_type()) == attrib_name: return str(attr.get_value()) return def is_a(self): """ check """ return self._in.this == "a" def parse_format(self, attrib_list): """ Get the attribute and add it to the string out """ name = self.get_name() return self.get_attribute(attrib_list, name) #------------------------------------------------------------------------ # VariableParse #------------------------------------------------------------------------ class VariableParse(object): """ Parse the individual variables """ def __init__(self, friend, database, consumer_in): self.friend = friend self.database = database self._in = consumer_in def is_a(self): """ check """ return self._in.this == "$" and self._in.next is not None and \ "nsijbBdDmMvVauetTpP".find(self._in.next) != -1 def get_event_by_type(self, marriage, e_type): """ get an event from a type """ if marriage is None: return None for e_ref in marriage.get_event_ref_list(): if not e_ref: continue event = self.friend.database.get_event_from_handle(e_ref.ref) if event.get_type() == e_type: return event return None def get_event_by_name(self, person, event_name): """ get an event from a name. """ if not person: return None for e_ref in person.get_event_ref_list(): if not e_ref: continue event = self.friend.database.get_event_from_handle(e_ref.ref) if event.get_type().is_type(event_name): return event return None def empty_item(self, item): """ return false if there is a valid item(date or place). Otherwise add a TXT.remove marker in the output string remove any format strings from the input string """ if item is not None: return False self._in.remove_start_end("(", ")") return True def empty_attribute(self, person): """ return false if there is a valid person. Otherwise add a TXT.remove marker in the output string remove any attribute name from the input string """ if person: return False self._in.remove_start_end("[", "]") return True def __parse_date(self, event): """ sub to process a date Given an event, get the date object, process the format, return the result """ date_f = DateFormat(self._in) date = date_f.get_date(event) if self.empty_item(date): return return date_f.parse_format(date) def __parse_place(self, event): """ sub to process a date Given an event, get the place object, process the format, return the result """ place_f = PlaceFormat(self._in) place = place_f.get_place(self.database, event) if self.empty_item(place): return return place_f.parse_format(place) def __parse_name(self, person): name_format = NameFormat(self._in) name = name_format.get_name(person) return name_format.parse_format(name) def __parse_id(self, first_class_object): if first_class_object is not None: return first_class_object.get_gramps_id() else: return def __parse_event(self, person, attrib_parse): event = self.get_event_by_name(person, attrib_parse.get_name()) event_f = EventFormat(self.database, self._in) if event: return event_f.parse_format(event) else: event_f.parse_empty() return def __get_photo(self, person_or_marriage): """ returns the first photo in the media list or None """ media_list = person_or_marriage.get_media_list() for media_ref in media_list: media_handle = media_ref.get_reference_handle() media = self.database.get_object_from_handle(media_handle) mime_type = media.get_mime_type() if mime_type and mime_type.startswith("image"): return media return None def __parse_photo(self, person_or_marriage): photo_f = GalleryFormat(self.database, self._in) if person_or_marriage is None: return photo_f.parse_empty() photo = self.__get_photo(person_or_marriage) if photo: return photo_f.parse_format(photo) else: return photo_f.parse_empty() def parse_format(self): """Parse the $ variables. """ if not self.is_a(): return attrib_parse = AttributeParse(self._in) next_char = self._in.next self._in.step2() if next_char == "n": #Person's name return self.__parse_name(self.friend.person) elif next_char == "s": #Souses name return self.__parse_name(self.friend.spouse) elif next_char == "i": #Person's Id return self.__parse_id(self.friend.person) elif next_char == "j": #Marriage Id return self.__parse_id(self.friend.family) elif next_char == "b": #Person's Birth date if self.empty_item(self.friend.person): return return self.__parse_date( get_birth_or_fallback(self.friend.database, self.friend.person)) elif next_char == "d": #Person's Death date if self.empty_item(self.friend.person): return return self.__parse_date( get_death_or_fallback(self.friend.database, self.friend.person)) elif next_char == "m": #Marriage date if self.empty_item(self.friend.family): return return self.__parse_date( self.get_event_by_type(self.friend.family, EventType.MARRIAGE)) elif next_char == "v": #Divorce date if self.empty_item(self.friend.family): return return self.__parse_date( self.get_event_by_type(self.friend.family, EventType.DIVORCE)) elif next_char == "T": #Todays date date_f = DateFormat(self._in) from gramps.gen.lib.date import Today date = Today() if self.empty_item(date): return return date_f.parse_format(date) elif next_char == "B": #Person's birth place if self.empty_item(self.friend.person): return return self.__parse_place( get_birth_or_fallback(self.friend.database, self.friend.person)) elif next_char == "D": #Person's death place if self.empty_item(self.friend.person): return return self.__parse_place( get_death_or_fallback(self.friend.database, self.friend.person)) elif next_char == "M": #Marriage place if self.empty_item(self.friend.family): return return self.__parse_place( self.get_event_by_type(self.friend.family, EventType.MARRIAGE)) elif next_char == "V": #Divorce place if self.empty_item(self.friend.family): return return self.__parse_place( self.get_event_by_type(self.friend.family, EventType.DIVORCE)) elif next_char == "a": #Person's Atribute if self.empty_attribute(self.friend.person): return return attrib_parse.parse_format( self.friend.person.get_attribute_list()) elif next_char == "u": #Marriage Atribute if self.empty_attribute(self.friend.family): return return attrib_parse.parse_format( self.friend.family.get_attribute_list()) elif next_char == "e": #person event return self.__parse_event(self.friend.person, attrib_parse) elif next_char == "t": #person event return self.__parse_event(self.friend.family, attrib_parse) elif next_char == 'p': #photo for the person return self.__parse_photo(self.friend.person) elif next_char == 'P': #photo for the marriage return self.__parse_photo(self.friend.family) #------------------------------------------------------------------------ # # SubstKeywords # #------------------------------------------------------------------------ class SubstKeywords(object): """Accepts a person/family with format lines and returns a new set of lines using variable substitution to make it. The individual variables are defined with the classes that look for them. Needed: Database object person_handle This will be the center person for the display family_handle this will specify the specific family/spouse to work with. If none given, then the first/preferred family/spouse is used """ def __init__(self, database, person_handle, family_handle=None): """get the person and find the family/spouse to use for this display""" self.database = database self.person = database.get_person_from_handle(person_handle) self.family = None self.spouse = None self.line = None #Consumable_string - set below if self.person is None: return fam_hand_list = self.person.get_family_handle_list() if fam_hand_list: if family_handle in fam_hand_list: self.family = database.get_family_from_handle(family_handle) else: #Error. fam_hand_list[0] below may give wrong marriage info. #only here because of OLD specifications. Specs read: # * $S/%S # Displays the name of the person's preferred ... # 'preferred' means FIRST. #The first might not be the correct marriage to display. #else: clause SHOULD be removed. self.family = database.get_family_from_handle(fam_hand_list[0]) father_handle = self.family.get_father_handle() mother_handle = self.family.get_mother_handle() self.spouse = None if father_handle == person_handle: if mother_handle: self.spouse = database.get_person_from_handle(mother_handle) else: if father_handle: self.spouse = database.get_person_from_handle(father_handle) def __parse_line(self): """parse each line of text and return the new displayable line There are four things we can find here A {} group which will make/end as needed. A <> separator A $ variable - Handled separately or text """ stack_var = [] curr_var = VarString(TXT.text) #First we are going take care of all variables/groups #break down all {} (groups) and $ (vars) into either #(TXT.text, resulting_string) or (TXT.remove, '') variable = VariableParse(self, self.database, self.line) # $ while self.line.this: if self.line.this == "{": #Start of a group #push what we have onto the stack stack_var.append(curr_var) #Setup curr_var = VarString() #step self.line.step() elif self.line.this == "}" and len(stack_var) > 0: #End of a group #add curr to what is on the (top) stack and pop into current #or pop the stack into current and add TXT.remove direction = curr_var.state if direction == TXT.display: #add curr onto the top slot of the stack stack_var[-1].extend(curr_var) #pop what we have on the stack curr_var = stack_var.pop() if direction == TXT.remove: #add remove que curr_var.add_remove() #step self.line.step() elif variable.is_a(): # $ (variables) rtrn = variable.parse_format() if rtrn is None: curr_var.add_remove() elif isinstance(rtrn, VarString): curr_var.extend(rtrn) else: curr_var.add_variable(rtrn) elif self.line.this == "<": # separator self.line.step() curr_var.add_separator(self.line.text_to_next(">")) else: #regular text curr_var.add_text(self.line.parse_format()) #the stack is for groups/subgroup and may contain items #if the user does not close his/her {} #squash down the stack while stack_var: direction = curr_var.state if direction == TXT.display: #add curr onto the top slot of the stack stack_var[-1].extend(curr_var) #pop what we have on the stack curr_var = stack_var.pop() if direction == TXT.remove: #add remove que curr_var.add_remove() #step self.line.step() #return what we have return curr_var.get_final() def __main_level(self): #Check only if the user wants to not display the line if TXT.remove remove_line_tag = False if self.line.this == "-": remove_line_tag = True self.line.step() state, line = self.__parse_line() if state is TXT.remove and remove_line_tag: return None return line def replace_and_clean(self, lines): """ return a new array of lines with all of the substitutions done """ new = [] for this_line in lines: if this_line == "": new.append(this_line) continue #print "- ", this_line self.line = ConsumableString(this_line) new_line = self.__main_level() #print "+ ", new_line if new_line is not None: new.append(new_line) if new == []: new = [""] return new #Acts 20:35 (New International Version) #In everything I did, I showed you that by this kind of hard work #we must help the weak, remembering the words the Lord Jesus himself #said: 'It is more blessed to give than to receive.' if __name__ == '__main__': #------------------------------------------------------------------------- # # For Testing everything except VariableParse, SubstKeywords and EventFormat # apply it as a script: # # ==> in command line do "PYTHONPATH=??? python libsubstkeyword.py" # # You will need to put in your own path to the src directory # #------------------------------------------------------------------------- # pylint: disable-msg=C0103 def combinations(c, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(range(c)) n = len(pool) if r > n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while True: for i in reversed(list(range(r))): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) def main_level_test(_in, testing_class, testing_what): """This is a mini def __main_level(self): """ main = LevelParse(_in) sepa = SeparatorParse(_in) test = testing_class(_in) while _in.this: if main.is_a(): main.parse_format(_in) elif sepa.is_a(): sepa.parse_format(main) elif _in.this == "$": _in.step() main.add_variable( test.parse_format(testing_what)) else: _in.parse_format(main) main.combine_all() state, line = main.get_string() if state is TXT.remove: return None else: return line from gramps.gen.lib.date import Date y_or_n = () date_to_test = Date() def date_set(): date_to_test.set_yr_mon_day( 1970 if 0 in y_or_n else 0, 9 if 1 in y_or_n else 0, 3 if 2 in y_or_n else 0 ) #print date_to_test line_in = "<Z>$(yyy) <a>$(<Z>Mm)<b>$(mm){<c>$(d)}{<d>$(yyyy)<e>}<f>$(yy)" consume_str = ConsumableString(line_in) print(line_in) print("#None are known") tmp = main_level_test(consume_str, DateFormat, date_to_test) print(tmp) print("Good" if tmp == " " else "!! bad !!") print() print() print("#One is known") answer = [] for y_or_n in combinations(3, 1): date_set() consume_str = ConsumableString(line_in) tmp = main_level_test(consume_str, DateFormat, date_to_test) print(tmp) answer.append(tmp) print("Good" if answer == [ "1970 d1970f70", " a99b09", " c3" ] else "!! bad !!") print() print() print("#Two are known") answer = [] for y_or_n in combinations(3, 2): date_set() consume_str = ConsumableString(line_in) tmp = main_level_test(consume_str, DateFormat, date_to_test) print(tmp) answer.append(tmp) print("Good" if answer == [ "1970 a99b09d1970f70", "1970 c3d1970f70", " a99b09c3" ] else "!! bad !!") print() print() print("#All are known") answer = [] y_or_n = (0, 1, 2) date_set() consume_str = ConsumableString(line_in) tmp = main_level_test(consume_str, DateFormat, date_to_test) print(tmp) answer.append(tmp) print("Good" if answer == ["1970 a99b09c3d1970f70" ] else "!! bad !!") import sys sys.exit() print() print() print("=============") print("=============") from gramps.gen.lib.name import Name y_or_n = () name_to_test = Name() def name_set(): #code = "tfcnxslg" name_to_test.set_call_name("Bob" if 0 in y_or_n else "") name_to_test.set_title("Dr." if 1 in y_or_n else "") name_to_test.set_first_name("Billy" if 2 in y_or_n else "") name_to_test.set_nick_name("Buck" if 3 in y_or_n else "") name_to_test.set_suffix("IV" if 4 in y_or_n else "") #now can we put something in for the last name? name_to_test.set_family_nick_name("The Clubs" if 5 in y_or_n else "") line_in = "{$(c)$(t)<1>{<2>$(f)}{<3>$(n){<0> <0>}<4>$(x)}$(s)<5>$(l)<6>$(g)<0>" consume_str = ConsumableString(line_in) print() print() print(line_in) print("#None are known") tmp = main_level_test(consume_str, NameFormat, name_to_test) print(tmp) print("Good" if tmp == None else "!! bad !!") print() print() print("#Two are known") answer = [] for y_or_n in combinations(6, 2): name_set() consume_str = ConsumableString(line_in) tmp = main_level_test(consume_str, NameFormat, name_to_test) print(tmp) answer.append(tmp) print("Good" if answer == [ "BobDr.4Bob", "Bob2Billy4Bob", "Bob3Buck4Bob", "Bob4BobIV", "Bob4BobThe Clubs", "Dr.2Billy4Billy", "Dr.3Buck", "Dr.1IV", "Dr.6The Clubs", "Billy3Buck4Billy", "Billy4BillyIV", "Billy4BillyThe Clubs", "BuckIV", "BuckThe Clubs", "IV6The Clubs" ] else "!! bad !!") print() print() print("#All are known") y_or_n = (0, 1, 2, 3, 4, 5) name_set() consume_str = ConsumableString(line_in) answer = main_level_test(consume_str, NameFormat, name_to_test) print(answer) print("Good" if answer == "BobDr.2Billy3Buck4BobIV6The Clubs" \ else "!! bad !!") print() print() print("=============") print("=============") from gramps.gen.lib.place import Place y_or_n = () place_to_test = Place() def place_set(): #code = "elcuspnitxy" main_loc = place_to_test.get_main_location() main_loc.set_street( "Lost River Ave." if 0 in y_or_n else "" ) main_loc.set_locality( "Second district" if 1 in y_or_n else "" ) main_loc.set_city( "Arco" if 2 in y_or_n else "" ) main_loc.set_county( "Butte" if 3 in y_or_n else "" ) main_loc.set_state( "Idaho" if 4 in y_or_n else "" ) main_loc.set_postal_code( "83213" if 5 in y_or_n else "" ) main_loc.set_country( "USA" if 6 in y_or_n else "" ) main_loc.set_parish( "St Anns" if 7 in y_or_n else "" ) place_to_test.set_title( "Atomic City" if 8 in y_or_n else "" ) place_to_test.set_longitude( "N43H38'5\"N" if 9 in y_or_n else "" ) place_to_test.set_latitude( "W113H18'5\"W" if 10 in y_or_n else "" ) #code = "txy" line_in = "$(e)<1>{<2>$(l) <3> $(c)<4><0><5>{$(s)<6>$(p)<7>" + \ "{<1>$(n)<2>}<3>$(i<0>)<4>}<5>$(t)<6>$(x)<7>}<8>$(y)" consume_str = ConsumableString(line_in) print() print() print(line_in) print("#None are known") tmp = main_level_test(consume_str, PlaceFormat, place_to_test) print(tmp) print("Good" if tmp == "" else "!! bad !!") print() print() print("#Three are known (string lengths only)") answer = [] for y_or_n in combinations(11, 4): place_set() consume_str = ConsumableString(line_in) tmp = main_level_test(consume_str, PlaceFormat, place_to_test) #print tmp answer.append(len(tmp)) print(answer) print("Good" if answer == [38, 44, 44, 42, 46, 50, 49, 50, 40, 40, 38, 42, 46, 45, 46, 46, 44, 48, 52, 51, 52, 44, 48, 52, 51, 52, 46, 50, 49, 50, 54, 53, 54, 57, 58, 57, 28, 28, 26, 30, 34, 33, 34, 34, 32, 36, 40, 39, 40, 32, 36, 40, 39, 40, 34, 38, 37, 38, 42, 41, 42, 45, 46, 45, 30, 28, 32, 36, 35, 36, 28, 32, 36, 35, 36, 30, 34, 33, 34, 38, 37, 38, 41, 42, 41, 34, 38, 42, 41, 42, 36, 40, 39, 40, 44, 43, 44, 47, 48, 47, 36, 40, 39, 40, 44, 43, 44, 47, 48, 47, 42, 41, 42, 45, 46, 45, 49, 50, 49, 53, 28, 28, 26, 30, 34, 33, 34, 34, 32, 36, 40, 39, 40, 32, 36, 40, 39, 40, 34, 38, 37, 38, 42, 41, 42, 45, 46, 45, 30, 28, 32, 36, 35, 36, 28, 32, 36, 35, 36, 30, 34, 33, 34, 38, 37, 38, 41, 42, 41, 34, 38, 42, 41, 42, 36, 40, 39, 40, 44, 43, 44, 47, 48, 47, 36, 40, 39, 40, 44, 43, 44, 47, 48, 47, 42, 41, 42, 45, 46, 45, 49, 50, 49, 53, 19, 17, 21, 25, 24, 25, 17, 21, 25, 24, 25, 19, 23, 22, 23, 27, 26, 27, 30, 31, 30, 23, 27, 31, 30, 31, 25, 29, 28, 29, 33, 32, 33, 36, 37, 36, 25, 29, 28, 29, 33, 32, 33, 36, 37, 36, 31, 30, 31, 34, 35, 34, 38, 39, 38, 42, 19, 23, 27, 26, 27, 21, 25, 24, 25, 29, 28, 29, 32, 33, 32, 21, 25, 24, 25, 29, 28, 29, 32, 33, 32, 27, 26, 27, 30, 31, 30, 34, 35, 34, 38, 27, 31, 30, 31, 35, 34, 35, 38, 39, 38, 33, 32, 33, 36, 37, 36, 40, 41, 40, 44, 33, 32, 33, 36, 37, 36, 40, 41, 40, 44, 38, 39, 38, 42, 46] else "!! bad !!")
Forage/Gramps
gramps/plugins/lib/libsubstkeyword.py
Python
gpl-2.0
48,355
0.007424
""" InaSAFE Disaster risk assessment tool developed by AusAid - **GUI Dialog.** Contact : ole.moller.nielsen@gmail.com .. note:: 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. .. todo:: Check raster is single band """ from safe.common.utilities import temp_dir __author__ = 'tim@linfiniti.com' __version__ = '0.5.0' __revision__ = '$Format:%H$' __date__ = '10/01/2011' __copyright__ = ('Copyright 2012, Australia Indonesia Facility for ' 'Disaster Reduction') __type__ = 'alpha' # beta, final etc will be shown in dock title import numpy import os from PyQt4 import QtGui, QtCore from PyQt4.QtCore import pyqtSlot from safe_qgis.dock_base import Ui_DockBase from safe_qgis.aggregation_attribute_dialog_base import\ Ui_AggregationAttributeDialogBase from safe_qgis.help import Help from safe_qgis.utilities import (getExceptionWithStacktrace, getWGS84resolution, logOnQgsMessageLog) from qgis.core import (QgsMapLayer, QgsVectorLayer, QgsRasterLayer, QgsMapLayerRegistry, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QGis, QgsFeature, QgsRectangle) from qgis.analysis import QgsZonalStatistics from safe_qgis.impact_calculator import ImpactCalculator from safe_qgis.safe_interface import (availableFunctions, getFunctionTitle, getOptimalExtent, getBufferedExtent, internationalisedNames, writeKeywordsToFile) from safe_qgis.keyword_io import KeywordIO from safe_qgis.clipper import clipLayer from safe_qgis.exceptions import (KeywordNotFoundException, InsufficientOverlapException, InvalidParameterException, InsufficientParametersException, HashNotFoundException) from safe_qgis.map import Map from safe.api import write_keywords, read_keywords, ReadLayerError from safe_qgis.utilities import (htmlHeader, htmlFooter, setVectorStyle, setRasterStyle, qgisVersion) # Don't remove this even if it is flagged as unused by your ide # it is needed for qrc:/ url resolution. See Qt Resources docs. import safe_qgis.resources # pylint: disable=W0611 #see if we can import pydev - see development docs for details try: from pydevd import * # pylint: disable=F0401 print 'Remote debugging is enabled.' DEBUG = True except ImportError: print 'Debugging was disabled' class Dock(QtGui.QDockWidget, Ui_DockBase): """Dock implementation class for the Risk In A Box plugin.""" def __init__(self, iface): """Constructor for the dialog. This dialog will allow the user to select layers and scenario details and subsequently run their model. .. note:: We use the multiple inheritance approach from Qt4 so that for elements are directly accessible in the form context and we can use autoconnect to set up slots. See article below: http://doc.qt.nokia.com/4.7-snapshot/designer-using-a-ui-file.html Args: * iface - a Quantum GIS QGisAppInterface instance. Returns: not applicable Raises: no exceptions explicitly raised """ QtGui.QDockWidget.__init__(self, None) self.setupUi(self) self.setWindowTitle(self.tr('InaSAFE %s %s' % ( __version__, __type__))) # Save reference to the QGIS interface self.iface = iface self.header = None # for storing html header template self.footer = None # for storing html footer template self.calculator = ImpactCalculator() self.keywordIO = KeywordIO() self.runner = None self.helpDialog = None self.state = None self.runInThreadFlag = False self.showOnlyVisibleLayersFlag = True self.setLayerNameFromTitleFlag = True self.zoomToImpactFlag = True self.hideExposureFlag = True self.hazardLayers = None # array of all hazard layers self.exposureLayers = None # array of all exposure layers self.readSettings() # getLayers called by this self.setOkButtonStatus() self._aggregationPrefix = 'aggr_' self.initPostprocessingOutput() myButton = self.pbnHelp QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'), self.showHelp) myButton = self.pbnPrint QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'), self.printMap) #self.showHelp() myButton = self.pbnRunStop QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'), self.accept) #myAttribute = QtWebKit.QWebSettings.DeveloperExtrasEnabled #QtWebKit.QWebSettings.setAttribute(myAttribute, True) def readSettings(self): """Set the dock state from QSettings. Do this on init and after changing options in the options dialog. Args: None Returns: None Raises: None """ mySettings = QtCore.QSettings() myFlag = mySettings.value('inasafe/useThreadingFlag', False).toBool() self.runInThreadFlag = myFlag myFlag = mySettings.value( 'inasafe/visibleLayersOnlyFlag', True).toBool() self.showOnlyVisibleLayersFlag = myFlag myFlag = mySettings.value( 'inasafe/setLayerNameFromTitleFlag', True).toBool() self.setLayerNameFromTitleFlag = myFlag myFlag = mySettings.value( 'inasafe/setZoomToImpactFlag', True).toBool() self.zoomToImpactFlag = myFlag # whether exposure layer should be hidden after model completes myFlag = mySettings.value( 'inasafe/setHideExposureFlag', False).toBool() self.hideExposureFlag = myFlag # whether to clip hazard and exposure layers to the viewport myFlag = mySettings.value( 'inasafe/clipToViewport', True).toBool() self.clipToViewport = myFlag self.getLayers() def connectLayerListener(self): """Establish a signal/slot to listen for changes in the layers loaded in QGIS. ..seealso:: disconnectLayerListener Args: None Returns: None Raises: None """ if qgisVersion() >= 10800: # 1.8 or newer QgsMapLayerRegistry.instance().layersWillBeRemoved.connect( self.layersWillBeRemoved) QgsMapLayerRegistry.instance().layersAdded.connect( self.layersAdded) # All versions of QGIS QtCore.QObject.connect(self.iface.mapCanvas(), QtCore.SIGNAL('layersChanged()'), self.getLayers) # pylint: disable=W0702 def disconnectLayerListener(self): """Destroy the signal/slot to listen for changes in the layers loaded in QGIS. ..seealso:: connectLayerListener Args: None Returns: None Raises: None """ try: QtCore.QObject.disconnect(QgsMapLayerRegistry.instance(), QtCore.SIGNAL('layerWillBeRemoved(QString)'), self.getLayers) except: pass try: QtCore.QObject.disconnect(QgsMapLayerRegistry.instance(), QtCore.SIGNAL('layerWasAdded(QgsMapLayer)'), self.getLayers) except: pass try: QgsMapLayerRegistry.instance().layersWillBeRemoved.disconnect( self.layersWillBeRemoved) QgsMapLayerRegistry.instance().layersAdded.disconnect( self.layersAdded) except: pass try: QtCore.QObject.disconnect(self.iface.mapCanvas(), QtCore.SIGNAL('layersChanged()'), self.getLayers) except: pass # pylint: enable=W0702 def validate(self): """Helper method to evaluate the current state of the dialog and determine if it is appropriate for the OK button to be enabled or not. .. note:: The enabled state of the OK button on the dialog will NOT be updated (set True or False) depending on the outcome of the UI readiness tests performed - **only** True or False will be returned by the function. Args: None. Returns: A two-tuple consisting of: * Boolean reflecting the results of the valudation tests. * A message indicating any reason why the validation may have failed. Example:: flag,myMessage = self.validate() Raises: no exceptions explicitly raised """ myHazardIndex = self.cboHazard.currentIndex() myExposureIndex = self.cboExposure.currentIndex() if myHazardIndex == -1 or myExposureIndex == -1: myMessage = '<table class="condensed">' myNotes = self.tr( 'To use this tool you need to add some layers to your ' 'QGIS project. Ensure that at least one <em>hazard</em> layer ' '(e.g. earthquake MMI) and one <em>exposure</em> layer (e.g. ' 'dwellings) re available. When you are ready, click the <em>' 'run</em> button below.') myMessage += ('<tr><th class="info button-cell">' + self.tr('Getting started:') + '</th></tr>\n' '<tr><td>' + myNotes + '</td></tr>\n') myMessage += '</table>' return (False, myMessage) if self.cboFunction.currentIndex() == -1: #myHazardFilename = self.getHazardLayer().source() myHazardKeywords = QtCore.QString(str(self.keywordIO.readKeywords( self.getHazardLayer()))) #myExposureFilename = self.getExposureLayer().source() myExposureKeywords = QtCore.QString( str(self.keywordIO.readKeywords( self.getExposureLayer()))) # TODO refactor impact_functions so it is accessible and user here myMessage = '<table class="condensed">' myNotes = self.tr('No functions are available for the inputs ' 'you have specified. ' 'Try selecting a different combination of inputs. ' 'Please consult the user manual <FIXME: add link> ' 'for details on what constitute valid inputs for ' 'a given risk function.') myMessage += ('<tr><th class="warning button-cell">' + self.tr('No valid functions:') + '</th></tr>\n' '<tr><td>' + myNotes + '</td></tr>\n') myMessage += ('<tr><th class="info button-cell">' + self.tr('Hazard keywords:') + '</th></tr>\n' '<tr><td>' + myHazardKeywords + '</td></tr>\n') myMessage += ('<tr><th class="info button-cell">' + self.tr('Exposure keywords:') + '</th></tr>\n' '<tr><td>' + myExposureKeywords + '</td></tr>\n') myMessage += '</table>' return (False, myMessage) else: # TODO refactor impact_functions so it is accessible and user here myMessage = '<table class="condensed">' myNotes = self.tr('You can now proceed to run your model by' ' clicking the <em>Run</em> button.') myMessage += ('<tr><th class="info button-cell">' + self.tr('Ready') + '</th></tr>\n' '<tr><td>' + myNotes + '</td></tr>\n') myMessage += '</table>' return (True, myMessage) def on_cboHazard_currentIndexChanged(self, theIndex): """Automatic slot executed when the Hazard combo is changed so that we can see if the ok button should be enabled. .. note:: Don't use the @pyqtSlot() decorator for autoslots! Args: None. Returns: None. Raises: No exceptions explicitly raised. """ # Add any other logic you might like here... del theIndex self.getFunctions() self._toggleCboAggregation() self.setOkButtonStatus() def on_cboExposure_currentIndexChanged(self, theIndex): """Automatic slot executed when the Exposure combo is changed so that we can see if the ok button should be enabled. .. note:: Don't use the @pyqtSlot() decorator for autoslots! Args: None. Returns: None. Raises: No exceptions explicitly raised. """ # Add any other logic you mught like here... del theIndex self.getFunctions() self._toggleCboAggregation() self.setOkButtonStatus() def on_cboFunction_currentIndexChanged(self, theIndex): """Automatic slot executed when the Function combo is changed so that we can see if the ok button should be enabled. .. note:: Don't use the @pyqtSlot() decorator for autoslots! Args: None. Returns: None. Raises: no exceptions explicitly raised. """ # Add any other logic you mught like here... del theIndex self._toggleCboAggregation() self.setOkButtonStatus() def setOkButtonStatus(self): """Helper function to set the ok button status if the form is valid and disable it if it is not. Args: None. Returns: None. Raises: no exceptions explicitly raised.""" myButton = self.pbnRunStop myFlag, myMessage = self.validate() myButton.setEnabled(myFlag) if myMessage is not '': self.displayHtml(myMessage) def canvasLayersetChanged(self): """A helper slot to update the dock combos if the canvas layerset has been changed (e.g. one or more layer visibilities changed). If self.showOnlyVisibleLayersFlag is set to False this method will simply return, doing nothing. Args: None Returns: None Raises: Any exceptions raised by the RIAB library will be propogated. """ if self.showOnlyVisibleLayersFlag: self.getLayers() @pyqtSlot() def layersWillBeRemoved(self): """Slot for the new (QGIS 1.8 and beyond api) to notify us when a group of layers is are removed. This is optimal since if many layers are removed this slot gets called only once. This slot simply delegates to getLayers and is only implemented here to make the connections between the different signals and slots clearer and better documented.""" self.getLayers() @pyqtSlot() def layersAdded(self, theLayers=None): """Slot for the new (QGIS 1.8 and beyond api) to notify us when a group of layers is are added. This is optimal since if many layers are added this slot gets called only once. This slot simply delegates to getLayers and is only implemented here to make the connections between the different signals and slots clearer and better documented.""" del theLayers self.getLayers() @pyqtSlot() def layerWillBeRemoved(self): """Slot for the old (pre QGIS 1.8 api) to notify us when a layer is removed. This is suboptimal since if many layers are removed this slot gets called multiple times. This slot simply delegates to getLayers and is only implemented here to make the connections between the different signals and slots clearer and better documented.""" self.getLayers() @pyqtSlot() def layerWasAdded(self): """Slot for the old (pre QGIS 1.8 api) to notify us when a layer is added. This is suboptimal since if many layers are added this slot gets called multiple times. This slot simply delegates to getLayers and is only implemented here to make the connections between the different signals and slots clearer and better documented.""" self.getLayers() def getLayers(self): """Helper function to obtain a list of layers currently loaded in QGIS. On invocation, this method will populate cboHazard, cboExposure and cboAggregate on the dialog with a list of available layers. Only **singleband raster** layers will be added to the hazard layer list,only **point vector** layers will be added to the exposure layer list and Only **polygon vector** layers will be added to the aggregate list Args: None. Returns: None Raises: no """ self.disconnectLayerListener() self.blockSignals(True) self.saveState() self.cboHazard.clear() self.cboExposure.clear() self.cboAggregation.clear() self.hazardLayers = [] self.exposureLayers = [] self.aggregationLayers = [] # Map registry may be invalid if QGIS is shutting down myRegistry = None # pylint: disable=W0702 try: myRegistry = QgsMapLayerRegistry.instance() except: return # pylint: enable=W0702 myCanvasLayers = self.iface.mapCanvas().layers() # MapLayers returns a QMap<QString id, QgsMapLayer layer> myLayers = myRegistry.mapLayers().values() for myLayer in myLayers: if (self.showOnlyVisibleLayersFlag and myLayer not in myCanvasLayers): continue # .. todo:: check raster is single band # store uuid in user property of list widget for layers myName = myLayer.name() mySource = str(myLayer.id()) # See if there is a title for this layer, if not, # fallback to the layer's filename try: myTitle = self.keywordIO.readKeywords(myLayer, 'title') except: # pylint: disable=W0702 myTitle = myName else: # Lookup internationalised title if available if myTitle in internationalisedNames: myTitle = internationalisedNames[myTitle] # Register title with layer if myTitle and self.setLayerNameFromTitleFlag: myLayer.setLayerName(myTitle) #check if layer is a vector polygon layer layer = myRegistry.mapLayer(mySource) if (layer.type() == QgsMapLayer.VectorLayer) and ( layer.geometryType() == QGis.Polygon): self.addComboItemInOrder(self.cboAggregation, myTitle, mySource) self.aggregationLayers.append(myLayer) # Find out if the layer is a hazard or an exposure # layer by querying its keywords. If the query fails, # the layer will be ignored. try: myCategory = self.keywordIO.readKeywords(myLayer, 'category') except: # pylint: disable=W0702 # continue ignoring this layer continue if myCategory == 'hazard': self.addComboItemInOrder(self.cboHazard, myTitle, mySource) self.hazardLayers.append(myLayer) elif myCategory == 'exposure': self.addComboItemInOrder(self.cboExposure, myTitle, mySource) self.exposureLayers.append(myLayer) #handle the cboAggregation combo self.cboAggregation.insertItem(0, self.tr('No aggregation')) self.cboAggregation.setCurrentIndex(0) self._toggleCboAggregation() # Now populate the functions list based on the layers loaded self.getFunctions() self.restoreState() self.setOkButtonStatus() # Note: Don't change the order of the next two lines otherwise there # will be a lot of unneeded looping around as the signal is handled self.connectLayerListener() self.blockSignals(False) self.getAggregationLayer() return def _toggleCboAggregation(self): """Helper function to toggle the aggregation combo depending on the current dock status Args: None. Returns: None Raises: no """ #FIXME (MB) remove hazardlayer and exposure layer type check when # vector aggregation is supported selectedHazardLayer = self.getHazardLayer() selectedExposureLayer = self.getExposureLayer() #more than 1 because No aggregation is always there if (self.cboAggregation.count() > 1 and selectedHazardLayer is not None and selectedExposureLayer is not None and selectedHazardLayer.type() == QgsMapLayer.RasterLayer and selectedExposureLayer.type() == QgsMapLayer.RasterLayer): self.cboAggregation.setEnabled(True) else: self.cboAggregation.setEnabled(False) def getFunctions(self): """Helper function to obtain a list of impact functions from the impact calculator. Args: None. Returns: None Raises: no """ # remember what the current function is myOriginalFunction = self.cboFunction.currentText() self.cboFunction.clear() # Get the keyword dictionaries for hazard and exposure myHazardLayer = self.getHazardLayer() if myHazardLayer is None: return myExposureLayer = self.getExposureLayer() if myExposureLayer is None: return myHazardKeywords = self.keywordIO.readKeywords(myHazardLayer) # We need to add the layer type to the returned keywords if myHazardLayer.type() == QgsMapLayer.VectorLayer: myHazardKeywords['layertype'] = 'vector' elif myHazardLayer.type() == QgsMapLayer.RasterLayer: myHazardKeywords['layertype'] = 'raster' myExposureKeywords = self.keywordIO.readKeywords(myExposureLayer) # We need to add the layer type to the returned keywords if myExposureLayer.type() == QgsMapLayer.VectorLayer: myExposureKeywords['layertype'] = 'vector' elif myExposureLayer.type() == QgsMapLayer.RasterLayer: myExposureKeywords['layertype'] = 'raster' # Find out which functions can be used with these layers myList = [myHazardKeywords, myExposureKeywords] try: myDict = availableFunctions(myList) # Populate the hazard combo with the available functions for myFunctionID in myDict: myFunction = myDict[myFunctionID] myFunctionTitle = getFunctionTitle(myFunction) # KEEPING THESE STATEMENTS FOR DEBUGGING UNTIL SETTLED #print #print 'myFunction (ID)', myFunctionID #print 'myFunction', myFunction #print 'Function title:', myFunctionTitle # Provide function title and ID to function combo: # myFunctionTitle is the text displayed in the combo # myFunctionID is the canonical identifier self.addComboItemInOrder(self.cboFunction, myFunctionTitle, theItemData=myFunctionID) except Exception, e: raise e self.restoreFunctionState(myOriginalFunction) def readImpactLayer(self, myEngineImpactLayer): """Helper function to read and validate layer. Args myEngineImpactLayer: Layer object as provided by the inasafe engine Returns validated qgis layer or None Raises Exception if layer is not valid """ myMessage = ('Input argument must be a InaSAFE spatial object. ' 'I got %s' % type(myEngineImpactLayer)) if not hasattr(myEngineImpactLayer, 'is_inasafe_spatial_object'): raise Exception(myMessage) if not myEngineImpactLayer.is_inasafe_spatial_object: raise Exception(myMessage) # Get associated filename and symbolic name myFilename = myEngineImpactLayer.get_filename() myName = myEngineImpactLayer.get_name() # Read layer if myEngineImpactLayer.is_vector: myQgisLayer = QgsVectorLayer(myFilename, myName, 'ogr') elif myEngineImpactLayer.is_raster: myQgisLayer = QgsRasterLayer(myFilename, myName) # Verify that new qgis layer is valid if myQgisLayer.isValid(): return myQgisLayer else: myMessage = self.tr('Loaded impact layer "%s" is not' ' valid' % myFilename) raise Exception(myMessage) def getHazardLayer(self): """Obtain qgsmaplayer id from the userrole of the QtCombo for exposure and return it as a QgsMapLayer""" myIndex = self.cboHazard.currentIndex() if myIndex < 0: return None myLayerId = self.cboHazard.itemData(myIndex, QtCore.Qt.UserRole).toString() myLayer = QgsMapLayerRegistry.instance().mapLayer(myLayerId) return myLayer def getExposureLayer(self): """Obtain the name of the path to the exposure file from the userrole of the QtCombo for exposure.""" myIndex = self.cboExposure.currentIndex() if myIndex < 0: return None myLayerId = self.cboExposure.itemData(myIndex, QtCore.Qt.UserRole).toString() myLayer = QgsMapLayerRegistry.instance().mapLayer(myLayerId) return myLayer def getAggregationLayer(self): """Obtain the name of the path to the aggregation file from the userrole of the QtCombo for aggregation. Args: None Returns: - None if no aggregation is selected or cboAggregation is disabled - else a polygon layer """ myNoSelectionValue = 0 myIndex = self.cboAggregation.currentIndex() if myIndex <= myNoSelectionValue: return None myLayerId = self.cboAggregation.itemData(myIndex, QtCore.Qt.UserRole).toString() myLayer = QgsMapLayerRegistry.instance().mapLayer(myLayerId) return myLayer def getAggregationFieldNameCount(self): return self._aggregationPrefix + 'count' def getAggregationFieldNameMean(self): return self._aggregationPrefix + 'mean' def getAggregationFieldNameSum(self): return self._aggregationPrefix + 'sum' def setupCalculator(self): """Initialise the ImpactCalculator based on the current state of the ui. Args: None Returns: None Raises: Propogates any error from :func:optimalClip() """ try: myHazardFilename, myExposureFilename = self.optimalClip() except: QtGui.qApp.restoreOverrideCursor() self.hideBusy() raise # Identify input layers self.calculator.setHazardLayer(myHazardFilename) self.calculator.setExposureLayer(myExposureFilename) # Use canonical function name to identify selected function myFunctionID = self.getFunctionID() self.calculator.setFunction(myFunctionID) def accept(self): """Execute analysis when ok button is clicked.""" #.. todo:: FIXME (Tim) We may have to implement some polling logic # because the button click accept() function and the updating # of the web view after model completion are asynchronous (when # threading mode is enabled especially) self.showBusy() myFlag, myMessage = self.validate() if not myFlag: self.displayHtml(myMessage) self.hideBusy() return #check and generate keywords for the aggregation layer self.aggregationLayer = self.getAggregationLayer() if self.aggregationLayer is not None: try: self.aggregationAttribute = self._checkAggregationAttribute() except Exception, e: # pylint: disable=W0703 # FIXME (MB): This branch is not covered by the tests QtGui.qApp.restoreOverrideCursor() self.hideBusy() myMessage = self.tr('An exception occurred when reading the ' 'aggregation attribute.') myMessage = getExceptionWithStacktrace(e, html=True, context=myMessage) self.displayHtml(myMessage) return try: self.setupCalculator() except InsufficientOverlapException, e: QtGui.qApp.restoreOverrideCursor() self.hideBusy() myMessage = self.tr('An exception occurred when setting up the ' 'impact calculator.') myMessage = getExceptionWithStacktrace(e, html=True, context=myMessage) self.displayHtml(myMessage) return try: self.runner = self.calculator.getRunner() except InsufficientParametersException, e: QtGui.qApp.restoreOverrideCursor() self.hideBusy() myContext = self.tr('An exception occurred when setting up the ' ' model runner.') myMessage = getExceptionWithStacktrace(e, html=True, context=myContext) self.displayHtml(myMessage) return QtCore.QObject.connect(self.runner, QtCore.SIGNAL('done()'), self.startPostprocessing) QtGui.qApp.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) self.repaint() QtGui.qApp.processEvents() myTitle = self.tr('Calculating impact...') myMessage = self.tr('This may take a little while - we are ' 'computing the areas that will be impacted ' 'by the hazard and writing the result to ' 'a new layer.') myProgress = 66 try: self.showBusy(myTitle, myMessage, myProgress) if self.runInThreadFlag: self.runner.start() # Run in different thread else: self.runner.run() # Run in same thread QtGui.qApp.restoreOverrideCursor() # .. todo :: Disconnect done slot/signal except Exception, e: # pylint: disable=W0703 # FIXME (Ole): This branch is not covered by the tests QtGui.qApp.restoreOverrideCursor() self.hideBusy() myContext = self.tr('An exception occurred when starting' ' the model.') myMessage = getExceptionWithStacktrace(e, html=True, context=myContext) self.displayHtml(myMessage) def completed(self): """Slot activated when the process is done.""" # Try to run completion code try: myReport = self._completed() except Exception, e: # pylint: disable=W0703 # FIXME (Ole): This branch is not covered by the tests # Display message and traceback myMessage = getExceptionWithStacktrace(e, html=True) self.displayHtml(myMessage) else: # On success, display generated report self.displayHtml(myReport) self.saveState() # Hide hour glass self.hideBusy() def startPostprocessing(self): """ Called on self.runner SIGNAL('done()') starts all postprocessing steps Args: None Returns: None """ if self.aggregationLayer is not None: self.aggregateResults(88) self.completed() self.initPostprocessingOutput() def initPostprocessingOutput(self): """ initializes and clears self.postprocessingOutput. needs to run at the end of startPostprocessing Returns: None """ #FIXME (MB) maybe this could be a {} to allow having a parseable # structure where each postprocessor adds a # postprocessorname:'report string' pair self.postprocessingOutput = [] def addPostprocessingOutput(self, output): """ adds text to the postprocessingOutput Args: * output: the output from a postprocessor to add to the global output. It should be valid HTML but no checks are enforced. Returns: None """ self.postprocessingOutput.append(str(output)) def getPostprocessingOutput(self): """ gets the of the postprocessingOutput Args: None Returns: a string concatenation of the list elements """ return ' '.join(self.postprocessingOutput) def aggregateResults(self, progress): """ Aggregation postprocessing step, this delas with the gui stuff and calls _aggregateResults to do the actual aggregation work Args: progress %to show in the progressbar Returns: None """ myTitle = self.tr('Aggregating results...') myMessage = self.tr('This may take a little while - we are ' ' aggregating the hazards by %1').arg( self.cboAggregation.currentText()) myProgress = progress try: self.showBusy(myTitle, myMessage, myProgress) self._aggregateResults() self._parseAggregationResults() QtGui.qApp.restoreOverrideCursor() except Exception, e: # pylint: disable=W0703 # FIXME (Ole): This branch is not covered by the tests QtGui.qApp.restoreOverrideCursor() self.hideBusy() myContext = self.tr( 'An exception occurred when aggregating ' 'the results') myMessage = getExceptionWithStacktrace(e, html=True, context=myContext) self.displayHtml(myMessage) def _aggregateResults(self): """ Performs Aggregation postprocessing step by - creating a copy of the dataset clipped by the impactlayer bounding box - stripping all attributes beside the aggregation attribute - delegating to the appropriate aggregator for raster and vectors Args: None Returns: None """ impactLayer = self.runner.impactLayer() myQgisImpactLayer = self.readImpactLayer(impactLayer) if not myQgisImpactLayer.isValid(): myMessage = self.tr('Error when reading %1').arg(myQgisImpactLayer) raise ReadLayerError(myMessage) lName = str(self.tr('%1 aggregated to %2') .arg(myQgisImpactLayer.name()) .arg(self.aggregationLayer.name())) clippedAggregationLayerPath = clipLayer( self.aggregationLayer, impactLayer.get_bounding_box()) self.aggregationLayer = QgsVectorLayer( clippedAggregationLayerPath, lName, 'ogr') if not self.aggregationLayer.isValid(): myMessage = self.tr('Error when reading %1').arg( self.aggregationLayer.lastError()) raise ReadLayerError(myMessage) #delete unwanted fields vProvider = self.aggregationLayer.dataProvider() vFields = vProvider.fields() toDel = [] for i in vFields: if vFields[i].name() != self.aggregationAttribute: toDel.append(i) try: vProvider.deleteAttributes(toDel) # FIXME (Ole): Disable pylint check for the moment # Need to work out what exceptions we will catch here, though. except: # pylint: disable=W0702 myMessage = self.tr('Could not remove the unneded fields') logOnQgsMessageLog(myMessage) del toDel, vProvider, vFields writeKeywordsToFile(clippedAggregationLayerPath, {'title': lName}) if myQgisImpactLayer.type() == QgsMapLayer.VectorLayer: self._aggregateResultsVector(myQgisImpactLayer) elif myQgisImpactLayer.type() == QgsMapLayer.RasterLayer: self._aggregateResultsRaster(myQgisImpactLayer) else: myMessage = self.tr('%1 is %2 but it should be either vector or ' 'raster').arg(myQgisImpactLayer.name()).arg( myQgisImpactLayer.type()) raise ReadLayerError(myMessage) def _aggregateResultsVector(self, myQgisImpactLayer): """ Performs Aggregation postprocessing step on vectorial impact layers Args: * myQgisImpactLayer a valid QgsRasterLayer Returns: None """ #TODO implement polygon to polygon aggregation (dissolve, # line in polygon, point in polygon) logOnQgsMessageLog('Vector aggregation not implemented yet. Called on' ' %s' % myQgisImpactLayer.name()) return def _aggregateResultsRaster(self, myQgisImpactLayer): """ Performs Aggregation postprocessing step on raster impact layers by calling QgsZonalStatistics Args: * myQgisImpactLayer a valid QgsVectorLayer Returns: None """ zonStat = QgsZonalStatistics( self.aggregationLayer, myQgisImpactLayer.dataProvider().dataSourceUri(), self._aggregationPrefix) progressDialog = QtGui.QProgressDialog( self.tr('Calculating zonal statistics'), self.tr('Abort...'), 0, 0) zonStat.calculateStatistics(progressDialog) if progressDialog.wasCanceled(): QtGui.QMessageBox.error(self, self.tr('ZonalStats: Error'), self.tr( 'You aborted aggregation, ' 'so there are no data for analysis. Exiting...')) # QgsMapLayerRegistry.instance().addMapLayer(self.aggregationLayer) return def _parseAggregationResults(self): if self.aggregationAttribute is None: aggrAttrTitle = self.tr('Aggregation unit') else: aggrAttrTitle = self.aggregationAttribute #open table myHTML = ('<table class="table table-striped condensed">' ' <tbody>' ' <tr>' ' <td colspan="100%">' ' <strong>' + self.aggregationLayer.name() + ' </strong>' ' </td>' ' </tr>' ' <tr>' ' <th width="35%">' + aggrAttrTitle + ' </th>' ' <th>' + self.tr('Sum') + ' </th>' ' </tr>') #fill table provider = self.aggregationLayer.dataProvider() allAttrs = provider.attributeIndexes() # start data retreival: fetch no geometry and all attributes for each # feature provider.select(allAttrs, QgsRectangle(), False) try: nameFieldIndex = self.aggregationLayer.fieldNameIndex( self.aggregationAttribute) # FIXME (Ole): Disable pylint check for the moment # Need to work out what exceptions we will catch here, though. except: # pylint: disable=W0702 nameFieldIndex = None try: sumFieldIndex = self.aggregationLayer.fieldNameIndex( self.getAggregationFieldNameSum()) except ReadLayerError, e: QtGui.qApp.restoreOverrideCursor() self.hideBusy() myMessage = self.tr('An exception occurred when reading the' 'aggregation data. %1 not found in %2')\ .arg(self.getAggregationFieldNameSum())\ .arg(self.aggregationLayer.name()) myMessage = getExceptionWithStacktrace(e, html=True, context=myMessage) self.displayHtml(myMessage) return feat = QgsFeature() while provider.nextFeature(feat): attrMap = feat.attributeMap() if nameFieldIndex is None: name = str(feat.id()) else: name = attrMap[nameFieldIndex].toString() aggrSum = attrMap[sumFieldIndex].toString() aggrSum = str(int(round(float(aggrSum)))) myHTML += (' <tr>' ' <td>' + name + ' </td>' ' <td>' + aggrSum + ' </td>' ' </tr>') #close table myHTML += (' </tbody>' '</table>') self.addPostprocessingOutput(myHTML) def _checkAggregationAttribute(self): """checks if the aggregation layer has a aggregation attribute keyword. If not it calls _promptForAggregationAttribute to prompt for an input Args: None Returns: the value of the aggregation attribute keyword Raises: Propogates any error """ myKeywordFilePath = os.path.splitext(str( self.aggregationLayer.source()))[0] myKeywordFilePath += '.keywords' if not os.path.isfile(myKeywordFilePath): self._promptForAggregationAttribute(self.aggregationLayer, myKeywordFilePath, None) else: keywords = read_keywords(myKeywordFilePath) if 'aggregation attribute' in keywords: try: myValue = keywords['aggregation attribute'] except: raise else: myValue = self._promptForAggregationAttribute(self .aggregationLayer, myKeywordFilePath, keywords) return myValue def _promptForAggregationAttribute(self, myLayer, myKeywordFilePath, myKeywords): """prompt user for a decision on which attribute has to be the key attribute for the aggregated data and writes the keywords file This could be swapped to a call to the keyword editor Args: None Returns: the value of the aggregation attribute keyword. None if no usable attribute has been found Raises: Propagates any error """ if myKeywords is None: myKeywords = dict() vProvider = myLayer.dataProvider() vFields = vProvider.fields() fields = [] for i in vFields: # show only int or string fields to be chosen as aggregation # attribute other possible would be float if vFields[i].type() in [ QtCore.QVariant.Int, QtCore.QVariant.String]: fields.append(vFields[i].name()) #there is no usable attribute, use None if len(fields) == 0: aggrAttribute = None logOnQgsMessageLog( 'there is no usable attribute, use None') #there is only one usable attribute, use it elif len(fields) == 1: aggrAttribute = fields[0] logOnQgsMessageLog('there is only one usable attribute, ' 'use it: ' + str(aggrAttribute)) #there are multiple usable attribute, prompt for an answer elif len(fields) > 1: myTitle = self.tr( 'Waiting for aggregation attribute selection...') myMessage = self.tr('Please select which attribute you want to' ' use as ID for the aggregated results') myProgress = 1 self.showBusy(myTitle, myMessage, myProgress) #open a AggregationAttributeDialog dialog = QtGui.QDialog() #remove all windows hints to avoid allowing for cancelling the # dialog dialog.setWindowFlags(QtCore.Qt.CustomizeWindowHint) dialogGui = Ui_AggregationAttributeDialogBase() dialogGui.setupUi(dialog) dialogGui.buttonBox.button( QtGui.QDialogButtonBox.Cancel).setHidden(True) cboAggr = dialogGui.cboAggregationAttributes cboAggr.clear() cboAggr.addItems(fields) cboAggr.setCurrentIndex(0) self.disableBusyCursor() if dialog.exec_() == QtGui.QDialog.Accepted: aggrAttribute = cboAggr.currentText() logOnQgsMessageLog('User selected: ' + str(aggrAttribute) + ' as aggregation attribute') else: #the user cancelled, use the first attribute as default aggrAttribute = fields[0] # myMessage = self.tr( # 'You have to select an aggregation attribute') # raise InvalidParameterException(myMessage) self.enableBusyCursor() myKeywords['aggregation attribute'] = aggrAttribute write_keywords(myKeywords, myKeywordFilePath) return aggrAttribute def _completed(self): """Helper function for slot activated when the process is done. Args None Returns Report to render on canvas Raises Exceptions on a range of error conditions Provides report out from impact_function to canvas """ myTitle = self.tr('Loading results...') myMessage = self.tr('The impact assessment is complete - loading ' 'the results into QGIS now...') myProgress = 99 self.showBusy(myTitle, myMessage, myProgress) myMessage = self.runner.result() # FIXME (Ole): This branch is not covered by the tests myEngineImpactLayer = self.runner.impactLayer() if myEngineImpactLayer is None: myMessage = str(self.tr('No impact layer was calculated. ' 'Error message: %s\n' % str(myMessage))) if self.runner.lastTraceback() is not None: myMessage += '<br/><ul>' for myItem in self.runner.lastTraceback(): # replace is to tidy up windows paths a little myMessage += ('<li>' + str(myItem.replace('\\\\\\\\', '')) + '</li>') myMessage += '</ul>' raise Exception(myMessage, self.runner.lastException()) # Load impact layer into QGIS myQgisImpactLayer = self.readImpactLayer(myEngineImpactLayer) myKeywords = self.keywordIO.readKeywords(myQgisImpactLayer) #write postprocessing report to keyword myKeywords['postprocessing_report'] = self.getPostprocessingOutput() self.keywordIO.writeKeywords(myQgisImpactLayer, myKeywords) # Get tabular information from impact layer myReport = self.keywordIO.readKeywords(myQgisImpactLayer, 'impact_summary') # Get requested style for impact layer of either kind myStyle = myEngineImpactLayer.get_style_info() # Determine styling for QGIS layer if myEngineImpactLayer.is_vector: if not myStyle: # Set default style if possible pass else: setVectorStyle(myQgisImpactLayer, myStyle) elif myEngineImpactLayer.is_raster: if not myStyle: myQgisImpactLayer.setDrawingStyle( QgsRasterLayer.SingleBandPseudoColor) myQgisImpactLayer.setColorShadingAlgorithm( QgsRasterLayer.PseudoColorShader) else: setRasterStyle(myQgisImpactLayer, myStyle) else: myMessage = self.tr('Impact layer %s was neither a raster or a ' 'vector layer' % myQgisImpactLayer.source()) raise ReadLayerError(myMessage) # Add layer to QGIS QgsMapLayerRegistry.instance().addMapLayer(myQgisImpactLayer) # then zoom to it if self.zoomToImpactFlag: self.iface.zoomToActiveLayer() if self.hideExposureFlag: myExposureLayer = self.getExposureLayer() myLegend = self.iface.legendInterface() myLegend.setLayerVisible(myExposureLayer, False) self.restoreState() #append postprocessing report myReport += self.getPostprocessingOutput() # Return text to display in report pane return myReport def showHelp(self): """Load the help text into the wvResults widget""" if not self.helpDialog: self.helpDialog = Help(self.iface.mainWindow(), 'dock') self.helpDialog.show() def showBusy(self, theTitle=None, theMessage=None, theProgress=0): """A helper function to indicate the plugin is processing. Args: * theTitle - an optional title for the status update. Should be plain text only * theMessage - an optional message to pass to the busy indicator. Can be an html snippet. * theProgress - a number between 0 and 100 indicating % complete Returns: None Raises: Any exceptions raised by the RIAB library will be propagated. ..note:: Uses bootstrap css for progress bar. """ #self.pbnRunStop.setText('Cancel') self.pbnRunStop.setEnabled(False) if theTitle is None: theTitle = self.tr('Analyzing this question...') myHtml = ('<table class="condensed">' ' <tr>' ' <th class="info button-cell">' + str(theTitle) + ' </th>' ' </tr>' ' <tr>' ' <td>' + str(theMessage) + ' </td>' ' </tr>' ' <tr>' ' <td>' ' <div class="progress">' ' <div class="bar" ' ' style="width: ' + str(theProgress) + '%;">' ' </div>' ' </div>' ' </td>' ' </tr>' '</table>') self.displayHtml(myHtml) self.repaint() QtGui.qApp.processEvents() self.grpQuestion.setEnabled(False) def hideBusy(self): """A helper function to indicate processing is done.""" #self.pbnRunStop.setText('Run') if self.runner: QtCore.QObject.disconnect(self.runner, QtCore.SIGNAL('done()'), self.startPostprocessing) self.runner = None self.grpQuestion.setEnabled(True) self.pbnRunStop.setEnabled(True) self.repaint() def enableBusyCursor(self): """Set the hourglass enabled.""" QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) def disableBusyCursor(self): """Disable the hourglass cursor""" QtGui.qApp.restoreOverrideCursor() def optimalClip(self): """ A helper function to perform an optimal clip of the input data. Optimal extent should be considered as the intersection between the three inputs. The inasafe library will perform various checks to ensure that the extent is tenable, includes data from both etc. The result of this function will be two layers which are clipped and resampled if needed, and in the EPSG:4326 geographic coordinate reference system. Args: None Returns: A two-tuple containing the paths to the clipped hazard and exposure layers. Raises: Any exceptions raised by the InaSAFE library will be propogated. """ # Get the hazard and exposure layers selected in the combos myHazardLayer = self.getHazardLayer() myExposureLayer = self.getExposureLayer() # Reproject all extents to EPSG:4326 if needed myGeoCrs = QgsCoordinateReferenceSystem() myGeoCrs.createFromEpsg(4326) # Get the current viewport extent as an array in EPSG:4326 myViewportGeoExtent = self.viewportGeoArray() # Get the Hazard extents as an array in EPSG:4326 myHazardGeoExtent = self.extentToGeoArray(myHazardLayer.extent(), myHazardLayer.crs()) # Get the Exposure extents as an array in EPSG:4326 myExposureGeoExtent = self.extentToGeoArray(myExposureLayer.extent(), myExposureLayer.crs()) # Now work out the optimal extent between the two layers and # the current view extent. The optimal extent is the intersection # between the two layers and the viewport. myGeoExtent = None try: # Extent is returned as an array [xmin,ymin,xmax,ymax] # We will convert it to a QgsRectangle afterwards. if self.clipToViewport: myGeoExtent = getOptimalExtent(myHazardGeoExtent, myExposureGeoExtent, myViewportGeoExtent) else: myGeoExtent = getOptimalExtent(myHazardGeoExtent, myExposureGeoExtent) except InsufficientOverlapException, e: # FIXME (MB): This branch is not covered by the tests myMessage = self.tr('<p>There ' 'was insufficient overlap between the input layers ' 'and / or the layers and the viewport. Please select ' 'two overlapping layers and zoom or pan to them or disable' ' viewport clipping in the options dialog' '. Full details follow:</p>' '<p>Failed to obtain the optimal extent given:</p>' '<p>Hazard: %1</p>' '<p>Exposure: %2</p>' '<p>Viewport Geo Extent: %3</p>' '<p>Hazard Geo Extent: %4</p>' '<p>Exposure Geo Extent: %5</p>' '<p>Viewport clipping enabled: %6</p>' '<p>Details: %7</p>').arg( myHazardLayer.source()).arg( myExposureLayer.source()).arg( QtCore.QString(str(myViewportGeoExtent))).arg( QtCore.QString(str(myHazardGeoExtent))).arg( QtCore.QString(str(myExposureGeoExtent))).arg( QtCore.QString(str(self.clipToViewport))).arg( str(e)) raise InsufficientOverlapException(myMessage) # Next work out the ideal spatial resolution for rasters # in the analysis. If layers are not native WGS84, we estimate # this based on the geographic extents # rather than the layers native extents so that we can pass # the ideal WGS84 cell size and extents to the layer prep routines # and do all preprocessing in a single operation. # All this is done in the function getWGS84resolution myBufferedGeoExtent = myGeoExtent # Bbox to use for hazard layer myCellSize = None extraExposureKeywords = {} if myHazardLayer.type() == QgsMapLayer.RasterLayer: # Hazard layer is raster myHazardGeoCellSize = getWGS84resolution(myHazardLayer) if myExposureLayer.type() == QgsMapLayer.RasterLayer: # In case of two raster layers establish common resolution myExposureGeoCellSize = getWGS84resolution(myExposureLayer) if myHazardGeoCellSize < myExposureGeoCellSize: myCellSize = myHazardGeoCellSize else: myCellSize = myExposureGeoCellSize # Record native resolution to allow rescaling of exposure data if not numpy.allclose(myCellSize, myExposureGeoCellSize): extraExposureKeywords['resolution'] = myExposureGeoCellSize else: # If exposure is vector data grow hazard raster layer to # ensure there are enough pixels for points at the edge of # the view port to be interpolated correctly. This requires # resolution to be available if myExposureLayer.type() != QgsMapLayer.VectorLayer: raise RuntimeError myBufferedGeoExtent = getBufferedExtent(myGeoExtent, myHazardGeoCellSize) else: # Hazard layer is vector # FIXME (Ole): Check that it is a polygon layer # FIXME (Ole): This should say something like this (issue #285) #if myHazardLayer.geometry() == QgsMapLayer.Point: # myGeoExtent = myExposureGeoExtent pass # Make sure that we have EPSG:4326 versions of the input layers # that are clipped and (in the case of two raster inputs) resampled to # the best resolution. myTitle = self.tr('Preparing hazard data...') myMessage = self.tr('We are resampling and clipping the hazard' 'layer to match the intersection of the exposure' 'layer and the current view extents.') myProgress = 22 self.showBusy(myTitle, myMessage, myProgress) myClippedHazardPath = clipLayer(myHazardLayer, myBufferedGeoExtent, myCellSize) myTitle = self.tr('Preparing exposure data...') myMessage = self.tr('We are resampling and clipping the exposure' 'layer to match the intersection of the hazard' 'layer and the current view extents.') myProgress = 44 self.showBusy(myTitle, myMessage, myProgress) myClippedExposurePath = clipLayer( myExposureLayer, myGeoExtent, myCellSize, theExtraKeywords=extraExposureKeywords) return myClippedHazardPath, myClippedExposurePath ############################################################ # logic checked to here.............. ############################################################ # .. todo:: Cleanup temporary working files, careful not to delete # User's own data' # FIXME: Turn paths back into layers temporarily and print res #myExposureLayer = QgsRasterLayer(myClippedExposurePath, 'exp') #myHazardLayer = QgsRasterLayer(myClippedHazardPath, 'haz') #myHazardUPP = myHazardLayer.rasterUnitsPerPixel() #myExposureUPP = myExposureLayer.rasterUnitsPerPixel() # FIXME (Ole): This causes some strange failures. Revisit! # Check that resolutions are equal up to some precision #myMessage = ('Resampled pixels sizes did not match: ' # 'Exposure pixel size = %.12f, ' # 'Hazard pixel size = %.12f' % (myExposureUPP, myHazardUPP)) #if not numpy.allclose(myExposureUPP, myHazardUPP, # # FIXME (Ole): I would like to make this tighter # rtol=1.0e-6, atol=1.0e-3): # raise RuntimeError(myMessage) #print "Resampled Exposure Units Per Pixel: %s" % myExposureUPP #print "Resampled Hazard Units Per Pixel: %s" % myHazardUPP def viewportGeoArray(self): """Obtain the map canvas current extent in EPSG:4326""" # get the current viewport extent myCanvas = self.iface.mapCanvas() myRect = myCanvas.extent() myCrs = None if myCanvas.hasCrsTransformEnabled(): myCrs = myCanvas.mapRenderer().destinationCrs() else: # some code duplication from extentToGeoArray here # in favour of clarity of logic... myCrs = QgsCoordinateReferenceSystem() myCrs.createFromEpsg(4326) return self.extentToGeoArray(myRect, myCrs) def extentToGeoArray(self, theExtent, theSourceCrs): """Convert the supplied extent to geographic and return as as array""" # FIXME (Ole): As there is no reference to self, this function # should be a general helper outside the class myGeoCrs = QgsCoordinateReferenceSystem() myGeoCrs.createFromEpsg(4326) myXForm = QgsCoordinateTransform( theSourceCrs, myGeoCrs) # Get the clip area in the layer's crs myTransformedExtent = myXForm.transformBoundingBox(theExtent) myGeoExtent = [myTransformedExtent.xMinimum(), myTransformedExtent.yMinimum(), myTransformedExtent.xMaximum(), myTransformedExtent.yMaximum()] return myGeoExtent def htmlHeader(self): """Get a standard html header for wrapping content in.""" if self.header is None: self.header = htmlHeader() return self.header def htmlFooter(self): """Get a standard html footer for wrapping content in.""" if self.footer is None: self.footer = htmlFooter() return self.footer def displayHtml(self, theMessage): """Given an html snippet, wrap it in a page header and footer and display it in the wvResults widget.""" myHtml = self.htmlHeader() + theMessage + self.htmlFooter() #f = file('/tmp/h.thml', 'wa') # for debugging #f.write(myHtml) #f.close() self.wvResults.setHtml(myHtml) def layerChanged(self, theLayer): """Handler for when the QGIS active layer is changed. If the active layer is changed and it has keywords and a report, show the report.. .. see also:: :func:`IS.layerChanged`. Args: theLayer - the QgsMapLayer instance that is now active.. Returns: None. Raises: no exceptions explicitly raised. """ myReport = ('<table class="table table-striped condensed' ' bordered-table">') # will be overridden if needed if theLayer is not None: try: myKeywords = self.keywordIO.readKeywords(theLayer) if 'impact_summary' in myKeywords: myReport = myKeywords['impact_summary'] if 'postprocessing_report' in myKeywords: myReport += myKeywords['postprocessing_report'] self.pbnPrint.setEnabled(True) else: self.pbnPrint.setEnabled(False) for myKeyword in myKeywords: myValue = myKeywords[myKeyword] # Translate titles explicitly if possible if myKeyword == 'title' and \ myValue in internationalisedNames: myValue = internationalisedNames[myValue] # Add this keyword to report myReport += ('<tr>' # FIXME (Ole): Not sure if this will work # with translations '<th>' + self.tr(myKeyword.capitalize()) + '</th>' '</tr>' '<tr>' '<td>' + myValue + '</td>' '</tr>') myReport += '</table>' except (KeywordNotFoundException, HashNotFoundException, InvalidParameterException), e: myContext = self.tr('No keywords have been defined' ' for this layer yet. If you wish to use it as' ' an impact or hazard layer in a scenario, please' ' use the keyword editor. You can open the keyword' ' editor by clicking on the' ' <img src="qrc:/plugins/inasafe/keywords.png" ' ' width="16" height="16"> icon' ' in the toolbar, or choosing Plugins -> InaSAFE' ' -> Keyword Editor from the menus.') myReport += getExceptionWithStacktrace(e, html=True, context=myContext) except Exception, e: myReport += getExceptionWithStacktrace(e, html=True) if myReport is not None: self.displayHtml(myReport) def saveState(self): """Save the current state of the ui to an internal class member so that it can be restored again easily. Args: None Returns: None Raises: Any exceptions raised by the InaSAFE library will be propogated. """ myStateDict = {'hazard': self.cboHazard.currentText(), 'exposure': self.cboExposure.currentText(), 'function': self.cboFunction.currentText(), 'aggregation': self.cboAggregation.currentText(), 'report': self.wvResults.page().currentFrame().toHtml()} self.state = myStateDict def restoreState(self): """Restore the state of the dock to the last known state. Args: None Returns: None Raises: Any exceptions raised by the InaSAFE library will be propogated. """ if self.state is None: return for myCount in range(0, self.cboExposure.count()): myItemText = self.cboExposure.itemText(myCount) if myItemText == self.state['exposure']: self.cboExposure.setCurrentIndex(myCount) break for myCount in range(0, self.cboHazard.count()): myItemText = self.cboHazard.itemText(myCount) if myItemText == self.state['hazard']: self.cboHazard.setCurrentIndex(myCount) break for myCount in range(0, self.cboAggregation.count()): myItemText = self.cboAggregation.itemText(myCount) if myItemText == self.state['aggregation']: self.cboAggregation.setCurrentIndex(myCount) break self.restoreFunctionState(self.state['function']) self.wvResults.setHtml(self.state['report']) def restoreFunctionState(self, theOriginalFunction): """Restore the function combo to a known state. Args: theOriginalFunction - name of function that should be selected Returns: None Raises: Any exceptions raised by the RIAB library will be propogated. """ # Restore previous state of combo for myCount in range(0, self.cboFunction.count()): myItemText = self.cboFunction.itemText(myCount) if myItemText == theOriginalFunction: self.cboFunction.setCurrentIndex(myCount) break def printMap(self): """Slot to print map when print map button pressed. Args: None Returns: None Raises: Any exceptions raised by the InaSAFE library will be propogated. """ myFilename = QtGui.QFileDialog.getSaveFileName(self, self.tr('Write to PDF'), temp_dir(), self.tr('Pdf File (*.pdf)')) myMap = Map(self.iface) myMap.setImpactLayer(self.iface.activeLayer()) self.showBusy(self.tr('Map Creator'), self.tr('Generating your map as a PDF document...'), theProgress=20) try: myMap.makePdf(myFilename) self.showBusy(self.tr('Map Creator'), self.tr('Your PDF was created....opening using ' 'the default PDF viewer on your system.' 'The generated pdf is saved as: %s' % myFilename), theProgress=80) QtGui.QDesktopServices.openUrl(QtCore.QUrl('file:///' + myFilename, QtCore.QUrl.TolerantMode)) self.showBusy(self.tr('Map Creator'), self.tr('Processing complete.' 'The generated pdf is saved as: %s' % myFilename), theProgress=100) except Exception, e: # pylint: disable=W0703 # FIXME (Ole): This branch is not covered by the tests myReport = getExceptionWithStacktrace(e, html=True) if myReport is not None: self.displayHtml(myReport) self.hideBusy() myMap.showComposer() def addComboItemInOrder(self, theCombo, theItemText, theItemData=None): """Although QComboBox allows you to set an InsertAlphabetically enum this only has effect when a user interactively adds combo items to an editable combo. This we have this little function to ensure that combos are always sorted alphabetically. Args: * theCombo - combo box receiving the new item * theItemText - display text for the combo * theItemData - optional UserRole data to be associated with the item Returns: None Raises: ..todo:: Move this to utilities """ mySize = theCombo.count() for myCount in range(0, mySize): myItemText = str(theCombo.itemText(myCount)) # see if theItemText alphabetically precedes myItemText if cmp(str(theItemText).lower(), myItemText.lower()) < 0: theCombo.insertItem(myCount, theItemText, theItemData) return #otherwise just add it to the end theCombo.insertItem(mySize, theItemText, theItemData) def getFunctionID(self, theIndex=None): """Get the canonical impact function ID for the currently selected function (or the specified combo entry if theIndex is supplied. Args: theIndex int - Optional index position in the combo that you want the function id for. Defaults to None. If not set / None the currently selected combo item's function id will be returned. Returns: myFunctionID str - String that identifies the function Raises: None """ if theIndex is None: myIndex = self.cboFunction.currentIndex() else: myIndex = theIndex myItemData = self.cboFunction.itemData(myIndex, QtCore.Qt.UserRole) myFunctionID = str(myItemData.toString()) return myFunctionID
takmid/inasafe
safe_qgis/dock.py
Python
gpl-3.0
73,919
0.00188
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('data_storage', '0002_auto_20150727_2312'), ] operations = [ migrations.RenameField( model_name='readonly', old_name='state', new_name='stateAbbreviation', ), migrations.RenameField( model_name='writeonly', old_name='state', new_name='stateAbbreviation', ), migrations.AddField( model_name='readonly', name='stateName', field=models.TextField(default='sexy jens'), preserve_default=False, ), migrations.AddField( model_name='writeonly', name='stateName', field=models.TextField(default='sexy cindy'), preserve_default=False, ), ]
nmccrory/job-visualization
jobvisualization/apps/data_storage/migrations/0003_auto_20150728_2302.py
Python
apache-2.0
953
0
#!/usr/bin/python # find_unicode.py # # Author: Jonathan Hosmer # Date: Sun Feb 15 14:06:15 2015 # import os import sys def help(): print 'Usage: {} [file, [dir, [file, ..]]]'.format(__file__) print 'Displays line:character position of all non-ascii Unicode character(s) in a file' def main(): args = sys.argv[1:] if '-h' in args or '--help' in args: sys.exit(help()) if not args: files = [sys.stdin] long_fname = len('stdin') + 1 else: # make a flat list of all files ## if a dir is given as an arg then take all files in that dir [non-recursive] files = [f for f in args if os.path.isfile(f)] + [x for y in [[os.path.join(d, f) for f in os.listdir(d) if os.path.isfile(os.path.join(d, f))] for d in args if os.path.isdir(d)] for x in y] long_fname = max(map(len, files)) + 1 chars = [] out_str = '{{:<{}}} {{:03}}:{{:04}} {{chars:^5}} {{chars!r:^13}}'.format(long_fname) if sys.stdin not in files: header = '{{:^{}}} {{}}:{{}} {{:^5}} {{:^10}}'.format(long_fname) head_out = header.format('File', 'Line', 'Col', 'char', '(ord)') print head_out + '\n' + '-'*len(head_out) for f in files: if f is sys.stdin: infile = sys.stdin fname = 'stdin' else: fname = f infile = open(f) for line_i, line in enumerate(infile): for char_i, char in enumerate(line): if ord(char) > 126: chars.append(char) else: if chars: print out_str.format(fname, line_i+1, char_i+1-len(chars), chars=''.join(chars)) chars = [] if __name__ == '__main__': sys.exit(main())
jhosmer/find_unicode
find_unicode.py
Python
gpl-2.0
1,875
0.005867
import json import re import unittest from datetime import datetime from coalib.output.JSONEncoder import create_json_encoder class TestClass1(object): def __init__(self): self.a = 0 class TestClass2(object): def __init__(self): self.a = 0 self.b = TestClass1() class TestClass3(object): def __init__(self): self.a = 0 self.b = TestClass1() @staticmethod def __getitem__(key): return 'val' @staticmethod def keys(): return ['key'] class PropertiedClass(object): def __init__(self): self._a = 5 @property def prop(self): return self._a class JSONAbleClass(object): @staticmethod def __json__(): return ['dont', 'panic'] class JSONEncoderTest(unittest.TestCase): JSONEncoder = create_json_encoder(use_relpath=True) kw = {'cls': JSONEncoder, 'sort_keys': True} def test_builtins(self): self.assertEqual('"test"', json.dumps('test', **self.kw)) self.assertEqual('1', json.dumps(1, **self.kw)) self.assertEqual('true', json.dumps(True, **self.kw)) self.assertEqual('null', json.dumps(None, **self.kw)) def test_iter(self): self.assertEqual('[0, 1]', json.dumps([0, 1], **self.kw)) self.assertEqual('[0, 1]', json.dumps((0, 1), **self.kw)) self.assertEqual('[0, 1]', json.dumps(range(2), **self.kw)) def test_dict(self): self.assertEqual('{"0": 1}', json.dumps({0: 1}, **self.kw)) self.assertEqual('{"0": 1}', json.dumps({'0': 1}, **self.kw)) self.assertEqual('{"0": "1"}', json.dumps({'0': '1'}, **self.kw)) def test_time(self): tf = datetime.today() self.assertEqual('"' + tf.isoformat() + '"', json.dumps(tf, **self.kw)) def test_re_object(self): uut = re.compile('x') self.assertEqual('"' + uut.pattern + '"', json.dumps(uut, **self.kw)) def test_class1(self): tc1 = TestClass1() self.assertEqual('{"a": 0}', json.dumps(tc1, **self.kw)) self.assertEqual('[{"a": 0}]', json.dumps([tc1], **self.kw)) self.assertEqual('{"0": {"a": 0}}', json.dumps({0: tc1}, **self.kw)) def test_class2(self): tc2 = TestClass2() self.assertEqual('{"a": 0, "b": {"a": 0}}', json.dumps(tc2, **self.kw)) def test_class3(self): tc3 = TestClass3() self.assertEqual('{"key": "val"}', json.dumps(tc3, **self.kw)) def test_propertied_class(self): uut = PropertiedClass() self.assertEqual('{"prop": 5}', json.dumps(uut, **self.kw)) def test_jsonable_class(self): uut = JSONAbleClass() self.assertEqual('["dont", "panic"]', json.dumps(uut, **self.kw)) def test_type_error(self): with self.assertRaises(TypeError): json.dumps(1j, **self.kw)
Nosferatul/coala
tests/output/JSONEncoderTest.py
Python
agpl-3.0
2,948
0
# Copyright 2012, Nachi Ueno, NTT MCL, Inc. # Copyright 2013, Big Switch Networks, 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. """ Views for managing Neutron Routers. """ from collections import OrderedDict from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import tables from horizon import tabs from horizon.utils import memoized from openstack_dashboard import api from openstack_dashboard.utils import filters from openstack_dashboard.dashboards.project.routers\ import forms as project_forms from openstack_dashboard.dashboards.project.routers import tables as rtables from openstack_dashboard.dashboards.project.routers import tabs as rdtabs class IndexView(tables.DataTableView): table_class = rtables.RoutersTable template_name = 'project/routers/index.html' page_title = _("Routers") FILTERS_MAPPING = {'admin_state_up': {_("up"): True, _("down"): False}} def _get_routers(self, search_opts=None): try: search_opts = self.get_filters( filters=search_opts, filters_map=self.FILTERS_MAPPING) tenant_id = self.request.user.tenant_id routers = api.neutron.router_list(self.request, tenant_id=tenant_id, **search_opts) except Exception: routers = [] exceptions.handle(self.request, _('Unable to retrieve router list.')) ext_net_dict = self._list_external_networks() for r in routers: r.name = r.name_or_id self._set_external_network(r, ext_net_dict) return routers def get_data(self): routers = self._get_routers() return routers def _list_external_networks(self): try: search_opts = {'router:external': True} ext_nets = api.neutron.network_list(self.request, **search_opts) ext_net_dict = OrderedDict((n['id'], n.name_or_id) for n in ext_nets) except Exception as e: msg = _('Unable to retrieve a list of external networks "%s".') % e exceptions.handle(self.request, msg) ext_net_dict = {} return ext_net_dict def _set_external_network(self, router, ext_net_dict): gateway_info = router.external_gateway_info if gateway_info: ext_net_id = gateway_info['network_id'] if ext_net_id in ext_net_dict: gateway_info['network'] = ext_net_dict[ext_net_id] else: msg_params = {'ext_net_id': ext_net_id, 'router_id': router.id} msg = _('External network "%(ext_net_id)s" expected but not ' 'found for router "%(router_id)s".') % msg_params messages.error(self.request, msg) # gateway_info['network'] is just the network name, so putting # in a smallish error message in the table is reasonable. # Translators: The usage is "<UUID of ext_net> (Not Found)" gateway_info['network'] = pgettext_lazy( 'External network not found', u'%s (Not Found)') % ext_net_id class DetailView(tabs.TabbedTableView): tab_group_class = rdtabs.RouterDetailTabs template_name = 'horizon/common/_detail.html' failure_url = reverse_lazy('horizon:project:routers:index') network_url = 'horizon:project:networks:detail' page_title = "{{ router.name|default:router.id }}" @memoized.memoized_method def _get_data(self): try: router_id = self.kwargs['router_id'] router = api.neutron.router_get(self.request, router_id) router.set_id_as_name_if_empty(length=0) except Exception: msg = _('Unable to retrieve details for router "%s".') \ % router_id exceptions.handle(self.request, msg, redirect=self.failure_url) if router.external_gateway_info: ext_net_id = router.external_gateway_info['network_id'] router.external_gateway_info['network_url'] = reverse( self.network_url, args=[ext_net_id]) try: ext_net = api.neutron.network_get(self.request, ext_net_id, expand_subnet=False) ext_net.set_id_as_name_if_empty(length=0) router.external_gateway_info['network'] = ext_net.name except Exception: msg = _('Unable to retrieve an external network "%s".') \ % ext_net_id exceptions.handle(self.request, msg) router.external_gateway_info['network'] = ext_net_id return router @memoized.memoized_method def _get_ports(self): try: ports = api.neutron.port_list(self.request, device_id=self.kwargs['router_id']) except Exception: ports = [] msg = _('Unable to retrieve port details.') exceptions.handle(self.request, msg) return ports def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) router = self._get_data() table = rtables.RoutersTable(self.request) context["router"] = router context["url"] = self.failure_url context["actions"] = table.render_row_actions(router) context['dvr_supported'] = api.neutron.get_feature_permission( self.request, "dvr", "get") context['ha_supported'] = api.neutron.get_feature_permission( self.request, "l3-ha", "get") choices = rtables.STATUS_DISPLAY_CHOICES router.status_label = filters.get_display_label(choices, router.status) choices = rtables.ADMIN_STATE_DISPLAY_CHOICES router.admin_state_label = ( filters.get_display_label(choices, router.admin_state)) return context def get_tabs(self, request, *args, **kwargs): router = self._get_data() ports = self._get_ports() return self.tab_group_class(request, router=router, ports=ports, **kwargs) class CreateView(forms.ModalFormView): form_class = project_forms.CreateForm form_id = "create_router_form" modal_header = _("Create Router") template_name = 'project/routers/create.html' success_url = reverse_lazy("horizon:project:routers:index") page_title = _("Create Router") submit_label = _("Create Router") submit_url = reverse_lazy("horizon:project:routers:create") class UpdateView(forms.ModalFormView): form_class = project_forms.UpdateForm form_id = "update_router_form" modal_header = _("Edit Router") template_name = 'project/routers/update.html' success_url = reverse_lazy("horizon:project:routers:index") page_title = _("Update Router") submit_label = _("Save Changes") submit_url = "horizon:project:routers:update" def get_context_data(self, **kwargs): context = super(UpdateView, self).get_context_data(**kwargs) args = (self.kwargs['router_id'],) context["router_id"] = self.kwargs['router_id'] context['submit_url'] = reverse(self.submit_url, args=args) return context def _get_object(self, *args, **kwargs): router_id = self.kwargs['router_id'] try: return api.neutron.router_get(self.request, router_id) except Exception: redirect = self.success_url msg = _('Unable to retrieve router details.') exceptions.handle(self.request, msg, redirect=redirect) def get_initial(self): router = self._get_object() initial = {'router_id': router['id'], 'tenant_id': router['tenant_id'], 'name': router['name'], 'admin_state': router['admin_state_up']} if hasattr(router, 'distributed'): initial['mode'] = ('distributed' if router.distributed else 'centralized') if hasattr(router, 'ha'): initial['ha'] = router.ha return initial
sandvine/horizon
openstack_dashboard/dashboards/project/routers/views.py
Python
apache-2.0
9,121
0
#!/usr/bin/python AGO_TELLSTICK_VERSION = '0.0.9' """ ############################################ # # Tellstick Duo class # # Date of origin: 2014-01-25 # __author__ = "Joakim Lindbom" __copyright__ = "Copyright 2014, Joakim Lindbom" __credits__ = ["Joakim Lindbom", "The ago control team"] __license__ = "GPL Public License Version 3" __maintainer__ = "Joakim Lindbom" __email__ = 'Joakim.Lindbom@gmail.com' __status__ = "Experimental" __version__ = AGO_TELLSTICK_VERSION ############################################ """ from tellstickbase import tellstickbase import td class tellstickduo(tellstickbase): """Class used for Tellstick & Tellstick Duo devices""" def __get__(self, obj, objtype=None): pass def __set__(self, obj, val): pass def __delete__(self, obj): pass def __init__(self): self.SensorEvent = None def init(self, SensorPollDelay, TempUnits): # TELLSTICK_BELL | TELLSTICK_TOGGLE | TELLSTICK_LEARN | TELLSTICK_EXECUTE | TELLSTICK_UP | TELLSTICK_DOWN | TELLSTICK_STOP td.init(defaultMethods=td.TELLSTICK_TURNON | td.TELLSTICK_TURNOFF | td.TELLSTICK_DIM) self.log.info("Init executed") def close(self): return td.close() def turnOn(self, devId): resCode = td.turnOn(devId) return self.getErrorString(resCode).lower() def turnOff(self, devId): resCode = td.turnOff(devId) return self.getErrorString(resCode).lower() def getErrorString(self, resCode): return td.getErrorString(resCode) def dim(self, devId, level): resCode = td.dim(devId, level) return self.getErrorString(resCode).lower() def getName(self, devId): return td.getName(devId) def methodsReadable(self, method, default): return td.methodsReadable(method, default) def getNumberOfDevices(self): return td.getNumberOfDevices() def getNumberOfSensors(self): return td.getNumberOfDevices() # wrong def getDeviceId(self, i): return td.getDeviceId(i) def getModel(self, devId): return td.getModel(devId) def registerDeviceEvent(self, deviceEvent): return td.registerDeviceEvent(deviceEvent) def registerDeviceChangedEvent(self, deviceEvent): return td.registerDeviceChangedEvent(deviceEvent) def newTempSensor(self, devId, model, value): self.log.debug("New temperature sensor intercepted: devId=" + devId + " model=" + model) s = { "id" : devId, "description" : "", "model" : model, "new" : True, "temp" : float(value), # C/F "offset" : 0.0, # TODO: Add to parameter & config file "lastTemp" : float(-274.0), "isTempSensor" : True, "isHumiditySensor" : False, "ignore" : False} return s def newHumiditySensor(self, devId, model, value): self.log.debug("New humidity sensor intercepted: devId=" + devId + " model=" + model) s = { "id" : devId, "description" : "", "model" : model, "new" : True, "humidity" : float(value), "offset" : 0.0, # TODO: Add to parameter & config file "lastHumidity" : float(-999.0), "isHumiditySensor" : True, "isTempSensor" : False, "ignore" : False} return s def SensorEventInterceptor(self, protocol, model, id, dataType, value, timestamp, callbackId): devId = 'S' + str(id) # Prefix 'S' to make sure name doesn't clash with self-defined devices devIdT = devId + "-temp" devIdH = devId + "-hum" # self.checkIgnore(self, devId) #TODO: Add once moved self.log.trace("SensorEventInterceptor called for " + devId) if str(id) not in self.ignoreDevices: # New temperature sensor? if devIdT not in self.sensors and dataType & td.TELLSTICK_TEMPERATURE == td.TELLSTICK_TEMPERATURE: self.sensors[devIdT] = self.newTempSensor(devIdT, model, value) # New humidity sensor? if devIdH not in self.sensors and dataType & td.TELLSTICK_HUMIDITY == td.TELLSTICK_HUMIDITY: self.sensors[devIdH] = self.newHumiditySensor(devIdH, model, value) # Call registered callback self.SensorEvent(protocol, model, devId, dataType, value, timestamp, callbackId) def registerSensorEvent(self, deviceEvent): self.SensorEvent = deviceEvent return td.registerSensorEvent(self.SensorEventInterceptor) def listSensors(self): sensors = td.listSensors() if len(sensors) != 0: for id, value in sensors.iteritems(): self.log.trace("listSensors: devId: %s ", str(id)) if id not in self.ignoreDevices: devId = str(id) + "-temp" if devId not in self.sensors: if value["isTempSensor"]: # New temp sensor found self.sensors[devId] = self.newTempSensor(devId, value["model"], value["temp"]) devId = str(id) + "-hum" if devId not in self.sensors: if value["isHumiditySensor"]: # New hum sensor found self.sensors[devId] = self.newHumiditySensor(devId, value["model"], value["humidity"]) if not value["new"]: continue return self.sensors def listSwitches(self): if len(self.switches) == 0: for i in range(self.getNumberOfDevices()): devId = self.getDeviceId(i) model = self.getModel(devId) if ('switch' in model or 'dimmer' in model): dev = { "id" : devId, "name" : self.getName(devId), "model" : model} if 'dimmer' in model: dev["isDimmer"] = True else: dev["isDimmer"] = False self.switches[devId] = dev return self.switches def listRemotes(self): self.log.trace("listRemotes start") if len(self.remotes) == 0: self.log.info("getNumberOfDevices=" + str(self.getNumberOfDevices())) for i in range(self.getNumberOfDevices()): devId = self.getDeviceId(i) model = self.getModel(devId) self.log.info("devId=" + str(devId) + " model=" + model) if 'switch' not in model and 'dimmer' not in model: dev = { "id" : str(devId), "name" : self.getName(devId), "model" : model} self.log.info("devId=" + str(devId) + " model=" + model) self.remotes[devId] = dev return self.remotes
JoakimLindbom/ago
tellstick/tellstickduo.py
Python
gpl-3.0
7,092
0.005781
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 __future__ import with_statement import os import sys import tempfile from io import BytesIO from libcloud.utils.py3 import httplib from libcloud.utils.py3 import urlparse from libcloud.utils.py3 import parse_qs from libcloud.utils.py3 import b from libcloud.utils.py3 import basestring from libcloud.common.types import InvalidCredsError from libcloud.common.types import LibcloudError from libcloud.storage.base import Container, Object from libcloud.storage.types import ContainerDoesNotExistError from libcloud.storage.types import ContainerIsNotEmptyError from libcloud.storage.types import ContainerAlreadyExistsError from libcloud.storage.types import InvalidContainerNameError from libcloud.storage.types import ObjectDoesNotExistError from libcloud.storage.types import ObjectHashMismatchError from libcloud.storage.drivers.azure_blobs import AzureBlobsStorageDriver from libcloud.storage.drivers.azure_blobs import AZURE_BLOCK_MAX_SIZE from libcloud.storage.drivers.azure_blobs import AZURE_PAGE_CHUNK_SIZE from libcloud.test import unittest from libcloud.test import MockHttp, generate_random_data # pylint: disable-msg=E0611 from libcloud.test.file_fixtures import StorageFileFixtures # pylint: disable-msg=E0611 from libcloud.test.secrets import STORAGE_AZURE_BLOBS_PARAMS class AzureBlobsMockHttp(MockHttp, unittest.TestCase): fixtures = StorageFileFixtures('azure_blobs') base_headers = {} def _UNAUTHORIZED(self, method, url, body, headers): return (httplib.UNAUTHORIZED, '', self.base_headers, httplib.responses[httplib.UNAUTHORIZED]) def _list_containers_EMPTY(self, method, url, body, headers): body = self.fixtures.load('list_containers_empty.xml') return (httplib.OK, body, self.base_headers, httplib.responses[httplib.OK]) def _list_containers(self, method, url, body, headers): query_string = urlparse.urlsplit(url).query query = parse_qs(query_string) if 'marker' not in query: body = self.fixtures.load('list_containers_1.xml') else: body = self.fixtures.load('list_containers_2.xml') return (httplib.OK, body, self.base_headers, httplib.responses[httplib.OK]) def _test_container_EMPTY(self, method, url, body, headers): if method == 'DELETE': body = u'' return (httplib.ACCEPTED, body, self.base_headers, httplib.responses[httplib.ACCEPTED]) else: body = self.fixtures.load('list_objects_empty.xml') return (httplib.OK, body, self.base_headers, httplib.responses[httplib.OK]) def _new__container_INVALID_NAME(self, method, url, body, headers): return (httplib.BAD_REQUEST, body, self.base_headers, httplib.responses[httplib.BAD_REQUEST]) def _test_container(self, method, url, body, headers): query_string = urlparse.urlsplit(url).query query = parse_qs(query_string) if 'marker' not in query: body = self.fixtures.load('list_objects_1.xml') else: body = self.fixtures.load('list_objects_2.xml') return (httplib.OK, body, self.base_headers, httplib.responses[httplib.OK]) def _test_container100(self, method, url, body, headers): body = '' if method != 'HEAD': return (httplib.BAD_REQUEST, body, self.base_headers, httplib.responses[httplib.BAD_REQUEST]) return (httplib.NOT_FOUND, body, self.base_headers, httplib.responses[httplib.NOT_FOUND]) def _test_container200(self, method, url, body, headers): body = '' if method != 'HEAD': return (httplib.BAD_REQUEST, body, self.base_headers, httplib.responses[httplib.BAD_REQUEST]) headers = {} headers['etag'] = '0x8CFB877BB56A6FB' headers['last-modified'] = 'Fri, 04 Jan 2013 09:48:06 GMT' headers['x-ms-lease-status'] = 'unlocked' headers['x-ms-lease-state'] = 'available' headers['x-ms-meta-meta1'] = 'value1' return (httplib.OK, body, headers, httplib.responses[httplib.OK]) def _test_container200_test(self, method, url, body, headers): body = '' if method != 'HEAD': return (httplib.BAD_REQUEST, body, self.base_headers, httplib.responses[httplib.BAD_REQUEST]) headers = {} headers['etag'] = '0x8CFB877BB56A6FB' headers['last-modified'] = 'Fri, 04 Jan 2013 09:48:06 GMT' headers['content-length'] = '12345' headers['content-type'] = 'application/zip' headers['x-ms-blob-type'] = 'Block' headers['x-ms-lease-status'] = 'unlocked' headers['x-ms-lease-state'] = 'available' headers['x-ms-meta-rabbits'] = 'monkeys' return (httplib.OK, body, headers, httplib.responses[httplib.OK]) def _test2_test_list_containers(self, method, url, body, headers): # test_get_object body = self.fixtures.load('list_containers.xml') headers = {'content-type': 'application/zip', 'etag': '"e31208wqsdoj329jd"', 'x-amz-meta-rabbits': 'monkeys', 'content-length': '12345', 'last-modified': 'Thu, 13 Sep 2012 07:13:22 GMT' } return (httplib.OK, body, headers, httplib.responses[httplib.OK]) def _new_container_ALREADY_EXISTS(self, method, url, body, headers): # test_create_container return (httplib.CONFLICT, body, headers, httplib.responses[httplib.CONFLICT]) def _new_container(self, method, url, body, headers): # test_create_container, test_delete_container headers = {} if method == 'PUT': status = httplib.CREATED headers['etag'] = '0x8CFB877BB56A6FB' headers['last-modified'] = 'Fri, 04 Jan 2013 09:48:06 GMT' headers['x-ms-lease-status'] = 'unlocked' headers['x-ms-lease-state'] = 'available' headers['x-ms-meta-meta1'] = 'value1' elif method == 'DELETE': status = httplib.NO_CONTENT return (status, body, headers, httplib.responses[status]) def _new_container_DOESNT_EXIST(self, method, url, body, headers): # test_delete_container return (httplib.NOT_FOUND, body, headers, httplib.responses[httplib.NOT_FOUND]) def _foo_bar_container_NOT_FOUND(self, method, url, body, headers): # test_delete_container_not_found return (httplib.NOT_FOUND, body, headers, httplib.responses[httplib.NOT_FOUND]) def _foo_bar_container_foo_bar_object_NOT_FOUND(self, method, url, body, headers): # test_delete_object_not_found return (httplib.NOT_FOUND, body, headers, httplib.responses[httplib.NOT_FOUND]) def _foo_bar_container_foo_bar_object_DELETE(self, method, url, body, headers): # test_delete_object return (httplib.ACCEPTED, body, headers, httplib.responses[httplib.ACCEPTED]) def _foo_bar_container_foo_test_upload(self, method, url, body, headers): # test_upload_object_success self._assert_content_length_header_is_string(headers=headers) body = '' headers = {} headers['etag'] = '0x8CFB877BB56A6FB' headers['content-md5'] = 'd4fe4c9829f7ca1cc89db7ad670d2bbd' return (httplib.CREATED, body, headers, httplib.responses[httplib.CREATED]) def _foo_bar_container_foo_test_upload_block(self, method, url, body, headers): # test_upload_object_success self._assert_content_length_header_is_string(headers=headers) body = '' headers = {} headers['etag'] = '0x8CFB877BB56A6FB' return (httplib.CREATED, body, headers, httplib.responses[httplib.CREATED]) def _foo_bar_container_foo_test_upload_page(self, method, url, body, headers): # test_upload_object_success body = '' headers = {} headers['etag'] = '0x8CFB877BB56A6FB' return (httplib.CREATED, body, headers, httplib.responses[httplib.CREATED]) def _foo_bar_container_foo_test_upload_blocklist(self, method, url, body, headers): # test_upload_object_success self._assert_content_length_header_is_string(headers=headers) body = '' headers = {} headers['etag'] = '0x8CFB877BB56A6FB' headers['content-md5'] = 'd4fe4c9829f7ca1cc89db7ad670d2bbd' return (httplib.CREATED, body, headers, httplib.responses[httplib.CREATED]) def _foo_bar_container_foo_test_upload_lease(self, method, url, body, headers): # test_upload_object_success self._assert_content_length_header_is_string(headers=headers) action = headers['x-ms-lease-action'] rheaders = {'x-ms-lease-id': 'someleaseid'} body = '' if action == 'acquire': return (httplib.CREATED, body, rheaders, httplib.responses[httplib.CREATED]) else: if headers.get('x-ms-lease-id', None) != 'someleaseid': return (httplib.BAD_REQUEST, body, rheaders, httplib.responses[httplib.BAD_REQUEST]) return (httplib.OK, body, headers, httplib.responses[httplib.CREATED]) def _foo_bar_container_foo_test_upload_INVALID_HASH(self, method, url, body, headers): # test_upload_object_invalid_hash1 self._assert_content_length_header_is_string(headers=headers) body = '' headers = {} headers['etag'] = '0x8CFB877BB56A6FB' headers['content-md5'] = 'd4fe4c9829f7ca1cc89db7ad670d2bbd' return (httplib.CREATED, body, headers, httplib.responses[httplib.CREATED]) def _foo_bar_container_foo_bar_object(self, method, url, body, headers): # test_upload_object_invalid_file_size self._assert_content_length_header_is_string(headers=headers) body = generate_random_data(1000) return (httplib.OK, body, headers, httplib.responses[httplib.OK]) def _foo_bar_container_foo_bar_object_INVALID_SIZE(self, method, url, body, headers): # test_upload_object_invalid_file_size self._assert_content_length_header_is_string(headers=headers) body = '' return (httplib.OK, body, headers, httplib.responses[httplib.OK]) def _assert_content_length_header_is_string(self, headers): if 'Content-Length' in headers: self.assertTrue(isinstance(headers['Content-Length'], basestring)) class AzureBlobsTests(unittest.TestCase): driver_type = AzureBlobsStorageDriver driver_args = STORAGE_AZURE_BLOBS_PARAMS mock_response_klass = AzureBlobsMockHttp @classmethod def create_driver(self): return self.driver_type(*self.driver_args) def setUp(self): self.driver_type.connectionCls.conn_class = self.mock_response_klass self.mock_response_klass.type = None self.driver = self.create_driver() def tearDown(self): self._remove_test_file() def _remove_test_file(self): file_path = os.path.abspath(__file__) + '.temp' try: os.unlink(file_path) except OSError: pass def test_invalid_credentials(self): self.mock_response_klass.type = 'UNAUTHORIZED' try: self.driver.list_containers() except InvalidCredsError: e = sys.exc_info()[1] self.assertEqual(True, isinstance(e, InvalidCredsError)) else: self.fail('Exception was not thrown') def test_list_containers_empty(self): self.mock_response_klass.type = 'list_containers_EMPTY' containers = self.driver.list_containers() self.assertEqual(len(containers), 0) def test_list_containers_success(self): self.mock_response_klass.type = 'list_containers' AzureBlobsStorageDriver.RESPONSES_PER_REQUEST = 2 containers = self.driver.list_containers() self.assertEqual(len(containers), 4) self.assertTrue('last_modified' in containers[1].extra) self.assertTrue('url' in containers[1].extra) self.assertTrue('etag' in containers[1].extra) self.assertTrue('lease' in containers[1].extra) self.assertTrue('meta_data' in containers[1].extra) def test_list_container_objects_empty(self): self.mock_response_klass.type = 'EMPTY' container = Container(name='test_container', extra={}, driver=self.driver) objects = self.driver.list_container_objects(container=container) self.assertEqual(len(objects), 0) def test_list_container_objects_success(self): self.mock_response_klass.type = None AzureBlobsStorageDriver.RESPONSES_PER_REQUEST = 2 container = Container(name='test_container', extra={}, driver=self.driver) objects = self.driver.list_container_objects(container=container) self.assertEqual(len(objects), 4) obj = objects[1] self.assertEqual(obj.name, 'object2.txt') self.assertEqual(obj.hash, '0x8CFB90F1BA8CD8F') self.assertEqual(obj.size, 1048576) self.assertEqual(obj.container.name, 'test_container') self.assertTrue('meta1' in obj.meta_data) self.assertTrue('meta2' in obj.meta_data) self.assertTrue('last_modified' in obj.extra) self.assertTrue('content_type' in obj.extra) self.assertTrue('content_encoding' in obj.extra) self.assertTrue('content_language' in obj.extra) def test_get_container_doesnt_exist(self): self.mock_response_klass.type = None try: self.driver.get_container(container_name='test_container100') except ContainerDoesNotExistError: pass else: self.fail('Exception was not thrown') def test_get_container_success(self): self.mock_response_klass.type = None container = self.driver.get_container( container_name='test_container200') self.assertTrue(container.name, 'test_container200') self.assertTrue(container.extra['etag'], '0x8CFB877BB56A6FB') self.assertTrue(container.extra['last_modified'], 'Fri, 04 Jan 2013 09:48:06 GMT') self.assertTrue(container.extra['lease']['status'], 'unlocked') self.assertTrue(container.extra['lease']['state'], 'available') self.assertTrue(container.extra['meta_data']['meta1'], 'value1') def test_get_object_container_doesnt_exist(self): # This method makes two requests which makes mocking the response a bit # trickier self.mock_response_klass.type = None try: self.driver.get_object(container_name='test_container100', object_name='test') except ContainerDoesNotExistError: pass else: self.fail('Exception was not thrown') def test_get_object_success(self): # This method makes two requests which makes mocking the response a bit # trickier self.mock_response_klass.type = None obj = self.driver.get_object(container_name='test_container200', object_name='test') self.assertEqual(obj.name, 'test') self.assertEqual(obj.container.name, 'test_container200') self.assertEqual(obj.size, 12345) self.assertEqual(obj.hash, '0x8CFB877BB56A6FB') self.assertEqual(obj.extra['last_modified'], 'Fri, 04 Jan 2013 09:48:06 GMT') self.assertEqual(obj.extra['content_type'], 'application/zip') self.assertEqual(obj.meta_data['rabbits'], 'monkeys') def test_create_container_invalid_name(self): # invalid container name self.mock_response_klass.type = 'INVALID_NAME' try: self.driver.create_container(container_name='new--container') except InvalidContainerNameError: pass else: self.fail('Exception was not thrown') def test_create_container_already_exists(self): # container with this name already exists self.mock_response_klass.type = 'ALREADY_EXISTS' try: self.driver.create_container(container_name='new-container') except ContainerAlreadyExistsError: pass else: self.fail('Exception was not thrown') def test_create_container_success(self): # success self.mock_response_klass.type = None name = 'new-container' container = self.driver.create_container(container_name=name) self.assertEqual(container.name, name) def test_delete_container_doesnt_exist(self): container = Container(name='new_container', extra=None, driver=self.driver) self.mock_response_klass.type = 'DOESNT_EXIST' try: self.driver.delete_container(container=container) except ContainerDoesNotExistError: pass else: self.fail('Exception was not thrown') def test_delete_container_not_empty(self): self.mock_response_klass.type = None AzureBlobsStorageDriver.RESPONSES_PER_REQUEST = 2 container = Container(name='test_container', extra={}, driver=self.driver) try: self.driver.delete_container(container=container) except ContainerIsNotEmptyError: pass else: self.fail('Exception was not thrown') def test_delete_container_success(self): self.mock_response_klass.type = 'EMPTY' AzureBlobsStorageDriver.RESPONSES_PER_REQUEST = 2 container = Container(name='test_container', extra={}, driver=self.driver) self.assertTrue(self.driver.delete_container(container=container)) def test_delete_container_not_found(self): self.mock_response_klass.type = 'NOT_FOUND' container = Container(name='foo_bar_container', extra={}, driver=self.driver) try: self.driver.delete_container(container=container) except ContainerDoesNotExistError: pass else: self.fail('Container does not exist but an exception was not' + 'thrown') def test_download_object_success(self): container = Container(name='foo_bar_container', extra={}, driver=self.driver) obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver_type) destination_path = os.path.abspath(__file__) + '.temp' result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True) self.assertTrue(result) def test_download_object_invalid_file_size(self): self.mock_response_klass.type = 'INVALID_SIZE' container = Container(name='foo_bar_container', extra={}, driver=self.driver) obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver_type) destination_path = os.path.abspath(__file__) + '.temp' result = self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True) self.assertFalse(result) def test_download_object_invalid_file_already_exists(self): self.mock_response_klass.type = 'INVALID_SIZE' container = Container(name='foo_bar_container', extra={}, driver=self.driver) obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver_type) destination_path = os.path.abspath(__file__) try: self.driver.download_object(obj=obj, destination_path=destination_path, overwrite_existing=False, delete_on_failure=True) except LibcloudError: pass else: self.fail('Exception was not thrown') def test_download_object_as_stream_success(self): container = Container(name='foo_bar_container', extra={}, driver=self.driver) obj = Object(name='foo_bar_object', size=1000, hash=None, extra={}, container=container, meta_data=None, driver=self.driver_type) stream = self.driver.download_object_as_stream(obj=obj, chunk_size=None) self.assertTrue(hasattr(stream, '__iter__')) def test_upload_object_invalid_ex_blob_type(self): # Invalid hash is detected on the amazon side and BAD_REQUEST is # returned file_path = os.path.abspath(__file__) container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' try: self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, verify_hash=True, ex_blob_type='invalid-blob') except LibcloudError: e = sys.exc_info()[1] self.assertTrue(str(e).lower().find('invalid blob type') != -1) else: self.fail('Exception was not thrown') def test_upload_object_invalid_md5(self): # Invalid md5 is returned by azure self.mock_response_klass.type = 'INVALID_HASH' container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' file_path = os.path.abspath(__file__) try: self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, verify_hash=True) except ObjectHashMismatchError: pass else: self.fail( 'Invalid hash was returned but an exception was not thrown') def test_upload_small_block_object_success(self): file_path = os.path.abspath(__file__) file_size = os.stat(file_path).st_size container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' extra = {'meta_data': {'some-value': 'foobar'}} obj = self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, extra=extra, verify_hash=False, ex_blob_type='BlockBlob') self.assertEqual(obj.name, 'foo_test_upload') self.assertEqual(obj.size, file_size) self.assertTrue('some-value' in obj.meta_data) def test_upload_big_block_object_success(self): file_path = tempfile.mktemp(suffix='.jpg') file_size = AZURE_BLOCK_MAX_SIZE + 1 with open(file_path, 'w') as file_hdl: file_hdl.write('0' * file_size) container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' extra = {'meta_data': {'some-value': 'foobar'}} obj = self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, extra=extra, verify_hash=False, ex_blob_type='BlockBlob') self.assertEqual(obj.name, 'foo_test_upload') self.assertEqual(obj.size, file_size) self.assertTrue('some-value' in obj.meta_data) os.remove(file_path) def test_upload_page_object_success(self): self.mock_response_klass.use_param = None file_path = tempfile.mktemp(suffix='.jpg') file_size = AZURE_PAGE_CHUNK_SIZE * 4 with open(file_path, 'w') as file_hdl: file_hdl.write('0' * file_size) container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' extra = {'meta_data': {'some-value': 'foobar'}} obj = self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, extra=extra, verify_hash=False, ex_blob_type='PageBlob') self.assertEqual(obj.name, 'foo_test_upload') self.assertEqual(obj.size, file_size) self.assertTrue('some-value' in obj.meta_data) os.remove(file_path) def test_upload_page_object_failure(self): file_path = tempfile.mktemp(suffix='.jpg') file_size = AZURE_PAGE_CHUNK_SIZE * 2 + 1 with open(file_path, 'w') as file_hdl: file_hdl.write('0' * file_size) container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' extra = {'meta_data': {'some-value': 'foobar'}} try: self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, extra=extra, verify_hash=False, ex_blob_type='PageBlob') except LibcloudError: e = sys.exc_info()[1] self.assertTrue(str(e).lower().find('not aligned') != -1) os.remove(file_path) def test_upload_small_block_object_success_with_lease(self): self.mock_response_klass.use_param = 'comp' file_path = os.path.abspath(__file__) file_size = os.stat(file_path).st_size container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' extra = {'meta_data': {'some-value': 'foobar'}} obj = self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, extra=extra, verify_hash=False, ex_blob_type='BlockBlob', ex_use_lease=True) self.assertEqual(obj.name, 'foo_test_upload') self.assertEqual(obj.size, file_size) self.assertTrue('some-value' in obj.meta_data) self.mock_response_klass.use_param = None def test_upload_big_block_object_success_with_lease(self): self.mock_response_klass.use_param = 'comp' file_path = tempfile.mktemp(suffix='.jpg') file_size = AZURE_BLOCK_MAX_SIZE * 2 with open(file_path, 'w') as file_hdl: file_hdl.write('0' * file_size) container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' extra = {'meta_data': {'some-value': 'foobar'}} obj = self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, extra=extra, verify_hash=False, ex_blob_type='BlockBlob', ex_use_lease=False) self.assertEqual(obj.name, 'foo_test_upload') self.assertEqual(obj.size, file_size) self.assertTrue('some-value' in obj.meta_data) os.remove(file_path) self.mock_response_klass.use_param = None def test_upload_page_object_success_with_lease(self): self.mock_response_klass.use_param = 'comp' file_path = tempfile.mktemp(suffix='.jpg') file_size = AZURE_PAGE_CHUNK_SIZE * 4 with open(file_path, 'w') as file_hdl: file_hdl.write('0' * file_size) container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' extra = {'meta_data': {'some-value': 'foobar'}} obj = self.driver.upload_object(file_path=file_path, container=container, object_name=object_name, extra=extra, verify_hash=False, ex_blob_type='PageBlob', ex_use_lease=True) self.assertEqual(obj.name, 'foo_test_upload') self.assertEqual(obj.size, file_size) self.assertTrue('some-value' in obj.meta_data) os.remove(file_path) self.mock_response_klass.use_param = None def test_upload_blob_object_via_stream(self): self.mock_response_klass.use_param = 'comp' container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' iterator = BytesIO(b('345')) extra = {'content_type': 'text/plain'} obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra, ex_blob_type='BlockBlob') self.assertEqual(obj.name, object_name) self.assertEqual(obj.size, 3) self.mock_response_klass.use_param = None def test_upload_blob_object_via_stream_with_lease(self): self.mock_response_klass.use_param = 'comp' container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' iterator = BytesIO(b('345')) extra = {'content_type': 'text/plain'} obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra, ex_blob_type='BlockBlob', ex_use_lease=True) self.assertEqual(obj.name, object_name) self.assertEqual(obj.size, 3) self.mock_response_klass.use_param = None def test_upload_page_object_via_stream(self): self.mock_response_klass.use_param = 'comp' container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' blob_size = AZURE_PAGE_CHUNK_SIZE iterator = BytesIO(b('1' * blob_size)) extra = {'content_type': 'text/plain'} obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra, ex_blob_type='PageBlob', ex_page_blob_size=blob_size) self.assertEqual(obj.name, object_name) self.assertEqual(obj.size, blob_size) self.mock_response_klass.use_param = None def test_upload_page_object_via_stream_with_lease(self): self.mock_response_klass.use_param = 'comp' container = Container(name='foo_bar_container', extra={}, driver=self.driver) object_name = 'foo_test_upload' blob_size = AZURE_PAGE_CHUNK_SIZE iterator = BytesIO(b('1' * blob_size)) extra = {'content_type': 'text/plain'} obj = self.driver.upload_object_via_stream(container=container, object_name=object_name, iterator=iterator, extra=extra, ex_blob_type='PageBlob', ex_page_blob_size=blob_size, ex_use_lease=True) self.assertEqual(obj.name, object_name) self.assertEqual(obj.size, blob_size) def test_delete_object_not_found(self): self.mock_response_klass.type = 'NOT_FOUND' container = Container(name='foo_bar_container', extra={}, driver=self.driver) obj = Object(name='foo_bar_object', size=1234, hash=None, extra=None, meta_data=None, container=container, driver=self.driver) try: self.driver.delete_object(obj=obj) except ObjectDoesNotExistError: pass else: self.fail('Exception was not thrown') def test_delete_object_success(self): self.mock_response_klass.type = 'DELETE' container = Container(name='foo_bar_container', extra={}, driver=self.driver) obj = Object(name='foo_bar_object', size=1234, hash=None, extra=None, meta_data=None, container=container, driver=self.driver) result = self.driver.delete_object(obj=obj) self.assertTrue(result) def test_storage_driver_host(self): # Non regression tests for issue LIBCLOUD-399 dealing with the bad # management of the connectionCls.host class attribute driver1 = self.driver_type('fakeaccount1', 'deadbeafcafebabe==') driver2 = self.driver_type('fakeaccount2', 'deadbeafcafebabe==') driver3 = self.driver_type('fakeaccount3', 'deadbeafcafebabe==', host='test.foo.bar.com') host1 = driver1.connection.host host2 = driver2.connection.host host3 = driver3.connection.host self.assertEqual(host1, 'fakeaccount1.blob.core.windows.net') self.assertEqual(host2, 'fakeaccount2.blob.core.windows.net') self.assertEqual(host3, 'test.foo.bar.com') if __name__ == '__main__': sys.exit(unittest.main())
pquentin/libcloud
libcloud/test/storage/test_azure_blobs.py
Python
apache-2.0
38,350
0.000078
#!/usr/bin/python # -*- coding: utf-8 -*- # kate: space-indent on; indent-width 4; mixedindent off; indent-mode python; import re import copy import os from trac.resource import Resource, ResourceNotFound from trac.util.translation import _ from trac.util.datefmt import from_utimestamp, to_utimestamp, utc, utcmax from trac.util.compat import set, sorted from trac.util.text import empty from trac.ticket.model import Ticket from .api import CrashDumpSystem from uuid import UUID from datetime import datetime def _fixup_cc_list(cc_value): """Fix up cc list separators and remove duplicates.""" cclist = [] for cc in re.split(r'[;,\s]+', cc_value): if cc and cc not in cclist: cclist.append(cc) return ', '.join(cclist) class CrashDump(object): # Fields that must not be modified directly by the user protected_fields = ('resolution', 'status', 'time', 'changetime') __db_fields = [ 'uuid', 'type', 'status', 'priority', 'milestone', 'component', 'severity', 'summary', 'description', 'keywords', 'owner', 'reporter', 'cc', 'crashtime', 'reporttime', 'uploadtime', 'changetime', 'closetime', 'applicationname', 'applicationfile', 'uploadhostname', 'uploadusername', 'crashhostname', 'crashusername', 'productname', 'productcodename', 'productversion', 'producttargetversion', 'buildtype', 'buildpostfix', 'machinetype', 'systemname', 'osversion', 'osrelease', 'osmachine', 'minidumpfile', 'minidumpreporttextfile', 'minidumpreportxmlfile', 'minidumpreporthtmlfile', 'coredumpfile', 'coredumpreporttextfile', 'coredumpreportxmlfile', 'coredumpreporthtmlfile', ] @staticmethod def id_is_valid(num): return 0 < int(num) <= 1L << 31 @staticmethod def uuid_is_valid(uuid): if isinstance(uuid, UUID): return True else: try: UUID(uuid) return True except: return False def __init__(self, id=None, uuid=None, env=None, version=None, must_exist=True, row=None): self.id = None self.status = None self.uuid = uuid self.env = env self._changes = None self.resource = Resource('crash', uuid, version) self.fields = CrashDumpSystem(self.env).get_crash_fields() self.std_fields, self.custom_fields, self.time_fields = [], [], [] for f in self.fields: if f.get('custom'): self.custom_fields.append(f['name']) else: self.std_fields.append(f['name']) if f['type'] == 'time': self.time_fields.append(f['name']) self.values = {} if uuid is not None: self._fetch_crash_by_uuid(uuid, must_exist=must_exist) elif id is not None: crash_id = CrashDumpSystem.get_crash_id(id) if crash_id is None: raise ResourceNotFound(_("Crash %(id)s does not exist.", id=id), _("Invalid crash identifier")) self._fetch_crash_by_id(crash_id, must_exist=must_exist) elif row is not None: self._load_from_record(row) else: self._init_defaults() self._old = {} def _init_defaults(self): for field in self.fields: default = None if field['name'] in self.protected_fields: # Ignore for new - only change through workflow pass elif not field.get('custom'): default = self.env.config.get('ticket', 'default_' + field['name']) else: default = self._custom_field_default(field) if default: self.values.setdefault(field['name'], default) exists = property(lambda self: self.id is not None) has_minidump = property(lambda self: self['minidumpfile'] or self['minidumpreporttextfile'] or self['minidumpreportxmlfile'] or self['minidumpreporthtmlfile'] ) has_coredump = property(lambda self: self['coredumpfile'] or self['coredumpreporttextfile'] or self['coredumpreportxmlfile'] or self['coredumpreporthtmlfile'] ) def __getitem__(self, name): return self.values.get(name) def __setitem__(self, name, value): """Log crash modifications so the table crashdump_change can be updated """ if name in self.values and self.values[name] == value: return if name not in self._old: # Changed field if name in self.time_fields: self._old[name] = to_utimestamp(self.values.get(name)) else: self._old[name] = self.values.get(name) elif self._old[name] == value: # Change of field reverted del self._old[name] if value: if isinstance(value, list): if len(value) == 1: value = value[0] else: raise ValueError(_("Multi-values field %s not supported yet: %s") % (name, value)) field = [field for field in self.fields if field['name'] == name] if field: field_type = field[0].get('type') if field_type == 'time': pass elif field_type != 'textarea': if isinstance(value, basestring): value = value.strip() self.values[name] = value def get_value_or_default(self, name): """Return the value of a field or the default value if it is undefined """ try: value = self.values[name] return value if value is not empty else self.get_default(name) except KeyError: pass def get_default(self, name): """Return the default value of a field.""" field = [field for field in self.fields if field['name'] == name] if field: return field[0].get('value', '') def populate(self, values): """Populate the ticket with 'suitable' values from a dictionary""" field_names = [f['name'] for f in self.fields] for name in [name for name in values.keys() if name in field_names]: self[name] = values.get(name, '') # We have to do an extra trick to catch unchecked checkboxes for name in [name for name in values.keys() if name[9:] in field_names and name.startswith('checkbox_')]: if name[9:] not in values: self[name[9:]] = '0' def _load_from_record(self, row): for i, field in enumerate(self.std_fields): #print('_load_from_record %i, %s=%s' % (i, field, row[i+1])) if i == 0: self.id = row[0] elif field == 'uuid': self.uuid = row[i + 1] else: value = row[i + 1] if value is None: self.values[field] = empty elif field in self.time_fields: self.values[field] = from_utimestamp(value) else: self.values[field] = value def _fetch_crash_by_id(self, id, must_exist=True): row = None if self.id_is_valid(id): # Fetch the standard crashdump fields for row in self.env.db_query("SELECT id,%s FROM crashdump WHERE id=%%s" % ','.join(self.std_fields), (id,)): break if not row and must_exist: raise ResourceNotFound(_("Crash %(id)s does not exist.", id=id), _("Invalid crash identifier")) if row: self.id = id self._load_from_record(row) def _fetch_crash_by_uuid(self, uuid, must_exist=True): row = None if self.uuid_is_valid(uuid): # Fetch the standard crashdump fields for row in self.env.db_query("SELECT id,%s FROM crashdump WHERE uuid=%%s" % ','.join(self.std_fields), (str(uuid),)): break if not row and must_exist: raise ResourceNotFound(_("Crash %(uuid)s does not exist.", uuid=uuid), _("Invalid crash identifier")) if row: self.uuid = uuid self._load_from_record(row) def insert(self, when=None, db=None): """Add crash to database. :since 1.0: the `db` parameter is no longer needed and will be removed in version 1.1.1 """ assert not self.exists, 'Cannot insert an existing ticket' if 'cc' in self.values: self['cc'] = _fixup_cc_list(self.values['cc']) # Add a timestamp if when is None: when = datetime.now(utc) self.values['uploadtime'] = self.values['changetime'] = when self.values['uuid'] = str(self.uuid) # The owner field defaults to the component owner if self.values.get('owner') == '< default >': default_to_owner = '' if self.values.get('component'): try: component = Component(self.env, self['component']) default_to_owner = component.owner # even if it's empty except ResourceNotFound: # No such component exists pass # If the current owner is "< default >", we need to set it to # _something_ else, even if that something else is blank. self['owner'] = default_to_owner # Perform type conversions values = dict(self.values) for field in self.time_fields: if field in values: values[field] = to_utimestamp(values[field]) # Insert ticket record std_fields = [] custom_fields = [] for f in self.fields: fname = f['name'] if fname in self.values: if f.get('custom'): custom_fields.append(fname) else: std_fields.append(fname) with self.env.db_transaction as db: cursor = db.cursor() cursor.execute("INSERT INTO crashdump (%s) VALUES (%s)" % (','.join(std_fields), ','.join(['%s'] * len(std_fields))), [values[name] for name in std_fields]) crash_id = db.get_last_id(cursor, 'crashdump') # Insert custom fields if custom_fields: db.executemany( """INSERT INTO crashdump_custom (crash, name, value) VALUES (%s, %s, %s) """, [(crash_id, c, self[c]) for c in custom_fields]) self.id = crash_id self.resource = self.resource(id=crash_id) self._old = {} return self.id def save_changes(self, author=None, comment=None, when=None, db=None, cnum='', replyto=None): """ Store ticket changes in the database. The ticket must already exist in the database. Returns False if there were no changes to save, True otherwise. :since 1.0: the `db` parameter is no longer needed and will be removed in version 1.1.1 :since 1.0: the `cnum` parameter is deprecated, and threading should be controlled with the `replyto` argument """ assert self.exists, "Cannot update a new crash dump" if 'cc' in self.values: self['cc'] = _fixup_cc_list(self.values['cc']) # Perform type conversions for field in self.time_fields: if field in self.values: self.values[field] = to_utimestamp(self.values[field]) props_unchanged = all(self.values.get(k) == v for k, v in self._old.iteritems()) if (not comment or not comment.strip()) and props_unchanged: return False # Not modified if when is None: when = datetime.now(utc) when_ts = to_utimestamp(when) if 'component' in self.values: # If the component is changed on a 'new' ticket # then owner field is updated accordingly. (#623). if self.values.get('status') == 'new' \ and 'component' in self._old \ and 'owner' not in self._old: try: old_comp = Component(self.env, self._old['component']) old_owner = old_comp.owner or '' current_owner = self.values.get('owner') or '' if old_owner == current_owner: new_comp = Component(self.env, self['component']) if new_comp.owner: self['owner'] = new_comp.owner except TracError: # If the old component has been removed from the database # we just leave the owner as is. pass with self.env.db_transaction as db: db("UPDATE crashdump SET changetime=%s WHERE id=%s", (when_ts, self.id)) # find cnum if it isn't provided if not cnum: num = 0 for ts, old in db(""" SELECT DISTINCT tc1.time, COALESCE(tc2.oldvalue,'') FROM crashdump_change AS tc1 LEFT OUTER JOIN crashdump_change AS tc2 ON tc2.crash=%s AND tc2.time=tc1.time AND tc2.field='comment' WHERE tc1.crash=%s ORDER BY tc1.time DESC """, (self.id, self.id)): # Use oldvalue if available, else count edits try: num += int(str(old).rsplit('.', 1)[-1]) break except ValueError: num += 1 cnum = str(num + 1) if replyto: cnum = '%s.%s' % (replyto, cnum) # store fields for name in self._old.keys(): if name in self.custom_fields: for row in db("""SELECT * FROM crash_custom WHERE crash=%s and name=%s """, (self.id, name)): db("""UPDATE crash_custom SET value=%s WHERE crash=%s AND name=%s """, (self[name], self.id, name)) break else: db("""INSERT INTO crash_custom (crash,name,value) VALUES(%s,%s,%s) """, (self.id, name, self[name])) else: db("UPDATE crashdump SET %s=%%s WHERE id=%%s" % name, (self[name], self.id)) db("""INSERT INTO crashdump_change (crash,time,author,field,oldvalue,newvalue) VALUES (%s, %s, %s, %s, %s, %s) """, (self.id, when_ts, author, name, self._old[name], self[name])) # always save comment, even if empty # (numbering support for timeline) db("""INSERT INTO crashdump_change (crash,time,author,field,oldvalue,newvalue) VALUES (%s,%s,%s,'comment',%s,%s) """, (self.id, when_ts, author, cnum, comment)) old_values = self._old self._old = {} self.values['changetime'] = when return int(cnum.rsplit('.', 1)[-1]) def get_changelog(self, when=None, db=None): """Return the changelog as a list of tuples of the form (time, author, field, oldvalue, newvalue, permanent). While the other tuple elements are quite self-explanatory, the `permanent` flag is used to distinguish collateral changes that are not yet immutable (like attachments, currently). :since 1.0: the `db` parameter is no longer needed and will be removed in version 1.1.1 """ sid = str(self.id) when_ts = to_utimestamp(when) if when_ts: sql = """ SELECT time, author, field, oldvalue, newvalue, 1 AS permanent FROM crashdump_change WHERE crash=%s AND time=%s UNION SELECT time, author, 'attachment', null, filename, 0 AS permanent FROM attachment WHERE type='crash' AND id=%s AND time=%s UNION SELECT time, author, 'comment', null, description, 0 AS permanent FROM attachment WHERE type='crash' AND id=%s AND time=%s ORDER BY time,permanent,author """ args = (self.id, when_ts, sid, when_ts, sid, when_ts) else: sql = """ SELECT time, author, field, oldvalue, newvalue, 1 AS permanent FROM crashdump_change WHERE crash=%s UNION SELECT time, author, 'attachment', null, filename, 0 AS permanent FROM attachment WHERE type='crash' AND id=%s UNION SELECT time, author, 'comment', null, description, 0 AS permanent FROM attachment WHERE type='crash' AND id=%s ORDER BY time,permanent,author """ args = (self.id, sid, sid) return [(from_utimestamp(t), author, field, oldvalue or '', newvalue or '', permanent) for t, author, field, oldvalue, newvalue, permanent in self.env.db_query(sql, args)] @staticmethod def query(env, status=None, threshold=None): ret = [] where_clause = '' if status is not None: if status == 'active': where_clause = ' WHERE status<>\'closed\'' elif status == 'closed': where_clause = ' WHERE status=\'closed\'' elif status == 'new': where_clause = ' WHERE status=\'new\'' else: where_clause = ' WHERE status=\'%s\'' % status if threshold is not None: (threshold_column, threshold_time) = threshold if where_clause: where_clause += ' AND %s < %i' % (threshold_column, to_utimestamp(threshold_time)) else: where_clause = ' WHERE %s < %i' % (threshold_column, to_utimestamp(threshold_time)) fields = CrashDumpSystem(env).get_crash_fields() std_fields = [] for f in fields: if f.get('custom'): pass else: std_fields.append(f['name']) # Fetch the standard crashdump fields for row in env.db_query("SELECT id,%s FROM crashdump %s" % (','.join(std_fields), where_clause)): crash = CrashDump(env=env, must_exist=True, row=row) ret.append(crash) return ret @staticmethod def find_by_uuid(env, uuid): ret = CrashDump(env=env, uuid=uuid, must_exist=False) return ret if ret.id is not None else None @staticmethod def find_by_id(env, id): ret = CrashDump(env=env, id=id, must_exist=False) return ret if ret.id is not None else None def does_exist(self): ret = False with self.env.db_transaction as db: cursor = db.cursor() sql = "SELECT id FROM crashdump WHERE uuid='%s'" % self.uuid cursor.execute(sql) for crashid in cursor: ret = True return ret def delete(self, dumpdata_dir): ret = False with self.env.db_transaction as db: cursor = db.cursor() ret = CrashDump._delete_crash_files(self, dumpdata_dir) sql = "DELETE FROM crashdump_change WHERE crash='%s'" % self.id cursor = db.cursor() sql = "DELETE FROM crashdump_ticket WHERE crash='%s'" % self.id cursor.execute(sql) sql = "DELETE FROM crashdump_stack WHERE crash='%s'" % self.id cursor.execute(sql) # finally delete the crash itself sql = "DELETE FROM crashdump WHERE uuid='%s'" % self.uuid cursor.execute(sql) return ret @property def changes(self): if self._changes is None: self._changes = [] return self._changes @property def linked_tickets(self): ret = [] with self.env.db_transaction as db: cursor = db.cursor() sql = "SELECT ticket FROM crashdump_ticket WHERE crash='%s'" % self.id cursor.execute(sql) for ticketid, in cursor: ret.append(int(ticketid)) return ret @staticmethod def query_old_data(env, threshold, column='crashtime'): return CrashDump.query(env=env, threshold=(column, threshold)) @staticmethod def _delete_crash_files(crashobj, dumpdata_dir): ret = True _crash_file_fields = [ 'minidumpfile', 'minidumpreporttextfile', 'minidumpreportxmlfile', 'minidumpreporthtmlfile', 'coredumpfile', 'coredumpreporttextfile', 'coredumpreportxmlfile', 'coredumpreporthtmlfile', ] crash_dir = os.path.join(dumpdata_dir, crashobj.uuid) for field in _crash_file_fields: if crashobj[field]: crash_file = os.path.join(crash_dir, crashobj[field]) if os.path.isfile(crash_file): try: os.remove(crash_file) except: ret = False if os.path.isdir(crash_dir): try: import shutil shutil.rmtree(crash_dir) except: ret = False return ret @staticmethod def purge_old_data(env, dumpdata_dir, threshold, column='crashtime'): ret = True crashes = CrashDump.query(env=env, threshold=(column, threshold)) for crashobj in crashes: if not CrashDump._delete_crash_files(crashobj, dumpdata_dir): ret = False return ret class CrashDumpStackFrame(object): __db_fields = [ 'crash', 'threadid', 'frameno', 'module', 'function', 'funcoff', 'source', 'line', 'lineoff', ] def __init__(self, crashid=None, threadid=None, frameno=None, env=None, version=None): self.crashid = crashid self.threadid = threadid self.frameno = frameno self.env = env self.values = {} self.exists = False if self.crashid is not None: self.values['crash'] = self.crashid if self.threadid is not None: self.values['threadid'] = self.threadid if self.frameno is not None: self.values['frameno'] = self.frameno def __getitem__(self, name): return self.values.get(name) def __setitem__(self, name, value): self.values[name] = value def insert(self, when=None, db=None): """Add crash stack frame to database. :since 1.0: the `db` parameter is no longer needed and will be removed in version 1.1.1 """ assert not self.exists, 'Cannot insert an existing stack frame' # Insert stack frame record std_fields = [] for fname in self.__db_fields: if fname in self.values: std_fields.append(fname) with self.env.db_transaction as db: cursor = db.cursor() cursor.execute("INSERT INTO crashdump_stack (%s) VALUES (%s)" % (','.join(std_fields), ','.join(['%s'] * len(std_fields))), [self.values[name] for name in std_fields]) crash_id = db.get_last_id(cursor, 'crashdump') return (self.crashid, self.threadid, self.frameno)
aroth-arsoft/arsoft-web-crashupload
app/crashdump/model.py
Python
gpl-3.0
24,814
0.00129
from __future__ import absolute_import from .notedown import * from .main import convert, markdown_template, __version__ # avoid having to require the notebook to install notedown try: from .contentsmanager import NotedownContentsManager except ImportError: NotedownContentsManager = 'You need to install the jupyter notebook.'
michhar/notedown
notedown/__init__.py
Python
bsd-2-clause
338
0
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, 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. from datetime import datetime from unittest import TestCase from paste.fixture import TestApp from sqlalchemy import orm from nailgun.db import engine from nailgun.db import flush from nailgun.db import NoCacheQuery from nailgun.db.sqlalchemy.models import Node from nailgun.wsgi import build_app class TestDBRefresh(TestCase): def setUp(self): self.app = TestApp(build_app().wsgifunc()) self.db = orm.scoped_session( orm.sessionmaker(bind=engine, query_cls=NoCacheQuery) )() self.db2 = orm.scoped_session( orm.sessionmaker(bind=engine, query_cls=NoCacheQuery) )() self.default_headers = { "Content-Type": "application/json" } flush() def test_session_update(self): node = Node() node.mac = u"ASDFGHJKLMNOPR" node.timestamp = datetime.now() self.db.add(node) self.db.commit() node2 = self.db2.query(Node).filter( Node.id == node.id ).first() node2.mac = u"12345678" self.db2.add(node2) self.db2.commit() self.db.query(Node).filter( Node.id == node.id ).first() self.assertEqual(node.mac, u"12345678")
andrei4ka/fuel-web-redhat
nailgun/nailgun/test/integration/test_db_refresh.py
Python
apache-2.0
1,879
0
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Project_Dependencies.is_public' db.delete_column('project_project_dependencies', 'is_public') def backwards(self, orm): # Adding field 'Project_Dependencies.is_public' db.add_column('project_project_dependencies', 'is_public', self.gf('django.db.models.fields.BooleanField')(default=True), keep_default=False) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'project.project': { 'Meta': {'object_name': 'Project'}, 'brief': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['project.ProjectCategory']", 'symmetrical': 'False'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 18, 0, 0)'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_refused_to_give_to_bitfund': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'maintainer': ('django.db.models.fields.related.ForeignKey', [], {'default': '0', 'to': "orm['auth.User']"}), 'status': ('django.db.models.fields.CharField', [], {'default': "'unclaimed'", 'max_length': '80'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'project.project_dependencies': { 'Meta': {'object_name': 'Project_Dependencies'}, 'brief': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 18, 0, 0)'}), 'dependee_project': ('django.db.models.fields.related.ForeignKey', [], {'default': '0', 'related_name': "'dependee_project'", 'to': "orm['project.Project']"}), 'depender_project': ('django.db.models.fields.related.ForeignKey', [], {'default': '0', 'related_name': "'depender_project'", 'to': "orm['project.Project']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'redonation_amount': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '2', 'blank': 'True'}), 'redonation_percent': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '2', 'blank': 'True'}), 'sort_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'project.projectcategory': { 'Meta': {'object_name': 'ProjectCategory'}, 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 18, 0, 0)'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'project.projectgoal': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectGoal'}, 'amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '12', 'decimal_places': '0'}), 'brief': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 18, 0, 0)'}), 'date_ending': ('django.db.models.fields.DateTimeField', [], {}), 'date_starting': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 18, 0, 0)'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'long_text': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['project.Project']"}), 'short_text': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'sort_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'video_url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, 'project.projectgratefulusers': { 'Meta': {'object_name': 'ProjectGratefulUsers'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['project.Project']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'project.projectneed': { 'Meta': {'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectNeed'}, 'amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'max_digits': '12', 'decimal_places': '0'}), 'brief': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 18, 0, 0)'}), 'date_ending': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'date_starting': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 18, 0, 0)', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '80'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['project.Project']"}), 'sort_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'project.projectothersource': { 'Meta': {'object_name': 'ProjectOtherSource'}, 'amount': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '2', 'blank': 'True'}), 'brief': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 18, 0, 0)'}), 'date_received': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_monthly': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['project.Project']"}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) } } complete_apps = ['project']
alexykot/bitfund
bitfund/project/migrations/0006_auto__del_field_project_dependencies_is_public.py
Python
gpl-3.0
11,471
0.008195
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.plant_heating_and_cooling_equipment import ChillerElectricReformulatedEir log = logging.getLogger(__name__) class TestChillerElectricReformulatedEir(unittest.TestCase): def setUp(self): self.fd, self.path = tempfile.mkstemp() def tearDown(self): os.remove(self.path) def test_create_chillerelectricreformulatedeir(self): pyidf.validation_level = ValidationLevel.error obj = ChillerElectricReformulatedEir() # alpha var_name = "Name" obj.name = var_name # real var_reference_capacity = 0.0001 obj.reference_capacity = var_reference_capacity # real var_reference_cop = 0.0001 obj.reference_cop = var_reference_cop # real var_reference_leaving_chilled_water_temperature = 4.4 obj.reference_leaving_chilled_water_temperature = var_reference_leaving_chilled_water_temperature # real var_reference_leaving_condenser_water_temperature = 5.5 obj.reference_leaving_condenser_water_temperature = var_reference_leaving_condenser_water_temperature # real var_reference_chilled_water_flow_rate = 0.0001 obj.reference_chilled_water_flow_rate = var_reference_chilled_water_flow_rate # real var_reference_condenser_water_flow_rate = 0.0001 obj.reference_condenser_water_flow_rate = var_reference_condenser_water_flow_rate # object-list var_cooling_capacity_function_of_temperature_curve_name = "object-list|Cooling Capacity Function of Temperature Curve Name" obj.cooling_capacity_function_of_temperature_curve_name = var_cooling_capacity_function_of_temperature_curve_name # object-list var_electric_input_to_cooling_output_ratio_function_of_temperature_curve_name = "object-list|Electric Input to Cooling Output Ratio Function of Temperature Curve Name" obj.electric_input_to_cooling_output_ratio_function_of_temperature_curve_name = var_electric_input_to_cooling_output_ratio_function_of_temperature_curve_name # alpha var_electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_type = "LeavingCondenserWaterTemperature" obj.electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_type = var_electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_type # object-list var_electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_name = "object-list|Electric Input to Cooling Output Ratio Function of Part Load Ratio Curve Name" obj.electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_name = var_electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_name # real var_minimum_part_load_ratio = 0.0 obj.minimum_part_load_ratio = var_minimum_part_load_ratio # real var_maximum_part_load_ratio = 0.0001 obj.maximum_part_load_ratio = var_maximum_part_load_ratio # real var_optimum_part_load_ratio = 0.0001 obj.optimum_part_load_ratio = var_optimum_part_load_ratio # real var_minimum_unloading_ratio = 0.0 obj.minimum_unloading_ratio = var_minimum_unloading_ratio # node var_chilled_water_inlet_node_name = "node|Chilled Water Inlet Node Name" obj.chilled_water_inlet_node_name = var_chilled_water_inlet_node_name # node var_chilled_water_outlet_node_name = "node|Chilled Water Outlet Node Name" obj.chilled_water_outlet_node_name = var_chilled_water_outlet_node_name # node var_condenser_inlet_node_name = "node|Condenser Inlet Node Name" obj.condenser_inlet_node_name = var_condenser_inlet_node_name # node var_condenser_outlet_node_name = "node|Condenser Outlet Node Name" obj.condenser_outlet_node_name = var_condenser_outlet_node_name # real var_fraction_of_compressor_electric_consumption_rejected_by_condenser = 0.50005 obj.fraction_of_compressor_electric_consumption_rejected_by_condenser = var_fraction_of_compressor_electric_consumption_rejected_by_condenser # real var_leaving_chilled_water_lower_temperature_limit = 21.21 obj.leaving_chilled_water_lower_temperature_limit = var_leaving_chilled_water_lower_temperature_limit # alpha var_chiller_flow_mode_type = "ConstantFlow" obj.chiller_flow_mode_type = var_chiller_flow_mode_type # real var_design_heat_recovery_water_flow_rate = 0.0 obj.design_heat_recovery_water_flow_rate = var_design_heat_recovery_water_flow_rate # node var_heat_recovery_inlet_node_name = "node|Heat Recovery Inlet Node Name" obj.heat_recovery_inlet_node_name = var_heat_recovery_inlet_node_name # node var_heat_recovery_outlet_node_name = "node|Heat Recovery Outlet Node Name" obj.heat_recovery_outlet_node_name = var_heat_recovery_outlet_node_name # real var_sizing_factor = 0.0001 obj.sizing_factor = var_sizing_factor # real var_condenser_heat_recovery_relative_capacity_fraction = 0.5 obj.condenser_heat_recovery_relative_capacity_fraction = var_condenser_heat_recovery_relative_capacity_fraction # object-list var_heat_recovery_inlet_high_temperature_limit_schedule_name = "object-list|Heat Recovery Inlet High Temperature Limit Schedule Name" obj.heat_recovery_inlet_high_temperature_limit_schedule_name = var_heat_recovery_inlet_high_temperature_limit_schedule_name # node var_heat_recovery_leaving_temperature_setpoint_node_name = "node|Heat Recovery Leaving Temperature Setpoint Node Name" obj.heat_recovery_leaving_temperature_setpoint_node_name = var_heat_recovery_leaving_temperature_setpoint_node_name idf = IDF() idf.add(obj) idf.save(self.path, check=False) with open(self.path, mode='r') as f: for line in f: log.debug(line.strip()) idf2 = IDF(self.path) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].name, var_name) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].reference_capacity, var_reference_capacity) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].reference_cop, var_reference_cop) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].reference_leaving_chilled_water_temperature, var_reference_leaving_chilled_water_temperature) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].reference_leaving_condenser_water_temperature, var_reference_leaving_condenser_water_temperature) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].reference_chilled_water_flow_rate, var_reference_chilled_water_flow_rate) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].reference_condenser_water_flow_rate, var_reference_condenser_water_flow_rate) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].cooling_capacity_function_of_temperature_curve_name, var_cooling_capacity_function_of_temperature_curve_name) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].electric_input_to_cooling_output_ratio_function_of_temperature_curve_name, var_electric_input_to_cooling_output_ratio_function_of_temperature_curve_name) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_type, var_electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_type) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_name, var_electric_input_to_cooling_output_ratio_function_of_part_load_ratio_curve_name) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].minimum_part_load_ratio, var_minimum_part_load_ratio) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].maximum_part_load_ratio, var_maximum_part_load_ratio) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].optimum_part_load_ratio, var_optimum_part_load_ratio) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].minimum_unloading_ratio, var_minimum_unloading_ratio) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].chilled_water_inlet_node_name, var_chilled_water_inlet_node_name) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].chilled_water_outlet_node_name, var_chilled_water_outlet_node_name) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].condenser_inlet_node_name, var_condenser_inlet_node_name) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].condenser_outlet_node_name, var_condenser_outlet_node_name) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].fraction_of_compressor_electric_consumption_rejected_by_condenser, var_fraction_of_compressor_electric_consumption_rejected_by_condenser) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].leaving_chilled_water_lower_temperature_limit, var_leaving_chilled_water_lower_temperature_limit) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].chiller_flow_mode_type, var_chiller_flow_mode_type) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].design_heat_recovery_water_flow_rate, var_design_heat_recovery_water_flow_rate) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].heat_recovery_inlet_node_name, var_heat_recovery_inlet_node_name) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].heat_recovery_outlet_node_name, var_heat_recovery_outlet_node_name) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].sizing_factor, var_sizing_factor) self.assertAlmostEqual(idf2.chillerelectricreformulatedeirs[0].condenser_heat_recovery_relative_capacity_fraction, var_condenser_heat_recovery_relative_capacity_fraction) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].heat_recovery_inlet_high_temperature_limit_schedule_name, var_heat_recovery_inlet_high_temperature_limit_schedule_name) self.assertEqual(idf2.chillerelectricreformulatedeirs[0].heat_recovery_leaving_temperature_setpoint_node_name, var_heat_recovery_leaving_temperature_setpoint_node_name)
rbuffat/pyidf
tests/test_chillerelectricreformulatedeir.py
Python
apache-2.0
10,596
0.005379
import bpy from .... base_types.node import AnimationNode class LineMeshNode(bpy.types.Node, AnimationNode): bl_idname = "an_LineMeshNode" bl_label = "Line Mesh" def create(self): self.newInput("Vector", "Start", "start") self.newInput("Vector", "End", "end", value = [0, 0, 10]) self.newInput("Integer", "Steps", "steps", value = 2, minValue = 2) self.newOutput("Vector List", "Vertices", "vertices") self.newOutput("Edge Indices List", "Edge Indices", "edgeIndices") def execute(self, start, end, steps): steps = max(steps, 2) divisor = steps - 1 vertices = [start * (1 - i / divisor) + end * i / divisor for i in range(steps)] edges = [(i, i + 1) for i in range(steps - 1)] return vertices, edges
Thortoise/Super-Snake
Blender/animation_nodes-master/nodes/mesh/generation/line.py
Python
gpl-3.0
799
0.010013
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "travis-ci.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
uw-it-aca/mdot-developers
travis-ci/manage.py
Python
apache-2.0
252
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('app', '0014_survey'), ] operations = [ migrations.AddField( model_name='survey', name='question2', field=models.CharField(default=50, max_length=50), preserve_default=False, ), ]
Saruus/drPencilcode
app/migrations/0015_survey_question2.py
Python
agpl-3.0
435
0
# -*- coding: utf-8 -*- # Copyright (c) 2009 - 2014 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing a dialog to manage history. """ from __future__ import unicode_literals from PyQt5.QtCore import pyqtSignal, Qt, QUrl from PyQt5.QtGui import QFontMetrics, QCursor from PyQt5.QtWidgets import QDialog, QMenu, QApplication from E5Gui.E5TreeSortFilterProxyModel import E5TreeSortFilterProxyModel from .HistoryModel import HistoryModel from .Ui_HistoryDialog import Ui_HistoryDialog class HistoryDialog(QDialog, Ui_HistoryDialog): """ Class implementing a dialog to manage history. @signal openUrl(QUrl, str) emitted to open a URL in the current tab @signal newUrl(QUrl, str) emitted to open a URL in a new tab """ openUrl = pyqtSignal(QUrl, str) newUrl = pyqtSignal(QUrl, str) def __init__(self, parent=None, manager=None): """ Constructor @param parent reference to the parent widget (QWidget @param manager reference to the history manager object (HistoryManager) """ super(HistoryDialog, self).__init__(parent) self.setupUi(self) self.__historyManager = manager if self.__historyManager is None: import Helpviewer.HelpWindow self.__historyManager = \ Helpviewer.HelpWindow.HelpWindow.historyManager() self.__model = self.__historyManager.historyTreeModel() self.__proxyModel = E5TreeSortFilterProxyModel(self) self.__proxyModel.setSortRole(HistoryModel.DateTimeRole) self.__proxyModel.setFilterKeyColumn(-1) self.__proxyModel.setSourceModel(self.__model) self.historyTree.setModel(self.__proxyModel) self.historyTree.expandAll() fm = QFontMetrics(self.font()) header = fm.width("m") * 40 self.historyTree.header().resizeSection(0, header) self.historyTree.header().setStretchLastSection(True) self.historyTree.setContextMenuPolicy(Qt.CustomContextMenu) self.historyTree.activated.connect(self.__activated) self.historyTree.customContextMenuRequested.connect( self.__customContextMenuRequested) self.searchEdit.textChanged.connect( self.__proxyModel.setFilterFixedString) self.removeButton.clicked.connect(self.historyTree.removeSelected) self.removeAllButton.clicked.connect(self.__historyManager.clear) self.__proxyModel.modelReset.connect(self.__modelReset) def __modelReset(self): """ Private slot handling a reset of the tree view's model. """ self.historyTree.expandAll() def __customContextMenuRequested(self, pos): """ Private slot to handle the context menu request for the bookmarks tree. @param pos position the context menu was requested (QPoint) """ menu = QMenu() idx = self.historyTree.indexAt(pos) idx = idx.sibling(idx.row(), 0) if idx.isValid() and not self.historyTree.model().hasChildren(idx): menu.addAction( self.tr("&Open"), self.__openHistoryInCurrentTab) menu.addAction( self.tr("Open in New &Tab"), self.__openHistoryInNewTab) menu.addSeparator() menu.addAction(self.tr("&Copy"), self.__copyHistory) menu.addAction(self.tr("&Remove"), self.historyTree.removeSelected) menu.exec_(QCursor.pos()) def __activated(self, idx): """ Private slot to handle the activation of an entry. @param idx reference to the entry index (QModelIndex) """ self.__openHistory( QApplication.keyboardModifiers() & Qt.ControlModifier) def __openHistoryInCurrentTab(self): """ Private slot to open a history entry in the current browser tab. """ self.__openHistory(False) def __openHistoryInNewTab(self): """ Private slot to open a history entry in a new browser tab. """ self.__openHistory(True) def __openHistory(self, newTab): """ Private method to open a history entry. @param newTab flag indicating to open the history entry in a new tab (boolean) """ idx = self.historyTree.currentIndex() if newTab: self.newUrl.emit( idx.data(HistoryModel.UrlRole), idx.data(HistoryModel.TitleRole)) else: self.openUrl.emit( idx.data(HistoryModel.UrlRole), idx.data(HistoryModel.TitleRole)) def __copyHistory(self): """ Private slot to copy a history entry's URL to the clipboard. """ idx = self.historyTree.currentIndex() if not idx.parent().isValid(): return url = idx.data(HistoryModel.UrlStringRole) clipboard = QApplication.clipboard() clipboard.setText(url)
davy39/eric
Helpviewer/History/HistoryDialog.py
Python
gpl-3.0
5,112
0.003912
# -*- coding: utf-8 -*- # Copyright (C) 2016-2018 Cordell Bloor # Published under the MIT License from nose.tools import * import guardonce.util as go def test_ok(): contents = ''' #ifndef MATCH_H #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 32) def test_ok_space_before_hash(): contents = ''' #ifndef MATCH_H #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 33) def test_ok_space_after_hash(): contents = ''' # ifndef MATCH_H # define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 34) @raises(ValueError) def test_no_ifndef(): contents = ''' #ifdef MATCH_H #define MATCH_H ''' go.guess_guard(contents) @raises(ValueError) def test_no_define(): contents = ''' #ifndef MATCH_H #defne MATCH_H ''' go.guess_guard(contents) @raises(ValueError) def test_mismatched_define_symbol(): contents = ''' #ifndef MATCH_H #define MISMATCH_H ''' go.guess_guard(contents) @raises(ValueError) def test_extra_junk_on_ifndef(): contents = ''' #ifndef MATCH_H WEIRD_HUH #define MATCH_H ''' go.guess_guard(contents) @raises(ValueError) def test_extra_junk_on_define(): contents = ''' #ifndef MATCH_H #define MATCH_H WEIRD_HUH ''' go.guess_guard(contents) def test_extra_whitespace_on_ifndef(): contents = ''' #ifndef MATCH_H #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 33) def test_extra_whitespace_on_define(): contents = ''' #ifndef MATCH_H #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 33) def test_define_with_value_1(): contents = ''' #ifndef MATCH_H #define MATCH_H 1 ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 34) @raises(ValueError) def test_define(): contents = ''' #ifndef ONE #define ONE 1 #endif ''' go.guess_guard(contents) @raises(ValueError) def test_define_with_space(): contents = ''' #ifndef ONE #define ONE 1 #endif ''' go.guess_guard(contents) def test_if_defined(): contents = ''' #if !defined(MATCH_H) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 38) def test_if_defined_no_parentheses(): contents = ''' #if !defined MATCH_H #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 37) def test_if_defined_space_after_bang(): contents = ''' #if ! defined(MATCH_H) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 39) def test_if_defined_space_before_parentheses(): contents = ''' #if !defined (MATCH_H) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 39) def test_if_defined_space_before_symbol(): contents = ''' #if !defined( MATCH_H) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 39) def test_if_defined_space_after_symbol(): contents = ''' #if !defined(MATCH_H ) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 39) def test_if_defined_space_before_newline(): contents = ''' #if !defined(MATCH_H) #define MATCH_H ''' g,s,e = go.guess_guard(contents) assert_equals(g, 'MATCH_H') assert_equals(s, 1) assert_equals(e, 39) @raises(ValueError) def test_if_defined_extra_junk_before_newline(): contents = ''' #if !defined(MATCH_H) WEIRD_HUH #define MATCH_H ''' go.guess_guard(contents) @raises(ValueError) def test_if_defined_extra_junk_in_defined(): contents = ''' #if !defined(MATCH_H WEIRD_HUH) #define MATCH_H ''' go.guess_guard(contents)
cgmb/guardonce
tests/test_guess_guard.py
Python
mit
4,227
0.012302
from django.core.management.base import BaseCommand from django.conf import settings from utils.amazon import default_s3_store from videos.models import Video, VIDEO_TYPE_FLV, VIDEO_TYPE_HTML5 import urllib import os import commands import sys from django.core.exceptions import ImproperlyConfigured from django.core.files.base import ContentFile from django.db.models import ObjectDoesNotExist VIDEO_UPLOAD_PATH = getattr(settings, 'VIDEO_UPLOAD_PATH', \ os.path.join(settings.MEDIA_ROOT, 'videos')) VIDEO_THUMBNAILS_FOLDER = getattr(settings, 'VIDEO_THUMBNAILS_PATH', 'videos/thumbnails/') THUMBNAILS_PATH = os.path.join(settings.MEDIA_ROOT, VIDEO_THUMBNAILS_FOLDER) class Command(BaseCommand): def handle(self, *args, **options): print 'Run load thumbnail command' self.verbosity = int(options.get('verbosity', 1)) self.s3_store = self.init_s3() if not os.path.exists(VIDEO_UPLOAD_PATH): os.makedirs(VIDEO_UPLOAD_PATH) if not os.path.exists(THUMBNAILS_PATH): os.makedirs(THUMBNAILS_PATH) qs = Video.objects.filter(thumbnail='', videourl__original=True, videourl__type__in=[VIDEO_TYPE_FLV, VIDEO_TYPE_HTML5]) for video in qs: self.print_to_console(u'Handling %s' % video.__unicode__()) try: video_url = video.videourl_set.filter(original=True)[:1].get() except ObjectDoesNotExist: continue path = self.get_file_path(video, video_url) if not os.path.exists(path): self.print_to_console(u'Saving...') urllib.urlretrieve(video_url.url, path) self.print_to_console(u'Video saved.') else: self.print_to_console(u'File exist.') self.get_thumbnail(video, path) self.print_to_console(u'-----------------') #--- Save original thumbnails to S3 Store --- self.print_to_console(u'Save original thumbnails to S3 Store...') qs = Video.objects.exclude(thumbnail='').filter(s3_thumbnail='') for video in qs: self.print_to_console(u'Handling %s' % video.__unicode__()) name = video.thumbnail.strip('/').split('/')[-1] cf = ContentFile(urllib.urlopen(video.thumbnail).read()) video.s3_thumbnail.save('%s/%s' % (video.video_id, name), cf, True) def print_to_console(self, msg, min_verbosity=1): if self.verbosity >= min_verbosity: print msg def init_s3(self): if not default_s3_store: raise ImproperlyConfigured('Have not settings for thumbnails uploading to S3 Store.') return default_s3_store def get_thumbnail(self, video, path): self.print_to_console(u'Get thumbnail...') grabimage = "ffmpeg -y -i %s -vframes 1 -ss 00:00:%s -an -vcodec png -f rawvideo %s" thumbnailfilename = "%s.png" % video.video_id thumbnailpath = os.path.normpath(os.path.join(THUMBNAILS_PATH, thumbnailfilename)) grab_result = 'Command is not runned yet' try: grab_result = commands.getoutput(grabimage % (path, 10, thumbnailpath)) if not os.path.exists(thumbnailpath): raise Exception('Error in converting: %s' % grab_result) if not os.path.getsize(thumbnailpath): grab_result = commands.getoutput(grabimage % (path, 5, thumbnailpath)) self.print_to_console(u'Saving in S3 Store...') cf = ContentFile(open(thumbnailpath, 'rb').read()) video.s3_thumbnail.save(thumbnailfilename, cf, True) video.thumbnail = video.s3_thumbnail.url video.save() os.remove(thumbnailpath) os.remove(path) except: if settings.DEBUG: raise self.handle_error(sys.exc_info()) def get_file_path(self, video, video_url): type = video_url.url.split('.')[-1] name = '%s.%s' % (video.video_id, type) return os.path.join(VIDEO_UPLOAD_PATH, name)
wevoice/wesub
apps/videos/management/commands/load_thumbnails.py
Python
agpl-3.0
4,320
0.00787
#! /usr/bin/python import bottle import settings from controller import admin as admin_controller from controller import email as email_controller app = application = bottle.Bottle() # Base url for regular users app.route(settings.BASEPATH, 'GET', admin_controller.index) app.route(settings.BASEPATH + '/', 'GET', admin_controller.index) app.route( settings.BASEPATH + '/tasks/<id>', 'GET', admin_controller.read_user_tasks ) app.route( settings.BASEPATH + '/update/<id>', 'POST', admin_controller.update_self ) # Email handler email = bottle.Bottle() app.mount(settings.EMAIL_PATH, email) email.route('/', 'POST', email_controller.receive_email) email.route('/', 'GET', email_controller.test_form) email.route('', 'GET', email_controller.test_form) # Ansible admin admin = bottle.Bottle() app.mount(settings.ADMIN_PATH, admin) admin.route('/tasks', 'GET', admin_controller.read_tasks) admin.route('/create', 'POST', admin_controller.create_person) admin.route('/delete', 'POST', admin_controller.delete_people) admin.route('/<id>', 'GET', admin_controller.read_person) admin.route('/<id>', 'POST', admin_controller.update_person) admin.route('/', 'GET', admin_controller.admin) # Static files app.route( settings.STATIC_PATH + '/<type>/<filename>', 'GET', lambda **kwargs: bottle.static_file( filename=kwargs['filename'], root='static/' + kwargs['type'] ) ) if __name__ == '__main__': bottle.run(app=app, reloader=True, **settings.SERVER)
TeachBoost/ansible
ansible.py
Python
mit
1,499
0
# https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons class Solution: def numOfArrays(self, n: int, m: int, k: int) -> int: M = 1000000007 ret = 0 for i in range(k, m+1): ret += ((i-1)**(k-1)) * (i**(n-k)) return ret % M # n = 2 # m = 3 # k = 1 # ans = 6 # n = 9 # m = 1 # k = 1 # ans = 1 n = 50 m = 100 k = 25 ans = 34549172 # n = 37 # m = 17 # k = 7 # ans = 418930126 sl = Solution() ret = sl.numOfArrays(n, m, k) print(ret, "O" if ret==ans else "X")
heyf/cloaked-octo-adventure
leetcode/1420_build-array-where-you-can-find-the-maximum-exactly-k-comparisons.py
Python
mit
550
0.003636
import json import os import unittest from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine from pymatgen.util.testing import PymatgenTest class PhononBandStructureSymmLineTest(PymatgenTest): def setUp(self): with open( os.path.join(PymatgenTest.TEST_FILES_DIR, "NaCl_phonon_bandstructure.json"), encoding="utf-8", ) as f: d = json.load(f) self.bs = PhononBandStructureSymmLine.from_dict(d) with open( os.path.join(PymatgenTest.TEST_FILES_DIR, "Si_phonon_bandstructure.json"), encoding="utf-8", ) as f: d = json.load(f) self.bs2 = PhononBandStructureSymmLine.from_dict(d) def test_basic(self): self.assertAlmostEqual(self.bs.bands[1][10], 0.7753555184) self.assertAlmostEqual(self.bs.bands[5][100], 5.2548379776) self.assertArrayEqual(self.bs.bands.shape, (6, 204)) self.assertArrayEqual(self.bs.eigendisplacements.shape, (6, 204, 2, 3)) self.assertArrayAlmostEqual( self.bs.eigendisplacements[3][50][0], [0.0 + 0.0j, 0.14166569 + 0.04098339j, -0.14166569 - 0.04098339j], ) self.assertTrue(self.bs.has_eigendisplacements, True) self.assertArrayEqual(self.bs.min_freq()[0].frac_coords, [0, 0, 0]) self.assertAlmostEqual(self.bs.min_freq()[1], -0.03700895020) self.assertTrue(self.bs.has_imaginary_freq()) self.assertFalse(self.bs.has_imaginary_freq(tol=0.5)) self.assertArrayAlmostEqual(self.bs.asr_breaking(), [-0.0370089502, -0.0370089502, -0.0221388897]) self.assertEqual(self.bs.nb_bands, 6) self.assertEqual(self.bs.nb_qpoints, 204) self.assertArrayAlmostEqual(self.bs.qpoints[1].frac_coords, [0.01, 0, 0]) def test_nac(self): self.assertTrue(self.bs.has_nac) self.assertFalse(self.bs2.has_nac) self.assertAlmostEqual(self.bs.get_nac_frequencies_along_dir([1, 1, 0])[3], 4.6084532143) self.assertIsNone(self.bs.get_nac_frequencies_along_dir([0, 1, 1])) self.assertIsNone(self.bs2.get_nac_frequencies_along_dir([0, 0, 1])) self.assertArrayAlmostEqual( self.bs.get_nac_eigendisplacements_along_dir([1, 1, 0])[3][1], [(0.1063906409128248 + 0j), 0j, 0j], ) self.assertIsNone(self.bs.get_nac_eigendisplacements_along_dir([0, 1, 1])) self.assertIsNone(self.bs2.get_nac_eigendisplacements_along_dir([0, 0, 1])) def test_branches(self): self.assertEqual(self.bs.branches[0]["end_index"], 50) self.assertEqual(self.bs.branches[1]["start_index"], 51) self.assertEqual(self.bs.branches[2]["name"], "Y-Gamma") self.assertAlmostEqual(self.bs.get_branch(10)[0]["name"], "Gamma-X") self.assertEqual(len(self.bs.branches), 4) def test_dict_methods(self): s = self.bs.as_dict() self.assertIsNotNone(s) self.assertIsNotNone(json.dumps(s)) s = self.bs2.as_dict() self.assertIsNotNone(s) self.assertIsNotNone(json.dumps(s)) s = self.bs2.as_phononwebsite() self.assertIsNotNone(s) self.assertIsNotNone(json.dumps(s)) self.assertMSONable(self.bs) self.assertMSONable(self.bs2) def test_write_methods(self): self.bs2.write_phononwebsite("test.json") def tearDown(self): if os.path.isfile("test.json"): os.remove("test.json") if __name__ == "__main__": unittest.main()
materialsproject/pymatgen
pymatgen/phonon/tests/test_bandstructure.py
Python
mit
3,536
0.00198
"""Manage Treadmill app manifest.""" from __future__ import absolute_import import logging import urllib import click from .. import cli from treadmill import restclient from treadmill import context _LOGGER = logging.getLogger(__name__) _STATE_FORMATTER = cli.make_formatter(cli.InstanceStatePrettyFormatter) _ENDPOINT_FORMATTER = cli.make_formatter(cli.EndpointPrettyFormatter) _APP_FORMATTER = cli.make_formatter(cli.AppPrettyFormatter) def _show_state(apis, match): """Show cell state.""" url = '/state/' if match: url += '?' + urllib.urlencode([('match', match)]) response = restclient.get(apis, url) cli.out(_STATE_FORMATTER(response.json())) def _show_list(apis, match, states): """Show list of instnces in given state.""" url = '/state/' if match: url += '?' + urllib.urlencode([('match', match)]) response = restclient.get(apis, url) names = [item['name'] for item in response.json() if item['state'] in states] for name in names: print name def _show_endpoints(apis, pattern, endpoint, proto): """Show cell endpoints.""" url = '/endpoint/%s' % urllib.quote(pattern) if endpoint: if proto: url += '/' + proto else: url += '/*' url += '/' + endpoint response = restclient.get(apis, url) endpoints = [{ 'name': end['name'], 'proto': end['proto'], 'endpoint': end['endpoint'], 'hostport': '{0}:{1}'.format(end['host'], end['port']) } for end in response.json()] cli.out(_ENDPOINT_FORMATTER(endpoints)) def _show_instance(apis, instance_id): """Show instance manifest.""" url = '/instance/%s' % urllib.quote(instance_id) response = restclient.get(apis, url) cli.out(_APP_FORMATTER(response.json())) def init(): """Return top level command handler.""" ctx = {} @click.group() @click.option('--cell', required=True, envvar='TREADMILL_CELL', callback=cli.handle_context_opt, expose_value=False) @click.option('--api', required=False, help='API url to use.', metavar='URL', envvar='TREADMILL_STATEAPI') def show(api): """Show state of scheduled applications.""" ctx['api'] = api @show.command() @cli.ON_REST_EXCEPTIONS @click.option('--match', help='Application name pattern match') def state(match): """Show state of Treadmill scheduled instances.""" apis = context.GLOBAL.state_api(ctx['api']) return _show_state(apis, match) @show.command() @cli.ON_REST_EXCEPTIONS @click.option('--match', help='Application name pattern match') def pending(match): """Show pending instances.""" apis = context.GLOBAL.state_api(ctx['api']) return _show_list(apis, match, ['pending']) @show.command() @cli.ON_REST_EXCEPTIONS @click.option('--match', help='Application name pattern match') def running(match): """Show running instances.""" apis = context.GLOBAL.state_api(ctx['api']) return _show_list(apis, match, ['running']) @show.command() @cli.ON_REST_EXCEPTIONS @click.option('--match', help='Application name pattern match') def scheduled(match): """Show scheduled instances.""" apis = context.GLOBAL.state_api(ctx['api']) return _show_list(apis, match, ['running', 'scheduled']) @show.command(name='all') @cli.ON_REST_EXCEPTIONS @click.option('--match', help='Application name pattern match') def _all(match): """Show scheduled instances.""" apis = context.GLOBAL.state_api(ctx['api']) return _show_list(apis, match, ['pending', 'running', 'scheduled']) @show.command() @cli.ON_REST_EXCEPTIONS @click.argument('pattern') @click.argument('endpoint', required=False) @click.argument('proto', required=False) def endpoints(pattern, endpoint, proto): """Show application endpoints.""" apis = context.GLOBAL.state_api(ctx['api']) return _show_endpoints(apis, pattern, endpoint, proto) @show.command() @cli.ON_REST_EXCEPTIONS @click.argument('instance_id') def instance(instance_id): """Show scheduled instance manifest.""" apis = context.GLOBAL.cell_api(ctx['api']) return _show_instance(apis, instance_id) del _all del running del scheduled del pending del instance del state del endpoints return show
toenuff/treadmill
lib/python/treadmill/cli/show.py
Python
apache-2.0
4,580
0
#!/usr/bin/env python # $Id: pythiaExample.py 545 2012-01-18 06:10:03Z cvermilion $ #---------------------------------------------------------------------- # Copyright (c) 2010-12, Pierre-Antoine Delsart, Kurtis Geerlings, Joey Huston, # Brian Martin, and Christopher Vermilion # #---------------------------------------------------------------------- # This file is part of SpartyJet. # # SpartyJet 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. # # SpartyJet 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 SpartyJet; if not, write to the Free Software # Foundation, Inc.: # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #---------------------------------------------------------------------- from spartyjet import SpartyJet as SJ, fastjet as fj, writeCurrentFile from ROOT import TPythia8, gSystem #=============================================== # Example showing how to pass events directly from Pythia to SpartyJet. # Requires that you have built ROOT's Pythia 6 and/or 8 interface. gSystem.Load('libEG') # import common event gen lib # Create a jet builder(MessageLevel = INFO)------ builder = SJ.JetBuilder(SJ.INFO) ######### PYTHIA8 ######### # Load Libraries gSystem.Load('libEGPythia8') # Creat TPythia8 object pythia = TPythia8() # Single W production pythia.ReadString('WeakSingleBoson:ffbar2W = on') # Force decay W->ev pythia.ReadString("24:onMode = off") pythia.ReadString("24:onIfAny = 11 12") # UE pythia.ReadString("PartonLevel:MI = off") # ISR,FSR, beam remnant pythia.ReadString("PartonLevel:ISR = on") pythia.ReadString("PartonLevel:FSR = on") pythia.ReadString("PartonLevel:Remnants = on") # Hadronize pythia.ReadString("HadronLevel:all = on") # Initialize for LHC pythia.Initialize(2212,2212, 7000.) # Initialize for Tevatron #pythia.Initialize( 2212, -2212, 1960.) ########################### ######### PYTHIA6 ######### ## Load Library #ROOT.gSystem.Load("libEGPythia6") ## Create TPythia8 object #pythia = ROOT.TPythia6() ## Turn on W+jet production #pythia.SetMSEL(14) ## Turn off all decay modes except W->e+nu #decayChOff = [190,191,192,194,195,196,198,199,200,207,208] #for dc in decayChOff: # pythia.SetMDME(dc,1,0) ## Turn on W->e+nu #pythia.SetMDME(206,1,1) ## Initialize for LHC #pythia.Initialize('cms','p+','p+',7000.) ## Initialize for Tevatron ##pythia.Initialize('cms','p+','p-',1960.) ########################### # Create input object and add to builder -------- input = SJ.PythiaInput(pythia) # Event Particle printout (Only usable in Pythia8) #input.printEvent(True) builder.configure_input(input) # Create jet finder and add to builder ---------- analysis = SJ.JetAnalysis(SJ.FastJet.FastJetFinder('AntiKt4', fj.antikt_algorithm, 0.4)) builder.add_analysis(analysis) # Configure text output-------------------------- builder.add_text_output("../data/output/pythia.dat") # Configure ntuple output------------------------ outfile = "../data/output/pythia.root" builder.configure_output("SpartyJet_Tree", outfile) # Run SpartyJet---------------------------------- builder.process_events(10) # Save this script in the ROOT file (needs to go after process_events or it # gets over-written!) writeCurrentFile(outfile)
mickypaganini/SSI2016-jet-clustering
spartyjet-4.0.2_mac/examples_py/pythiaExample.py
Python
mit
3,668
0.008179
from django.conf.urls import patterns, include, url from django.contrib import admin import views from django.contrib.auth.decorators import login_required urlpatterns = patterns('', url(r'^library$', views.library, name='profile-library'), url(r'^stream$', views.stream, name='profile-stream'), url(r'^add_photo/', login_required(views.PhotoCreate.as_view( template_name="imager_images/create_form.html", success_url='/images/library')), name='add_photo'), url(r'^add_album/', login_required(views.AlbumCreate.as_view( template_name="imager_images/create_form.html", success_url='/images/library')), name='add_album'), url(r'^update_album/(?P<pk>\d+)/$', login_required(views.AlbumUpdate.as_view( template_name="imager_images/update_album.html", success_url='/images/library')), name='update_album'), url(r'^update_photo/(?P<pk>\d+)/$', login_required(views.PhotoUpdate.as_view( template_name="imager_images/update_photo.html", success_url='/images/library')), name='update_photo'), url(r'^delete_photo/(?P<pk>\d+)/$', login_required(views.PhotoDelete.as_view( template_name="imager_images/delete_form.html", success_url='/images/library')), name='delete_photo'), url(r'^delete_album/(?P<pk>\d+)/$', login_required(views.AlbumDelete.as_view( template_name="imager_images/delete_form.html", success_url='/images/library')), name='delete_album'), )
joelstanner/django-imager
imager/imager_images/urls.py
Python
mit
1,528
0.003927
""" Generic relations Generic relations let an object have a foreign key to any object through a content-type/object-id field. A ``GenericForeignKey`` field can point to any object, be it animal, vegetable, or mineral. The canonical example is tags (although this example implementation is *far* from complete). """ from __future__ import unicode_literals from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class TaggedItem(models.Model): """A tag on an item.""" tag = models.SlugField() content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: ordering = ["tag", "content_type__model"] def __str__(self): return self.tag class ValuableTaggedItem(TaggedItem): value = models.PositiveIntegerField() class AbstractComparison(models.Model): comparative = models.CharField(max_length=50) content_type1 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative1_set") object_id1 = models.PositiveIntegerField() first_obj = GenericForeignKey(ct_field="content_type1", fk_field="object_id1") @python_2_unicode_compatible class Comparison(AbstractComparison): """ A model that tests having multiple GenericForeignKeys. One is defined through an inherited abstract model and one defined directly on this class. """ content_type2 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative2_set") object_id2 = models.PositiveIntegerField() other_obj = GenericForeignKey(ct_field="content_type2", fk_field="object_id2") def __str__(self): return "%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj) @python_2_unicode_compatible class Animal(models.Model): common_name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) tags = GenericRelation(TaggedItem, related_query_name='animal') comparisons = GenericRelation(Comparison, object_id_field="object_id1", content_type_field="content_type1") def __str__(self): return self.common_name @python_2_unicode_compatible class Vegetable(models.Model): name = models.CharField(max_length=150) is_yucky = models.BooleanField(default=True) tags = GenericRelation(TaggedItem) def __str__(self): return self.name @python_2_unicode_compatible class Mineral(models.Model): name = models.CharField(max_length=150) hardness = models.PositiveSmallIntegerField() # note the lack of an explicit GenericRelation here... def __str__(self): return self.name class GeckoManager(models.Manager): def get_queryset(self): return super(GeckoManager, self).get_queryset().filter(has_tail=True) class Gecko(models.Model): has_tail = models.BooleanField(default=False) objects = GeckoManager() # To test fix for #11263 class Rock(Mineral): tags = GenericRelation(TaggedItem) class ManualPK(models.Model): id = models.IntegerField(primary_key=True) tags = GenericRelation(TaggedItem, related_query_name='manualpk') class ForProxyModelModel(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() obj = GenericForeignKey(for_concrete_model=False) title = models.CharField(max_length=255, null=True) class ForConcreteModelModel(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() obj = GenericForeignKey() class ConcreteRelatedModel(models.Model): bases = GenericRelation(ForProxyModelModel, for_concrete_model=False) class ProxyRelatedModel(ConcreteRelatedModel): class Meta: proxy = True # To test fix for #7551 class AllowsNullGFK(models.Model): content_type = models.ForeignKey(ContentType, models.SET_NULL, null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey()
megaumi/django
tests/generic_relations/models.py
Python
bsd-3-clause
4,327
0.001156
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'BIOMD0000000462.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbmlString)
biomodels/BIOMD0000000462
BIOMD0000000462/model.py
Python
cc0-1.0
427
0.009368
# # Gordon McMillan (as inspired and influenced by Greg Stein) # # subclasses may not need marshal or struct, but since they're # builtin, importing is safe. # # While an Archive is really an abstraction for any "filesystem # within a file", it is tuned for use with imputil.FuncImporter. # This assumes it contains python code objects, indexed by the # the internal name (ie, no '.py'). # See carchive.py for a more general archive (contains anything) # that can be understood by a C program. #archive_rt is a stripped down version of MEInc.Dist.archive. #It has had all building logic removed. #It's purpose is to bootstrap the Python installation. import marshal import struct class Archive: """ A base class for a repository of python code objects. The extract method is used by imputil.ArchiveImporter to get code objects by name (fully qualified name), so an enduser "import a.b" would become extract('a.__init__') extract('a.b') """ MAGIC = 'PYL\0' HDRLEN = 12 # default is MAGIC followed by python's magic, int pos of toc TOCPOS = 8 TRLLEN = 0 # default - no trailer TOCTMPLT = {} # os = None def __init__(self, path=None, start=0): "Initialize an Archive. If path is omitted, it will be an empty Archive." self.toc = None self.path = path self.start = start import imp self.pymagic = imp.get_magic() if path is not None: self.lib = open(self.path, 'rb') self.checkmagic() self.loadtoc() ####### Sub-methods of __init__ - override as needed ############# def checkmagic(self): """ Overridable. Check to see if the file object self.lib actually has a file we understand. """ self.lib.seek(self.start) #default - magic is at start of file if self.lib.read(len(self.MAGIC)) != self.MAGIC: raise RuntimeError, "%s is not a valid %s archive file" \ % (self.path, self.__class__.__name__) if self.lib.read(len(self.pymagic)) != self.pymagic: raise RuntimeError, "%s has version mismatch to dll" % (self.path) def loadtoc(self): """ Overridable. Default: After magic comes an int (4 byte native) giving the position of the TOC within self.lib. Default: The TOC is a marshal-able string. """ self.lib.seek(self.start + self.TOCPOS) (offset,) = struct.unpack('=i', self.lib.read(4)) self.lib.seek(self.start + offset) self.toc = marshal.load(self.lib) ######## This is what is called by FuncImporter ####### ## Since an Archive is flat, we ignore parent and modname. def get_code(self, parent, modname, fqname): print "parent: ", parent print "modname: ", modname print "fqname: ", fqname return self.extract(fqname) # None if not found, (ispkg, code) otherwise if rslt is None: return None ispkg, code = rslt if ispkg: return ispkg, code, {'__path__': []} return rslt ####### Core method - Override as needed ######### def extract(self, name): """ Get the object corresponding to name, or None. For use with imputil ArchiveImporter, object is a python code object. 'name' is the name as specified in an 'import name'. 'import a.b' will become: extract('a') (return None because 'a' is not a code object) extract('a.__init__') (return a code object) extract('a.b') (return a code object) Default implementation: self.toc is a dict self.toc[name] is pos self.lib has the code object marshal-ed at pos """ ispkg, pos = self.toc.get(name, (0, None)) if pos is None: return None self.lib.seek(self.start + pos) return ispkg, marshal.load(self.lib) ######################################################################## # Informational methods def contents(self): """Return a list of the contents Default implementation assumes self.toc is a dict like object. Not required by ArchiveImporter. """ return self.toc.keys() ######################################################################## # Building ####### Top level method - shouldn't need overriding ####### ## def build(self, path, lTOC): ## """Create an archive file of name 'path'. ## lTOC is a 'logical TOC' - a list of (name, path, ...) ## where name is the internal name, eg 'a' ## and path is a file to get the object from, eg './a.pyc'. ## """ ## self.path = path ## self.lib = open(path, 'wb') ## #reserve space for the header ## if self.HDRLEN: ## self.lib.write('\0'*self.HDRLEN) ## ## #create an empty toc ## ## if type(self.TOCTMPLT) == type({}): ## self.toc = {} ## else: # assume callable ## self.toc = self.TOCTMPLT() ## ## for tocentry in lTOC: ## self.add(tocentry) # the guts of the archive ## ## tocpos = self.lib.tell() ## self.save_toc(tocpos) ## if self.TRLLEN: ## self.save_trailer(tocpos) ## if self.HDRLEN: ## self.update_headers(tocpos) ## self.lib.close() ## ## ## ####### manages keeping the internal TOC and the guts in sync ####### ## def add(self, entry): ## """Override this to influence the mechanics of the Archive. ## Assumes entry is a seq beginning with (nm, pth, ...) where ## nm is the key by which we'll be asked for the object. ## pth is the name of where we find the object. Overrides of ## get_obj_from can make use of further elements in entry. ## """ ## if self.os is None: ## import os ## self.os = os ## nm = entry[0] ## pth = entry[1] ## ispkg = self.os.path.splitext(self.os.path.basename(pth))[0] == '__init__' ## self.toc[nm] = (ispkg, self.lib.tell()) ## f = open(entry[1], 'rb') ## f.seek(8) #skip magic and timestamp ## self.lib.write(f.read()) ## ## def save_toc(self, tocpos): ## """Default - toc is a dict ## Gets marshaled to self.lib ## """ ## marshal.dump(self.toc, self.lib) ## ## def save_trailer(self, tocpos): ## """Default - not used""" ## pass ## ## def update_headers(self, tocpos): ## """Default - MAGIC + Python's magic + tocpos""" ## self.lib.seek(self.start) ## self.lib.write(self.MAGIC) ## self.lib.write(self.pymagic) ## self.lib.write(struct.pack('=i', tocpos)) ############################################################## # # ZlibArchive - an archive with compressed entries # class ZlibArchive(Archive): MAGIC = 'PYZ\0' TOCPOS = 8 HDRLEN = 12 TRLLEN = 0 TOCTMPLT = {} LEVEL = 9 def __init__(self, path=None, offset=0): Archive.__init__(self, path, offset) # dynamic import so not imported if not needed global zlib import zlib def extract(self, name): (ispkg, pos, lngth) = self.toc.get(name, (0, None, 0)) if pos is None: return None self.lib.seek(self.start + pos) return ispkg, marshal.loads(zlib.decompress(self.lib.read(lngth))) ## def add(self, entry): ## if self.os is None: ## import os ## self.os = os ## nm = entry[0] ## pth = entry[1] ## ispkg = self.os.path.splitext(self.os.path.basename(pth))[0] == '__init__' ## f = open(pth, 'rb') ## f.seek(8) #skip magic and timestamp ## obj = zlib.compress(f.read(), self.LEVEL) ## self.toc[nm] = (ispkg, self.lib.tell(), len(obj)) ## self.lib.write(obj) ##
toontownfunserver/Panda3D-1.9.0
direct/pyinst/archive_rt.py
Python
bsd-3-clause
7,405
0.017016
class Point: Empty = " " Full = "XX" def __init__(self, x, y): if not type(x) == int \ or not type(y) == int: raise Exception('Can only assign int type to x or y value') self.X = x self.Y = y self.Value = self.Empty def __eq__(self, other): if isinstance(other, self.__class__): return self.X == other.X and self.Y == other.Y def __ne__(self, other): return not self.__eq__(other) def __str__(self): return "P(" + str(self.X) + "," + str(self.Y) + ")" def __repr__(self): return "P(" + str(self.X) + "," + str(self.Y) + ")"
acbilson/py-lex-lib
point.py
Python
gpl-3.0
593
0.016863
#!/usr/bin/env python """Download data files needed by SLURP.""" # Copyright (C) 2012-2013 Constantine Lignos # # 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 os import gzip from datamanager import download, unzip # Assume that download.py and pennpipeline.py are located in the same # directory PIPELINE_NAME = "SUBTLEPipeline-master" ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) PIPELINE_URL = "https://github.com/PennNLP/SUBTLEPipeline/archive/master.zip" FILENAME = os.path.join(ROOT_DIR, PIPELINE_NAME + ".zip") download(PIPELINE_URL, FILENAME) unzip(FILENAME, ROOT_DIR) # Now we need to additionally unzip the model file contained in the pipeline print "Decompressing parser model file..." model_gz = gzip.open(os.path.join(ROOT_DIR, PIPELINE_NAME, "models", "wsjall.obj.gz")) open(os.path.join(ROOT_DIR, PIPELINE_NAME, "models", "wsjall.obj"), 'wb').write(model_gz.read())
PennNLP/SLURP
download.py
Python
gpl-3.0
1,488
0.001344
##################################################################################### # # # Script to update Hostname # # # # Usage : wsadmin -lang jython -f updateHostName.py <node name > < host name > # # # ##################################################################################### def updateHostName(nodename,hostname): nlist = AdminConfig.list('ServerIndex') attr=[["hostName", hostname ]] AdminConfig.modify(nlist,attr) AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName BOOTSTRAP_ADDRESS -host '+ hostname +' -port 2809 -modifyShared true]') AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName CSIV2_SSL_MUTUALAUTH_LISTENER_ADDRESS -host '+ hostname +' -port 9202 -modifyShared true]') AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName CSIV2_SSL_SERVERAUTH_LISTENER_ADDRESS -host '+ hostname +' -port 9201 -modifyShared true]') AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName ORB_LISTENER_ADDRESS -host '+ hostname +' -port 9900 -modifyShared true]') AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName SAS_SSL_SERVERAUTH_LISTENER_ADDRESS -host '+ hostname +' -port 9901 -modifyShared true]') AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName SOAP_CONNECTOR_ADDRESS -host '+ hostname +' -port 8878 -modifyShared true]') AdminConfig.save() updateHostName(sys.argv[0], sys.argv[1])
davidcurrie/ci.docker.websphere-traditional
network-deployment/appserver/updateHostName.py
Python
apache-2.0
1,804
0.033259
from setuptools import find_packages from setuptools import setup with open('README.md') as f: setup( name = 'swarm', version = '0.5.0', author = 'arvin.x', author_email = 'arvin.x@icloud.com', description = 'A modular distributed penetration testing tool', license = 'GPLv3', long_description = f.read(), packages = find_packages(), scripts = ['swarm.py','swarm_s.py'], entry_points = { 'console_scripts': [ 'swarm = swarm:main', 'swarm-s = swarm_s:main', ] }, install_requires = [ 'pymongo>=3.3.0', 'beautifulsoup4>=4.5.0', 'python-libnmap>=0.7.0', 'requests>=2.7.0', 'IPy>=0.83', 'argparse>=1.2.1', ], data_files=[ ('/etc/swarm',['swarm.conf']), ('/etc/swarm',['etc/dirsc.conf','etc/domainsc.conf','etc/nmap.conf', 'etc/sitemap.conf','etc/intruder.conf']), ], classifiers = [ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 2.6', ], )
Arvin-X/swarm
setup.py
Python
gpl-3.0
1,370
0.024818
import config def debug(*args): if config.DEBUG: print(*args)
BobWhitelock/termtris
termtris/debug.py
Python
mit
74
0.027027
#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('compat', parent_package, top_path) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
LumPenPacK/NetworkExtractionFromImages
win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/compat/setup.py
Python
bsd-2-clause
371
0.005391
from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.models import Group def group_required(names, login_url=None): """ Checks if the user is a member of a particular group (or at least one group from the list) """ if not hasattr(names,'__iter__'): names = [names] return user_passes_test(lambda u: u.groups.filter(name__in=names), login_url=login_url)
solex/django-odesk
django_odesk/auth/decorators.py
Python
bsd-3-clause
446
0.004484
# LogicalFile Management Providers # # Copyright (C) 2013-2014 Red Hat, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of the FreeBSD Project. # # Authors: Jan Synacek <jsynacek@redhat.com> # """ File and directory management functions. Usage: %(cmd)s list <directory> [ <depth> ] %(cmd)s createdir <directory> %(cmd)s deletedir <directory> %(cmd)s show <target> Commands: list List a directory. When depth is specified, at most depth levels will be listed recursively. The files and directories are listed in a tree-like structure. Possible listed file types are: * F : Regular data file. * Dev : Device file. Can be either block or character device. * Dir : Directory. * P : Pipe file. * L : Symbolic link. * S : Unix socket. createdir Create a directory. The parent directory must exist. deletedir Delete a directory. The directory must be empty. show Show detailed information about target. Target can be any file on the remote system. """ from lmi.scripts.common import command from lmi.scripts.logicalfile import logicalfile class Lister(command.LmiLister): COLUMNS = ('Type', 'Name', 'Mode', 'Current SELinux Context') OPT_NO_UNDERSCORES = True CALLABLE = logicalfile.lf_list class Show(command.LmiLister): COLUMNS = ('Name', 'Value') OPT_NO_UNDERSCORES = True CALLABLE = logicalfile.lf_show class CreateDir(command.LmiCheckResult): EXPECT = None CALLABLE = logicalfile.lf_createdir class DeleteDir(command.LmiCheckResult): EXPECT = None CALLABLE = logicalfile.lf_deletedir Lf = command.register_subcommands( 'Lf', __doc__, { 'list' : Lister, 'createdir' : CreateDir, 'deletedir' : DeleteDir, 'show' : Show, }, )
openlmi/openlmi-doc
doc/python/lmi/scripts/logicalfile/lf_cmd.py
Python
gpl-2.0
3,427
0.003502
# @author Avtandil Kikabidze # @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com) # @link http://longman.me # @license The MIT License (MIT) import os import sys import sublime import sublime_plugin st_version = 2 if sublime.version() == '' or int(sublime.version()) > 3000: st_version = 3 reloader_name = 'codeformatter.reloader' # ST3 loads each package as a module, so it needs an extra prefix if st_version == 3: reloader_name = 'CodeFormatter.' + reloader_name from imp import reload if reloader_name in sys.modules: reload(sys.modules[reloader_name]) try: # Python 3 from .codeformatter.formatter import Formatter except (ValueError): # Python 2 from codeformatter.formatter import Formatter # fix for ST2 cprint = globals()['__builtins__']['print'] debug_mode = False def plugin_loaded(): cprint('CodeFormatter: Plugin Initialized') # settings = sublime.load_settings('CodeFormatter.sublime-settings') # debug_mode = settings.get('codeformatter_debug', False) # if debug_mode: # from pprint import pprint # pprint(settings) # debug_write('Debug mode enabled') # debug_write('Platform ' + sublime.platform() + ' ' + sublime.arch()) # debug_write('Sublime Version ' + sublime.version()) # debug_write('Settings ' + pprint(settings)) if (sublime.platform() != 'windows'): import stat path = ( sublime.packages_path() + '/CodeFormatter/codeformatter/lib/phpbeautifier/fmt.phar' ) st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IEXEC) if st_version == 2: plugin_loaded() class CodeFormatterCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=None, saving=None): run_formatter(self.view, edit, syntax=syntax, saving=saving) class CodeFormatterOpenTabsCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=None): window = sublime.active_window() for view in window.views(): run_formatter(view, edit, quiet=True) class CodeFormatterEventListener(sublime_plugin.EventListener): def on_pre_save(self, view): view.run_command('code_formatter', {'saving': True}) class CodeFormatterShowPhpTransformationsCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=False): import subprocess import re platform = sublime.platform() settings = sublime.load_settings('CodeFormatter.sublime-settings') opts = settings.get('codeformatter_php_options') php_path = 'php' if ('php_path' in opts and opts['php_path']): php_path = opts['php_path'] php55_compat = False if ('php55_compat' in opts and opts['php55_compat']): php55_compat = opts['php55_compat'] cmd = [] cmd.append(str(php_path)) if php55_compat: cmd.append( '{}/CodeFormatter/codeformatter/lib/phpbeautifier/fmt.phar'.format( sublime.packages_path())) else: cmd.append( '{}/CodeFormatter/codeformatter/lib/phpbeautifier/phpf.phar'.format( sublime.packages_path())) cmd.append('--list') #print(cmd) stderr = '' stdout = '' try: if (platform == 'windows'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, creationflags=subprocess.SW_HIDE) else: p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() except Exception as e: stderr = str(e) if (not stderr and not stdout): stderr = 'Error while gethering list of php transformations' if len(stderr) == 0 and len(stdout) > 0: text = stdout.decode('utf-8') text = re.sub( 'Usage:.*?PASSNAME', 'Available PHP Tranformations:', text) window = self.view.window() pt = window.get_output_panel('paneltranformations') pt.set_read_only(False) pt.insert(edit, pt.size(), text) window.run_command( 'show_panel', {'panel': 'output.paneltranformations'}) else: show_error('Formatter error:\n' + stderr) def run_formatter(view, edit, *args, **kwargs): if view.is_scratch(): show_error('File is scratch') return # default parameters syntax = kwargs.get('syntax') saving = kwargs.get('saving', False) quiet = kwargs.get('quiet', False) formatter = Formatter(view, syntax) if not formatter.exists(): if not quiet and not saving: show_error('Formatter for this file type ({}) not found.'.format( formatter.syntax)) return if (saving and not formatter.format_on_save_enabled()): return file_text = sublime.Region(0, view.size()) file_text_utf = view.substr(file_text).encode('utf-8') if (len(file_text_utf) == 0): return stdout, stderr = formatter.format(file_text_utf) if len(stderr) == 0 and len(stdout) > 0: view.replace(edit, file_text, stdout) elif not quiet: show_error('Format error:\n' + stderr) def console_write(text, prefix=False): if prefix: sys.stdout.write('CodeFormatter: ') sys.stdout.write(text + '\n') def debug_write(text, prefix=False): console_write(text, True) def show_error(text): sublime.error_message(u'CodeFormatter\n\n%s' % text)
crlang/sublime-text---front-end-config
Data/Packages/CodeFormatter/CodeFormatter.py
Python
mit
6,068
0.000989
# Xandikos # Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al. # # 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; version 3 # of the License or (at your option) any later version of # the License. # # 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. """VCard file handling. """ from .store import File, InvalidFileContents class VCardFile(File): content_type = "text/vcard" def __init__(self, content, content_type): super(VCardFile, self).__init__(content, content_type) self._addressbook = None def validate(self): c = b"".join(self.content).strip() # TODO(jelmer): Do more extensive checking of VCards if not c.startswith((b"BEGIN:VCARD\r\n", b"BEGIN:VCARD\n")) or not c.endswith( b"\nEND:VCARD" ): raise InvalidFileContents( self.content_type, self.content, "Missing header and trailer lines", ) if not self.addressbook.validate(): # TODO(jelmer): Get data about what is invalid raise InvalidFileContents( self.content_type, self.content, "Invalid VCard file") @property def addressbook(self): if self._addressbook is None: import vobject text = b"".join(self.content).decode('utf-8', 'surrogateescape') try: self._addressbook = vobject.readOne(text) except vobject.base.ParseError as e: raise InvalidFileContents(self.content_type, self.content, str(e)) return self._addressbook
jelmer/xandikos
xandikos/vcard.py
Python
gpl-3.0
2,165
0.000924
# 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 django.core.urlresolvers import reverse from django import http from mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.test import helpers as test INDEX_URL = reverse('horizon:project:data_processing.job_executions:index') DETAILS_URL = reverse( 'horizon:project:data_processing.job_executions:details', args=['id']) class DataProcessingJobExecutionTests(test.TestCase): @test.create_stubs({api.sahara: ('job_execution_list',)}) def test_index(self): api.sahara.job_execution_list(IsA(http.HttpRequest)) \ .AndReturn(self.job_executions.list()) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed( res, 'project/data_processing.job_executions/job_executions.html') self.assertContains(res, 'Executions') @test.create_stubs({api.sahara: ('job_execution_get',)}) def test_details(self): api.sahara.job_execution_get(IsA(http.HttpRequest), IsA(unicode)) \ .AndReturn(self.job_executions.list()[0]) self.mox.ReplayAll() res = self.client.get(DETAILS_URL) self.assertTemplateUsed( res, 'project/data_processing.job_executions/details.html') self.assertContains(res, 'RUNNING') @test.create_stubs({api.sahara: ('job_execution_list', 'job_execution_delete')}) def test_delete(self): job_exec = self.job_executions.first() api.sahara.job_execution_list(IsA(http.HttpRequest)) \ .AndReturn(self.job_executions.list()) api.sahara.job_execution_delete(IsA(http.HttpRequest), job_exec.id) self.mox.ReplayAll() form_data = {'action': 'job_executions__delete__%s' % job_exec.id} res = self.client.post(INDEX_URL, form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) self.assertMessageCount(success=1)
CiscoSystems/avos
openstack_dashboard/dashboards/project/data_processing/job_executions/tests.py
Python
apache-2.0
2,517
0
from Gaudi.Configuration import * from Configurables import GaudiSequencer from Configurables import DaVinci simulation=False from Configurables import EventNodeKiller eventNodeKiller = EventNodeKiller('DAQkiller') eventNodeKiller.Nodes = ['DAQ','pRec'] #MySequencer.Members+=[eventNodeKiller] from Configurables import DecayTreeTuple from DecayTreeTuple.Configuration import * tuple=DecayTreeTuple() tuple.Decay="[B0 -> ^(K*(892)0 -> ^K+ ^pi-) ^(eta_prime -> ^pi- ^pi+ ^(eta -> ^gamma ^gamma))]CC" tuple.Branches={"B0":"[B0 -> (K*(892)0 -> K+ pi-) (eta_prime -> pi- pi+ (eta -> gamma gamma))]CC"} tuple.Inputs=["/Event/Bhadron/Phys/B2XEtaB2etapKstarLine/Particles"] tuple.ToolList += [ "TupleToolGeometry" , "TupleToolDira" , "TupleToolAngles" , "TupleToolPid" , "TupleToolKinematic" , "TupleToolPropertime" , "TupleToolPrimaries" , "TupleToolEventInfo" , "TupleToolTrackInfo" , "TupleToolVtxIsoln" , "TupleToolPhotonInfo" #, "TupleToolMCTruth" #, "TupleToolMCBackgroundInfo" , "TupleToolCaloHypo" #, "TupleToolTrackIsolation" ] tuple.addTool(TupleToolDecay,name="B0") from Configurables import TupleToolDecayTreeFitter tuple.B0.addTool(TupleToolDecayTreeFitter("PVFit")) tuple.B0.PVFit.Verbose=True tuple.B0.PVFit.constrainToOriginVertex=True tuple.B0.PVFit.daughtersToConstrain = ["K*(892)0","eta_prime"] tuple.B0.ToolList+=["TupleToolDecayTreeFitter/PVFit"] from Configurables import TupleToolTISTOS tistos = tuple.B0.addTupleTool(TupleToolTISTOS, name="TupleToolTISTOS") tistos.VerboseL0=True tistos.VerboseHlt1=True tistos.VerboseHlt2=True tistos.TriggerList=["L0PhotonDecision", "L0ElectronDecision", "Hlt1TrackPhotonDecision", "Hlt1TrackAllL0Decision", "Hlt1TrackMuonDecision", "Hlt1TrackForwardPassThroughDecision", "Hlt1TrackForwardPassThroughLooseDecision", "Hlt1SingleElectronNoIPDecision", "L0HadronDecision", "L0LocalPi0Decision", "L0GlobalPi0Decision", "L0MuonDecision", "Hlt2Topo2BodyBBDTDecision", "Hlt2Topo3BodyBBDTDecision", "Hlt2Topo4BodyBBDTDecision", "Hlt2RadiativeTopoTrackTOSDecision", "Hlt2RadiativeTopoPhotonL0Decision", "Hlt2TopoRad2BodyBBDTDecision", "Hlt2TopoRad2plus1BodyBBDTDecision", "Hlt2Topo2BodySimpleDecision", "Hlt2Topo3BodySimpleDecision", "Hlt2Topo4BodySimpleDecision"] DaVinci().InputType='MDST' #DaVinci().RootInTES='/Event/Bhadron/' DaVinci().UserAlgorithms+=[eventNodeKiller,tuple] DaVinci().TupleFile="Output.root" DaVinci().HistogramFile="histos.root" DaVinci().DataType='2012' DaVinci().EvtMax=-1 DaVinci().PrintFreq=1000 DaVinci().MoniSequence=[tuple] DaVinci().Simulation=False
Williams224/davinci-scripts
kstetappipieta/DNTupleMaker.py
Python
mit
3,046
0.017072
import logging from django import template from django.conf import settings from django.core.urlresolvers import reverse from django.http import Http404 from apps.dasforms.forms import ContactForm from apps.dasforms.utils import get_form register = template.Library() logger = logging.getLogger(__name__) @register.inclusion_tag('dasforms/inline_form.html', takes_context=True) def render_inline_form(context, formtype): """Render inline form.""" formtype = formtype.encode('utf8') try: formclass = get_form(formtype) form = formclass(referer, topic) action = reverse("dasform", kwargs={'formtype':formtype}) except: logger.warning('Form class could not be found: %s' % formtype) form = ContactForm() action = reverse("dasform", kwargs={'formtype':'ContactForm'}) senturl = reverse("sent") return { 'action': action, 'form': form, 'formtype': formtype, 'senturl': senturl, } @register.inclusion_tag('dasforms/honeypot_field.html') def render_honeypot_field(field_name=None): """ Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME). """ if not field_name: field_name = settings.HONEYPOT_FIELD_NAME value = getattr(settings, 'HONEYPOT_VALUE', '') if callable(value): value = value() return {'fieldname': field_name, 'value': value}
vinder/django-instaforms
templatetags/instaforms_tags.py
Python
mit
1,416
0.003531
#-*- coding:utf8 -*- def crawl_folder(folder): import os os_objects = [] seen = set([folder]) for os_object_name in os.listdir(folder): full_path = os.path.normpath(os.path.join(folder, os_object_name)) if not full_path in seen: os_objects.append((full_path, os_object_name,)) seen.add(full_path) return os_objects class TCustomCounter: def __init__(self, name, log_stream, verbosity, interval=10): self.name = name self.verbosity = verbosity self.log_stream = log_stream self.interval = interval self.value = 0 def add(self): from datetime import datetime self.value += 1 if self.verbosity and self.value % self.interval == 0: self.log_stream.write("Logger: " + self.name + ", value: " + str(self.value) + ", time: " + str(datetime.now())+ "\n") self.log_stream.flush() def log_state(self): from datetime import datetime self.log_stream.write("Logger: " + self.name + ", value: " + str(self.value) + ", time: " + str(datetime.now())+ "\n") self.log_stream.flush()
mavlyutovrus/light_search
lib/utils.py
Python
mit
1,167
0.010283
#!/usr/bin/python # Example using an RGB character LCD wired directly to Raspberry Pi or BeagleBone Black. import time import Adafruit_CharLCD as LCD # Raspberry Pi configuration: lcd_rs = 27 # Change this to pin 21 on older revision Raspberry Pi's lcd_en = 22 lcd_d4 = 25 lcd_d5 = 24 lcd_d6 = 23 lcd_d7 = 18 lcd_red = 4 lcd_green = 17 lcd_blue = 7 # Pin 7 is CE1 # Define LCD column and row size for 16x2 LCD. lcd_columns = 16 lcd_rows = 2 # Initialize the LCD using the pins above. lcd = LCD.Adafruit_RGBCharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_red, lcd_green, lcd_blue) # Show some basic colors. lcd.set_color(1.0, 0.0, 0.0) lcd.clear() lcd.message('Joyeux') time.sleep(3.0) lcd.set_color(0.0, 1.0, 0.0) lcd.clear() lcd.message('Noel') time.sleep(3.0) lcd.set_color(0.0, 0.0, 1.0) lcd.clear() lcd.message('Je vais') time.sleep(3.0) lcd.set_color(1.0, 1.0, 0.0) lcd.clear() lcd.message('te faire') time.sleep(3.0) lcd.set_color(0.0, 1.0, 1.0) lcd.clear() lcd.message('des trucs') time.sleep(3.0) lcd.set_color(1.0, 0.0, 1.0) lcd.clear() lcd.message('de fou') time.sleep(3.0) lcd.set_color(1.0, 1.0, 1.0) lcd.clear() lcd.message('MOUAHHH') time.sleep(3.0)
qkzk/sncf_lcd
adafruit_lcd/examples/red.py
Python
gpl-3.0
1,310
0.003817
# -*- coding: utf-8 -*- import logging from unittest import mock import olympia.core.logger from olympia.amo.tests import TestCase from olympia.users.models import UserProfile class LoggerTests(TestCase): @mock.patch('olympia.core.get_remote_addr', lambda: '127.0.0.1') @mock.patch('olympia.core.get_user', lambda: UserProfile(username=u'fôo')) def test_get_logger_adapter(self): log = olympia.core.logger.getLogger('test') expected_kwargs = { 'extra': { 'REMOTE_ADDR': '127.0.0.1', 'USERNAME': u'fôo', } } assert log.process('test msg', {}) == ('test msg', expected_kwargs) @mock.patch('olympia.core.get_remote_addr', lambda: '127.0.0.1') @mock.patch('olympia.core.get_user', lambda: None) def test_logger_adapter_user_is_none(self): log = olympia.core.logger.getLogger('test') expected_kwargs = { 'extra': { 'REMOTE_ADDR': '127.0.0.1', 'USERNAME': '<anon>', } } assert log.process('test msg', {}) == ('test msg', expected_kwargs) @mock.patch('olympia.core.get_remote_addr', lambda: None) @mock.patch('olympia.core.get_user', lambda: UserProfile(username='bar')) def test_logger_adapter_addr_is_none(self): log = olympia.core.logger.getLogger('test') expected_kwargs = { 'extra': { 'REMOTE_ADDR': '', 'USERNAME': 'bar', } } assert log.process('test msg', {}) == ('test msg', expected_kwargs) def test_formatter(self): formatter = olympia.core.logger.Formatter() record = logging.makeLogRecord({}) formatter.format(record) assert 'USERNAME' in record.__dict__ assert 'REMOTE_ADDR' in record.__dict__ def test_json_formatter(self): formatter = olympia.core.logger.JsonFormatter() record = logging.makeLogRecord({}) # These would be set by the adapter. record.__dict__['USERNAME'] = 'foo' record.__dict__['REMOTE_ADDR'] = '127.0.0.1' formatter.format(record) assert record.__dict__['uid'] == 'foo' assert record.__dict__['remoteAddressChain'] == '127.0.0.1'
kumar303/addons-server
src/olympia/core/tests/test_logger.py
Python
bsd-3-clause
2,279
0
import json import datetime from django.core.files.base import ContentFile from django.core.exceptions import ValidationError from django.utils.timezone import utc from ..models import AgentProfile from ..exceptions import IDNotFoundError, ParamError from ..utils import etag class AgentProfileManager(): def __init__(self, agent): self.Agent = agent def save_non_json_profile(self, p, profile, request_dict): p.content_type = request_dict['headers']['CONTENT_TYPE'] p.etag = etag.create_tag(profile.read()) if 'updated' in request_dict['headers'] and request_dict['headers']['updated']: p.updated = request_dict['headers']['updated'] else: p.updated = datetime.datetime.utcnow().replace(tzinfo=utc) # Go to beginning of file profile.seek(0) fn = "%s_%s" % (p.agent_id, request_dict.get('filename', p.id)) p.profile.save(fn, profile) p.save() def post_profile(self, request_dict): # get/create profile p, created = AgentProfile.objects.get_or_create( profile_id=request_dict['params']['profileId'], agent=self.Agent) post_profile = request_dict['profile'] # If incoming profile is application/json and if a profile didn't # already exist with the same agent and profileId if created: p.json_profile = post_profile p.content_type = "application/json" p.etag = etag.create_tag(post_profile) # If incoming profile is application/json and if a profile already # existed with the same agent and profileId else: orig_prof = json.loads(p.json_profile) post_profile = json.loads(post_profile) merged = json.dumps( dict(list(orig_prof.items()) + list(post_profile.items()))) p.json_profile = merged p.etag = etag.create_tag(merged) # Set updated if 'updated' in request_dict['headers'] and request_dict['headers']['updated']: p.updated = request_dict['headers']['updated'] else: p.updated = datetime.datetime.utcnow().replace(tzinfo=utc) p.save() def put_profile(self, request_dict): # get/create profile p, created = AgentProfile.objects.get_or_create( profile_id=request_dict['params']['profileId'], agent=self.Agent) # Profile being PUT is not json if "application/json" not in request_dict['headers']['CONTENT_TYPE']: try: profile = ContentFile(request_dict['profile'].read()) except: try: profile = ContentFile(request_dict['profile']) except: profile = ContentFile(str(request_dict['profile'])) etag.check_preconditions(request_dict, p, created) # If it already exists delete it if p.profile: try: p.profile.delete() except OSError: # probably was json before p.json_profile = {} self.save_non_json_profile(p, profile, request_dict) # Profile being PUT is json else: # (overwrite existing profile data) etag.check_preconditions(request_dict, p, created) the_profile = request_dict['profile'] p.json_profile = the_profile p.content_type = request_dict['headers']['CONTENT_TYPE'] p.etag = etag.create_tag(the_profile) # Set updated if 'updated' in request_dict['headers'] and request_dict['headers']['updated']: p.updated = request_dict['headers']['updated'] else: p.updated = datetime.datetime.utcnow().replace(tzinfo=utc) p.save() def get_profile(self, profile_id): try: return self.Agent.agentprofile_set.get(profile_id=profile_id) except: err_msg = 'There is no agent profile associated with the id: %s' % profile_id raise IDNotFoundError(err_msg) def get_profile_ids(self, since=None): ids = [] if since: try: # this expects iso6801 date/time format # "2013-02-15T12:00:00+00:00" profs = self.Agent.agentprofile_set.filter(updated__gt=since) except ValidationError: err_msg = 'Since field is not in correct format for retrieval of agent profiles' raise ParamError(err_msg) ids = [p.profile_id for p in profs] else: ids = self.Agent.agentprofile_set.values_list( 'profile_id', flat=True) return ids def delete_profile(self, profile_id): try: self.get_profile(profile_id).delete() # we don't want it anyway except AgentProfile.DoesNotExist: pass except IDNotFoundError: pass
adlnet/ADL_LRS
lrs/managers/AgentProfileManager.py
Python
apache-2.0
5,034
0.001589
# -*- coding: utf-8 -*- # © 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import test_hr_expense
acsone/hr
hr_expense_product_policy/tests/__init__.py
Python
agpl-3.0
156
0
# -*- coding: utf-8 -*- # © 2016 ClearCorp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import account_invoice_incoterm
sysadminmatmoz/odoo-clearcorp
account_invoice_incoterm/models/__init__.py
Python
agpl-3.0
153
0
import datetime class Store: def parse(self,line): fields=line.split('\t') self.id = fields[0] self.name = fields[1] return self def __repr__(self): return "Store: id=%s \t name=%s"%(self.id,self.name) class Product: def parse(self,line): fields=line.split('\t') self.id = fields[0] self.name = fields[1] self.category=fields[2] return self def __repr__(self): return "Product: id=%s \t name=%s"%(self.id,self.name) class SaleRow: def parse(self,line): fields=line.split('\t') self.day=fields[0] # maybe parse as date? see below:) # self.day=datetime.datetime.strptime(fields[0],"%Y-%m-%d") self.store_id=fields[1] self.product_id=fields[2] self.quantity=int(fields[3]) # let's parse this return self def __repr__(self): return "SaleRow: day=%s \t store_id=%s \t product_id=%s quantity=%d"%(self.day,self.store_id,self.product_id, self.quantity)
sk-rai/Intro-to-SPARK-with-Python
code/sales/sales_schema.py
Python
unlicense
899
0.053393
# -*- coding: utf-8 -*- # Copyright 2022 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. # from typing import ( Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, ) from google.cloud.artifactregistry_v1beta2.types import file from google.cloud.artifactregistry_v1beta2.types import package from google.cloud.artifactregistry_v1beta2.types import repository from google.cloud.artifactregistry_v1beta2.types import tag from google.cloud.artifactregistry_v1beta2.types import version class ListRepositoriesPager: """A pager for iterating through ``list_repositories`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListRepositoriesResponse` object, and provides an ``__iter__`` method to iterate through its ``repositories`` field. If there are more pages, the ``__iter__`` method will make additional ``ListRepositories`` requests and continue to iterate through the ``repositories`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListRepositoriesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., repository.ListRepositoriesResponse], request: repository.ListRepositoriesRequest, response: repository.ListRepositoriesResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListRepositoriesRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListRepositoriesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = repository.ListRepositoriesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterator[repository.ListRepositoriesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[repository.Repository]: for page in self.pages: yield from page.repositories def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListRepositoriesAsyncPager: """A pager for iterating through ``list_repositories`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListRepositoriesResponse` object, and provides an ``__aiter__`` method to iterate through its ``repositories`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListRepositories`` requests and continue to iterate through the ``repositories`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListRepositoriesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., Awaitable[repository.ListRepositoriesResponse]], request: repository.ListRepositoriesRequest, response: repository.ListRepositoriesResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListRepositoriesRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListRepositoriesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = repository.ListRepositoriesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterator[repository.ListRepositoriesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterator[repository.Repository]: async def async_generator(): async for page in self.pages: for response in page.repositories: yield response return async_generator() def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListPackagesPager: """A pager for iterating through ``list_packages`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListPackagesResponse` object, and provides an ``__iter__`` method to iterate through its ``packages`` field. If there are more pages, the ``__iter__`` method will make additional ``ListPackages`` requests and continue to iterate through the ``packages`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListPackagesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., package.ListPackagesResponse], request: package.ListPackagesRequest, response: package.ListPackagesResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListPackagesRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListPackagesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = package.ListPackagesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterator[package.ListPackagesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[package.Package]: for page in self.pages: yield from page.packages def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListPackagesAsyncPager: """A pager for iterating through ``list_packages`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListPackagesResponse` object, and provides an ``__aiter__`` method to iterate through its ``packages`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListPackages`` requests and continue to iterate through the ``packages`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListPackagesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., Awaitable[package.ListPackagesResponse]], request: package.ListPackagesRequest, response: package.ListPackagesResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListPackagesRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListPackagesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = package.ListPackagesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterator[package.ListPackagesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterator[package.Package]: async def async_generator(): async for page in self.pages: for response in page.packages: yield response return async_generator() def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListVersionsPager: """A pager for iterating through ``list_versions`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListVersionsResponse` object, and provides an ``__iter__`` method to iterate through its ``versions`` field. If there are more pages, the ``__iter__`` method will make additional ``ListVersions`` requests and continue to iterate through the ``versions`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListVersionsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., version.ListVersionsResponse], request: version.ListVersionsRequest, response: version.ListVersionsResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListVersionsRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListVersionsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = version.ListVersionsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterator[version.ListVersionsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[version.Version]: for page in self.pages: yield from page.versions def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListVersionsAsyncPager: """A pager for iterating through ``list_versions`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListVersionsResponse` object, and provides an ``__aiter__`` method to iterate through its ``versions`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListVersions`` requests and continue to iterate through the ``versions`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListVersionsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., Awaitable[version.ListVersionsResponse]], request: version.ListVersionsRequest, response: version.ListVersionsResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListVersionsRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListVersionsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = version.ListVersionsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterator[version.ListVersionsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterator[version.Version]: async def async_generator(): async for page in self.pages: for response in page.versions: yield response return async_generator() def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListFilesPager: """A pager for iterating through ``list_files`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListFilesResponse` object, and provides an ``__iter__`` method to iterate through its ``files`` field. If there are more pages, the ``__iter__`` method will make additional ``ListFiles`` requests and continue to iterate through the ``files`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListFilesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., file.ListFilesResponse], request: file.ListFilesRequest, response: file.ListFilesResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListFilesRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListFilesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = file.ListFilesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterator[file.ListFilesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[file.File]: for page in self.pages: yield from page.files def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListFilesAsyncPager: """A pager for iterating through ``list_files`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListFilesResponse` object, and provides an ``__aiter__`` method to iterate through its ``files`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListFiles`` requests and continue to iterate through the ``files`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListFilesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., Awaitable[file.ListFilesResponse]], request: file.ListFilesRequest, response: file.ListFilesResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListFilesRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListFilesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = file.ListFilesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterator[file.ListFilesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterator[file.File]: async def async_generator(): async for page in self.pages: for response in page.files: yield response return async_generator() def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListTagsPager: """A pager for iterating through ``list_tags`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListTagsResponse` object, and provides an ``__iter__`` method to iterate through its ``tags`` field. If there are more pages, the ``__iter__`` method will make additional ``ListTags`` requests and continue to iterate through the ``tags`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListTagsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., tag.ListTagsResponse], request: tag.ListTagsRequest, response: tag.ListTagsResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListTagsRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListTagsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = tag.ListTagsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterator[tag.ListTagsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[tag.Tag]: for page in self.pages: yield from page.tags def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListTagsAsyncPager: """A pager for iterating through ``list_tags`` requests. This class thinly wraps an initial :class:`google.cloud.artifactregistry_v1beta2.types.ListTagsResponse` object, and provides an ``__aiter__`` method to iterate through its ``tags`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListTags`` requests and continue to iterate through the ``tags`` field on the corresponding responses. All the usual :class:`google.cloud.artifactregistry_v1beta2.types.ListTagsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., Awaitable[tag.ListTagsResponse]], request: tag.ListTagsRequest, response: tag.ListTagsResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.artifactregistry_v1beta2.types.ListTagsRequest): The initial request object. response (google.cloud.artifactregistry_v1beta2.types.ListTagsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = tag.ListTagsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterator[tag.ListTagsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterator[tag.Tag]: async def async_generator(): async for page in self.pages: for response in page.tags: yield response return async_generator() def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
googleapis/python-artifact-registry
google/cloud/artifactregistry_v1beta2/services/artifact_registry/pagers.py
Python
apache-2.0
25,894
0.00197
from mock import MagicMock, patch import pytest from adbpy.adb import Adb from adbpy import Target, AdbError @pytest.fixture def adb(): adb = Adb(()) adb.socket = MagicMock() return adb def test_get_transport(): assert Adb._get_transport(Target.ANY) == "host:transport-any" assert Adb._get_transport(Target.USB) == "host:transport-usb" assert Adb._get_transport(Target.EMULATOR) == "host:transport-local" assert Adb._get_transport("950a8ad5") == "host:transport:950a8ad5" def test_adb_version(adb): adb.version() adb.socket.send.assert_called_once_with("host:version") def test_adb_get_serialno_any(adb): adb.get_serialno(Target.ANY) adb.socket.send.assert_called_once_with("host:get-serialno") def test_adb_get_serialno_serial(adb): adb.get_serialno("6097191b") adb.socket.send.assert_called_once_with("host-serial:6097191b:get-serialno") def test_adb_get_product(adb): adb.get_product("950a8ad5") adb.socket.send.assert_called_once_with("host-serial:950a8ad5:get-product") def test_adb_get_devpath(adb): adb.get_devpath(Target.USB) adb.socket.send.assert_called_once_with("host-usb:get-devpath") def test_adb_get_state(adb): adb.get_state(Target.EMULATOR) adb.socket.send.assert_called_once_with("host-local:get-state") def test_shell(adb): with patch.object(Adb, "_setup_target"): adb.shell("ls -l") adb.socket.send.assert_called_once_with("shell:ls -l") adb._setup_target.assert_called_once() def test_forward(adb): device_id = "950a8ad5" adb.forward("tcp:6001", "tcp:36001", device_id, norebind=False) adb.socket.send.assert_called_once_with("host-serial:950a8ad5:" "forward:tcp:6001;" "tcp:36001") def test_forward_rebind(adb): device_id = "950a8ad5" adb.forward("tcp:6001", "tcp:36001", device_id, norebind=True) adb.socket.send.assert_called_once_with("host-serial:950a8ad5:" "forward:norebind:" "tcp:6001;tcp:36001") def test_devices(adb): adb.socket.receive = MagicMock(return_value="950a8ad5\tdevice\n") output = adb.devices() assert output == [("950a8ad5", "device")] def test_start(adb): adb.process = MagicMock() adb.process.running = MagicMock(return_value=False) with pytest.raises(AdbError): adb.start()
noahgoldman/adbpy
tests/test_adb.py
Python
mit
2,479
0.006858
from netools import nextIpInPool, ping, aliveHost, hostsUnDone def main(): aliveHosts = [] # pool IP ipStart = "192.168.56.1" ipEnd = "192.168.56.5" print"Pools: ", ipStart + " -> " + ipEnd print"Scanning online Router on network..." aliveHosts = aliveHost(ipStart, ipEnd) print "online Router:" print aliveHosts # print"New Hosts Alive in Pools:",hostsUnDone(aliveHosts, aliveHost(ipStart,ipEnd)) if __name__ == '__main__': main()
gravufo/commotion-router-testbench
ping/mainTest.py
Python
gpl-2.0
479
0.004175
# This document is part of Acronym # https://github.com/geowurster/Acronym # =================================================================================== # # # New BSD License # # Copyright (c) 2014, Kevin D. Wurster # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * The names of its contributors may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # =================================================================================== # """ Algorithms that can be easily ported from one datatype to another with little work """ from . import tileindex
geowurster/Acronym
acronym/cmdl/_portable_algorithms/__init__.py
Python
bsd-3-clause
1,916
0.004175
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2012 thomasv@ecdsa.org # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import util from bitcoin import * MAX_TARGET = 0x00000000FFFF0000000000000000000000000000000000000000000000000000 class Blockchain(util.PrintError): '''Manages blockchain headers and their verification''' def __init__(self, config, network): self.config = config self.network = network self.headers_url = "https://headers.electrum.org/blockchain_headers" self.local_height = 0 self.set_local_height() def height(self): return self.local_height def init(self): self.init_headers_file() self.set_local_height() self.print_error("%d blocks" % self.local_height) def verify_header(self, header, prev_header, bits, target): prev_hash = self.hash_header(prev_header) assert prev_hash == header.get('prev_block_hash'), "prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash')) assert bits == header.get('bits'), "bits mismatch: %s vs %s" % (bits, header.get('bits')) _hash = self.hash_header(header) assert int('0x' + _hash, 16) <= target, "insufficient proof of work: %s vs target %s" % (int('0x' + _hash, 16), target) def verify_chain(self, chain): first_header = chain[0] prev_header = self.read_header(first_header.get('block_height') - 1) for header in chain: height = header.get('block_height') bits, target = self.get_target(height / 2016, chain) self.verify_header(header, prev_header, bits, target) prev_header = header def verify_chunk(self, index, data): num = len(data) / 80 prev_header = None if index != 0: prev_header = self.read_header(index*2016 - 1) bits, target = self.get_target(index) for i in range(num): raw_header = data[i*80:(i+1) * 80] header = self.deserialize_header(raw_header) self.verify_header(header, prev_header, bits, target) prev_header = header def serialize_header(self, res): s = int_to_hex(res.get('version'), 4) \ + rev_hex(res.get('prev_block_hash')) \ + rev_hex(res.get('merkle_root')) \ + int_to_hex(int(res.get('timestamp')), 4) \ + int_to_hex(int(res.get('bits')), 4) \ + int_to_hex(int(res.get('nonce')), 4) return s def deserialize_header(self, s): hex_to_int = lambda s: int('0x' + s[::-1].encode('hex'), 16) h = {} h['version'] = hex_to_int(s[0:4]) h['prev_block_hash'] = hash_encode(s[4:36]) h['merkle_root'] = hash_encode(s[36:68]) h['timestamp'] = hex_to_int(s[68:72]) h['bits'] = hex_to_int(s[72:76]) h['nonce'] = hex_to_int(s[76:80]) return h def hash_header(self, header): if header is None: return '0' * 64 return hash_encode(Hash(self.serialize_header(header).decode('hex'))) def path(self): return util.get_headers_path(self.config) def init_headers_file(self): filename = self.path() if os.path.exists(filename): return try: import urllib, socket socket.setdefaulttimeout(30) self.print_error("downloading ", self.headers_url) urllib.urlretrieve(self.headers_url, filename) self.print_error("done.") except Exception: self.print_error("download failed. creating file", filename) open(filename, 'wb+').close() def save_chunk(self, index, chunk): filename = self.path() f = open(filename, 'rb+') f.seek(index * 2016 * 80) h = f.write(chunk) f.close() self.set_local_height() def save_header(self, header): data = self.serialize_header(header).decode('hex') assert len(data) == 80 height = header.get('block_height') filename = self.path() f = open(filename, 'rb+') f.seek(height * 80) h = f.write(data) f.close() self.set_local_height() def set_local_height(self): name = self.path() if os.path.exists(name): h = os.path.getsize(name)/80 - 1 if self.local_height != h: self.local_height = h def read_header(self, block_height): name = self.path() if os.path.exists(name): f = open(name, 'rb') f.seek(block_height * 80) h = f.read(80) f.close() if len(h) == 80: h = self.deserialize_header(h) return h def get_target(self, index, chain=None): if index == 0: return 0x1d00ffff, MAX_TARGET first = self.read_header((index-1) * 2016) last = self.read_header(index*2016 - 1) if last is None: for h in chain: if h.get('block_height') == index*2016 - 1: last = h assert last is not None # bits to target bits = last.get('bits') bitsN = (bits >> 24) & 0xff assert bitsN >= 0x03 and bitsN <= 0x1d, "First part of bits should be in [0x03, 0x1d]" bitsBase = bits & 0xffffff assert bitsBase >= 0x8000 and bitsBase <= 0x7fffff, "Second part of bits should be in [0x8000, 0x7fffff]" target = bitsBase << (8 * (bitsN-3)) # new target nActualTimespan = last.get('timestamp') - first.get('timestamp') nTargetTimespan = 14 * 24 * 60 * 60 nActualTimespan = max(nActualTimespan, nTargetTimespan / 4) nActualTimespan = min(nActualTimespan, nTargetTimespan * 4) new_target = min(MAX_TARGET, (target*nActualTimespan) / nTargetTimespan) # convert new target to bits c = ("%064x" % new_target)[2:] while c[:2] == '00' and len(c) > 6: c = c[2:] bitsN, bitsBase = len(c) / 2, int('0x' + c[:6], 16) if bitsBase >= 0x800000: bitsN += 1 bitsBase >>= 8 new_bits = bitsN << 24 | bitsBase return new_bits, bitsBase << (8 * (bitsN-3)) def connect_header(self, chain, header): '''Builds a header chain until it connects. Returns True if it has successfully connected, False if verification failed, otherwise the height of the next header needed.''' chain.append(header) # Ordered by decreasing height previous_height = header['block_height'] - 1 previous_header = self.read_header(previous_height) # Missing header, request it if not previous_header: return previous_height # Does it connect to my chain? prev_hash = self.hash_header(previous_header) if prev_hash != header.get('prev_block_hash'): self.print_error("reorg") return previous_height # The chain is complete. Reverse to order by increasing height chain.reverse() try: self.verify_chain(chain) self.print_error("new height:", previous_height + len(chain)) for header in chain: self.save_header(header) return True except BaseException as e: self.print_error(str(e)) return False def connect_chunk(self, idx, hexdata): try: data = hexdata.decode('hex') self.verify_chunk(idx, data) self.print_error("validated chunk %d" % idx) self.save_chunk(idx, data) return idx + 1 except BaseException as e: self.print_error('verify_chunk failed', str(e)) return idx - 1
imrehg/electrum
lib/blockchain.py
Python
mit
8,852
0.00113
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_website.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
shawnfuryan/django_website_core
django_website/manage.py
Python
mit
257
0
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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. # # ##### END GPL LICENSE BLOCK ##### # Copyright (C) 2013-2019: SCS Software import bpy from bpy.types import Panel from io_scs_tools.ui import shared as _shared class _MeshPanelBlDefs(_shared.HeaderIconPanel): bl_space_type = "PROPERTIES" bl_region_type = "WINDOW" bl_ui_units_x = 15 @classmethod def poll(cls, context): return hasattr(context, "active_object") and context.active_object and context.active_object.type == "MESH" def get_layout(self): """Returns layout depending where it's drawn into. If popover create extra box to make it distinguisable between different sub-panels.""" if self.is_popover: layout = self.layout.box().column() else: layout = self.layout return layout class SCS_TOOLS_PT_Mesh(_MeshPanelBlDefs, Panel): """ Creates "SCS Mesh" panel in the Object properties window. """ bl_label = "SCS Mesh" bl_context = "data" def draw(self, context): """UI draw function. :param context: Blender Context :type context: bpy.context """ if not self.poll(context): self.layout.label(text="No active mesh object!", icon="INFO") return layout = self.get_layout() mesh = context.active_object.data layout.use_property_split = True layout.use_property_decorate = False classes = ( SCS_TOOLS_PT_Mesh, ) def register(): # for cls in classes: # bpy.utils.register_class(cls) # # from io_scs_tools import SCS_TOOLS_MT_MainMenu # SCS_TOOLS_MT_MainMenu.append_props_entry("Mesh Properties", SCS_TOOLS_PT_Mesh.__name__) # No mesh settings available currently, thus commented out and just passing pass def unregister(): # for cls in classes: # bpy.utils.unregister_class(cls) # No mesh settings available currently, thus commented out and just passing pass
SCSSoftware/BlenderTools
addon/io_scs_tools/ui/mesh.py
Python
gpl-2.0
2,693
0.001114
from .engine import BloggingEngine from .processor import PostProcessor from .sqlastorage import SQLAStorage from .storage import Storage """ Flask-Blogging is a Flask extension to add blog support to your web application. This extension uses Markdown to store and then render the webpage. Author: Gouthaman Balaraman Date: June 1, 2015 """ __author__ = 'Gouthaman Balaraman' __version__ = '0.4.2'
wdm0006/Flask-Blogging
flask_blogging/__init__.py
Python
mit
403
0
# 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. """Request body validating middleware for OpenStack Identity resources.""" from keystone.common.validation import validators def lazy_validate(request_body_schema, resource_to_validate): """A non-decorator way to validate a request, to be used inline. :param request_body_schema: a schema to validate the resource reference :param resource_to_validate: dictionary to validate :raises keystone.exception.ValidationError: if `resource_to_validate` is None. (see wrapper method below). :raises TypeError: at decoration time when the expected resource to validate isn't found in the decorated method's signature """ schema_validator = validators.SchemaValidator(request_body_schema) schema_validator.validate(resource_to_validate) def nullable(property_schema): """Clone a property schema into one that is nullable. :param dict property_schema: schema to clone into a nullable schema :returns: a new dict schema """ # TODO(dstanek): deal with the case where type is already a list; we don't # do that yet so I'm not wasting time on it new_schema = property_schema.copy() new_schema['type'] = [property_schema['type'], 'null'] # NOTE(kmalloc): If enum is specified (such as our boolean case) ensure we # add null to the enum as well so that null can be passed/validated as # expected. Without adding to the enum, null will not validate as enum is # explicitly listing valid values. According to the JSON Schema # specification, the values must be unique in the enum array. if 'enum' in new_schema and None not in new_schema['enum']: # In the enum the 'null' is NoneType new_schema['enum'].append(None) return new_schema
mahak/keystone
keystone/common/validation/__init__.py
Python
apache-2.0
2,344
0
#!/usr/bin/python3 import argparse import os import sys import configuration import shouter from gitFunctions import Commiter from gitFunctions import Initializer, Differ from rtcFunctions import ImportHandler from rtcFunctions import RTCInitializer from rtcFunctions import RTCLogin from rtcFunctions import WorkspaceHandler def initialize(): config = configuration.get() directory = config.workDirectory if os.path.exists(directory): sys.exit("Configured directory '" + directory + "' already exists, please make sure to use a " + "non-existing directory") shouter.shout("Migration will take place in " + directory) os.makedirs(directory) os.chdir(directory) config.deletelogfolder() git = Initializer() git.initalize() RTCInitializer.initialize() if Differ.has_diff(): git.initialcommit() Commiter.pushmaster() def resume(): shouter.shout("Found existing git repo in work directory, resuming migration...") config = configuration.get() os.chdir(config.workDirectory) os.chdir(config.clonedGitRepoName) if Differ.has_diff(): sys.exit("Your git repo has some uncommited changes, please add/remove them manually") RTCLogin.loginandcollectstreamuuid() Initializer.preparerepo() if config.previousstreamname: prepare() else: Commiter.branch(config.streamname) WorkspaceHandler().load() def existsrepo(): config = configuration.get() repodirectory = os.path.join(config.workDirectory, config.gitRepoName) return os.path.exists(repodirectory) def migrate(): rtc = ImportHandler() rtcworkspace = WorkspaceHandler() git = Commiter if existsrepo(): resume() else: initialize() config = configuration.get() streamuuid = config.streamuuid streamname = config.streamname branchname = streamname + "_branchpoint" componentbaselineentries = rtc.getcomponentbaselineentriesfromstream(streamuuid) rtcworkspace.setnewflowtargets(streamuuid) history = rtc.readhistory(componentbaselineentries, streamname) changeentries = rtc.getchangeentriesofstreamcomponents(componentbaselineentries) if len(changeentries) > 0: git.branch(branchname) rtc.acceptchangesintoworkspace(rtc.getchangeentriestoaccept(changeentries, history)) shouter.shout("All changes until creation of stream '%s' accepted" % streamname) git.pushbranch(branchname) rtcworkspace.setcomponentstobaseline(componentbaselineentries, streamuuid) rtcworkspace.load() git.branch(streamname) changeentries = rtc.getchangeentriesofstream(streamuuid) amountofacceptedchanges = rtc.acceptchangesintoworkspace(rtc.getchangeentriestoaccept(changeentries, history)) if amountofacceptedchanges > 0: git.pushbranch(streamname) git.promotebranchtomaster(streamname) RTCLogin.logout() summary(streamname) def prepare(): config = configuration.get() rtc = ImportHandler() rtcworkspace = WorkspaceHandler() # git checkout branchpoint Commiter.checkout(config.previousstreamname + "_branchpoint") # list baselines of current workspace componentbaselineentries = rtc.getcomponentbaselineentriesfromstream(config.previousstreamuuid) # set components to that baselines rtcworkspace.setcomponentstobaseline(componentbaselineentries, config.previousstreamuuid) rtcworkspace.load() def summary(streamname): config = configuration.get() shouter.shout("\nAll changes accepted - Migration of stream '%s' is completed." "\nYou can distribute the git-repo '%s'." % (streamname, config.gitRepoName)) if len(config.ignorefileextensions) > 0: # determine and log the ignored but still present files os.chdir(config.workDirectory) os.chdir(config.clonedGitRepoName) pathtoclonedgitrepo = config.workDirectory + os.sep + config.clonedGitRepoName if pathtoclonedgitrepo[-1:] != os.sep: pathtoclonedgitrepo += os.sep ignoredbutexist = [] with open('.gitignore', 'r') as gitignore: for line in gitignore.readlines(): line = line.strip() if line != ".jazz5" and line != ".metadata" and line != ".jazzShed": pathtoignored = pathtoclonedgitrepo + line if os.path.exists(pathtoignored): ignoredbutexist.append(line) if len(ignoredbutexist) > 0: shouter.shout("\nThe following files have been ignored in the new git repository, " + "but still exist in the actual RTC workspace:") ignoredbutexist.sort() for ignored in ignoredbutexist: shouter.shout("\t" + ignored) def parsecommandline(): parser = argparse.ArgumentParser() configfiledefault = 'config.ini' configfilehelp = 'name of the config file, or full path to the config file; defaults to ' + configfiledefault parser.add_argument('-c', '--configfile', metavar='file', dest='configfile', help=configfilehelp, default=configfiledefault) parser.add_argument('-u', '--user', metavar='user', dest='user', help='RTC user', default=None) parser.add_argument('-p', '--password', metavar='password', dest='password', help='RTC password', default=None) parser.add_argument('-s', '--stored', help='Use stored password for the repository connection', action='store_true') arguments = parser.parse_args() configuration.setconfigfile(arguments.configfile) configuration.setUser(arguments.user) configuration.setPassword(arguments.password) configuration.setStored(arguments.stored) def validate(): config = configuration.get() streamname = config.streamname branchname = streamname + "_branchpoint" previousstreamname = config.previousstreamname offendingbranchname = None if not Commiter.checkbranchname(streamname): offendingbranchname = streamname elif not Commiter.checkbranchname(branchname): offendingbranchname = branchname elif not Commiter.checkbranchname(previousstreamname): offendingbranchname = previousstreamname if offendingbranchname: sys.exit(offendingbranchname + " is not a valid git branch name - consider renaming the stream") if __name__ == "__main__": parsecommandline() validate() migrate()
rtcTo/rtc2git
migration.py
Python
mit
6,494
0.003388
""" Lua pattern matcher based on a NFA inspired by http://swtch.com/~rsc/regexp/regexp1.html """ from rpyre.interface.lua import compile_re from rpyre.matching import find def main(args): n = 20 s = args[1] #s = "(a|b)*a%sa(a|b)*$" % ("(a|b)" * n, ) print s evilregex = compile_re(s) import os chunks = [] # use os.read to be RPython compatible while True: s = os.read(0, 4096) if not s: break chunks.append(s) s = "".join(chunks) print len(s) print find(evilregex, s, 0) """ for x in find2(evilregex, s, 0): print x """ return 0 # needed for the PyPy translation toolchain def target(*args): return main, None def jitpolicy(*args): from rpython.jit.codewriter.policy import JitPolicy return JitPolicy() if __name__ == '__main__': import sys sys.exit(main(sys.argv))
fhahn/rpyre
tools/cli.py
Python
mit
904
0.001106
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation. # 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. # service type constants: CORE = "CORE" DUMMY = "DUMMY" LOADBALANCER = "LOADBALANCER" FIREWALL = "FIREWALL" VPN = "VPN" METERING = "METERING" L3_ROUTER_NAT = "L3_ROUTER_NAT" #maps extension alias to service type EXT_TO_SERVICE_MAPPING = { 'dummy': DUMMY, 'lbaas': LOADBALANCER, 'fwaas': FIREWALL, 'vpnaas': VPN, 'metering': METERING, 'router': L3_ROUTER_NAT } # TODO(salvatore-orlando): Move these (or derive them) from conf file ALLOWED_SERVICES = [CORE, DUMMY, LOADBALANCER, FIREWALL, VPN, METERING, L3_ROUTER_NAT] COMMON_PREFIXES = { CORE: "", DUMMY: "/dummy_svc", LOADBALANCER: "/lb", FIREWALL: "/fw", VPN: "/vpn", METERING: "/metering", L3_ROUTER_NAT: "", } # Service operation status constants ACTIVE = "ACTIVE" DOWN = "DOWN" PENDING_CREATE = "PENDING_CREATE" PENDING_UPDATE = "PENDING_UPDATE" PENDING_DELETE = "PENDING_DELETE" INACTIVE = "INACTIVE" ERROR = "ERROR" # FWaaS firewall rule action FWAAS_ALLOW = "allow" FWAAS_DENY = "deny" # L3 Protocol name constants TCP = "tcp" UDP = "udp" ICMP = "icmp" # Network Type constants TYPE_FLAT = 'flat' TYPE_GRE = 'gre' TYPE_LOCAL = 'local' TYPE_VXLAN = 'vxlan' TYPE_VLAN = 'vlan' TYPE_NONE = 'none'
ntt-sic/neutron
neutron/plugins/common/constants.py
Python
apache-2.0
1,913
0.000523
# author: Milan Kubik
apophys/ipaqe-provision-hosts
ipaqe_provision_hosts/backend/__init__.py
Python
mit
22
0
##################################################### # # A library for getting match information for a given team at a given event # out of the Blue Alliance API # # Authors: Andrew Merrill and Jacob Bendicksen (Fall 2014) # # Requires the blueapi.py library ###################################################### #this doesn't currently fully work import blueapi teamNumber = 1540 eventKey = '2014pncmp' #returns a list of qualification matches that the team played in def getTeamQualMatches(teamNumber,eventKey): matches = [] for n in range(0,len(blueapi.getTeamEventMatches(eventKey,teamNumber))): if blueapi.getTeamEventMatches(teamNumber,eventKey)[n]['comp_level'] == 'qm': matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number']) matches.sort() return matches #returns a list of qualification matches that the team played in def getQualMatches(eventKey): matches = [] for n in range(0,len(blueapi.getEventMatches(eventKey))): if blueapi.getEventMatches(eventKey)[n]['comp_level'] == 'qm': matches.append(blueapi.getEventMatches(eventKey)[n]['match_number']) matches.sort() return matches #returns a list of quarterfinal matches that the team played in def getTeamQFMatches(teamNumber, eventKey): matches = [] for n in range(0,len(blueapi.getTeamEventMatches(eventKey))): if blueapi.getTeamEventMatches(eventKey)[n]['comp_level'] == 'qf': matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number']) matches.sort() return matches #returns a list of quarterfinal matches that the team played in def getQFMatches(eventKey): matches = [] for n in range(0,len(blueapi.getEventMatches(eventKey))): if blueapi.getEventMatches(eventKey)[n]['comp_level'] == 'qf': matches.append(blueapi.getEventMatches(eventKey)[n]['match_number']) matches.sort() return matches #returns a list of semifinal matches that the team played in def getTeamSFMatches(teamNumber, eventKey): matches = [] for n in range(0,len(blueapi.getTeamEventMatches(eventKey))): if blueapi.getTeamEventMatches(eventKey)[n]['comp_level'] == 'sf': matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number']) matches.sort() return matches #returns a list of semifinal matches that the team played in def getSFMatches(eventKey): matches = [] for n in range(0,len(blueapi.getEventMatches(eventKey))): if blueapi.getEventMatches(eventKey)[n]['comp_level'] == 'sf': matches.append(blueapi.getEventMatches(eventKey)[n]['match_number']) matches.sort() return matches #returns a list of finals matches that the team played in def getTeamFMatches(teamNumber, eventKey): matches = [] for n in range(0,len(blueapi.getTeamEventMatches(eventKey))): if blueapi.getTeamEventMatches(eventKey)[n]['comp_level'] == 'f': matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number']) matches.sort() return matches #returns a list of qualification matches that the team played in def getFMatches(eventKey): matches = [] for n in range(0,len(blueapi.getEventMatches(eventKey))): if blueapi.getEventMatches(eventKey)[n]['comp_level'] == 'f': matches.append(blueapi.getEventMatches(eventKey)[n]['match_number']) matches.sort() return matches def getMatchRedScore(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['alliances']['red']['score'] def getMatchBlueScore(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['alliances']['blue']['teams'] def getMatchRedTeams(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['alliances']['red']['teams'] def getMatchBlueTeams(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['alliances']['blue']['teams'] def getMatchVideo(matchNumber,eventKey): videos = blueapi.getEventMatches(eventKey)[matchNumber]['videos'] for n in range(0,5): if videos[n]['type'] == 'youtube': return "youtu.be/" + videos[n]['key'] elif videos[n]['type'] == 'tba': return videos[n]['key'] def getSetNumber(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['set_number'] def getTimeString(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['time_string'] def getMatchKey(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['key'] def getMatchTime(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['time'] def getScoreBreakdown(matchNumber,eventKey): return blueapi.getEventMatches(eventKey)[matchNumber]['score_breakdown']
jacobbendicksen/BlueAPI
matchinfo.py
Python
mit
4,831
0.012834
# Copyright 2013 OpenStack Foundation # 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 tempest_lib.common.utils import data_utils from tempest.api.network import base from tempest import test class ExtraDHCPOptionsTestJSON(base.BaseNetworkTest): """ Tests the following operations with the Extra DHCP Options Neutron API extension: port create port list port show port update v2.0 of the Neutron API is assumed. It is also assumed that the Extra DHCP Options extension is enabled in the [network-feature-enabled] section of etc/tempest.conf """ @classmethod def skip_checks(cls): super(ExtraDHCPOptionsTestJSON, cls).skip_checks() if not test.is_extension_enabled('extra_dhcp_opt', 'network'): msg = "Extra DHCP Options extension not enabled." raise cls.skipException(msg) @classmethod def resource_setup(cls): super(ExtraDHCPOptionsTestJSON, cls).resource_setup() cls.network = cls.create_network() cls.subnet = cls.create_subnet(cls.network) cls.port = cls.create_port(cls.network) cls.ip_tftp = ('123.123.123.123' if cls._ip_version == 4 else '2015::dead') cls.ip_server = ('123.123.123.45' if cls._ip_version == 4 else '2015::badd') cls.extra_dhcp_opts = [ {'opt_value': 'pxelinux.0', 'opt_name': 'bootfile-name'}, {'opt_value': cls.ip_tftp, 'opt_name': 'tftp-server'}, {'opt_value': cls.ip_server, 'opt_name': 'server-ip-address'} ] @test.idempotent_id('d2c17063-3767-4a24-be4f-a23dbfa133c9') def test_create_list_port_with_extra_dhcp_options(self): # Create a port with Extra DHCP Options body = self.client.create_port( network_id=self.network['id'], extra_dhcp_opts=self.extra_dhcp_opts) port_id = body['port']['id'] self.addCleanup(self.client.delete_port, port_id) # Confirm port created has Extra DHCP Options body = self.client.list_ports() ports = body['ports'] port = [p for p in ports if p['id'] == port_id] self.assertTrue(port) self._confirm_extra_dhcp_options(port[0], self.extra_dhcp_opts) @test.idempotent_id('9a6aebf4-86ee-4f47-b07a-7f7232c55607') def test_update_show_port_with_extra_dhcp_options(self): # Update port with extra dhcp options name = data_utils.rand_name('new-port-name') body = self.client.update_port( self.port['id'], name=name, extra_dhcp_opts=self.extra_dhcp_opts) # Confirm extra dhcp options were added to the port body = self.client.show_port(self.port['id']) self._confirm_extra_dhcp_options(body['port'], self.extra_dhcp_opts) def _confirm_extra_dhcp_options(self, port, extra_dhcp_opts): retrieved = port['extra_dhcp_opts'] self.assertEqual(len(retrieved), len(extra_dhcp_opts)) for retrieved_option in retrieved: for option in extra_dhcp_opts: if (retrieved_option['opt_value'] == option['opt_value'] and retrieved_option['opt_name'] == option['opt_name']): break else: self.fail('Extra DHCP option not found in port %s' % str(retrieved_option)) class ExtraDHCPOptionsIpV6TestJSON(ExtraDHCPOptionsTestJSON): _ip_version = 6
roopali8/tempest
tempest/api/network/test_extra_dhcp_options.py
Python
apache-2.0
4,062
0.000246
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v2alpha1_horizontal_pod_autoscaler_spec import V2alpha1HorizontalPodAutoscalerSpec class TestV2alpha1HorizontalPodAutoscalerSpec(unittest.TestCase): """ V2alpha1HorizontalPodAutoscalerSpec unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV2alpha1HorizontalPodAutoscalerSpec(self): """ Test V2alpha1HorizontalPodAutoscalerSpec """ model = kubernetes.client.models.v2alpha1_horizontal_pod_autoscaler_spec.V2alpha1HorizontalPodAutoscalerSpec() if __name__ == '__main__': unittest.main()
skuda/client-python
kubernetes/test/test_v2alpha1_horizontal_pod_autoscaler_spec.py
Python
apache-2.0
1,023
0.00391
from django import forms from django.utils.html import escape from django.forms.utils import ErrorList from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from booktype.utils.misc import booktype_slugify from booki.editor.models import BookiGroup from booktype.utils import misc from booktype.apps.core.forms import BaseBooktypeForm from widgets import RemovableImageWidget class SpanErrorList(ErrorList): def __unicode__(self): return unicode(self.as_spans()) def as_spans(self): return "<span style='color: red'>%s</span>" % ( ",".join([e for e in self]) ) class BaseGroupForm(BaseBooktypeForm, forms.ModelForm): name = forms.CharField() description = forms.CharField( label=_('Description (250 characters)'), required=False, max_length=250, widget=forms.Textarea(attrs={'rows': '10', 'cols': '40'}) ) group_image = forms.FileField( label=_('Group image'), required=False, widget=RemovableImageWidget(attrs={ 'label_class': 'checkbox-inline', 'input_class': 'group-image-removable' } ) ) class Meta: model = BookiGroup fields = [ 'name', 'description' ] def __init__(self, *args, **kwargs): kwargs.update({'error_class': SpanErrorList}) super(BaseGroupForm, self).__init__(*args, **kwargs) def clean_name(self): new_url_name = booktype_slugify(self.cleaned_data['name']) group_data_url_name = BookiGroup.objects.filter(url_name=new_url_name).exclude(pk=self.instance.pk) if len(group_data_url_name) > 0: raise ValidationError(_('Group name is already in use')) return self.cleaned_data.get('name', '') def clean_description(self): return escape(self.cleaned_data.get('description', '')) def set_group_image(self, group_id, group_image): try: filename = misc.set_group_image(group_id, group_image, 240, 240) if len(filename) == 0: raise ValidationError(_('Only JPEG file is allowed for group image.')) else: misc.set_group_image( "{}_small".format(group_id), group_image, 18, 18) except Exception as err: # TODO: we should do something here print err class GroupCreateForm(BaseGroupForm): pass class GroupUpdateForm(BaseGroupForm): def clean_group_image(self): group_image = self.files.get('group_image', None) group_id = str(self.instance.pk) if group_image: self.set_group_image(group_id, group_image) return group_image
MiczFlor/Booktype
lib/booktype/apps/portal/forms.py
Python
agpl-3.0
2,755
0.002178
# coding=utf-8 from __future__ import absolute_import import gevent from gevent.pywsgi import WSGIHandler import sys from webob import Request from .response import Response from .socket import Socket from ..event_emitter import EventEmitter from .transports import WebsocketTransport import logging logger = logging.getLogger(__name__) __all__ = ['EngineHandler'] class EngineHandler(WSGIHandler, EventEmitter): """ The WSGIHandler for EngineServer It filters out interested requests and process them, leave other requests to the WSGIHandler """ transports = ('polling', 'websocket') def __init__(self, server_context, *args, **kwargs): super(EngineHandler, self).__init__(*args, **kwargs) EventEmitter.__init__(self) self.server_context = server_context if self.server_context.transports: self.transports = self.server_context.transports def bind_framework_info(self, socket): # Run framework's wsgi application to hook up framework specific info eg. request # This is why we define /socket.io url in web frameworks and points them to a view logger.debug("[EngineHandler] Bind the framework specific info to engine socket") self.environ['engine_socket'] = socket try: def start_response(status, headers): logger.debug("[EngineHandler] [%s] [%s]" % (status, headers)) res = self.application(self.environ, start_response) logger.debug("[EngineHandler] %s" % res) except Exception, e: logger.debug("[EngineHandler] bind framework info met exception %s" % e) self.handle_error(*sys.exc_info()) def handle_one_response(self): """ There are 3 situations we get a new request: 1. Handshake. 2. Upgrade. 3. Polling Request. After the transport been upgraded, all data transferring handled by the WebSocketTransport """ path = self.environ.get('PATH_INFO') if not path.lstrip('/').startswith(self.server_context.resource + '/'): return super(EngineHandler, self).handle_one_response() # Create a request and a response request = Request(self.get_environ()) setattr(request, 'handler', self) setattr(request, 'response', Response()) logger.debug("[EngineHandler] Incoming request with %s" % request.GET) # Upgrade the websocket if needed is_websocket = False if request.GET.get("transport", None) == "websocket": if 'Upgrade' in request.headers: logger.debug("[EngineHandler] It is a websocket upgrade request") # This is the ws upgrade request, here we handles the upgrade ws_handler = self.server_context.ws_handler_class(self.socket, self.client_address, self.server) ws_handler.__dict__.update(self.__dict__) ws_handler.prevent_wsgi_call = True ws_handler.handle_one_response() # Suppose here we have an websocket connection setattr(request, 'websocket', ws_handler.websocket) is_websocket = True else: logger.warning("[EngineHandler] Client fired a websocket but the 'Upgrade' Header loose somewhere, maybe your proxy") return sid = request.GET.get("sid", None) b64 = request.GET.get("b64", False) socket = self.server_context.engine_sockets.get(sid, None) # FIXME CHECK WHETHER WE NEED THIS? if socket and not is_websocket: # We spawn a new gevent here, let socket do its own business. # In current event loop, we will wait on request.response, which is set in socket.set_request logger.debug("[EngineHandler] Found existing socket") self.bind_framework_info(socket) gevent.spawn(socket.process_request, request) else: if socket is None: logger.debug("[EngineHandler] No existing socket, handshake") socket = self._do_handshake(b64=b64, request=request) if not is_websocket: logger.debug("[EngineHandler] The incoming request not websocket, bind framework info") self.bind_framework_info(socket) if is_websocket and socket.transport.name != 'websocket': logger.debug("[EngineHandler] websocket, proceed as upgrade") # Here we have a upgrade ws_transport = WebsocketTransport(self, {}) ws_transport.process_request(request) socket.maybe_upgrade(ws_transport) # wait till the response ends logger.debug("[EngineHandler] Waiting for the response signal") request.response.join() # The response object can be used as a wsgi application which will send out the buffer self.application = request.response # Call super handle_one_repsponse() to do timing, logging etc super(EngineHandler, self).handle_one_response() self.emit('cleanup') def _do_handshake(self, b64, request): """ handshake with client to build a socket :param b64: :param request: :return: """ transport_name = request.GET.get('transport', None) if transport_name not in self.transports: raise ValueError("transport name [%s] not supported" % transport_name) socket = Socket(request, supports_binary=not bool(b64)) self.server_context.engine_sockets[socket.id] = socket def remove_socket(*args, **kwargs): self.server_context.engine_sockets.pop(socket.id) socket.on('close', remove_socket) request.response.headers['Set-Cookie'] = 'io=%s' % socket.id socket.open() self.emit('connection', socket) return socket
shuoli84/gevent_socketio2
socketio/engine/handler.py
Python
mit
5,977
0.002175
# 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. 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 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 importutils from oslo_utils import timeutils from oslo_utils import units from oslo_utils import uuidutils 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 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 fields from nova.pci import manager as pci_manager 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 import utils from nova import version from nova.virt import block_device as driver_block_device from nova.virt import configdrive from nova.virt.disk import api as disk 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.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.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 CONF = cfg.CONF CONF.import_opt('compute_manager', 'nova.service') CONF.import_opt('host', 'nova.netconf') CONF.import_opt('my_ip', 'nova.netconf') CONF.import_opt('image_cache_subdirectory_name', 'nova.virt.imagecache') CONF.import_opt('instances_path', 'nova.compute.manager') _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>"""} _fake_cpu_info = { "arch": "test_arch", "model": "test_model", "vendor": "test_vendor", "topology": { "sockets": 1, "cores": 8, "threads": 16 }, "features": ["feature1", "feature2"] } def _concurrency(signal, wait, done, target, is_block_dev=False): signal.send() wait.wait() done.send() class FakeVirDomainSnapshot(object): def __init__(self, dom=None): self.dom = dom def delete(self, flags): pass 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 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.stubs.Set(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.""" return self.get_config() 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=1, id=2, name=u'm1.small', ephemeral_gb=0, rxtx_factor=1.0, flavorid=u'1', vcpus=1, 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', } class LibvirtConnTestCase(test.NoDBTestCase): REQUIRES_LOCKING = True _EPHEMERAL_20_DEFAULT = ('ephemeral_20_%s' % utils.get_hash_str(disk._DEFAULT_FILE_SYSTEM)[:7]) def setUp(self): super(LibvirtConnTestCase, self).setUp() self.flags(fake_call=True) 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") 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, '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.stubs) 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') 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=utils.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): # 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': '0.10.2'} 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=utils.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): # 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': '0.10.2'} 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=utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_KVM_S390_VERSION) - 1) @mock.patch.object(fakelibvirt.Connection, 'getVersion', return_value=utils.convert_version_to_int( libvirt_driver.MIN_QEMU_S390_VERSION)) @mock.patch.object(arch, "from_host", return_value=arch.S390X) def test_min_version_s390_old_libvirt(self, mock_arch, mock_qemu_version, mock_lv_version): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertRaises(exception.NovaException, drvr.init_host, "dummyhost") @mock.patch.object(fakelibvirt.Connection, 'getLibVersion', return_value=utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_KVM_S390_VERSION)) @mock.patch.object(fakelibvirt.Connection, 'getVersion', return_value=utils.convert_version_to_int( libvirt_driver.MIN_QEMU_S390_VERSION) - 1) @mock.patch.object(arch, "from_host", return_value=arch.S390X) def test_min_version_s390_old_qemu(self, mock_arch, mock_qemu_version, mock_lv_version): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertRaises(exception.NovaException, drvr.init_host, "dummyhost") @mock.patch.object(fakelibvirt.Connection, 'getLibVersion', return_value=utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_KVM_S390_VERSION)) @mock.patch.object(fakelibvirt.Connection, 'getVersion', return_value=utils.convert_version_to_int( libvirt_driver.MIN_QEMU_S390_VERSION)) @mock.patch.object(arch, "from_host", return_value=arch.S390X) def test_min_version_s390_ok(self, mock_arch, mock_qemu_version, mock_lv_version): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) drvr.init_host("dummyhost") @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('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): self.flags(virt_type='kvm', 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('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='foo', 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, 'get_by_compute_host') def test_set_host_enabled_with_disable(self, mock_svc): # 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.patch.object(objects.Service, 'get_by_compute_host') def test_set_host_enabled_with_enable(self, mock_svc): # 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) self.assertTrue(svc.disabled) @mock.patch.object(objects.Service, 'get_by_compute_host') def test_set_host_enabled_with_enable_state_enabled(self, mock_svc): # 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.patch.object(objects.Service, 'get_by_compute_host') def test_set_host_enabled_with_disable_state_disabled(self, mock_svc): # 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) 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) def test_detach_pci_devices_exception(self): pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid')] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(host.Host, 'has_min_version') host.Host.has_min_version = lambda x, y: False self.assertRaises(exception.PciDeviceDetachFailed, drvr._detach_pci_devices, None, pci_devices) def test_detach_pci_devices(self): fake_domXML1 =\ """<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="0x0000" bus="0x04"/> </source> </hostdev></devices></domain>""" pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid', address="0001:04:10:1")] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(host.Host, 'has_min_version') host.Host.has_min_version = lambda x, y: True self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_get_guest_pci_device') class FakeDev(object): def to_xml(self): pass libvirt_driver.LibvirtDriver._get_guest_pci_device =\ lambda x, y: FakeDev() class FakeDomain(object): def detachDeviceFlags(self, xml, flags): pci_devices[0]['hypervisor_name'] = 'marked' pass def XMLDesc(self, flags): return fake_domXML1 guest = libvirt_guest.Guest(FakeDomain()) drvr._detach_pci_devices(guest, pci_devices) self.assertEqual(pci_devices[0]['hypervisor_name'], 'marked') def test_detach_pci_devices_timeout(self): fake_domXML1 =\ """<domain> <devices> <hostdev mode="subsystem" type="pci" managed="yes"> <source> <address function="0x1" slot="0x10" domain="0x0000" bus="0x04"/> </source> </hostdev> </devices> </domain>""" pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid', address="0000:04:10:1")] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(host.Host, 'has_min_version') host.Host.has_min_version = lambda x, y: True self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_get_guest_pci_device') class FakeDev(object): def to_xml(self): pass libvirt_driver.LibvirtDriver._get_guest_pci_device =\ lambda x, y: FakeDev() class FakeDomain(object): def detachDeviceFlags(self, xml, flags): pass def XMLDesc(self, flags): return fake_domXML1 guest = libvirt_guest.Guest(FakeDomain()) 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 contextlib.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.stubs, 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.stubs, 1), image_meta, {'mapping': {}}) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, 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.stubs, 1), image_meta, {'mapping': {}}) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, 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) def test_get_guest_config_numa_host_instance_fits(self): 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 contextlib.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) def test_get_guest_config_numa_host_instance_no_fit(self): 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 contextlib.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_config_numa_host_instance_pci_no_numa_info(self): 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 contextlib.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) def test_get_guest_config_numa_host_instance_2pci_no_fit(self): 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 contextlib.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( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) - 1, utils.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_bad_version_libvirt(self): self.flags(virt_type='kvm', group='libvirt') self._test_get_guest_config_numa_unsupported( utils.convert_version_to_int( libvirt_driver.BAD_LIBVIRT_NUMA_VERSIONS[0]), utils.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, 'warn') 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 xrange(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( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION), utils.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( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION), utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION), host.HV_DRIVER_QEMU, arch.PPC64, 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( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION), utils.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( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION) - 1, utils.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( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION), utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) - 1, host.HV_DRIVER_QEMU, arch.X86_64, exception.NUMATopologyUnsupported, 2048) def test_get_guest_config_numa_host_instance_fit_w_cpu_pinset(self): 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 contextlib.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) def test_get_guest_config_non_numa_host_instance_topo(self): 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 contextlib.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) def test_get_guest_config_numa_host_instance_topo(self): 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 contextlib.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 contextlib.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 contextlib.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 contextlib.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) 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(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_numa, mock_hp): 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_numa, mock_hp): 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 = "x86_64" caps.host.topology = self._fake_caps_numa_topology() mock_caps.return_value = caps host_topology = drvr._get_host_numa_topology() 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.stubs, 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.stubs, 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_feature1(self, mock_version): def fake_version(lv_ver=None, hv_ver=None, hv_type=None): if lv_ver == (1, 0, 0) and hv_ver == (1, 1, 0): return True return False mock_version.side_effect = fake_version 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.stubs, 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.assertFalse(cfg.features[2].spinlocks) self.assertFalse(cfg.features[2].vapic) @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.stubs, 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.stubs, 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, 2 * units.Mi) self.assertEqual(cfg.vcpus, 1) 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, 2 * units.Mi) self.assertEqual(cfg.vcpus, 1) 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_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'} info = {'block_device_mapping': driver_block_device.convert_volumes([ 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'][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'} info = {'block_device_mapping': driver_block_device.convert_volumes([ 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'][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"} 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'} bd_info = { 'block_device_mapping': driver_block_device.convert_volumes([ 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'][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', 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), 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.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.object(host.Host, "get_domain") def test_get_serial_ports_from_instance(self, mock_get_domain): i = self._test_get_serial_ports_from_instance(None, mock_get_domain) 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(host.Host, "get_domain") def test_get_serial_ports_from_instance_bind_only(self, mock_get_domain): i = self._test_get_serial_ports_from_instance('bind', mock_get_domain) self.assertEqual([ ('127.0.0.1', 101), ('127.0.0.2', 100)], list(i)) @mock.patch.object(host.Host, "get_domain") def test_get_serial_ports_from_instance_connect_only(self, mock_get_domain): i = self._test_get_serial_ports_from_instance('connect', mock_get_domain) self.assertEqual([ ('127.0.0.1', 100), ('127.0.0.2', 101)], list(i)) @mock.patch.object(host.Host, "get_domain") def test_get_serial_ports_from_instance_on_s390(self, mock_get_domain): i = self._test_get_serial_ports_from_instance(None, mock_get_domain, '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_instance(self, mode, mock_get_domain, 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} dom = mock.MagicMock() dom.XMLDesc.return_value = xml mock_get_domain.return_value = dom drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance = objects.Instance(**self.test_instance) return drvr._get_serial_ports_from_instance( instance, 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): 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) return drvr._get_guest_usb_tablet(os_type) 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_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 contextlib.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', use_usb_tablet=False, group='libvirt') 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', use_usb_tablet=False, 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_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', use_usb_tablet=False, group='libvirt') 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', use_usb_tablet=False, rng_dev_path='/dev/hw_rng', group='libvirt') 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) def test_guest_cpu_shares_with_multi_vcpu(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.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) def test_get_guest_config_with_cpu_quota(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 = {'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) def test_get_guest_config_with_bogus_cpu_quota(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 = {'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) 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 contextlib.nested( mock.patch('__builtin__.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 contextlib.nested( mock.patch('__builtin__.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 contextlib.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 contextlib.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 test_get_guest_config_sysinfo_serial_invalid(self): self.flags(sysinfo_serial="invalid", group="libvirt") self.assertRaises(exception.NovaException, libvirt_driver.LibvirtDriver, fake.FakeVirtAPI(), True) 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.stubs, 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.stubs, 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.stubs, 1), image_meta, disk_info) self.assertNotEqual(cfg.os_cmdline, "") def test_get_guest_config_armv7(self): 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.stubs, 1), image_meta, disk_info) self.assertEqual(cfg.os_mach_type, "vexpress-a15") def test_get_guest_config_aarch64(self): 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.stubs, 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.stubs, 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.stubs, 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.stubs, 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, 1) 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.stubs, 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, 1) 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.stubs, 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.stubs, 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.stubs, 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, 1) 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.stubs, 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, 1) 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.stubs, 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, 1) self.assertEqual(conf.cpu.cores, 1) self.assertEqual(conf.cpu.threads, 1) @mock.patch.object(host.Host, "has_min_version", return_value=True) def test_get_guest_cpu_config_numa_topology(self, mock_has_min_version): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.vcpus = 2 instance_ref.numa_topology = objects.InstanceNUMATopology(cells=[ objects.InstanceNUMACell( id=0, cpuset=set([0, 1]), memory=1024, cpu_pinning={})]) 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.assertIsNone(instance_ref.numa_topology.cells[0].cpu_topology) drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), image_meta, disk_info) topo = instance_ref.numa_topology.cells[0].cpu_topology self.assertIsNotNone(topo) self.assertEqual(topo.cores * topo.sockets * topo.threads, instance_ref.flavor.vcpus) 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.stubs, 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) 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")} 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")} 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_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_running=False) @mock.patch.object(host.Host, "list_instance_domains") def test_get_all_block_devices(self, mock_list): xml = [ """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> </disk> </devices> </domain> """, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> </devices> </domain> """, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <disk type='block'> <source dev='/path/to/dev/3'/> </disk> </devices> </domain> """, ] mock_list.return_value = [ FakeVirtDomain(xml[0], id=3, name="instance00000001"), FakeVirtDomain(xml[1], id=1, name="instance00000002"), FakeVirtDomain(xml[2], id=5, name="instance00000003")] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) devices = drvr._get_all_block_devices() self.assertEqual(devices, ['/path/to/dev/1', '/path/to/dev/3']) mock_list.assert_called_with() @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) img_meta = {"properties": {"hw_qemu_guest_agent": "yes", "os_require_quiesce": "yes"}} self.assertIsNone(drvr.quiesce(self.context, instance, img_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) img_meta = {"properties": {"hw_qemu_guest_agent": "yes", "os_require_quiesce": "yes"}} self.assertIsNone(drvr.unquiesce(self.context, instance, img_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='fake_type', 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") @mock.patch.object(fakelibvirt.virConnect, "getLibVersion") def test_attach_blockio_invalid_version(self, mock_version): mock_version.return_value = (0 * 1000 * 1000) + (9 * 1000) + 8 self.flags(virt_type='qemu', 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.Invalid, drvr.attach_volume, None, {"driver_volume_type": "fake", "data": {"logical_block_size": "4096", "physical_block_size": "4096"} }, instance, "/dev/sda") @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 contextlib.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') ) as (mock_connect_volume, mock_get_volume_config, mock_set_cache_mode): 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.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 = """<domain> <devices> <disk type='file'> <source file='/path/to/fake-volume'/> <target dev='vdc' bus='virtio'/> </disk> </devices> </domain>""" mock_dom = mock.MagicMock() mock_dom.XMLDesc.return_value = mock_xml 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') def test_multi_nic(self): network_info = _fake_network_info(self.stubs, 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) else: 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.stubs, 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.assertTrue(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.stubs, 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.stubs.Set(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.stubs, 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.stubs, 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.stubs, 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.stubs, 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'].replace(':', '') fw = firewall.NWFilterFirewall(fake.FakeVirtAPI(), 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.stubs, 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(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): 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) self.assertThat({"filename": "file", 'image_type': 'default', 'disk_available_mb': 409600, "disk_over_commit": False, "block_migration": True}, matchers.DictMatches(return_value)) @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): 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) self.assertThat({"filename": "file", "image_type": 'default', "block_migration": False, "disk_over_commit": False, "disk_available_mb": None}, matchers.DictMatches(return_value)) @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'} result = drvr.check_can_live_migrate_destination( self.context, instance_ref, compute_info, compute_info) mock_cpu.assert_called_once_with(None, 'asdf') expected_result = {"filename": 'fake', "image_type": CONF.libvirt.images_type, "block_migration": False, "disk_over_commit": False, "disk_available_mb": None} self.assertDictEqual(expected_result, result) @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): 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} })} 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) self.assertThat({"filename": "file", "image_type": 'default', "block_migration": False, "disk_over_commit": False, "disk_available_mb": None}, matchers.DictMatches(return_value)) @mock.patch.object(fakelibvirt.Connection, 'compareCPU') def test_check_can_live_migrate_dest_incompatible_cpu_raises( self, mock_cpu): 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'} 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): mock_compare.return_value = 5 conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = conn._compare_cpu(None, jsonutils.dumps(_fake_cpu_info)) 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): 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)) 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): mock_compare.return_value = 6 conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = conn._compare_cpu(jsonutils.dumps(_fake_cpu_info), None) self.assertIsNone(ret) def test_compare_cpu_virt_type_xen(self): self.flags(virt_type='xen', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = conn._compare_cpu(None, None) 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): 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)) @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): 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)) def test_check_can_live_migrate_dest_cleanup_works_correctly(self): objects.Instance(**self.test_instance) dest_check_data = {"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.check_can_live_migrate_destination_cleanup(self.context, dest_check_data) 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 = {'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').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, dict) self.assertIn('is_shared_block_storage', ret) self.assertIn('is_shared_instance_path', ret) self.assertEqual(ret['is_shared_instance_path'], ret['is_shared_storage']) 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) 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() 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, {'image_type': 'rbd'}, block_device_info=bdi)) self.assertEqual(0, mock_get_instance_disk_info.call_count) 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) 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, {'image_type': 'lvm'}, 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) 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, {'image_type': 'qcow2'}, 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) 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, {'is_shared_instance_path': False}, 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) 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, {'image_type': 'rbd', 'is_shared_instance_path': False}, 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) with mock.patch.object(host.Host, 'get_domain', mock_lookup): self.assertTrue(drvr._is_shared_block_storage(instance, {'is_volume_backed': True, 'is_shared_instance_path': False}, 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) with contextlib.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, {'is_volume_backed': True, 'is_shared_instance_path': False}, 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() with mock.patch.object(drvr, 'get_instance_disk_info', mock_get_instance_disk_info): self.assertTrue(drvr._is_shared_block_storage('instance', {'is_shared_instance_path': True}, 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)) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI2") _bandwidth = CONF.libvirt.live_migration_bandwidth vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE).AndReturn( initial_xml) vdmock.migrateToURI2(CONF.libvirt.live_migration_uri % 'dest', None, target_xml, mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError("ERR")) # start test migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '10.0.0.1', 'spice': '10.0.0.2'}}} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) 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 migrate_data = {'pre_live_migration_result': {'volume': {u'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', 'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}}, 'disk_info': {'bus': u'virtio', 'type': u'disk', 'dev': u'vdb'}}}}, 'graphics_listen_addrs': {}} pre_live_migrate_data = ((migrate_data or {}). get('pre_live_migration_result', {})) volume = pre_live_migrate_data.get('volume') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) test_mock = mock.MagicMock() 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(drvr, '_update_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, test_mock)) mupdate.assert_called_once_with(target_xml, volume, None, None) 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" volume_xml = {'volume': {}} volume_xml['volume'][serial] = {'connection_info': {}, 'disk_info': {}} volume_xml['volume'][serial]['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'}} volume_xml['volume'][serial]['disk_info'] = {'bus': u'virtio', 'type': u'disk', 'dev': u'vdb'} connection_info = volume_xml['volume'][serial]['connection_info'] disk_info = volume_xml['volume'][serial]['disk_info'] conf = vconfig.LibvirtConfigGuestDisk() conf.source_device = disk_info['type'] conf.driver_name = "qemu" conf.driver_format = "raw" conf.driver_cache = "none" conf.target_dev = disk_info['dev'] conf.target_bus = disk_info['bus'] conf.serial = connection_info.get('serial') conf.source_type = "block" conf.source_path = connection_info['data'].get('device_path') with mock.patch.object(drvr, '_get_volume_config', return_value=conf): parser = etree.XMLParser(remove_blank_text=True) xml_doc = etree.fromstring(initial_xml, parser) config = drvr._update_volume_xml(xml_doc, volume_xml['volume']) xml_doc = etree.fromstring(target_xml, parser) self.assertEqual(etree.tostring(xml_doc), etree.tostring(config)) 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" volume_xml = {'volume': {}} volume_xml['volume'][serial] = {'connection_info': {}, 'disk_info': {}} volume_xml['volume'][serial]['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'}} volume_xml['volume'][serial]['disk_info'] = {'bus': u'virtio', 'type': u'disk', 'dev': u'vdb'} connection_info = volume_xml['volume'][serial]['connection_info'] disk_info = volume_xml['volume'][serial]['disk_info'] conf = vconfig.LibvirtConfigGuestDisk() conf.source_device = disk_info['type'] conf.driver_name = "qemu" conf.driver_format = "raw" conf.driver_cache = "none" conf.target_dev = disk_info['dev'] conf.target_bus = disk_info['bus'] conf.serial = connection_info.get('serial') conf.source_type = "block" conf.source_path = connection_info['data'].get('device_path') with mock.patch.object(drvr, '_get_volume_config', return_value=conf): xml_doc = etree.fromstring(initial_xml) config = drvr._update_volume_xml(xml_doc, volume_xml['volume']) self.assertEqual(target_xml, etree.tostring(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" volume_xml = {'volume': {}} volume_xml['volume'][serial] = {'info1': {}, 'info2': {}} conf = vconfig.LibvirtConfigGuestDisk() with mock.patch.object(drvr, '_get_volume_config', return_value=conf): xml_doc = etree.fromstring(initial_xml) config = drvr._update_volume_xml(xml_doc, volume_xml['volume']) self.assertEqual(target_xml, etree.tostring(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 = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '10.0.0.1', 'spice': '10.0.0.2'}, 'serial_listen_addr': '9.0.0.12'}} dom = fakelibvirt.virDomain drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, dom) mock_xml.assert_called_once_with( flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE) mock_migrate.assert_called_once_with( CONF.libvirt.live_migration_uri % 'dest', None, target_xml, mock.ANY, None, 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 drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.MigrationError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, None, 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) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI") _bandwidth = CONF.libvirt.live_migration_bandwidth vdmock.migrateToURI(CONF.libvirt.live_migration_uri % 'dest', mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError("ERR")) # start test migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '0.0.0.0', 'spice': '0.0.0.0'}}} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) 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) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI") _bandwidth = CONF.libvirt.live_migration_bandwidth vdmock.migrateToURI(CONF.libvirt.live_migration_uri % 'dest', mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError("ERR")) # start test migrate_data = {} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) @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 = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '1.2.3.4', 'spice': '1.2.3.4'}}} 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) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI2") _bandwidth = CONF.libvirt.live_migration_bandwidth if getattr(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None) is None: vdmock.migrateToURI(CONF.libvirt.live_migration_uri % 'dest', mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError('ERR')) else: vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE ).AndReturn(FakeVirtDomain().XMLDesc(flags=0)) vdmock.migrateToURI2(CONF.libvirt.live_migration_uri % 'dest', None, mox.IgnoreArg(), mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError('ERR')) # start test migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '127.0.0.1', 'spice': '127.0.0.1'}}} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) self.assertEqual(vm_states.ACTIVE, instance_ref.vm_state) self.assertEqual(power_state.RUNNING, instance_ref.power_state) def test_live_migration_raises_unsupported_config_exception(self): # Tests that when migrateToURI2 fails with VIR_ERR_CONFIG_UNSUPPORTED, # migrateToURI is used instead. # Preparing data instance_ref = objects.Instance(**self.test_instance) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, 'migrateToURI2') self.mox.StubOutWithMock(vdmock, 'migrateToURI') _bandwidth = CONF.libvirt.live_migration_bandwidth vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE).AndReturn( FakeVirtDomain().XMLDesc(flags=0)) unsupported_config_error = fakelibvirt.libvirtError('ERR') unsupported_config_error.err = ( fakelibvirt.VIR_ERR_CONFIG_UNSUPPORTED,) # This is the first error we hit but since the error code is # VIR_ERR_CONFIG_UNSUPPORTED we'll try migrateToURI. vdmock.migrateToURI2(CONF.libvirt.live_migration_uri % 'dest', None, mox.IgnoreArg(), mox.IgnoreArg(), None, _bandwidth).AndRaise(unsupported_config_error) # This is the second and final error that will actually kill the run, # we use TestingException to make sure it's not the same libvirtError # above. vdmock.migrateToURI(CONF.libvirt.live_migration_uri % 'dest', mox.IgnoreArg(), None, _bandwidth).AndRaise(test.TestingException('oops')) graphics_listen_addrs = {'vnc': '0.0.0.0', 'spice': '127.0.0.1'} migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': graphics_listen_addrs}} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock( drvr, '_check_graphics_addresses_can_live_migrate') drvr._check_graphics_addresses_can_live_migrate(graphics_listen_addrs) self.mox.ReplayAll() # start test self.assertRaises(test.TestingException, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) @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 = {'is_shared_instance_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 = {'is_shared_instance_path': True} 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(fakelibvirt.Domain, "XMLDesc") def test_live_migration_copy_disk_paths(self, mock_xml): 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"/> </disk> <disk type="file"> <source file="/var/lib/nova/instance/123/disk.shared"/> <shareable/> </disk> <disk type="file"> <source file="/var/lib/nova/instance/123/disk.config"/> <readonly/> </disk> <disk type="block"> <source dev="/dev/mapper/somevol"/> </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(guest) self.assertEqual(["/var/lib/nova/instance/123/disk.root", "/dev/mapper/somevol"], paths) @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) dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", False) guest = libvirt_guest.Guest(dom) instance = objects.Instance(**self.test_instance) data_gb = drvr._live_migration_data_gb(instance, guest, False) self.assertEqual(2, data_gb) self.assertEqual(0, mock_paths.call_count) @mock.patch.object(libvirt_driver.LibvirtDriver, "_live_migration_copy_disk_paths") def test_live_migration_data_gb_block(self, mock_paths): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", False) guest = libvirt_guest.Guest(dom) 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") mock_paths.return_value = ["/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, guest, True) # 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) self.assertEqual(1, mock_paths.call_count) EXPECT_SUCCESS = 1 EXPECT_FAILURE = 2 EXPECT_ABORT = 3 @mock.patch.object(time, "time") @mock.patch.object(time, "sleep", side_effect=lambda x: eventlet.sleep(0)) @mock.patch.object(host.DomainJobInfo, "for_domain") @mock.patch.object(objects.Instance, "save") @mock.patch.object(fakelibvirt.Connection, "_mark_running") @mock.patch.object(fakelibvirt.virDomain, "abortJob") def _test_live_migration_monitoring(self, job_info_records, time_records, expect_result, mock_abort, mock_running, mock_save, mock_job_info, mock_sleep, mock_time): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", True) guest = libvirt_guest.Guest(dom) finish_event = eventlet.event.Event() def fake_job_info(hostself): while True: self.assertTrue(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() 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 migrate_data = mock.sentinel.migrate_data 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, dom, finish_event) 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') 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') fake_recover_method.assert_called_once_with( self.context, instance, dest, False, migrate_data) def test_live_migration_monitor_success(self): # A normal sequence where see all the normal job states domain_info_records = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED), ] self._test_live_migration_monitoring(domain_info_records, [], self.EXPECT_SUCCESS) 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 = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( 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 = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", host.DomainJobInfo( 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 = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", host.DomainJobInfo( 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 = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED), ] self._test_live_migration_monitoring(domain_info_records, [], self.EXPECT_FAILURE) @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 = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( 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 = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED), ] self._test_live_migration_monitoring(domain_info_records, fake_times, self.EXPECT_ABORT) 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 = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED), ] self._test_live_migration_monitoring(domain_info_records, fake_times, self.EXPECT_ABORT) 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.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") def test_live_migration_main(self, mock_running, mock_guest, mock_monitor, mock_thread): 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 = {} mock_guest.return_value = guest def fake_post(): pass def fake_recover(): pass drvr._live_migration(self.context, instance, "fakehost", fake_post, fake_recover, False, migrate_data) 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", False, migrate_data, dom) mock_monitor.assert_called_once_with( self.context, instance, guest, "fakehost", fake_post, fake_recover, False, migrate_data, dom, AnyEventletEvent()) def _do_test_create_images_and_backing(self, disk_type): 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, self.test_instance, fallback_from_host=None) self.mox.ReplayAll() self.stubs.Set(os.path, 'exists', lambda *args: False) drvr._create_images_and_backing(self.context, self.test_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) disk_info = [ {u'backing_file': u'fake_image_backing_file', u'disk_size': 10747904, u'path': u'disk_path', u'type': u'qcow2', u'virt_disk_size': 25165824}] self.test_instance.update({'user_id': 'fake-user', 'os_type': None, 'project_id': 'fake-project'}) instance = objects.Instance(**self.test_instance) 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) disk_info = [ {u'backing_file': u'fake_image_backing_file', u'disk_size': 10747904, u'path': u'disk_path', u'type': u'qcow2', u'virt_disk_size': 25165824}] 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': 'fake_kernel_id', 'ramdisk_id': 'fake_ramdisk_id', 'project_id': 'fake-project'}) instance = objects.Instance(**self.test_instance) with contextlib.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="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, 'fake_image_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'], user_id=self.test_instance['user_id'], project_id=self.test_instance['project_id'], max_size=25165824), mock.call(self.context, kernel_path, self.test_instance['kernel_id'], self.test_instance['user_id'], self.test_instance['project_id']), mock.call(self.context, ramdisk_path, self.test_instance['ramdisk_id'], self.test_instance['user_id'], self.test_instance['project_id']), ]) @mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image') @mock.patch.object(os.path, 'exists', return_value=True) def test_create_images_and_backing_images_exist(self, mock_exists, mock_fetch_image): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) disk_info = [ {u'backing_file': u'fake_image_backing_file', u'disk_size': 10747904, u'path': u'disk_path', u'type': u'qcow2', u'virt_disk_size': 25165824}] 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) 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) disk_info = [ {u'backing_file': u'fake_image_backing_file', u'disk_size': 10747904, u'path': u'disk_path', u'type': u'qcow2', u'virt_disk_size': 25165824}, {u'backing_file': u'ephemeral_1_default', u'disk_size': 393216, u'over_committed_disk_size': 1073348608, u'path': u'disk_eph_path', u'type': u'qcow2', u'virt_disk_size': 1073741824}] base_dir = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name) instance = objects.Instance(**self.test_instance) with contextlib.nested( mock.patch.object(drvr, '_fetch_instance_kernel_ramdisk'), mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image'), mock.patch.object(drvr, '_create_ephemeral'), mock.patch.object(imagebackend.Image, 'verify_base_size') ) as (fetch_kernel_ramdisk_mock, fetch_image_mock, create_ephemeral_mock, verify_base_size_mock): drvr._create_images_and_backing(self.context, instance, "/fake/instance/dir", disk_info) self.assertEqual(len(create_ephemeral_mock.call_args_list), 1) m_args, m_kwargs = create_ephemeral_mock.call_args_list[0] self.assertEqual( os.path.join(base_dir, 'ephemeral_1_default'), 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( os.path.join(base_dir, 'fake_image_backing_file'), m_kwargs['target']) verify_base_size_mock.assert_has_calls([ mock.call(os.path.join(base_dir, 'fake_image_backing_file'), 25165824), mock.call(os.path.join(base_dir, 'ephemeral_1_default'), 1073741824) ]) def test_create_images_and_backing_disk_info_none(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock(drvr, '_fetch_instance_kernel_ramdisk') drvr._fetch_instance_kernel_ramdisk(self.context, self.test_instance, fallback_from_host=None) self.mox.ReplayAll() drvr._create_images_and_backing(self.context, self.test_instance, "/fake/instance/dir", None) def test_pre_live_migration_works_correctly_mocked(self): # 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() result = drvr.pre_live_migration( c, instance, vol, nw_info, None, migrate_data={"block_migration": False}) target_ret = { 'graphics_listen_addrs': {'spice': '127.0.0.1', 'vnc': '127.0.0.1'}, '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(result, target_ret) def test_pre_live_migration_block_with_config_drive_mocked(self): # 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) def fake_true(*args, **kwargs): return True self.stubs.Set(configdrive, 'required_by', fake_true) instance = objects.Instance(**self.test_instance) c = context.get_admin_context() self.assertRaises(exception.NoLiveMigrationForConfigDriveInLibVirt, drvr.pre_live_migration, c, instance, vol, None, None, {'is_shared_instance_path': False, 'is_shared_block_storage': False}) @mock.patch('nova.virt.driver.block_device_info_get_mapping', return_value=()) @mock.patch('nova.virt.configdrive.required_by', return_value=True) def test_pre_live_migration_block_with_config_drive_mocked_with_vfat( self, mock_required_by, 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) res_data = drvr.pre_live_migration( self.context, instance, vol, [], None, {'is_shared_instance_path': False, 'is_shared_block_storage': False}) 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'}, 'serial_listen_addr': '127.0.0.1', 'volume': {}}, res_data) 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 = {'is_shared_instance_path': False, 'is_volume_backed': True, 'block_migration': False, 'instance_relative_path': inst_ref['name'] } 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'}, '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, 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({}) self.assertRaises(processutils.ProcessExecutionError, drvr.pre_live_migration, self.context, instance, block_device_info=None, network_info=[], disk_info=disk_info_json) 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({}) drvr.pre_live_migration(self.context, instance, block_device_info=None, network_info=[], disk_info=disk_info_json) def test_pre_live_migration_image_not_created_with_shared_storage(self): migrate_data_set = [{'is_shared_block_storage': False, 'block_migration': False}, {'is_shared_block_storage': True, 'block_migration': False}, {'is_shared_block_storage': False, 'block_migration': True}] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) # creating mocks with contextlib.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, dict) def test_pre_live_migration_with_not_shared_instance_path(self): migrate_data = {'is_shared_block_storage': False, 'is_shared_instance_path': False} 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 contextlib.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, dict) def test_pre_live_migration_block_migrate_fails(self): bdms = [{ 'connection_info': { 'serial': '12345', u'data': { 'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.t-lun-X' } }, 'mount_device': '/dev/sda'}] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), mock.patch.object(drvr, 'ensure_filtering_rules_for_instance'), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr, '_connect_volume'), mock.patch.object(driver, 'block_device_info_get_mapping', return_value=bdms)): disk_info_json = jsonutils.dumps({}) self.assertRaises(exception.MigrationError, drvr.pre_live_migration, self.context, instance, block_device_info=None, network_info=[], disk_info=disk_info_json, migrate_data={}) 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').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 contextlib.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').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 9011 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.stubs, 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) image_meta = self.test_image_meta # 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)) def test_spawn_without_image_meta(self): self.create_image_called = False def fake_none(*args, **kwargs): return def fake_create_image(*args, **kwargs): self.create_image_called = True 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_image', fake_create_image) self.stubs.Set(drvr, '_create_domain_and_network', fake_none) self.stubs.Set(drvr, 'get_info', fake_get_info) drvr.spawn(self.context, instance, self.test_image_meta, [], None) self.assertTrue(self.create_image_called) drvr.spawn(self.context, instance, self.test_image_meta, [], None) self.assertTrue(self.create_image_called) 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} ] } # 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, self.test_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, self.test_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, self.test_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 = {} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), 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_image', fake_none) self.stubs.Set(drvr, '_create_domain_and_network', fake_none) self.stubs.Set(drvr, 'get_info', fake_get_info) drvr._conn.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')]) drvr.spawn(self.context, instance, self.test_image_meta, [], None) def test_chown_disk_config_for_instance(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) self.mox.StubOutWithMock(fake_libvirt_utils, 'get_instance_path') self.mox.StubOutWithMock(os.path, 'exists') self.mox.StubOutWithMock(fake_libvirt_utils, 'chown') fake_libvirt_utils.get_instance_path(instance).AndReturn('/tmp/uuid') os.path.exists('/tmp/uuid/disk.config').AndReturn(True) fake_libvirt_utils.chown('/tmp/uuid/disk.config', os.getuid()) self.mox.ReplayAll() drvr._chown_disk_config_for_instance(instance) def _test_create_image_plain(self, os_type='', filename='', mkfs=False): gotFiles = [] def fake_image(self, instance, name, image_type=''): class FakeImage(imagebackend.Image): def __init__(self, instance, name, is_block_dev=False): self.path = os.path.join(instance['name'], name) self.is_block_dev = is_block_dev def create_image(self, prepare_template, base, size, *args, **kwargs): pass def cache(self, fetch_func, filename, size=None, *args, **kwargs): gotFiles.append({'filename': filename, 'size': size}) def snapshot(self, name): pass return FakeImage(instance, name) def fake_none(*args, **kwargs): return def fake_get_info(instance): return hardware.InstanceInfo(state=power_state.RUNNING) # Stop 'libvirt_driver._create_image' touching filesystem self.stubs.Set(nova.virt.libvirt.imagebackend.Backend, "image", fake_image) 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) drvr._create_image(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 _create_image_helper(self, callback, suffix=''): gotFiles = [] imported_files = [] def fake_image(self, instance, name, image_type=''): class FakeImage(imagebackend.Image): def __init__(self, instance, name, is_block_dev=False): self.path = os.path.join(instance['name'], name) self.is_block_dev = is_block_dev def create_image(self, prepare_template, base, size, *args, **kwargs): pass def cache(self, fetch_func, filename, size=None, *args, **kwargs): gotFiles.append({'filename': filename, 'size': size}) def import_file(self, instance, local_filename, remote_filename): imported_files.append((local_filename, remote_filename)) def snapshot(self, name): pass return FakeImage(instance, name) def fake_none(*args, **kwargs): return def fake_get_info(instance): return hardware.InstanceInfo(state=power_state.RUNNING) # Stop 'libvirt_driver._create_image' touching filesystem self.stubs.Set(nova.virt.libvirt.imagebackend.Backend, "image", fake_image) 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) drvr._create_image(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) def test_create_image_with_configdrive(self): 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) self.assertTrue(imported_files[0][0].endswith('/disk.config')) self.assertEqual('disk.config', imported_files[0][1]) def test_create_image_with_configdrive_rescue(self): 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, suffix='.rescue') self.assertTrue(imported_files[0][0].endswith('/disk.config.rescue')) self.assertEqual('disk.config.rescue', 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', 'fake-max-size') # 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(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, max_size=20, 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 contextlib.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')): 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, max_size=20) 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, max_size=20) 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) 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, 'warn') @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 contextlib.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 contextlib.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)): 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 contextlib.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)): 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.stubs, 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.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): 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.stubs, 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) # 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') @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.stubs, 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_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.stubs, 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) @mock.patch.object(FakeVirtDomain, 'detachDeviceFlags') @mock.patch.object(utils, 'get_image_from_system_metadata', return_value=None) def test_detach_sriov_ports(self, mock_get_image_metadata, mock_detachDeviceFlags, mock_has_min_version): instance = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT instance.info_cache = objects.InstanceInfoCache( network_info=network_info) domain = FakeVirtDomain() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) guest = libvirt_guest.Guest(domain) drvr._detach_sriov_ports(self.context, instance, guest) mock_get_image_metadata.assert_called_once_with( instance.system_metadata) self.assertTrue(mock_detachDeviceFlags.called) 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.stubs, 1) block_device_info = None drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) guest = libvirt_guest.Guest('fake_dom') with contextlib.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") def test_disk_over_committed_size_total(self, mock_list): # Ensure destroy calls managedSaveRemove for saved instance. class DiagFakeDomain(object): def __init__(self, name): self._name = name def ID(self): return 1 def name(self): return self._name def UUIDString(self): return "19479fee-07a5-49bb-9138-d3738280d63c" def XMLDesc(self, flags): return "<domain/>" mock_list.return_value = [ DiagFakeDomain("instance0000001"), DiagFakeDomain("instance0000002")] 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) 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_with() self.assertTrue(mock_info.called) @mock.patch.object(host.Host, "list_instance_domains") def test_disk_over_committed_size_total_eperm(self, mock_list): # Ensure destroy calls managedSaveRemove for saved instance. class DiagFakeDomain(object): def __init__(self, name): self._name = name def ID(self): return 1 def name(self): return self._name def UUIDString(self): return "19479fee-07a5-49bb-9138-d3738280d63c" def XMLDesc(self, flags): return "<domain/>" mock_list.return_value = [ DiagFakeDomain("instance0000001"), DiagFakeDomain("instance0000002")] 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'}]} def side_effect(name, dom): if name == 'instance0000001': raise OSError(errno.EACCES, 'Permission denied') if name == 'instance0000002': 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 result = drvr._get_disk_over_committed_size_total() self.assertEqual(21474836480, result) mock_list.assert_called_with() @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')) def test_disk_over_committed_size_total_bdm_not_found(self, 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.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": {"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) 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, "phys_function": '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, "phys_function": '0000:04:00.3', } 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 contextlib.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 = utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION) - 1 mock_version.return_value = utils.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 contextlib.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 = utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) - 1 mock_version.return_value = utils.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 = utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) mock_version.return_value = utils.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) timeutils.set_time_override(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) timeutils.set_time_override(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) timeutils.set_time_override(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) timeutils.set_time_override(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) timeutils.set_time_override(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(timeutils, 'utcnow') @mock.patch.object(host.Host, 'get_domain') def test_diagnostic_full_with_multiple_interfaces(self, mock_get_domain, mock_utcnow): 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) mock_utcnow.return_value = 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() @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() 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 contextlib.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 contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), 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 contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), 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_create_images_and_backing, 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 contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), 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 contextlib.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.stubs, 1) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) fake_image_meta = {'id': instance['image_ref']} fake_image_meta_obj = objects.ImageMeta.from_dict( fake_image_meta) 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_obj, 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 = {'id': 'fake'} root_bdm = {'source_type': 'image', 'detination_type': 'volume', 'image_id': 'fake_id'} self.flags(virt_type='fake_libvirt_type', 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, 'fake_libvirt_type', mox.IsA(objects.ImageMeta), 'disk').InAnyOrder().\ AndReturn('virtio') blockinfo.get_disk_bus_for_device_type(instance, 'fake_libvirt_type', mox.IsA(objects.ImageMeta), 'cdrom').InAnyOrder().\ AndReturn('ide') blockinfo.get_root_info(instance, 'fake_libvirt_type', mox.IsA(objects.ImageMeta), 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.FS_FORMAT_EXT2, disk.FS_FORMAT_EXT3, disk.FS_FORMAT_EXT4, disk.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 9011 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 = {} 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.stubs, 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) block_device_info = {'block_device_mapping': driver_block_device.convert_volumes([ 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'][0]['connection_info'] = ( {'driver_volume_type': 'iscsi'}) with contextlib.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='fake-uuid', image_ref='my_fake_image') with contextlib.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 contextlib.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 contextlib.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) 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': {}} bdi = {'block_device_mapping': driver_block_device.convert_volumes([ fake_block_device.FakeDbBlockDeviceDict({ 'id': 1, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/vdc'}) ])} 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 contextlib.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('nova.virt.driver.block_device_info_get_mapping') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.' '_get_serial_ports_from_instance') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain') def test_cleanup_serial_console_enabled( self, undefine, get_ports, block_device_info_get_mapping): self.flags(enabled="True", group='serial_console') instance = 'i1' network_info = {} bdm_info = {} firewall_driver = mock.MagicMock() get_ports.return_value = iter([('127.0.0.1', 10000)]) block_device_info_get_mapping.return_value = () # We want to ensure undefine_domain is called after # lookup_domain. def undefine_domain(instance): get_ports.side_effect = Exception("domain undefined") undefine.side_effect = undefine_domain drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) drvr.firewall_driver = firewall_driver drvr.cleanup( 'ctx', instance, network_info, block_device_info=bdm_info, destroy_disks=False, destroy_vifs=False) get_ports.assert_called_once_with(instance) undefine.assert_called_once_with(instance) firewall_driver.unfilter_instance.assert_called_once_with( instance, network_info=network_info) block_device_info_get_mapping.assert_called_once_with(bdm_info) @mock.patch('nova.virt.driver.block_device_info_get_mapping') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.' '_get_serial_ports_from_instance') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain') def test_cleanup_serial_console_domain_gone( self, undefine, get_ports, block_device_info_get_mapping): self.flags(enabled="True", group='serial_console') instance = {'name': 'i1'} network_info = {} bdm_info = {} firewall_driver = mock.MagicMock() block_device_info_get_mapping.return_value = () # Ensure _get_serial_ports_from_instance raises same exception # that would have occurred if domain was gone. def exception_with_yield(instance): raise exception.InstanceNotFound("domain undefined") yield get_ports.side_effect = exception_with_yield drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) drvr.firewall_driver = firewall_driver drvr.cleanup( 'ctx', instance, network_info, block_device_info=bdm_info, destroy_disks=False, destroy_vifs=False) get_ports.assert_called_once_with(instance) undefine.assert_called_once_with(instance) firewall_driver.unfilter_instance.assert_called_once_with( instance, network_info=network_info) block_device_info_get_mapping.assert_called_once_with(bdm_info) 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 = {} 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.virt.block_device.DriverVolumeBlockDevice.save') @mock.patch('nova.objects.block_device.BlockDeviceMapping.' 'get_by_volume_id') @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_id, volume_save, swap_volume, disconnect_volume): 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': 'fake-instance', 'device_name': '/dev/vdb', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-volume-id-2', 'boot_index': 0})) get_by_volume_id.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() def test_live_snapshot(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) mock_dom = mock.MagicMock() with contextlib.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'), ) as (mock_define, mock_size, mock_backing, mock_create_cow, mock_chown, mock_snapshot): 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) image_meta = objects.ImageMeta.from_dict(self.test_image_meta) drvr._live_snapshot(self.context, self.test_instance, guest, srcfile, dstfile, "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) mock_backing.assert_called_once_with(srcfile, basename=False) 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.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) @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.stubs, 1), image_meta, disk_info) self.assertEqual("parallels", cfg.virt_type) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, 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(self): 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) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), image_meta, {'mapping': {'disk': {}}}) self.assertEqual("parallels", cfg.virt_type) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, cfg.vcpus) self.assertEqual(vm_mode.EXE, cfg.os_type) self.assertEqual("/sbin/init", cfg.os_init_path) self.assertIsNone(cfg.os_root) self.assertEqual(4, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestFilesys) fs = cfg.devices[0] self.assertEqual(fs.source_type, "file") self.assertEqual(fs.driver_type, "ploop") self.assertEqual(fs.target_dir, "/") self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[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'} info = {'block_device_mapping': driver_block_device.convert_volumes([ fake_block_device.FakeDbBlockDeviceDict( {'id': 0, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/sda'}), ])} 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.stubs, 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(2 * units.Mi, cfg.memory) self.assertEqual(1, 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) 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"], 1001000) 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() 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) inst = {} inst['id'] = 1 inst['uuid'] = '52d3b512-1152-431f-a8f7-28f0288a622b' inst['os_type'] = 'linux' inst['image_ref'] = '1' 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.update(params) return objects.Instance(flavor=flavor, old_flavor=None, new_flavor=None, **inst) @staticmethod def _disk_info(): # 10G root and 512M swap disk disk_info = [{'disk_size': 1, 'type': 'qcow2', 'virt_disk_size': 10737418240, 'path': '/test/disk', 'backing_file': '/base/disk'}, {'disk_size': 1, 'type': 'qcow2', 'virt_disk_size': 536870912, 'path': '/test/disk.swap', 'backing_file': '/base/swap_512'}] return jsonutils.dumps(disk_info) 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.stubs.Set(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. """ disk_info = self._disk_info() 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) ins_ref = self._create_instance(params=params_for_instance) # dest is different host case out = self.drvr.migrate_disk_and_power_off( context.get_admin_context(), ins_ref, '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(), ins_ref, '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, '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 disk_info = self._disk_info() 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) # Original instance config instance = self._create_instance({'root_gb': 10, 'ephemeral_gb': 0}) # 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. """ def fake_get_instance_disk_info(instance, xml=None, block_device_info=None): return self._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) ins_ref = self._create_instance() 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, ins_ref, '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 = self._disk_info() 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 = self._disk_info() 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 = self._disk_info() 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) 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): instance_data = {'root_gb': 10, 'ephemeral_gb': 20, 'swap_gb': 30} inst = objects.Instance(**instance_data) info = {'path': '/path/disk'} self.assertEqual(10 * units.Gi, self.drvr._disk_size_from_instance(inst, info)) info = {'path': '/path/disk.local'} self.assertEqual(20 * units.Gi, self.drvr._disk_size_from_instance(inst, info)) info = {'path': '/path/disk.swap'} self.assertEqual(0, self.drvr._disk_size_from_instance(inst, info)) @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 contextlib.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 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) 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): 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): 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) ins_ref = self._create_instance() 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' self.drvr.finish_migration( context.get_admin_context(), migration, ins_ref, self._disk_info(), [], self.test_image_meta, resize_instance, None, power_on) 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): class FakeLoopingCall(object): def start(self, *a, **k): return self def wait(self): return None context = 'fake_context' instance = self._create_instance() self.mox.StubOutWithMock(libvirt_utils, 'get_instance_path') self.mox.StubOutWithMock(os.path, 'exists') self.mox.StubOutWithMock(shutil, 'rmtree') self.mox.StubOutWithMock(utils, 'execute') self.stubs.Set(blockinfo, 'get_disk_info', lambda *a: None) self.stubs.Set(self.drvr, '_get_guest_xml', lambda *a, **k: None) self.stubs.Set(self.drvr, '_create_domain_and_network', lambda *a, **kw: None) self.stubs.Set(loopingcall, 'FixedIntervalLoopingCall', lambda *a, **k: FakeLoopingCall()) libvirt_utils.get_instance_path(instance).AndReturn('/fake/foo') os.path.exists('/fake/foo_resize').AndReturn(backup_made) if backup_made: if del_inst_failed: os_error = OSError(errno.ENOENT, 'No such file or directory') shutil.rmtree('/fake/foo').AndRaise(os_error) else: shutil.rmtree('/fake/foo') utils.execute('mv', '/fake/foo_resize', '/fake/foo') self.mox.ReplayAll() self.drvr.finish_revert_migration(context, instance, []) 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 contextlib.nested( 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_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.stubs, 1)) self.mox.ReplayAll() self.drvr.confirm_migration("migration_ref", ins_ref, _fake_network_info(self.stubs, 1)) def test_cleanup_resize_same_host(self): CONF.set_override('policy_dirs', []) ins_ref = self._create_instance({'host': CONF.host}) def fake_os_path_exists(path): return True self.stubs.Set(os.path, 'exists', fake_os_path_exists) self.mox.StubOutWithMock(libvirt_utils, 'get_instance_path') self.mox.StubOutWithMock(utils, 'execute') libvirt_utils.get_instance_path(ins_ref, forceold=True).AndReturn('/fake/inst') utils.execute('rm', '-rf', '/fake/inst_resize', delay_on_retry=True, attempts=5) self.mox.ReplayAll() self.drvr._cleanup_resize(ins_ref, _fake_network_info(self.stubs, 1)) def test_cleanup_resize_not_same_host(self): CONF.set_override('policy_dirs', []) host = 'not' + CONF.host ins_ref = self._create_instance({'host': host}) def fake_os_path_exists(path): return True def fake_undefine_domain(instance): pass def fake_unplug_vifs(instance, network_info, ignore_errors=False): pass def fake_unfilter_instance(instance, network_info): pass self.stubs.Set(os.path, 'exists', fake_os_path_exists) self.stubs.Set(self.drvr, '_undefine_domain', fake_undefine_domain) self.stubs.Set(self.drvr, 'unplug_vifs', fake_unplug_vifs) self.stubs.Set(self.drvr.firewall_driver, 'unfilter_instance', fake_unfilter_instance) self.mox.StubOutWithMock(libvirt_utils, 'get_instance_path') self.mox.StubOutWithMock(utils, 'execute') libvirt_utils.get_instance_path(ins_ref, forceold=True).AndReturn('/fake/inst') utils.execute('rm', '-rf', '/fake/inst_resize', delay_on_retry=True, attempts=5) self.mox.ReplayAll() self.drvr._cleanup_resize(ins_ref, _fake_network_info(self.stubs, 1)) 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='fake-uuid', id=1) self.flags(images_volume_group='vols', group='libvirt') exists.return_value = True listlvs.return_value = ['fake-uuid_foo', 'other-uuid_foo'] disks = self.drvr._lvm_disks(instance) self.assertEqual(['/dev/vols/fake-uuid_foo'], 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.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 check_image_exists(self): if self.path == '/fail/path': return False return True 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(**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, 'suffix': '' } 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.stubs, 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 = {'id': instance.image_ref} fake_image_meta_obj = objects.ImageMeta.from_dict( fake_image_meta) expected = self.drvr.vif_driver.get_config( instance, network_info[0], fake_image_meta_obj, 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)) def test_rescue(self): instance = self._create_instance({'config_drive': 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>") network_info = _fake_network_info(self.stubs, 1) self.mox.StubOutWithMock(self.drvr, '_get_existing_domain_xml') self.mox.StubOutWithMock(libvirt_utils, 'write_to_file') self.mox.StubOutWithMock(imagebackend.Backend, 'image') self.mox.StubOutWithMock(imagebackend.Image, 'cache') self.mox.StubOutWithMock(self.drvr, '_get_guest_xml') self.mox.StubOutWithMock(self.drvr, '_destroy') self.mox.StubOutWithMock(self.drvr, '_create_domain') self.drvr._get_existing_domain_xml(mox.IgnoreArg(), mox.IgnoreArg()).MultipleTimes().AndReturn(dummyxml) libvirt_utils.write_to_file(mox.IgnoreArg(), mox.IgnoreArg()) libvirt_utils.write_to_file(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) imagebackend.Backend.image(instance, 'kernel.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'ramdisk.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'disk.rescue', 'default' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Image.cache(context=mox.IgnoreArg(), fetch_func=mox.IgnoreArg(), filename=mox.IgnoreArg(), image_id=mox.IgnoreArg(), project_id=mox.IgnoreArg(), user_id=mox.IgnoreArg()).MultipleTimes() imagebackend.Image.cache(context=mox.IgnoreArg(), fetch_func=mox.IgnoreArg(), filename=mox.IgnoreArg(), image_id=mox.IgnoreArg(), project_id=mox.IgnoreArg(), size=None, user_id=mox.IgnoreArg()) image_meta = {'id': 'fake', 'name': 'fake'} self.drvr._get_guest_xml(mox.IgnoreArg(), instance, network_info, mox.IgnoreArg(), mox.IsA(objects.ImageMeta), rescue=mox.IgnoreArg(), write_to_disk=mox.IgnoreArg() ).AndReturn(dummyxml) self.drvr._destroy(instance) self.drvr._create_domain(mox.IgnoreArg()) self.mox.ReplayAll() rescue_password = 'fake_password' self.drvr.rescue(self.context, instance, network_info, image_meta, rescue_password) self.mox.VerifyAll() @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='fake=uuid', 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') rescue_file = os.path.join('/path', 'rescue.file') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with contextlib.nested( mock.patch.object(drvr, '_destroy'), mock.patch.object(drvr, '_create_domain'), mock.patch.object(libvirt_utils, 'file_delete'), 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]) ) as (mock_destroy, mock_create, mock_del, mock_lvm_disks, mock_remove_volumes, mock_glob): drvr.unrescue(instance, None) 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(rescue_file, mock_del.call_args_list[1][0][0]) mock_remove_volumes.assert_called_once_with(['lvm.rescue']) @mock.patch( 'nova.virt.configdrive.ConfigDriveBuilder.add_instance_metadata') @mock.patch('nova.virt.configdrive.ConfigDriveBuilder.make_drive') def test_rescue_config_drive(self, mock_make, mock_add): instance = self._create_instance() uuid = instance.uuid configdrive_path = uuid + '/disk.config.rescue' 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>") network_info = _fake_network_info(self.stubs, 1) self.mox.StubOutWithMock(self.drvr, '_get_existing_domain_xml') self.mox.StubOutWithMock(libvirt_utils, 'write_to_file') self.mox.StubOutWithMock(imagebackend.Backend, 'image') self.mox.StubOutWithMock(imagebackend.Image, 'cache') self.mox.StubOutWithMock(instance_metadata.InstanceMetadata, '__init__') self.mox.StubOutWithMock(self.drvr, '_get_guest_xml') self.mox.StubOutWithMock(self.drvr, '_destroy') self.mox.StubOutWithMock(self.drvr, '_create_domain') self.drvr._get_existing_domain_xml(mox.IgnoreArg(), mox.IgnoreArg()).MultipleTimes().AndReturn(dummyxml) libvirt_utils.write_to_file(mox.IgnoreArg(), mox.IgnoreArg()) libvirt_utils.write_to_file(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) imagebackend.Backend.image(instance, 'kernel.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'ramdisk.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'disk.rescue', 'default' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'disk.config.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Image.cache(context=mox.IgnoreArg(), fetch_func=mox.IgnoreArg(), filename=mox.IgnoreArg(), image_id=mox.IgnoreArg(), project_id=mox.IgnoreArg(), user_id=mox.IgnoreArg()).MultipleTimes() imagebackend.Image.cache(context=mox.IgnoreArg(), fetch_func=mox.IgnoreArg(), filename=mox.IgnoreArg(), image_id=mox.IgnoreArg(), project_id=mox.IgnoreArg(), size=None, user_id=mox.IgnoreArg()) instance_metadata.InstanceMetadata.__init__(mox.IgnoreArg(), content=mox.IgnoreArg(), extra_md=mox.IgnoreArg(), network_info=mox.IgnoreArg()) image_meta = {'id': 'fake', 'name': 'fake'} self.drvr._get_guest_xml(mox.IgnoreArg(), instance, network_info, mox.IgnoreArg(), mox.IsA(objects.ImageMeta), rescue=mox.IgnoreArg(), write_to_disk=mox.IgnoreArg() ).AndReturn(dummyxml) self.drvr._destroy(instance) self.drvr._create_domain(mox.IgnoreArg()) self.mox.ReplayAll() rescue_password = 'fake_password' self.drvr.rescue(self.context, instance, network_info, image_meta, rescue_password) self.mox.VerifyAll() mock_add.assert_any_call(mock.ANY) expected_call = [mock.call(os.path.join(CONF.instances_path, configdrive_path))] mock_make.assert_has_calls(expected_call) @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='fake-uuid', 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='fake-uuid', 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='fake-uuid', 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='fake-uuid', 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='fake-uuid', 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='fake-uuid', 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='fake-uuid', 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='fake-uuid', 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='fake-uuid', 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='fake-uuid', id=1) self.assertTrue(drvr.instance_on_disk(instance)) def test_get_interfaces(self): dom_xml = """ <domain type="qemu"> <devices> <interface type="ethernet"> <mac address="fe:eb:da:ed:ef:ac"/> <model type="virtio"/> <target dev="eth0"/> </interface> <interface type="bridge"> <mac address="ca:fe:de:ad:be:ef"/> <model type="virtio"/> <target dev="br0"/> </interface> </devices> </domain>""" list_interfaces = ['eth0', 'br0'] drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertEqual(list_interfaces, drv._get_interfaces(dom_xml)) 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) 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])) 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) def test_tpool_execute_calls_libvirt(self): 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.assertEqual(True, 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_id') def test_volume_refresh_connection_info(self, mock_get_by_volume_id, mock_refresh_connection_info): fake_bdm = fake_block_device.FakeDbBlockDeviceDict({ 'id': 123, 'instance_uuid': 'fake-instance', 'device_name': '/dev/sdb', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-volume-id-1', 'connection_info': '{"fake": "connection_info"}'}) mock_get_by_volume_id.return_value = fake_bdm self.drvr._volume_refresh_connection_info(self.c, self.inst, self.volume_uuid) mock_get_by_volume_id.assert_called_once_with(self.c, self.volume_uuid) mock_refresh_connection_info.assert_called_once_with(self.c, self.inst, 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, snap_flags_q) else: domain.snapshotCreateXML(snap_xml_src, snap_flags_q).\ AndRaise(fakelibvirt.libvirtError( 'quiescing failed, no qemu-ga')) domain.snapshotCreateXML(snap_xml_src, snap_flags).AndReturn(0) self.mox.ReplayAll() self.drvr._volume_snapshot_create(self.c, instance, domain, 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, snap_flags_q) else: domain.snapshotCreateXML(snap_xml_src, snap_flags_q).\ AndRaise(fakelibvirt.libvirtError( 'quiescing failed, no qemu-ga')) domain.snapshotCreateXML(snap_xml_src, snap_flags).AndReturn(0) self.mox.ReplayAll() self.drvr._volume_snapshot_create(self.c, instance, domain, 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='xxx', 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) def test_volume_snapshot_create_outer_success(self): instance = objects.Instance(**self.inst) domain = 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_create') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._volume_snapshot_create(self.c, instance, domain, self.volume_uuid, self.create_info['new_file']) self.drvr._volume_api.update_snapshot_status( self.c, self.create_info['snapshot_id'], 'creating') self.mox.StubOutWithMock(self.drvr._volume_api, 'get_snapshot') self.drvr._volume_api.get_snapshot(self.c, self.create_info['snapshot_id']).AndReturn({'status': 'available'}) 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_create(self.c, instance, self.volume_uuid, self.create_info) def test_volume_snapshot_create_outer_failure(self): instance = objects.Instance(**self.inst) domain = 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_create') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._volume_snapshot_create(self.c, instance, domain, 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(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockRebase('vda', 'snap.img', 0, flags=0) domain.blockJobInfo('vda', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vda', flags=0).AndReturn( {'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(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_guest(instance).AndReturn(guest) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockRebase('vda', 'snap.img', 0, flags=fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE) domain.blockJobInfo('vda', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vda', flags=0).AndReturn( {'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_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(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) 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(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockCommit('vda', 'other-snap.img', 'snap.img', 0, flags=fakelibvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE) domain.blockJobInfo('vda', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vda', flags=0).AndReturn({}) 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 contextlib.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(self.drvr._host, 'has_min_version', return_value=True), mock.patch.object(domain, 'blockRebase'), mock.patch.object(domain, 'blockJobInfo', return_value={'cur': 1000, 'end': 1000}) ) as (mock_xmldesc, mock_get_guest, mock_has_min_version, 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_has_min_version.assert_called_once_with((1, 1, 1,)) 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 contextlib.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(self.drvr._host, 'has_min_version', return_value=True), mock.patch.object(domain, 'blockRebase'), mock.patch.object(domain, 'blockJobInfo', return_value={'cur': 1000, 'end': 1000}) ) as (mock_xmldesc, mock_get_guest, mock_has_min_version, 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_has_min_version.assert_called_once_with((1, 1, 1,)) 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.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) 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(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockRebase('vdb', 'vdb[1]', 0, flags=0) domain.blockJobInfo('vdb', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vdb', flags=0).AndReturn( {'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(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockRebase('vdb', 'vdb[1]', 0, flags=fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE) domain.blockJobInfo('vdb', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vdb', flags=0).AndReturn( {'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(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) 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(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockCommit('vdb', 'vdb[0]', 'vdb[1]', 0, flags=fakelibvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE) domain.blockJobInfo('vdb', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vdb', flags=0).AndReturn( {'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, 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.stubs) 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(imagebackend.Image, 'resolve_driver_format') @mock.patch.object(host.Host, 'get_domain') def _snapshot(self, image_id, mock_get_domain, mock_resolve): 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') 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) 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') 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, 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')
yosshy/nova
nova/tests/unit/virt/libvirt/test_driver.py
Python
apache-2.0
667,651
0.000443
import copy from threading import Lock from .metrics_core import Metric class CollectorRegistry(object): """Metric collector registry. Collectors must have a no-argument method 'collect' that returns a list of Metric objects. The returned metrics should be consistent with the Prometheus exposition formats. """ def __init__(self, auto_describe=False): self._collector_to_names = {} self._names_to_collectors = {} self._auto_describe = auto_describe self._lock = Lock() def register(self, collector): """Add a collector to the registry.""" with self._lock: names = self._get_names(collector) duplicates = set(self._names_to_collectors).intersection(names) if duplicates: raise ValueError( 'Duplicated timeseries in CollectorRegistry: {0}'.format( duplicates)) for name in names: self._names_to_collectors[name] = collector self._collector_to_names[collector] = names def unregister(self, collector): """Remove a collector from the registry.""" with self._lock: for name in self._collector_to_names[collector]: del self._names_to_collectors[name] del self._collector_to_names[collector] def _get_names(self, collector): """Get names of timeseries the collector produces.""" desc_func = None # If there's a describe function, use it. try: desc_func = collector.describe except AttributeError: pass # Otherwise, if auto describe is enabled use the collect function. if not desc_func and self._auto_describe: desc_func = collector.collect if not desc_func: return [] result = [] type_suffixes = { 'counter': ['_total', '_created'], 'summary': ['', '_sum', '_count', '_created'], 'histogram': ['_bucket', '_sum', '_count', '_created'], 'gaugehistogram': ['_bucket', '_gsum', '_gcount'], 'info': ['_info'], } for metric in desc_func(): for suffix in type_suffixes.get(metric.type, ['']): result.append(metric.name + suffix) return result def collect(self): """Yields metrics from the collectors in the registry.""" collectors = None with self._lock: collectors = copy.copy(self._collector_to_names) for collector in collectors: for metric in collector.collect(): yield metric def restricted_registry(self, names): """Returns object that only collects some metrics. Returns an object which upon collect() will return only samples with the given names. Intended usage is: generate_latest(REGISTRY.restricted_registry(['a_timeseries'])) Experimental.""" names = set(names) collectors = set() with self._lock: for name in names: if name in self._names_to_collectors: collectors.add(self._names_to_collectors[name]) metrics = [] for collector in collectors: for metric in collector.collect(): samples = [s for s in metric.samples if s[0] in names] if samples: m = Metric(metric.name, metric.documentation, metric.type) m.samples = samples metrics.append(m) class RestrictedRegistry(object): def collect(self): return metrics return RestrictedRegistry() def get_sample_value(self, name, labels=None): """Returns the sample value, or None if not found. This is inefficient, and intended only for use in unittests. """ if labels is None: labels = {} for metric in self.collect(): for s in metric.samples: if s.name == name and s.labels == labels: return s.value return None REGISTRY = CollectorRegistry(auto_describe=True)
cloudera/hue
desktop/core/ext-py/prometheus_client-0.7.1/prometheus_client/registry.py
Python
apache-2.0
4,226
0.000237
#!/usr/bin/env python # # Generated Sat Jul 18 17:11:29 2015 by generateDS.py version 2.16a. # # Command line options: # ('-o', 'meetCI.py') # ('-s', 'meetCI_sub.py') # # Command line arguments: # meetCI.xsd # # Command line: # generateDS.py -o "meetCI.py" -s "meetCI_sub.py" meetCI.xsd # # Current working directory (os.getcwd()): # generateDS-2.16a0 # import sys from lxml import etree as etree_ import ??? as supermod def parsexml_(infile, parser=None, **kwargs): if parser is None: # Use the lxml ElementTree compatible parser so that, e.g., # we ignore comments. parser = etree_.ETCompatXMLParser() doc = etree_.parse(infile, parser=parser, **kwargs) return doc # # Globals # ExternalEncoding = 'ascii' # # Data representation classes # class MeetCISub(supermod.MeetCI): def __init__(self, MachineLearning=None, ExpertSystem=None): super(MeetCISub, self).__init__(MachineLearning, ExpertSystem, ) supermod.MeetCI.subclass = MeetCISub # end class MeetCISub class MachineLearningSub(supermod.MachineLearning): def __init__(self, classification=None, prediction=None): super(MachineLearningSub, self).__init__(classification, prediction, ) supermod.MachineLearning.subclass = MachineLearningSub # end class MachineLearningSub class MultiLayerPerceptronSub(supermod.MultiLayerPerceptron): def __init__(self, inputLayerActivation='Linear', hiddenLayerActivation=None, hiddenLayers=None, outputLayerActivation=None, momentum=None, epochs=None, learningRate=None): super(MultiLayerPerceptronSub, self).__init__(inputLayerActivation, hiddenLayerActivation, hiddenLayers, outputLayerActivation, momentum, epochs, learningRate, ) supermod.MultiLayerPerceptron.subclass = MultiLayerPerceptronSub # end class MultiLayerPerceptronSub class RadialBasisFunctionNetworkSub(supermod.RadialBasisFunctionNetwork): def __init__(self, hiddenNeurons=None, outputLayerActivation=None, momentum=None, epochs=None, learningRate=None): super(RadialBasisFunctionNetworkSub, self).__init__(hiddenNeurons, outputLayerActivation, momentum, epochs, learningRate, ) supermod.RadialBasisFunctionNetwork.subclass = RadialBasisFunctionNetworkSub # end class RadialBasisFunctionNetworkSub class RecurrentNeuralNetworkSub(supermod.RecurrentNeuralNetwork): def __init__(self, RNN_Type=None, hiddenLayerActivation=None, hiddenNeurons=None, outputLayerActivation=None, epochs=None, momentum=None, learningRate=None): super(RecurrentNeuralNetworkSub, self).__init__(RNN_Type, hiddenLayerActivation, hiddenNeurons, outputLayerActivation, epochs, momentum, learningRate, ) supermod.RecurrentNeuralNetwork.subclass = RecurrentNeuralNetworkSub # end class RecurrentNeuralNetworkSub class RandomForestSub(supermod.RandomForest): def __init__(self, nTrees=None, maxDepth=None, maxLeafNodes=None, minSamplesSplit=None, minSamplesLeaf=None, minFractionLeaf=None): super(RandomForestSub, self).__init__(nTrees, maxDepth, maxLeafNodes, minSamplesSplit, minSamplesLeaf, minFractionLeaf, ) supermod.RandomForest.subclass = RandomForestSub # end class RandomForestSub class SupportVectorMachineSub(supermod.SupportVectorMachine): def __init__(self, kernel=None, degree=None, gamma=None, coef=None, tol=None, maxIter=None): super(SupportVectorMachineSub, self).__init__(kernel, degree, gamma, coef, tol, maxIter, ) supermod.SupportVectorMachine.subclass = SupportVectorMachineSub # end class SupportVectorMachineSub class classificationSub(supermod.classification): def __init__(self, datafile=None, input=None, output=None, classes=None, split=None, delimiter=None, algorithm=None): super(classificationSub, self).__init__(datafile, input, output, classes, split, delimiter, algorithm, ) supermod.classification.subclass = classificationSub # end class classificationSub class predictionSub(supermod.prediction): def __init__(self, datafile=None, input=None, output=None, classes=None, split=None, delimiter=None, algorithm=None): super(predictionSub, self).__init__(datafile, input, output, classes, split, delimiter, algorithm, ) supermod.prediction.subclass = predictionSub # end class predictionSub class clauseTypeSub(supermod.clauseType): def __init__(self, extensiontype_=None): super(clauseTypeSub, self).__init__(extensiontype_, ) supermod.clauseType.subclass = clauseTypeSub # end class clauseTypeSub class greaterThanTypeSub(supermod.greaterThanType): def __init__(self, value2=None, value1=None): super(greaterThanTypeSub, self).__init__(value2, value1, ) supermod.greaterThanType.subclass = greaterThanTypeSub # end class greaterThanTypeSub class greaterThanOrEqualTypeSub(supermod.greaterThanOrEqualType): def __init__(self, value2=None, value1=None): super(greaterThanOrEqualTypeSub, self).__init__(value2, value1, ) supermod.greaterThanOrEqualType.subclass = greaterThanOrEqualTypeSub # end class greaterThanOrEqualTypeSub class lessThanTypeSub(supermod.lessThanType): def __init__(self, value2=None, value1=None): super(lessThanTypeSub, self).__init__(value2, value1, ) supermod.lessThanType.subclass = lessThanTypeSub # end class lessThanTypeSub class lessThanOrEqualTypeSub(supermod.lessThanOrEqualType): def __init__(self, value2=None, value1=None): super(lessThanOrEqualTypeSub, self).__init__(value2, value1, ) supermod.lessThanOrEqualType.subclass = lessThanOrEqualTypeSub # end class lessThanOrEqualTypeSub class equalTypeSub(supermod.equalType): def __init__(self, value2=None, value1=None): super(equalTypeSub, self).__init__(value2, value1, ) supermod.equalType.subclass = equalTypeSub # end class equalTypeSub class notEqualTypeSub(supermod.notEqualType): def __init__(self, value2=None, value1=None): super(notEqualTypeSub, self).__init__(value2, value1, ) supermod.notEqualType.subclass = notEqualTypeSub # end class notEqualTypeSub class betweenTypeSub(supermod.betweenType): def __init__(self, max=None, value=None, min=None): super(betweenTypeSub, self).__init__(max, value, min, ) supermod.betweenType.subclass = betweenTypeSub # end class betweenTypeSub class notBetweenTypeSub(supermod.notBetweenType): def __init__(self, max=None, value=None, min=None): super(notBetweenTypeSub, self).__init__(max, value, min, ) supermod.notBetweenType.subclass = notBetweenTypeSub # end class notBetweenTypeSub class orTypeSub(supermod.orType): def __init__(self, clause=None): super(orTypeSub, self).__init__(clause, ) supermod.orType.subclass = orTypeSub # end class orTypeSub class andTypeSub(supermod.andType): def __init__(self, clause=None): super(andTypeSub, self).__init__(clause, ) supermod.andType.subclass = andTypeSub # end class andTypeSub class factTypeSub(supermod.factType): def __init__(self, name=None, extensiontype_=None): super(factTypeSub, self).__init__(name, extensiontype_, ) supermod.factType.subclass = factTypeSub # end class factTypeSub class predicateTypeSub(supermod.predicateType): def __init__(self, name=None, value=None): super(predicateTypeSub, self).__init__(name, value, ) supermod.predicateType.subclass = predicateTypeSub # end class predicateTypeSub class structTypeSub(supermod.structType): def __init__(self, name=None, comment=None, field=None): super(structTypeSub, self).__init__(name, comment, field, ) supermod.structType.subclass = structTypeSub # end class structTypeSub class instanceTypeSub(supermod.instanceType): def __init__(self, name=None, type_=None, comment=None, field=None): super(instanceTypeSub, self).__init__(name, type_, comment, field, ) supermod.instanceType.subclass = instanceTypeSub # end class instanceTypeSub class actionTypeSub(supermod.actionType): def __init__(self, extensiontype_=None): super(actionTypeSub, self).__init__(extensiontype_, ) supermod.actionType.subclass = actionTypeSub # end class actionTypeSub class setTypeSub(supermod.setType): def __init__(self, name=None, value=None): super(setTypeSub, self).__init__(name, value, ) supermod.setType.subclass = setTypeSub # end class setTypeSub class runRuleTypeSub(supermod.runRuleType): def __init__(self, name=None, argument=None): super(runRuleTypeSub, self).__init__(name, argument, ) supermod.runRuleType.subclass = runRuleTypeSub # end class runRuleTypeSub class ExpertSystemSub(supermod.ExpertSystem): def __init__(self, comment=None, fact=None, rule=None): super(ExpertSystemSub, self).__init__(comment, fact, rule, ) supermod.ExpertSystem.subclass = ExpertSystemSub # end class ExpertSystemSub class algorithmTypeSub(supermod.algorithmType): def __init__(self, RadialBasisFunctionNetwork=None, MultiLayerPerceptron=None): super(algorithmTypeSub, self).__init__(RadialBasisFunctionNetwork, MultiLayerPerceptron, ) supermod.algorithmType.subclass = algorithmTypeSub # end class algorithmTypeSub class algorithmType4Sub(supermod.algorithmType4): def __init__(self, RecurrentNeuralNetwork=None): super(algorithmType4Sub, self).__init__(RecurrentNeuralNetwork, ) supermod.algorithmType4.subclass = algorithmType4Sub # end class algorithmType4Sub class fieldTypeSub(supermod.fieldType): def __init__(self, initialValue=None, type_=None, name=None): super(fieldTypeSub, self).__init__(initialValue, type_, name, ) supermod.fieldType.subclass = fieldTypeSub # end class fieldTypeSub class fieldType5Sub(supermod.fieldType5): def __init__(self, name=None, value=None): super(fieldType5Sub, self).__init__(name, value, ) supermod.fieldType5.subclass = fieldType5Sub # end class fieldType5Sub class argumentTypeSub(supermod.argumentType): def __init__(self, name=None, value=None): super(argumentTypeSub, self).__init__(name, value, ) supermod.argumentType.subclass = argumentTypeSub # end class argumentTypeSub class ruleTypeSub(supermod.ruleType): def __init__(self, name=None, comment=None, parameter=None, if_=None, then=None, else_=None): super(ruleTypeSub, self).__init__(name, comment, parameter, if_, then, else_, ) supermod.ruleType.subclass = ruleTypeSub # end class ruleTypeSub class parameterTypeSub(supermod.parameterType): def __init__(self, type_=None, name=None): super(parameterTypeSub, self).__init__(type_, name, ) supermod.parameterType.subclass = parameterTypeSub # end class parameterTypeSub class ifTypeSub(supermod.ifType): def __init__(self, clause=None): super(ifTypeSub, self).__init__(clause, ) supermod.ifType.subclass = ifTypeSub # end class ifTypeSub class thenTypeSub(supermod.thenType): def __init__(self, action=None): super(thenTypeSub, self).__init__(action, ) supermod.thenType.subclass = thenTypeSub # end class thenTypeSub class elseTypeSub(supermod.elseType): def __init__(self, action=None): super(elseTypeSub, self).__init__(action, ) supermod.elseType.subclass = elseTypeSub # end class elseTypeSub def get_root_tag(node): tag = supermod.Tag_pattern_.match(node.tag).groups()[-1] rootClass = None rootClass = supermod.GDSClassesMapping.get(tag) if rootClass is None and hasattr(supermod, tag): rootClass = getattr(supermod, tag) return tag, rootClass def parse(inFilename, silence=False): parser = None doc = parsexml_(inFilename, parser) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'MeetCI' rootClass = supermod.MeetCI rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None if not silence: sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export( sys.stdout, 0, name_=rootTag, namespacedef_='', pretty_print=True) return rootObj def parseEtree(inFilename, silence=False): parser = None doc = parsexml_(inFilename, parser) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'MeetCI' rootClass = supermod.MeetCI rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None mapping = {} rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) if not silence: content = etree_.tostring( rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8") sys.stdout.write(content) sys.stdout.write('\n') return rootObj, rootElement, mapping, reverse_mapping def parseString(inString, silence=False): from StringIO import StringIO parser = None doc = parsexml_(StringIO(inString), parser) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'MeetCI' rootClass = supermod.MeetCI rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None if not silence: sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export( sys.stdout, 0, name_=rootTag, namespacedef_='') return rootObj def parseLiteral(inFilename, silence=False): parser = None doc = parsexml_(inFilename, parser) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'MeetCI' rootClass = supermod.MeetCI rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None if not silence: sys.stdout.write('#from ??? import *\n\n') sys.stdout.write('import ??? as model_\n\n') sys.stdout.write('rootObj = model_.rootClass(\n') rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) sys.stdout.write(')\n') return rootObj USAGE_TEXT = """ Usage: python ???.py <infilename> """ def usage(): print(USAGE_TEXT) sys.exit(1) def main(): args = sys.argv[1:] if len(args) != 1: usage() infilename = args[0] parse(infilename) if __name__ == '__main__': #import pdb; pdb.set_trace() main()
RathinakumarVisweswaran/MeetCI
python/meetCI_sub.py
Python
mit
14,507
0.004067
"""Generate reports no holdings. """ __author__ = "Martin Blais <blais@furius.ca>" import csv from beancount.core.number import D from beancount.core.number import ZERO from beancount.core import account from beancount.core import data from beancount.core import flags from beancount.parser import options from beancount.parser import printer from beancount.ops import prices from beancount.ops import holdings from beancount.ops import summarize from beancount.reports import table from beancount.reports import report def get_assets_holdings(entries, options_map, currency=None): """Return holdings for all assets and liabilities. Args: entries: A list of directives. options_map: A dict of parsed options. currency: If specified, a string, the target currency to convert all holding values to. Returns: A list of Holding instances and a price-map. """ # Compute a price map, to perform conversions. price_map = prices.build_price_map(entries) # Get the list of holdings. account_types = options.get_account_types(options_map) holdings_list = holdings.get_final_holdings(entries, (account_types.assets, account_types.liabilities), price_map) # Convert holdings to a unified currency. if currency: holdings_list = holdings.convert_to_currency(price_map, currency, holdings_list) return holdings_list, price_map # A field spec that renders all fields. FIELD_SPEC = [ ('account', ), ('number', "Units", '{:,.2f}'.format), ('currency', ), ('cost_currency', ), ('cost_number', 'Average Cost', '{:,.2f}'.format), ('price_number', 'Price', '{:,.2f}'.format), ('book_value', 'Book Value', '{:,.2f}'.format), ('market_value', 'Market Value', '{:,.2f}'.format), ] # A field spec for relative reports. Skipping the book value here because by # combining it with market value % and price one could theoretically determined # the total value of the portfolio. RELATIVE_FIELD_SPEC = [ field_desc for field_desc in FIELD_SPEC if field_desc[0] not in ('account', 'number', 'book_value', 'market_value') ] + [ ('market_value', 'Frac Folio', '{:,.2%}'.format), ] def get_holdings_entries(entries, options_map): """Summarizes the entries to list of entries representing the final holdings.. This list includes the latest prices entries as well. This can be used to load a full snapshot of holdings without including the entire history. This is a way of summarizing a balance sheet in a way that filters away history. Args: entries: A list of directives. options_map: A dict of parsed options. Returns: A string, the entries to print out. """ # The entries will be create at the latest date, against an equity account. latest_date = entries[-1].date _, equity_account, _ = options.get_previous_accounts(options_map) # Get all the assets. holdings_list, _ = get_assets_holdings(entries, options_map) # Create synthetic entries for them. holdings_entries = [] for index, holding in enumerate(holdings_list): meta = data.new_metadata('report_holdings_print', index) entry = data.Transaction(meta, latest_date, flags.FLAG_SUMMARIZE, None, "", None, None, []) # Convert the holding to a position. position_ = holdings.holding_to_position(holding) entry.postings.append( data.Posting(holding.account, position_, None, None, None)) entry.postings.append( data.Posting(equity_account, -position_.cost(), None, None, None)) holdings_entries.append(entry) # Get opening directives for all the accounts. used_accounts = {holding.account for holding in holdings_list} open_entries = summarize.get_open_entries(entries, latest_date) used_open_entries = [open_entry for open_entry in open_entries if open_entry.account in used_accounts] # Add an entry for the equity account we're using. meta = data.new_metadata('report_holdings_print', -1) used_open_entries.insert(0, data.Open(meta, latest_date, equity_account, None, None)) # Get the latest price entries. price_entries = prices.get_last_price_entries(entries, None) return used_open_entries + holdings_entries + price_entries def report_holdings(currency, relative, entries, options_map, aggregation_key=None, sort_key=None): """Generate a detailed list of all holdings. Args: currency: A string, a currency to convert to. If left to None, no conversion is carried out. relative: A boolean, true if we should reduce this to a relative value. entries: A list of directives. options_map: A dict of parsed options. aggregation_key: A callable use to generate aggregations. sort_key: A function to use to sort the holdings, if specified. Returns: A Table instance. """ holdings_list, _ = get_assets_holdings(entries, options_map, currency) if aggregation_key: holdings_list = holdings.aggregate_holdings_by(holdings_list, aggregation_key) if relative: holdings_list = holdings.reduce_relative(holdings_list) field_spec = RELATIVE_FIELD_SPEC else: field_spec = FIELD_SPEC if sort_key: holdings_list.sort(key=sort_key, reverse=True) return table.create_table(holdings_list, field_spec) def load_from_csv(fileobj): """Load a list of holdings from a CSV file. Args: fileobj: A file object. Yields: Instances of Holding, as read from the file. """ column_spec = [ ('Account', 'account', None), ('Units', 'number', D), ('Currency', 'currency', None), ('Cost Currency', 'cost_currency', None), ('Average Cost', 'cost_number', D), ('Price', 'price_number', D), ('Book Value', 'book_value', D), ('Market Value', 'market_value', D), ('Price Date', 'price_date', None), ] column_dict = {name: (attr, converter) for name, attr, converter in column_spec} klass = holdings.Holding # Create a set of default values for the namedtuple. defaults_dict = {attr: None for attr in klass._fields} # Start reading the file. reader = csv.reader(fileobj) # Check that the header is readable. header = next(reader) attr_converters = [] for header_name in header: try: attr_converter = column_dict[header_name] attr_converters.append(attr_converter) except KeyError: raise IOError("Invalid file contents for holdings") for line in reader: value_dict = defaults_dict.copy() for (attr, converter), value in zip(attr_converters, line): if converter: value = converter(value) value_dict[attr] = value yield holdings.Holding(**value_dict) class HoldingsReport(report.TableReport): """The full list of holdings for Asset and Liabilities accounts.""" names = ['holdings'] aggregations = { 'commodity': dict(aggregation_key=lambda holding: holding.currency), 'account': dict(aggregation_key=lambda holding: holding.account), 'root-account': dict( aggregation_key=lambda holding: account.root(3, holding.account), sort_key=lambda holding: holding.market_value or ZERO), 'currency': dict(aggregation_key=lambda holding: holding.cost_currency), } def __init__(self, *rest, **kwds): super().__init__(*rest, **kwds) if self.args.relative and not self.args.currency: self.parser.error("--relative needs to have --currency set") @classmethod def add_args(cls, parser): parser.add_argument('-c', '--currency', action='store', default=None, help="Which currency to convert all the holdings to") parser.add_argument('-r', '--relative', action='store_true', help="True if we should render as relative values only") parser.add_argument('-g', '--groupby', '--by', action='store', default=None, choices=cls.aggregations.keys(), help="How to group the holdings (default is: don't group)") def generate_table(self, entries, errors, options_map): keywords = self.aggregations[self.args.groupby] if self.args.groupby else {} return report_holdings(self.args.currency, self.args.relative, entries, options_map, **keywords) def render_beancount(self, entries, errors, options_map, file): # Don't allow any aggregations if we output as beancount format. for attribute in 'currency', 'relative', 'groupby': if getattr(self.args, attribute): self.parser.error( "'beancount' format does not support --{} option".format(attribute)) # Get the summarized entries and print them out. holdings_entries = get_holdings_entries(entries, options_map) dcontext = options_map['dcontext'] printer.print_entries(holdings_entries, dcontext, file=file) class CashReport(report.TableReport): """The list of cash holdings (defined as currency = cost-currency).""" names = ['cash'] @classmethod def add_args(cls, parser): parser.add_argument('-c', '--currency', action='store', default=None, help="Which currency to convert all the holdings to") parser.add_argument('-i', '--ignored', action='store_true', help="Report on ignored holdings instead of included ones") parser.add_argument('-o', '--operating-only', action='store_true', help="Only report on operating currencies") def generate_table(self, entries, errors, options_map): holdings_list, price_map = get_assets_holdings(entries, options_map) holdings_list_orig = holdings_list # Keep only the holdings where currency is the same as the cost-currency. holdings_list = [holding for holding in holdings_list if (holding.currency == holding.cost_currency or holding.cost_currency is None)] # Keep only those holdings held in one of the operating currencies. if self.args.operating_only: operating_currencies = set(options_map['operating_currency']) holdings_list = [holding for holding in holdings_list if holding.currency in operating_currencies] # Compute the list of ignored holdings and optionally report on them. if self.args.ignored: ignored_holdings = set(holdings_list_orig) - set(holdings_list) holdings_list = ignored_holdings # Convert holdings to a unified currency. if self.args.currency: holdings_list = holdings.convert_to_currency(price_map, self.args.currency, holdings_list) return table.create_table(holdings_list, FIELD_SPEC) class NetWorthReport(report.TableReport): """Generate a table of total net worth for each operating currency.""" names = ['networth', 'equity'] def generate_table(self, entries, errors, options_map): holdings_list, price_map = get_assets_holdings(entries, options_map) net_worths = [] for currency in options_map['operating_currency']: # Convert holdings to a unified currency. # # Note: It's entirely possible that the price map does not have all # the necessary rate conversions here. The resulting holdings will # simply have no cost when that is the case. We must handle this # gracefully below. currency_holdings_list = holdings.convert_to_currency(price_map, currency, holdings_list) if not currency_holdings_list: continue holdings_list = holdings.aggregate_holdings_by( currency_holdings_list, lambda holding: holding.cost_currency) holdings_list = [holding for holding in holdings_list if holding.currency and holding.cost_currency] # If after conversion there are no valid holdings, skip the currency # altogether. if not holdings_list: continue net_worths.append((currency, holdings_list[0].market_value)) field_spec = [ (0, 'Currency'), (1, 'Net Worth', '{:,.2f}'.format), ] return table.create_table(net_worths, field_spec) __reports__ = [ HoldingsReport, CashReport, NetWorthReport, ]
iocoop/beancount
src/python/beancount/reports/holdings_reports.py
Python
gpl-2.0
13,561
0.00118
# -*- coding: utf-8 -*- from . import app, db from flask import request, g, session, redirect from Lotus.model.user import User from hashlib import md5 from Lotus.lib.msg_code import Msg import json @app.route('/user/login', methods=['POST']) def user_login(): email = request.form.get('email', None) psw = request.form.get('psw', None) if email is not None and psw is not None: users = User.query.filter_by(email=email, psw=psw) if users: g.user = users[0] session['userid'] = users[0].userid else: return '{"code":%d,"msg":$s}'.format(Msg['faild'], 'user not exist') else: return '{"code":%d,"msg":$s}'.format(Msg['faild'], 'params not enougth') @app.route('/user/register', methods=['POST']) def user_register(): # todo (参数不够)有插入异常怎么办? # todo 忘记密码.. try: u = User() u.username = request.form.get('username', None) u.description = request.form.get('description', None) u.type = request.form.get('type', User.CONST_TYPE_USER) u.email = request.form.get('email', None) m = md5() m.update(request.form.get('psw', User.CONST_DEFAULT_PASSWORD)) # 默认密码 u.psw = m.hexdigest() db.session.add(u) db.session.commit() except Exception as e: return '{"code":%d,"msg":$s}'.format(Msg['faild'], 'register faild') return '{"code":%d,"msg":$s}'.format(Msg['success'], 'register success') @app.route('/user/<int:userid>/avatar', methods=['GET', 'POST']) def user_avatar(userid): #upload #TODO support upload avater if request.method == 'POST': pass else: pass @app.route('/user/<int:userid>/profile', methods=['GET']) def user_profile(userid): if session.get('userid'): result = { 'userid': g.user.userid, 'username': g.user.username, 'avatar': g.user.avatar, 'description': g.user.description, 'type': g.user.type, 'email': g.user.email } return json.dumps(result) else: redirect('/user/login') @app.route('/user/<int:userid>/issue/sends/page/<int:page>', methods=['GET']) def user_issues_send(userid, page): pass @app.route('/user/<int:userid>/issue/favours/page/<int:page>', methods=['GET']) def user_issues_favour(userid, page): pass @app.route('/user/<int:userid>/issue/favours/page/<int:page>', methods=['GET']) def user_messages(userid, page): pass
Jayin/Lotus
Lotus/controller/user.py
Python
apache-2.0
2,550
0.001994
#!/usr/bin/python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import io import random import string import unittest import coap import config def any_delta(): return random.getrandbits(4) def any_coap_option_type(): return random.getrandbits(4) def any_value(): return random.getrandbits(8) def any_4bits_value_different_than_13_and_14(): value = None while value is None: value = random.getrandbits(4) if value == 13 or value == 14: value = None return value def any_4bits_value_lower_or_equal_than_12(): value = None while value is None: value = random.getrandbits(4) if value > 12: value = None return value def any_bytearray(length): return bytearray([random.getrandbits(8) for _ in range(length)]) def any_version(): return random.getrandbits(2) def any_type(): return random.getrandbits(2) def any_code(): return random.getrandbits(8) def any_message_id(): return random.getrandbits(16) def any_token(): length = random.randint(0, 8) return bytearray([random.getrandbits(8) for _ in range(length)]) def any_options(): return [] def any_payload(length=None): length = length if length is not None else random.randint(0, 64) return bytearray([random.getrandbits(8) for _ in range(length)]) def any_uri_path(): return "/" + random.choice(string.ascii_lowercase) class TestCoapMessageOptionHeader(unittest.TestCase): def test_should_return_passed_on_value_when_read_extended_value_is_called_with_value_different_than_13_and_14(self): # GIVEN value = any_4bits_value_different_than_13_and_14() # WHEN actual_value = coap.CoapOptionHeader._read_extended_value(None, value) # THEN self.assertEqual(value, actual_value) def test_should_return_value_stored_in_first_byte_plus_13_when_read_extended_value_is_called_with_value_equal_13(self): # GIVEN value = 13 extended_value = any_value() data = io.BytesIO(bytearray([extended_value])) # WHEN actual_value = coap.CoapOptionHeader._read_extended_value(data, value) # THEN self.assertEqual(extended_value + 13, actual_value) def test_should_return_value_stored_in_first_byte_plus_269_when_read_extended_value_is_called_with_value_equal_14(self): # GIVEN value = 14 extended_value = any_value() data = io.BytesIO(bytearray([any_value(), extended_value])) # WHEN actual_value = coap.CoapOptionHeader._read_extended_value(data, value) # THEN self.assertEqual(extended_value + 269, actual_value) def test_should_create_CoapOptionHeader_when_from_bytes_classmethod_is_called(self): # GIVEN delta = any_4bits_value_different_than_13_and_14() length = any_4bits_value_different_than_13_and_14() data = bytearray([delta << 4 | length]) # WHEN option_header = coap.CoapOptionHeader.from_bytes(io.BytesIO(data)) # THEN self.assertEqual(delta, option_header.delta) self.assertEqual(length, option_header.length) def test_should_return_True_when_is_payload_marker_property_called_with_delta_and_length_equal_15(self): # GIVEN delta = 15 length = 15 data = bytearray([delta << 4 | length]) # WHEN option_header = coap.CoapOptionHeader.from_bytes(io.BytesIO(data)) # THEN self.assertTrue(option_header.is_payload_marker) class TestCoapOption(unittest.TestCase): def test_should_return_type_value_when_type_property_is_called(self): # GIVEN _type = any_coap_option_type() coap_opt = coap.CoapOption(_type, any_value()) # WHEN actual_type = coap_opt.type # THEN self.assertEqual(_type, actual_type) def test_should_return_value_value_when_value_property_is_called(self): # GIVEN value = any_value() coap_opt = coap.CoapOption(any_coap_option_type(), value) # WHEN actual_value = coap_opt.value # THEN self.assertEqual(value, actual_value) class TestCoapOptionsFactory(unittest.TestCase): def test_should_create_list_of_CoapOption_from_bytearray_when_parse_method_is_called(self): # GIVEN delta = any_4bits_value_lower_or_equal_than_12() length = any_4bits_value_lower_or_equal_than_12() value = any_bytearray(length) data = bytearray([delta << 4 | length]) + value factory = coap.CoapOptionsFactory() # WHEN coap_options = factory.parse(io.BytesIO(data), None) # THEN self.assertEqual(1, len(coap_options)) self.assertEqual(delta, coap_options[0].type) self.assertEqual(value, coap_options[0].value) class TestCoapCode(unittest.TestCase): def test_should_return_code_value_when_code_property_is_called(self): # GIVEN code = any_code() code_obj = coap.CoapCode(code) # WHEN actual_code = code_obj.code # THEN self.assertEqual(code, actual_code) def test_should_return_class_value_when_class_property_is_called(self): # GIVEN code = any_code() code_obj = coap.CoapCode(code) # WHEN actual_class = code_obj._class # THEN self.assertEqual((code >> 5) & 0x7, actual_class) def test_should_return_detail_value_when_detail_property_is_called(self): # GIVEN code = any_code() code_obj = coap.CoapCode(code) # WHEN actual_detail = code_obj.detail # THEN self.assertEqual(code & 0x1f, actual_detail) def test_should_return_dotted_value_when_dotted_property_is_called(self): # GIVEN code = any_code() code_obj = coap.CoapCode(code) # WHEN actual_dotted = code_obj.dotted # THEN _class, detail = actual_dotted.split(".") self.assertEqual(code, (int(_class) << 5) | int(detail)) def test_should_create_CoapCode_when_from_class_and_detail_classmethod_is_called(self): # GIVEN code = any_code() _class = (code >> 5) & 0x7 detail = code & 0x1f # WHEN actual_coap_obj = coap.CoapCode.from_class_and_detail(_class, detail) # THEN self.assertEqual(code, actual_coap_obj.code) def test_should_create_CoapCode_when_from_dotted_string_classmethod_is_called(self): # GIVEN code = any_code() code_obj = coap.CoapCode(code) # WHEN actual_coap_obj = coap.CoapCode.from_dotted(code_obj.dotted) # THEN self.assertEqual(code, actual_coap_obj.code) class TestCoapMessage(unittest.TestCase): def test_should_return_version_value_when_version_property_is_called(self): # GIVEN version = any_version() coap_message = coap.CoapMessage(version, any_type(), any_code(), any_message_id(), any_token(), any_options(), any_payload()) # WHEN actual_version = coap_message.version # THEN self.assertEqual(version, actual_version) def test_should_return_type_value_when_type_property_is_called(self): # GIVEN _type = any_type() coap_message = coap.CoapMessage(any_version(), _type, any_code(), any_message_id(), any_token(), any_options(), any_payload()) # WHEN actual_type = coap_message.type # THEN self.assertEqual(_type, actual_type) def test_should_return_code_value_when_code_property_is_called(self): # GIVEN code = any_code() coap_message = coap.CoapMessage(any_version(), any_type(), code, any_message_id(), any_token(), any_options(), any_payload()) # WHEN actual_code = coap_message.code # THEN self.assertEqual(code, actual_code) def test_should_return_message_id_value_when_message_id_property_is_called(self): # GIVEN message_id = any_message_id() coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), message_id, any_token(), any_options(), any_payload()) # WHEN actual_message_id = coap_message.message_id # THEN self.assertEqual(message_id, actual_message_id) def test_should_return_token_value_when_token_property_is_called(self): # GIVEN token = any_token() coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), token, any_options(), any_payload()) # WHEN actual_token = coap_message.token # THEN self.assertEqual(token, actual_token) def test_should_return_tkl_value_when_tkl_property_is_called(self): # GIVEN token = any_token() coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), token, any_options(), any_payload()) # WHEN actual_tkl = coap_message.tkl # THEN self.assertEqual(len(token), actual_tkl) def test_should_return_options_value_when_options_property_is_called(self): # GIVEN options = any_options() coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), any_token(), options, any_payload()) # WHEN actual_options = coap_message.options # THEN self.assertEqual(options, actual_options) def test_should_return_payload_value_when_payload_property_is_called(self): # GIVEN payload = any_payload() coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), any_token(), any_options(), payload) # WHEN actual_payload = coap_message.payload # THEN self.assertEqual(payload, actual_payload) def test_should_return_uri_path_value_when_uri_path_property_is_called(self): # GIVEN uri_path = any_uri_path() coap_message = coap.CoapMessage(any_version(), any_type(), any_code(), any_message_id(), any_token(), any_options(), any_payload(), uri_path) # WHEN actual_uri_path = coap_message.uri_path # THEN self.assertEqual(uri_path, actual_uri_path) class TestCoapMessageIdToUriPathBinder(unittest.TestCase): def test_should_add_uri_path_to_binds_when_add_uri_path_for_method_is_called(self): # GIVEN message_id = any_message_id() token = any_token() uri_path = any_uri_path() binder = coap.CoapMessageIdToUriPathBinder() # WHEN binder.add_uri_path_for(message_id, token, uri_path) # THEN self.assertEqual(uri_path, binder.get_uri_path_for(message_id, token)) def test_should_raise_KeyError_when_get_uri_path_for_is_called_but_it_is_not_present_in_database(self): # GIVEN message_id = any_message_id() token = any_token() uri_path = any_uri_path() binder = coap.CoapMessageIdToUriPathBinder() # THEN self.assertRaises(RuntimeError, binder.get_uri_path_for, message_id, token) class TestCoapMessageFactory(unittest.TestCase): def _create_dummy_payload_factory(self): class DummyPayloadFactory: def parse(self, data, message_info): return data.read() return DummyPayloadFactory() def _create_coap_message_factory(self): return coap.CoapMessageFactory( options_factory=coap.CoapOptionsFactory(), uri_path_based_payload_factories={ "/a/as": self._create_dummy_payload_factory() }, message_id_to_uri_path_binder=coap.CoapMessageIdToUriPathBinder()) def test_should_create_CoapMessage_from_solicit_request_data_when_parse_method_is_called(self): # GIVEN data = bytearray([0x42, 0x02, 0x00, 0xbd, 0x65, 0xee, 0xb1, 0x61, 0x02, 0x61, 0x73, 0xff, 0x01, 0x08, 0x16, 0x6e, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x02, 0x04, 0x01, 0x02]) factory = self._create_coap_message_factory() # WHEN coap_message = factory.parse(io.BytesIO(data), None) # THEN self.assertEqual(1, coap_message.version) self.assertEqual(0, coap_message.type) self.assertEqual(2, coap_message.tkl) self.assertEqual(2, coap_message.code) self.assertEqual(189, coap_message.message_id) self.assertEqual(bytearray([0x65, 0xee]), coap_message.token) self.assertEqual("a", coap_message.options[0].value.decode("utf-8")) self.assertEqual("as", coap_message.options[1].value.decode("utf-8")) self.assertEqual("/a/as", coap_message.uri_path) self.assertEqual(bytearray([0x01, 0x08, 0x16, 0x6e, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x02, 0x04, 0x01, 0x02]), coap_message.payload) def test_should_create_CoapMessage_from_solicit_response_data_when_parse_method_is_called(self): # GIVEN data = bytearray([0x62, 0x44, 0x00, 0xbd, 0x65, 0xee, 0xff, 0x04, 0x01, 0x00, 0x02, 0x02, 0x00, 0x00, 0x07, 0x09, 0x76, 0x80, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]) mid_binder = coap.CoapMessageIdToUriPathBinder() mid_binder.add_uri_path_for(189, bytearray([0x65, 0xee]), "/a/as") factory = coap.CoapMessageFactory( options_factory=coap.CoapOptionsFactory(), uri_path_based_payload_factories={ "/a/as": self._create_dummy_payload_factory() }, message_id_to_uri_path_binder=mid_binder) # WHEN coap_message = factory.parse(io.BytesIO(data), None) # THEN self.assertEqual(1, coap_message.version) self.assertEqual(2, coap_message.type) self.assertEqual(2, coap_message.tkl) self.assertEqual("2.04", coap_message.code) self.assertEqual(189, coap_message.message_id) self.assertEqual(bytearray([0x65, 0xee]), coap_message.token) self.assertEqual(None, coap_message.uri_path) self.assertEqual(bytearray([0x04, 0x01, 0x00, 0x02, 0x02, 0x00, 0x00, 0x07, 0x09, 0x76, 0x80, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]), coap_message.payload) if __name__ == "__main__": unittest.main()
Zolertia/openthread
tests/scripts/thread-cert/test_coap.py
Python
bsd-3-clause
16,471
0.002064
# coding: utf-8 """ Qc API Qc API # noqa: E501 The version of the OpenAPI document: 3.0.0 Contact: cloudsupport@telestream.net Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from telestream_cloud_qc.configuration import Configuration class PartitionStatusTest(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'closed_complete': 'bool', 'open_incomplete': 'bool', 'closed_incomplete': 'bool', 'open_complete': 'bool', 'not_present': 'bool', 'reject_on_error': 'bool', 'checked': 'bool' } attribute_map = { 'closed_complete': 'closed_complete', 'open_incomplete': 'open_incomplete', 'closed_incomplete': 'closed_incomplete', 'open_complete': 'open_complete', 'not_present': 'not_present', 'reject_on_error': 'reject_on_error', 'checked': 'checked' } def __init__(self, closed_complete=None, open_incomplete=None, closed_incomplete=None, open_complete=None, not_present=None, reject_on_error=None, checked=None, local_vars_configuration=None): # noqa: E501 """PartitionStatusTest - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._closed_complete = None self._open_incomplete = None self._closed_incomplete = None self._open_complete = None self._not_present = None self._reject_on_error = None self._checked = None self.discriminator = None if closed_complete is not None: self.closed_complete = closed_complete if open_incomplete is not None: self.open_incomplete = open_incomplete if closed_incomplete is not None: self.closed_incomplete = closed_incomplete if open_complete is not None: self.open_complete = open_complete if not_present is not None: self.not_present = not_present if reject_on_error is not None: self.reject_on_error = reject_on_error if checked is not None: self.checked = checked @property def closed_complete(self): """Gets the closed_complete of this PartitionStatusTest. # noqa: E501 :return: The closed_complete of this PartitionStatusTest. # noqa: E501 :rtype: bool """ return self._closed_complete @closed_complete.setter def closed_complete(self, closed_complete): """Sets the closed_complete of this PartitionStatusTest. :param closed_complete: The closed_complete of this PartitionStatusTest. # noqa: E501 :type: bool """ self._closed_complete = closed_complete @property def open_incomplete(self): """Gets the open_incomplete of this PartitionStatusTest. # noqa: E501 :return: The open_incomplete of this PartitionStatusTest. # noqa: E501 :rtype: bool """ return self._open_incomplete @open_incomplete.setter def open_incomplete(self, open_incomplete): """Sets the open_incomplete of this PartitionStatusTest. :param open_incomplete: The open_incomplete of this PartitionStatusTest. # noqa: E501 :type: bool """ self._open_incomplete = open_incomplete @property def closed_incomplete(self): """Gets the closed_incomplete of this PartitionStatusTest. # noqa: E501 :return: The closed_incomplete of this PartitionStatusTest. # noqa: E501 :rtype: bool """ return self._closed_incomplete @closed_incomplete.setter def closed_incomplete(self, closed_incomplete): """Sets the closed_incomplete of this PartitionStatusTest. :param closed_incomplete: The closed_incomplete of this PartitionStatusTest. # noqa: E501 :type: bool """ self._closed_incomplete = closed_incomplete @property def open_complete(self): """Gets the open_complete of this PartitionStatusTest. # noqa: E501 :return: The open_complete of this PartitionStatusTest. # noqa: E501 :rtype: bool """ return self._open_complete @open_complete.setter def open_complete(self, open_complete): """Sets the open_complete of this PartitionStatusTest. :param open_complete: The open_complete of this PartitionStatusTest. # noqa: E501 :type: bool """ self._open_complete = open_complete @property def not_present(self): """Gets the not_present of this PartitionStatusTest. # noqa: E501 :return: The not_present of this PartitionStatusTest. # noqa: E501 :rtype: bool """ return self._not_present @not_present.setter def not_present(self, not_present): """Sets the not_present of this PartitionStatusTest. :param not_present: The not_present of this PartitionStatusTest. # noqa: E501 :type: bool """ self._not_present = not_present @property def reject_on_error(self): """Gets the reject_on_error of this PartitionStatusTest. # noqa: E501 :return: The reject_on_error of this PartitionStatusTest. # noqa: E501 :rtype: bool """ return self._reject_on_error @reject_on_error.setter def reject_on_error(self, reject_on_error): """Sets the reject_on_error of this PartitionStatusTest. :param reject_on_error: The reject_on_error of this PartitionStatusTest. # noqa: E501 :type: bool """ self._reject_on_error = reject_on_error @property def checked(self): """Gets the checked of this PartitionStatusTest. # noqa: E501 :return: The checked of this PartitionStatusTest. # noqa: E501 :rtype: bool """ return self._checked @checked.setter def checked(self, checked): """Sets the checked of this PartitionStatusTest. :param checked: The checked of this PartitionStatusTest. # noqa: E501 :type: bool """ self._checked = checked def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_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() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.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""" if not isinstance(other, PartitionStatusTest): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, PartitionStatusTest): return True return self.to_dict() != other.to_dict()
Telestream/telestream-cloud-python-sdk
telestream_cloud_qc_sdk/telestream_cloud_qc/models/partition_status_test.py
Python
mit
8,207
0
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = 'nosedjango' DATABASE_USER = 'root' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = '' TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True MEDIA_ROOT = '' MEDIA_URL = '' ADMIN_MEDIA_PREFIX = '/media/' SECRET_KEY = 'w9*+(qevfn*j2959ikv-_7kj7ivptt#8&n*gy0o&ktisx@%rzt' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'nosedjangotests.urls' TEMPLATE_DIRS = ( ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'nosedjangotests.polls', )
nosedjango/nosedjango
nosedjangotests/settings_legacy.py
Python
lgpl-3.0
1,056
0
"""Leetcode 100. Same Tree Easy URL: https://leetcode.com/problems/same-tree/ Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true Example 2: Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false Example 3: Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class SolutionPreorderRecur(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool Apply recursive preorder traversal to check same tree. Time complexity: O(n). Space complexity: O(n). """ # Check if both root don't exist. if not p and not q: return True # Check if just one of roots exits. if not p or not q: return False # If both exist, check their values are the same. if p.val != q.val: return False # Recursively check left/right subtrees. return (self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)) class SolutionPreorderIter(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool Apply iterative preorder traversal to check same tree. Time complexity: O(n). Space complexity: O(n). """ stack = [(p, q)] while stack: cur_p, cur_q = stack.pop() # Check if both root don't exist, continue, # since there may be other node pairs to check. if not cur_p and not cur_q: continue # Check if just one of roots exits. if not cur_p or not cur_q: return False # If both exist, check their values are the same. if cur_p.val != cur_q.val: return False # Add root's right and then left to stack, since stack is FILO. stack.append((cur_p.right, cur_q.right)) stack.append((cur_p.left, cur_q.left)) return True def main(): # Input: 1 1 # / \ / \ # 2 3 2 3 # [1,2,3], [1,2,3] # Output: true p = TreeNode(1) p.left = TreeNode(2) p.right = TreeNode(3) q = TreeNode(1) q.left = TreeNode(2) q.right = TreeNode(3) print SolutionPreorderRecur().isSameTree(p, q) print SolutionPreorderIter().isSameTree(p, q) # Input: 1 1 # / \ # 2 2 # [1,2], [1,null,2] # Output: false p = TreeNode(1) p.left = TreeNode(2) q = TreeNode(1) q.right = TreeNode(2) print SolutionPreorderRecur().isSameTree(p, q) print SolutionPreorderIter().isSameTree(p, q) # Input: 1 1 # / \ / \ # 2 1 1 2 # [1,2,1], [1,1,2] # Output: false p = TreeNode(1) p.left = TreeNode(2) p.right = TreeNode(1) q = TreeNode(1) q.left = TreeNode(1) q.right = TreeNode(2) print SolutionPreorderRecur().isSameTree(p, q) print SolutionPreorderIter().isSameTree(p, q) # Input: [10,5,15], [10,5,null,null,15] p = TreeNode(10) p.left = TreeNode(5) p.right = TreeNode(15) q = TreeNode(10) q.left = TreeNode(5) q.left.right = TreeNode(15) print SolutionPreorderRecur().isSameTree(p, q) print SolutionPreorderIter().isSameTree(p, q) if __name__ == '__main__': main()
bowen0701/algorithms_data_structures
lc0100_same_tree.py
Python
bsd-2-clause
4,044
0.001731
# -*- coding: utf-8 -*- """ Created on Mon Jan 11 17:55:48 2016 用欧拉法计算自行车从静止起步后的速度 @author: nightwing """ import matplotlib.pyplot as plt DENSITY = 1.29 #空气密度(kg/m3) C = 1.0 #阻力系数 A = 0.33 #截面积(m2) M = 70.0 #人车质量(kg) v = 7.0 #转折速度(m/s) v1 = 0.0 #(无阻力)速度(m/s) v2 = 0.0 #(有阻力)速度(m/s) P = 400.0 #功率(w) t = 0 #初始时间 t_max = 200 #截止时间(s) dt = 0.1 #时间间隔 time = [] #此列表存储时间 velocity1 = [] #此列表存储无空气阻力时的速度 velocity2 = [] #此列表存储有空气阻力时的速度 #---欧拉法计算自行车运动速度--- while t <= t_max: velocity1.append(v1) velocity2.append(v2) time.append(t) if v1 <= v: v1 += P/(M*v)*dt if v2 <= v: v2 += P/(M*v)*dt-C*DENSITY*A*v2**2/(2*M)*dt if v1 > v: v1 += P/(M*v1)*dt if v2 > v: v2 += P/(M*v2)*dt-C*DENSITY*A*v2**2/(2*M)*dt t += dt #------------绘图--------------- plt.title("Bicycling simulation: velocity vs. time") plt.xlabel("time (s)") plt.ylabel("velocity (m/s)") plt.plot(time,velocity1,"k-",label="No air resistence") plt.plot(time,velocity2,"k--",label="With air resistence") plt.legend(loc=2) plt.show()
WuShichao/computational-physics
2/2_5/2_5.py
Python
gpl-3.0
1,353
0.026667
# 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. # ============================================================================== """Utilities for probability distributions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import hashlib import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.util import tf_inspect def assert_integer_form( x, data=None, summarize=None, message=None, int_dtype=None, name="assert_integer_form"): """Assert that x has integer components (or floats equal to integers). Args: x: Floating-point `Tensor` data: The tensors to print out if the condition is `False`. Defaults to error message and first few entries of `x` and `y`. summarize: Print this many entries of each tensor. message: A string to prefix to the default message. int_dtype: A `tf.dtype` used to cast the float to. The default (`None`) implies the smallest possible signed int will be used for casting. name: A name for this operation (optional). Returns: Op raising `InvalidArgumentError` if `cast(x, int_dtype) != x`. """ with ops.name_scope(name, values=[x, data]): x = ops.convert_to_tensor(x, name="x") if x.dtype.is_integer: return control_flow_ops.no_op() message = message or "{} has non-integer components".format(x) if int_dtype is None: try: int_dtype = { dtypes.float16: dtypes.int16, dtypes.float32: dtypes.int32, dtypes.float64: dtypes.int64, }[x.dtype.base_dtype] except KeyError: raise TypeError("Unrecognized type {}".format(x.dtype.name)) return check_ops.assert_equal( x, math_ops.cast(math_ops.cast(x, int_dtype), x.dtype), data=data, summarize=summarize, message=message, name=name) def assert_symmetric(matrix): matrix_t = array_ops.matrix_transpose(matrix) return control_flow_ops.with_dependencies( [check_ops.assert_equal(matrix, matrix_t)], matrix) def embed_check_nonnegative_integer_form( x, name="embed_check_nonnegative_integer_form"): """Assert x is a non-negative tensor, and optionally of integers.""" with ops.name_scope(name, values=[x]): x = ops.convert_to_tensor(x, name="x") assertions = [ check_ops.assert_non_negative( x, message="'{}' must be non-negative.".format(x)), ] if not x.dtype.is_integer: assertions += [ assert_integer_form( x, message="'{}' cannot contain fractional components.".format( x)), ] return control_flow_ops.with_dependencies(assertions, x) def same_dynamic_shape(a, b): """Returns whether a and b have the same dynamic shape. Args: a: `Tensor` b: `Tensor` Returns: `bool` `Tensor` representing if both tensors have the same shape. """ a = ops.convert_to_tensor(a, name="a") b = ops.convert_to_tensor(b, name="b") # Here we can't just do math_ops.equal(a.shape, b.shape), since # static shape inference may break the equality comparison between # shape(a) and shape(b) in math_ops.equal. def all_shapes_equal(): return math_ops.reduce_all(math_ops.equal( array_ops.concat([array_ops.shape(a), array_ops.shape(b)], 0), array_ops.concat([array_ops.shape(b), array_ops.shape(a)], 0))) # One of the shapes isn't fully defined, so we need to use the dynamic # shape. return control_flow_ops.cond( math_ops.equal(array_ops.rank(a), array_ops.rank(b)), all_shapes_equal, lambda: constant_op.constant(False)) def maybe_get_static_value(x, dtype=None): """Helper which tries to return a static value. Given `x`, extract it's value statically, optionally casting to a specific dtype. If this is not possible, None is returned. Args: x: `Tensor` for which to extract a value statically. dtype: Optional dtype to cast to. Returns: Statically inferred value if possible, otherwise None. """ if x is None: return x try: # This returns an np.ndarray. x_ = tensor_util.constant_value(x) except TypeError: x_ = x if x_ is None or dtype is None: return x_ return np.array(x_, dtype) def get_logits_and_probs(logits=None, probs=None, multidimensional=False, validate_args=False, name="get_logits_and_probs", dtype=None): """Converts logit to probabilities (or vice-versa), and returns both. Args: logits: Floating-point `Tensor` representing log-odds. probs: Floating-point `Tensor` representing probabilities. multidimensional: Python `bool`, default `False`. If `True`, represents whether the last dimension of `logits` or `probs`, a `[N1, N2, ... k]` dimensional tensor, representing the logit or probability of `shape[-1]` classes. validate_args: Python `bool`, default `False`. When `True`, either assert `0 <= probs <= 1` (if not `multidimensional`) or that the last dimension of `probs` sums to one. name: A name for this operation (optional). dtype: `tf.DType` to prefer when converting args to `Tensor`s. Returns: logits, probs: Tuple of `Tensor`s. If `probs` has an entry that is `0` or `1`, then the corresponding entry in the returned logit will be `-Inf` and `Inf` respectively. Raises: ValueError: if neither `probs` nor `logits` were passed in, or both were. """ with ops.name_scope(name, values=[probs, logits]): if (probs is None) == (logits is None): raise ValueError("Must pass probs or logits, but not both.") if probs is None: logits = ops.convert_to_tensor(logits, name="logits", dtype=dtype) if not logits.dtype.is_floating: raise TypeError("logits must having floating type.") # We can early return since we constructed probs and therefore know # they're valid. if multidimensional: if validate_args: logits = embed_check_categorical_event_shape(logits) return logits, nn.softmax(logits, name="probs") return logits, math_ops.sigmoid(logits, name="probs") probs = ops.convert_to_tensor(probs, name="probs", dtype=dtype) if not probs.dtype.is_floating: raise TypeError("probs must having floating type.") if validate_args: with ops.name_scope("validate_probs"): one = constant_op.constant(1., probs.dtype) dependencies = [check_ops.assert_non_negative(probs)] if multidimensional: probs = embed_check_categorical_event_shape(probs) dependencies += [ check_ops.assert_near( math_ops.reduce_sum(probs, -1), one, message="probs does not sum to 1.") ] else: dependencies += [check_ops.assert_less_equal( probs, one, message="probs has components greater than 1.")] probs = control_flow_ops.with_dependencies(dependencies, probs) with ops.name_scope("logits"): if multidimensional: # Here we don't compute the multidimensional case, in a manner # consistent with respect to the unidimensional case. We do so # following the TF convention. Typically, you might expect to see # logits = log(probs) - log(probs[pivot]). A side-effect of # being consistent with the TF approach is that the unidimensional case # implicitly handles the second dimension but the multidimensional case # explicitly keeps the pivot dimension. return math_ops.log(probs), probs return math_ops.log(probs) - math_ops.log1p(-1. * probs), probs def _is_known_unsigned_by_dtype(dt): """Helper returning True if dtype is known to be unsigned.""" return { dtypes.bool: True, dtypes.uint8: True, dtypes.uint16: True, }.get(dt.base_dtype, False) def _is_known_signed_by_dtype(dt): """Helper returning True if dtype is known to be signed.""" return { dtypes.float16: True, dtypes.float32: True, dtypes.float64: True, dtypes.int8: True, dtypes.int16: True, dtypes.int32: True, dtypes.int64: True, }.get(dt.base_dtype, False) def _is_known_dtype(dt): """Helper returning True if dtype is known.""" return _is_known_unsigned_by_dtype(dt) or _is_known_signed_by_dtype(dt) def _largest_integer_by_dtype(dt): """Helper returning the largest integer exactly representable by dtype.""" if not _is_known_dtype(dt): raise TypeError("Unrecognized dtype: {}".format(dt.name)) if dt.is_floating: return int(2**(np.finfo(dt.as_numpy_dtype).nmant + 1)) if dt.is_integer: return np.iinfo(dt.as_numpy_dtype).max if dt.base_dtype == dtypes.bool: return int(1) # We actually can't land here but keep the case for completeness. raise TypeError("Unrecognized dtype: {}".format(dt.name)) def _smallest_integer_by_dtype(dt): """Helper returning the smallest integer exactly representable by dtype.""" if not _is_known_dtype(dt): raise TypeError("Unrecognized dtype: {}".format(dt.name)) if _is_known_unsigned_by_dtype(dt): return 0 return -1 * _largest_integer_by_dtype(dt) def _is_integer_like_by_dtype(dt): """Helper returning True if dtype.is_integer or is `bool`.""" if not _is_known_dtype(dt): raise TypeError("Unrecognized dtype: {}".format(dt.name)) return dt.is_integer or dt.base_dtype == dtypes.bool def embed_check_categorical_event_shape( categorical_param, name="embed_check_categorical_event_shape"): """Embeds checks that categorical distributions don't have too many classes. A categorical-type distribution is one which, e.g., returns the class label rather than a one-hot encoding. E.g., `Categorical(probs)`. Since distributions output samples in the same dtype as the parameters, we must ensure that casting doesn't lose precision. That is, the `parameter.dtype` implies a maximum number of classes. However, since shape is `int32` and categorical variables are presumed to be indexes into a `Tensor`, we must also ensure that the number of classes is no larger than the largest possible `int32` index, i.e., `2**31-1`. In other words the number of classes, `K`, must satisfy the following condition: ```python K <= min( int(2**31 - 1), # Largest float as an index. { dtypes.float16: int(2**11), # Largest int as a float16. dtypes.float32: int(2**24), dtypes.float64: int(2**53), }.get(categorical_param.dtype.base_dtype, 0)) ``` Args: categorical_param: Floating-point `Tensor` representing parameters of distribution over categories. The rightmost shape is presumed to be the number of categories. name: A name for this operation (optional). Returns: categorical_param: Input `Tensor` with appropriate assertions embedded. Raises: TypeError: if `categorical_param` has an unknown `dtype`. ValueError: if we can statically identify `categorical_param` as being too large (for being closed under int32/float casting). """ with ops.name_scope(name, values=[categorical_param]): x = ops.convert_to_tensor(categorical_param, name="categorical_param") # The size must not exceed both of: # - The largest possible int32 (since categorical values are presumed to be # indexes into a Tensor). # - The largest possible integer exactly representable under the given # floating-point dtype (since we need to cast to/from). # # The chosen floating-point thresholds are 2**(1 + mantissa_bits). # For more details, see: # https://en.wikipedia.org/wiki/Floating-point_arithmetic#Internal_representation x_dtype = x.dtype.base_dtype max_event_size = (_largest_integer_by_dtype(x_dtype) if x_dtype.is_floating else 0) if max_event_size == 0: raise TypeError("Unable to validate size of unrecognized dtype " "({}).".format(x_dtype.name)) try: x_shape_static = x.get_shape().with_rank_at_least(1) except ValueError: raise ValueError("A categorical-distribution parameter must have " "at least 1 dimension.") if tensor_shape.dimension_value(x_shape_static[-1]) is not None: event_size = x_shape_static.dims[-1].value if event_size < 2: raise ValueError("A categorical-distribution parameter must have at " "least 2 events.") if event_size > max_event_size: raise ValueError( "Number of classes exceeds `dtype` precision, i.e., " "{} implies shape ({}) cannot exceed {}.".format( x_dtype.name, event_size, max_event_size)) return x else: event_size = array_ops.shape(x, name="x_shape")[-1] return control_flow_ops.with_dependencies([ check_ops.assert_rank_at_least( x, 1, message=("A categorical-distribution parameter must have " "at least 1 dimension.")), check_ops.assert_greater_equal( array_ops.shape(x)[-1], 2, message=("A categorical-distribution parameter must have at " "least 2 events.")), check_ops.assert_less_equal( event_size, max_event_size, message="Number of classes exceeds `dtype` precision, " "i.e., {} dtype cannot exceed {} shape.".format( x_dtype.name, max_event_size)), ], x) def embed_check_integer_casting_closed( x, target_dtype, assert_nonnegative=True, name="embed_check_casting_closed"): """Ensures integers remain unaffected despite casting to/from int/float types. Example integer-types: `uint8`, `int32`, `bool`. Example floating-types: `float32`, `float64`. The largest possible integer representable by an IEEE754 floating-point is `2**(1 + mantissa_bits)` yet the largest possible integer as an int-type is `2**(bits - 1) - 1`. This function ensures that a `Tensor` purporting to have integer-form values can be cast to some other type without loss of precision. The smallest representable integer is the negative of the largest representable integer, except for types: `uint8`, `uint16`, `bool`. For these types, the smallest representable integer is `0`. Args: x: `Tensor` representing integer-form values. target_dtype: TF `dtype` under which `x` should have identical values. assert_nonnegative: `bool` indicating `x` should contain nonnegative values. name: A name for this operation (optional). Returns: x: Input `Tensor` with appropriate assertions embedded. Raises: TypeError: if `x` is neither integer- nor floating-type. TypeError: if `target_dtype` is neither integer- nor floating-type. TypeError: if neither `x` nor `target_dtype` are integer-type. """ with ops.name_scope(name, values=[x]): x = ops.convert_to_tensor(x, name="x") if (not _is_integer_like_by_dtype(x.dtype) and not x.dtype.is_floating): raise TypeError("{}.dtype must be floating- or " "integer-type.".format(x.dtype.name)) if (not _is_integer_like_by_dtype(target_dtype) and not target_dtype.is_floating): raise TypeError("target_dtype ({}) must be floating- or " "integer-type.".format(target_dtype.name)) if (not _is_integer_like_by_dtype(x.dtype) and not _is_integer_like_by_dtype(target_dtype)): raise TypeError("At least one of {}.dtype ({}) and target_dtype ({}) " "must be integer-type.".format( x, x.dtype.name, target_dtype.name)) assertions = [] if assert_nonnegative: assertions += [ check_ops.assert_non_negative( x, message="Elements must be non-negative."), ] if x.dtype.is_floating: # Being here means _is_integer_like_by_dtype(target_dtype) = True. # Since this check implies the magnitude check below, we need only it. assertions += [ assert_integer_form( x, int_dtype=target_dtype, message="Elements must be {}-equivalent.".format( target_dtype.name)), ] else: if (_largest_integer_by_dtype(x.dtype) > _largest_integer_by_dtype(target_dtype)): # Cast may lose integer precision. assertions += [ check_ops.assert_less_equal( x, _largest_integer_by_dtype(target_dtype), message=("Elements cannot exceed {}.".format( _largest_integer_by_dtype(target_dtype)))), ] if (not assert_nonnegative and (_smallest_integer_by_dtype(x.dtype) < _smallest_integer_by_dtype(target_dtype))): assertions += [ check_ops.assert_greater_equal( x, _smallest_integer_by_dtype(target_dtype), message=("Elements cannot be smaller than {}.".format( _smallest_integer_by_dtype(target_dtype)))), ] if not assertions: return x return control_flow_ops.with_dependencies(assertions, x) def log_combinations(n, counts, name="log_combinations"): """Multinomial coefficient. Given `n` and `counts`, where `counts` has last dimension `k`, we compute the multinomial coefficient as: ```n! / sum_i n_i!``` where `i` runs over all `k` classes. Args: n: Floating-point `Tensor` broadcastable with `counts`. This represents `n` outcomes. counts: Floating-point `Tensor` broadcastable with `n`. This represents counts in `k` classes, where `k` is the last dimension of the tensor. name: A name for this operation (optional). Returns: `Tensor` representing the multinomial coefficient between `n` and `counts`. """ # First a bit about the number of ways counts could have come in: # E.g. if counts = [1, 2], then this is 3 choose 2. # In general, this is (sum counts)! / sum(counts!) # The sum should be along the last dimension of counts. This is the # "distribution" dimension. Here n a priori represents the sum of counts. with ops.name_scope(name, values=[n, counts]): n = ops.convert_to_tensor(n, name="n") counts = ops.convert_to_tensor(counts, name="counts") total_permutations = math_ops.lgamma(n + 1) counts_factorial = math_ops.lgamma(counts + 1) redundant_permutations = math_ops.reduce_sum(counts_factorial, axis=[-1]) return total_permutations - redundant_permutations def matrix_diag_transform(matrix, transform=None, name=None): """Transform diagonal of [batch-]matrix, leave rest of matrix unchanged. Create a trainable covariance defined by a Cholesky factor: ```python # Transform network layer into 2 x 2 array. matrix_values = tf.contrib.layers.fully_connected(activations, 4) matrix = tf.reshape(matrix_values, (batch_size, 2, 2)) # Make the diagonal positive. If the upper triangle was zero, this would be a # valid Cholesky factor. chol = matrix_diag_transform(matrix, transform=tf.nn.softplus) # LinearOperatorLowerTriangular ignores the upper triangle. operator = LinearOperatorLowerTriangular(chol) ``` Example of heteroskedastic 2-D linear regression. ```python tfd = tfp.distributions # Get a trainable Cholesky factor. matrix_values = tf.contrib.layers.fully_connected(activations, 4) matrix = tf.reshape(matrix_values, (batch_size, 2, 2)) chol = matrix_diag_transform(matrix, transform=tf.nn.softplus) # Get a trainable mean. mu = tf.contrib.layers.fully_connected(activations, 2) # This is a fully trainable multivariate normal! dist = tfd.MultivariateNormalTriL(mu, chol) # Standard log loss. Minimizing this will "train" mu and chol, and then dist # will be a distribution predicting labels as multivariate Gaussians. loss = -1 * tf.reduce_mean(dist.log_prob(labels)) ``` Args: matrix: Rank `R` `Tensor`, `R >= 2`, where the last two dimensions are equal. transform: Element-wise function mapping `Tensors` to `Tensors`. To be applied to the diagonal of `matrix`. If `None`, `matrix` is returned unchanged. Defaults to `None`. name: A name to give created ops. Defaults to "matrix_diag_transform". Returns: A `Tensor` with same shape and `dtype` as `matrix`. """ with ops.name_scope(name, "matrix_diag_transform", [matrix]): matrix = ops.convert_to_tensor(matrix, name="matrix") if transform is None: return matrix # Replace the diag with transformed diag. diag = array_ops.matrix_diag_part(matrix) transformed_diag = transform(diag) transformed_mat = array_ops.matrix_set_diag(matrix, transformed_diag) return transformed_mat def rotate_transpose(x, shift, name="rotate_transpose"): """Circularly moves dims left or right. Effectively identical to: ```python numpy.transpose(x, numpy.roll(numpy.arange(len(x.shape)), shift)) ``` When `validate_args=False` additional graph-runtime checks are performed. These checks entail moving data from to GPU to CPU. Example: ```python x = tf.random_normal([1, 2, 3, 4]) # Tensor of shape [1, 2, 3, 4]. rotate_transpose(x, -1).shape == [2, 3, 4, 1] rotate_transpose(x, -2).shape == [3, 4, 1, 2] rotate_transpose(x, 1).shape == [4, 1, 2, 3] rotate_transpose(x, 2).shape == [3, 4, 1, 2] rotate_transpose(x, 7).shape == rotate_transpose(x, 3).shape # [2, 3, 4, 1] rotate_transpose(x, -7).shape == rotate_transpose(x, -3).shape # [4, 1, 2, 3] ``` Args: x: `Tensor`. shift: `Tensor`. Number of dimensions to transpose left (shift<0) or transpose right (shift>0). name: Python `str`. The name to give this op. Returns: rotated_x: Input `Tensor` with dimensions circularly rotated by shift. Raises: TypeError: if shift is not integer type. """ with ops.name_scope(name, values=[x, shift]): x = ops.convert_to_tensor(x, name="x") shift = ops.convert_to_tensor(shift, name="shift") # We do not assign back to preserve constant-ness. check_ops.assert_integer(shift) shift_value_static = tensor_util.constant_value(shift) ndims = x.get_shape().ndims if ndims is not None and shift_value_static is not None: if ndims < 2: return x shift_value_static = np.sign(shift_value_static) * ( abs(shift_value_static) % ndims) if shift_value_static == 0: return x perm = np.roll(np.arange(ndims), shift_value_static) return array_ops.transpose(x, perm=perm) else: # Consider if we always had a positive shift, and some specified # direction. # When shifting left we want the new array: # last(x, n-shift) + first(x, shift) # and if shifting right then we want: # last(x, shift) + first(x, n-shift) # Observe that last(a) == slice(a, n) and first(a) == slice(0, a). # Also, we can encode direction and shift as one: direction * shift. # Combining these facts, we have: # a = cond(shift<0, -shift, n-shift) # last(x, n-a) + first(x, a) == x[a:n] + x[0:a] # Finally, we transform shift by modulo length so it can be specified # independently from the array upon which it operates (like python). ndims = array_ops.rank(x) shift = array_ops.where(math_ops.less(shift, 0), math_ops.mod(-shift, ndims), ndims - math_ops.mod(shift, ndims)) first = math_ops.range(0, shift) last = math_ops.range(shift, ndims) perm = array_ops.concat([last, first], 0) return array_ops.transpose(x, perm=perm) def pick_vector(cond, true_vector, false_vector, name="pick_vector"): """Picks possibly different length row `Tensor`s based on condition. Value `Tensor`s should have exactly one dimension. If `cond` is a python Boolean or `tf.constant` then either `true_vector` or `false_vector` is immediately returned. I.e., no graph nodes are created and no validation happens. Args: cond: `Tensor`. Must have `dtype=tf.bool` and be scalar. true_vector: `Tensor` of one dimension. Returned when cond is `True`. false_vector: `Tensor` of one dimension. Returned when cond is `False`. name: Python `str`. The name to give this op. Example: ```python pick_vector(tf.less(0, 5), tf.range(10, 12), tf.range(15, 18)) # [10, 11] pick_vector(tf.less(5, 0), tf.range(10, 12), tf.range(15, 18)) # [15, 16, 17] ``` Returns: true_or_false_vector: `Tensor`. Raises: TypeError: if `cond.dtype != tf.bool` TypeError: if `cond` is not a constant and `true_vector.dtype != false_vector.dtype` """ with ops.name_scope(name, values=(cond, true_vector, false_vector)): cond = ops.convert_to_tensor(cond, name="cond") if cond.dtype != dtypes.bool: raise TypeError("%s.dtype=%s which is not %s" % (cond, cond.dtype, dtypes.bool)) cond_value_static = tensor_util.constant_value(cond) if cond_value_static is not None: return true_vector if cond_value_static else false_vector true_vector = ops.convert_to_tensor(true_vector, name="true_vector") false_vector = ops.convert_to_tensor(false_vector, name="false_vector") if true_vector.dtype != false_vector.dtype: raise TypeError( "%s.dtype=%s does not match %s.dtype=%s" % (true_vector, true_vector.dtype, false_vector, false_vector.dtype)) n = array_ops.shape(true_vector)[0] return array_ops.slice( array_ops.concat([true_vector, false_vector], 0), [array_ops.where(cond, 0, n)], [array_ops.where(cond, n, -1)]) def prefer_static_broadcast_shape( shape1, shape2, name="prefer_static_broadcast_shape"): """Convenience function which statically broadcasts shape when possible. Args: shape1: `1-D` integer `Tensor`. Already converted to tensor! shape2: `1-D` integer `Tensor`. Already converted to tensor! name: A string name to prepend to created ops. Returns: The broadcast shape, either as `TensorShape` (if broadcast can be done statically), or as a `Tensor`. """ with ops.name_scope(name, values=[shape1, shape2]): def make_shape_tensor(x): return ops.convert_to_tensor(x, name="shape", dtype=dtypes.int32) def get_tensor_shape(s): if isinstance(s, tensor_shape.TensorShape): return s s_ = tensor_util.constant_value(make_shape_tensor(s)) if s_ is not None: return tensor_shape.TensorShape(s_) return None def get_shape_tensor(s): if not isinstance(s, tensor_shape.TensorShape): return make_shape_tensor(s) if s.is_fully_defined(): return make_shape_tensor(s.as_list()) raise ValueError("Cannot broadcast from partially " "defined `TensorShape`.") shape1_ = get_tensor_shape(shape1) shape2_ = get_tensor_shape(shape2) if shape1_ is not None and shape2_ is not None: return array_ops.broadcast_static_shape(shape1_, shape2_) shape1_ = get_shape_tensor(shape1) shape2_ = get_shape_tensor(shape2) return array_ops.broadcast_dynamic_shape(shape1_, shape2_) def prefer_static_rank(x): """Return static rank of tensor `x` if available, else `tf.rank(x)`. Args: x: `Tensor` (already converted). Returns: Numpy array (if static rank is obtainable), else `Tensor`. """ return prefer_static_value(array_ops.rank(x)) def prefer_static_shape(x): """Return static shape of tensor `x` if available, else `tf.shape(x)`. Args: x: `Tensor` (already converted). Returns: Numpy array (if static shape is obtainable), else `Tensor`. """ return prefer_static_value(array_ops.shape(x)) def prefer_static_value(x): """Return static value of tensor `x` if available, else `x`. Args: x: `Tensor` (already converted). Returns: Numpy array (if static value is obtainable), else `Tensor`. """ static_x = tensor_util.constant_value(x) if static_x is not None: return static_x return x def gen_new_seed(seed, salt): """Generate a new seed, from the given seed and salt.""" if seed is None: return None string = (str(seed) + salt).encode("utf-8") return int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF def fill_triangular(x, upper=False, name=None): """Creates a (batch of) triangular matrix from a vector of inputs. Created matrix can be lower- or upper-triangular. (It is more efficient to create the matrix as upper or lower, rather than transpose.) Triangular matrix elements are filled in a clockwise spiral. See example, below. If `x.get_shape()` is `[b1, b2, ..., bB, d]` then the output shape is `[b1, b2, ..., bB, n, n]` where `n` is such that `d = n(n+1)/2`, i.e., `n = int(np.sqrt(0.25 + 2. * m) - 0.5)`. Example: ```python fill_triangular([1, 2, 3, 4, 5, 6]) # ==> [[4, 0, 0], # [6, 5, 0], # [3, 2, 1]] fill_triangular([1, 2, 3, 4, 5, 6], upper=True) # ==> [[1, 2, 3], # [0, 5, 6], # [0, 0, 4]] ``` For comparison, a pure numpy version of this function can be found in `util_test.py`, function `_fill_triangular`. Args: x: `Tensor` representing lower (or upper) triangular elements. upper: Python `bool` representing whether output matrix should be upper triangular (`True`) or lower triangular (`False`, default). name: Python `str`. The name to give this op. Returns: tril: `Tensor` with lower (or upper) triangular elements filled from `x`. Raises: ValueError: if `x` cannot be mapped to a triangular matrix. """ with ops.name_scope(name, "fill_triangular", values=[x]): x = ops.convert_to_tensor(x, name="x") if tensor_shape.dimension_value( x.shape.with_rank_at_least(1)[-1]) is not None: # Formula derived by solving for n: m = n(n+1)/2. m = np.int32(x.shape.dims[-1].value) n = np.sqrt(0.25 + 2. * m) - 0.5 if n != np.floor(n): raise ValueError("Input right-most shape ({}) does not " "correspond to a triangular matrix.".format(m)) n = np.int32(n) static_final_shape = x.shape[:-1].concatenate([n, n]) else: m = array_ops.shape(x)[-1] # For derivation, see above. Casting automatically lops off the 0.5, so we # omit it. We don't validate n is an integer because this has # graph-execution cost; an error will be thrown from the reshape, below. n = math_ops.cast( math_ops.sqrt(0.25 + math_ops.cast(2 * m, dtype=dtypes.float32)), dtype=dtypes.int32) static_final_shape = x.shape.with_rank_at_least(1)[:-1].concatenate( [None, None]) # We now concatenate the "tail" of `x` to `x` (and reverse one of them). # # We do this based on the insight that the input `x` provides `ceil(n/2)` # rows of an `n x n` matrix, some of which will get zeroed out being on the # wrong side of the diagonal. The first row will not get zeroed out at all, # and we need `floor(n/2)` more rows, so the first is what we omit from # `x_tail`. If we then stack those `ceil(n/2)` rows with the `floor(n/2)` # rows provided by a reversed tail, it is exactly the other set of elements # of the reversed tail which will be zeroed out for being on the wrong side # of the diagonal further up/down the matrix. And, in doing-so, we've filled # the triangular matrix in a clock-wise spiral pattern. Neat! # # Try it out in numpy: # n = 3 # x = np.arange(n * (n + 1) / 2) # m = x.shape[0] # n = np.int32(np.sqrt(.25 + 2 * m) - .5) # x_tail = x[(m - (n**2 - m)):] # np.concatenate([x_tail, x[::-1]], 0).reshape(n, n) # lower # # ==> array([[3, 4, 5], # [5, 4, 3], # [2, 1, 0]]) # np.concatenate([x, x_tail[::-1]], 0).reshape(n, n) # upper # # ==> array([[0, 1, 2], # [3, 4, 5], # [5, 4, 3]]) # # Note that we can't simply do `x[..., -(n**2 - m):]` because this doesn't # correctly handle `m == n == 1`. Hence, we do nonnegative indexing. # Furthermore observe that: # m - (n**2 - m) # = n**2 / 2 + n / 2 - (n**2 - n**2 / 2 + n / 2) # = 2 (n**2 / 2 + n / 2) - n**2 # = n**2 + n - n**2 # = n ndims = prefer_static_rank(x) if upper: x_list = [x, array_ops.reverse(x[..., n:], axis=[ndims - 1])] else: x_list = [x[..., n:], array_ops.reverse(x, axis=[ndims - 1])] new_shape = ( static_final_shape.as_list() if static_final_shape.is_fully_defined() else array_ops.concat([array_ops.shape(x)[:-1], [n, n]], axis=0)) x = array_ops.reshape(array_ops.concat(x_list, axis=-1), new_shape) x = array_ops.matrix_band_part( x, num_lower=(0 if upper else -1), num_upper=(-1 if upper else 0)) x.set_shape(static_final_shape) return x def fill_triangular_inverse(x, upper=False, name=None): """Creates a vector from a (batch of) triangular matrix. The vector is created from the lower-triangular or upper-triangular portion depending on the value of the parameter `upper`. If `x.shape` is `[b1, b2, ..., bB, n, n]` then the output shape is `[b1, b2, ..., bB, d]` where `d = n (n + 1) / 2`. Example: ```python fill_triangular_inverse( [[4, 0, 0], [6, 5, 0], [3, 2, 1]]) # ==> [1, 2, 3, 4, 5, 6] fill_triangular_inverse( [[1, 2, 3], [0, 5, 6], [0, 0, 4]], upper=True) # ==> [1, 2, 3, 4, 5, 6] ``` Args: x: `Tensor` representing lower (or upper) triangular elements. upper: Python `bool` representing whether output matrix should be upper triangular (`True`) or lower triangular (`False`, default). name: Python `str`. The name to give this op. Returns: flat_tril: (Batch of) vector-shaped `Tensor` representing vectorized lower (or upper) triangular elements from `x`. """ with ops.name_scope(name, "fill_triangular_inverse", values=[x]): x = ops.convert_to_tensor(x, name="x") if tensor_shape.dimension_value( x.shape.with_rank_at_least(2)[-1]) is not None: n = np.int32(x.shape.dims[-1].value) m = np.int32((n * (n + 1)) // 2) static_final_shape = x.shape[:-2].concatenate([m]) else: n = array_ops.shape(x)[-1] m = (n * (n + 1)) // 2 static_final_shape = x.shape.with_rank_at_least(2)[:-2].concatenate( [None]) ndims = prefer_static_rank(x) if upper: initial_elements = x[..., 0, :] triangular_portion = x[..., 1:, :] else: initial_elements = array_ops.reverse(x[..., -1, :], axis=[ndims - 2]) triangular_portion = x[..., :-1, :] rotated_triangular_portion = array_ops.reverse( array_ops.reverse(triangular_portion, axis=[ndims - 1]), axis=[ndims - 2]) consolidated_matrix = triangular_portion + rotated_triangular_portion end_sequence = array_ops.reshape( consolidated_matrix, array_ops.concat([array_ops.shape(x)[:-2], [n * (n - 1)]], axis=0)) y = array_ops.concat([initial_elements, end_sequence[..., :m - n]], axis=-1) y.set_shape(static_final_shape) return y def tridiag(below=None, diag=None, above=None, name=None): """Creates a matrix with values set above, below, and on the diagonal. Example: ```python tridiag(below=[1., 2., 3.], diag=[4., 5., 6., 7.], above=[8., 9., 10.]) # ==> array([[ 4., 8., 0., 0.], # [ 1., 5., 9., 0.], # [ 0., 2., 6., 10.], # [ 0., 0., 3., 7.]], dtype=float32) ``` Warning: This Op is intended for convenience, not efficiency. Args: below: `Tensor` of shape `[B1, ..., Bb, d-1]` corresponding to the below diagonal part. `None` is logically equivalent to `below = 0`. diag: `Tensor` of shape `[B1, ..., Bb, d]` corresponding to the diagonal part. `None` is logically equivalent to `diag = 0`. above: `Tensor` of shape `[B1, ..., Bb, d-1]` corresponding to the above diagonal part. `None` is logically equivalent to `above = 0`. name: Python `str`. The name to give this op. Returns: tridiag: `Tensor` with values set above, below and on the diagonal. Raises: ValueError: if all inputs are `None`. """ def _pad(x): """Prepends and appends a zero to every vector in a batch of vectors.""" shape = array_ops.concat([array_ops.shape(x)[:-1], [1]], axis=0) z = array_ops.zeros(shape, dtype=x.dtype) return array_ops.concat([z, x, z], axis=-1) def _add(*x): """Adds list of Tensors, ignoring `None`.""" s = None for y in x: if y is None: continue elif s is None: s = y else: s += y if s is None: raise ValueError("Must specify at least one of `below`, `diag`, `above`.") return s with ops.name_scope(name, "tridiag", [below, diag, above]): if below is not None: below = ops.convert_to_tensor(below, name="below") below = array_ops.matrix_diag(_pad(below))[..., :-1, 1:] if diag is not None: diag = ops.convert_to_tensor(diag, name="diag") diag = array_ops.matrix_diag(diag) if above is not None: above = ops.convert_to_tensor(above, name="above") above = array_ops.matrix_diag(_pad(above))[..., 1:, :-1] # TODO(jvdillon): Consider using scatter_nd instead of creating three full # matrices. return _add(below, diag, above) def reduce_weighted_logsumexp( logx, w=None, axis=None, keep_dims=False, return_sign=False, name=None): """Computes `log(abs(sum(weight * exp(elements across tensor dimensions))))`. If all weights `w` are known to be positive, it is more efficient to directly use `reduce_logsumexp`, i.e., `tf.reduce_logsumexp(logx + tf.log(w))` is more efficient than `du.reduce_weighted_logsumexp(logx, w)`. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `axis` has no entries, all dimensions are reduced, and a tensor with a single element is returned. This function is more numerically stable than log(sum(w * exp(input))). It avoids overflows caused by taking the exp of large inputs and underflows caused by taking the log of small inputs. For example: ```python x = tf.constant([[0., 0, 0], [0, 0, 0]]) w = tf.constant([[-1., 1, 1], [1, 1, 1]]) du.reduce_weighted_logsumexp(x, w) # ==> log(-1*1 + 1*1 + 1*1 + 1*1 + 1*1 + 1*1) = log(4) du.reduce_weighted_logsumexp(x, w, axis=0) # ==> [log(-1+1), log(1+1), log(1+1)] du.reduce_weighted_logsumexp(x, w, axis=1) # ==> [log(-1+1+1), log(1+1+1)] du.reduce_weighted_logsumexp(x, w, axis=1, keep_dims=True) # ==> [[log(-1+1+1)], [log(1+1+1)]] du.reduce_weighted_logsumexp(x, w, axis=[0, 1]) # ==> log(-1+5) ``` Args: logx: The tensor to reduce. Should have numeric type. w: The weight tensor. Should have numeric type identical to `logx`. axis: The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. keep_dims: If true, retains reduced dimensions with length 1. return_sign: If `True`, returns the sign of the result. name: A name for the operation (optional). Returns: lswe: The `log(abs(sum(weight * exp(x))))` reduced tensor. sign: (Optional) The sign of `sum(weight * exp(x))`. """ with ops.name_scope(name, "reduce_weighted_logsumexp", [logx, w]): logx = ops.convert_to_tensor(logx, name="logx") if w is None: lswe = math_ops.reduce_logsumexp(logx, axis=axis, keepdims=keep_dims) if return_sign: sgn = array_ops.ones_like(lswe) return lswe, sgn return lswe w = ops.convert_to_tensor(w, dtype=logx.dtype, name="w") log_absw_x = logx + math_ops.log(math_ops.abs(w)) max_log_absw_x = math_ops.reduce_max(log_absw_x, axis=axis, keepdims=True) # If the largest element is `-inf` or `inf` then we don't bother subtracting # off the max. We do this because otherwise we'd get `inf - inf = NaN`. That # this is ok follows from the fact that we're actually free to subtract any # value we like, so long as we add it back after taking the `log(sum(...))`. max_log_absw_x = array_ops.where( math_ops.is_inf(max_log_absw_x), array_ops.zeros_like(max_log_absw_x), max_log_absw_x) wx_over_max_absw_x = ( math_ops.sign(w) * math_ops.exp(log_absw_x - max_log_absw_x)) sum_wx_over_max_absw_x = math_ops.reduce_sum( wx_over_max_absw_x, axis=axis, keepdims=keep_dims) if not keep_dims: max_log_absw_x = array_ops.squeeze(max_log_absw_x, axis) sgn = math_ops.sign(sum_wx_over_max_absw_x) lswe = max_log_absw_x + math_ops.log(sgn * sum_wx_over_max_absw_x) if return_sign: return lswe, sgn return lswe # TODO(jvdillon): Merge this test back into: # tensorflow/python/ops/softplus_op_test.py # once TF core is accepting new ops. def softplus_inverse(x, name=None): """Computes the inverse softplus, i.e., x = softplus_inverse(softplus(x)). Mathematically this op is equivalent to: ```none softplus_inverse = log(exp(x) - 1.) ``` Args: x: `Tensor`. Non-negative (not enforced), floating-point. name: A name for the operation (optional). Returns: `Tensor`. Has the same type/shape as input `x`. """ with ops.name_scope(name, "softplus_inverse", values=[x]): x = ops.convert_to_tensor(x, name="x") # We begin by deriving a more numerically stable softplus_inverse: # x = softplus(y) = Log[1 + exp{y}], (which means x > 0). # ==> exp{x} = 1 + exp{y} (1) # ==> y = Log[exp{x} - 1] (2) # = Log[(exp{x} - 1) / exp{x}] + Log[exp{x}] # = Log[(1 - exp{-x}) / 1] + Log[exp{x}] # = Log[1 - exp{-x}] + x (3) # (2) is the "obvious" inverse, but (3) is more stable than (2) for large x. # For small x (e.g. x = 1e-10), (3) will become -inf since 1 - exp{-x} will # be zero. To fix this, we use 1 - exp{-x} approx x for small x > 0. # # In addition to the numerically stable derivation above, we clamp # small/large values to be congruent with the logic in: # tensorflow/core/kernels/softplus_op.h # # Finally, we set the input to one whenever the input is too large or too # small. This ensures that no unchosen codepath is +/- inf. This is # necessary to ensure the gradient doesn't get NaNs. Recall that the # gradient of `where` behaves like `pred*pred_true + (1-pred)*pred_false` # thus an `inf` in an unselected path results in `0*inf=nan`. We are careful # to overwrite `x` with ones only when we will never actually use this # value. Note that we use ones and not zeros since `log(expm1(0.)) = -inf`. threshold = np.log(np.finfo(x.dtype.as_numpy_dtype).eps) + 2. is_too_small = math_ops.less(x, np.exp(threshold)) is_too_large = math_ops.greater(x, -threshold) too_small_value = math_ops.log(x) too_large_value = x # This `where` will ultimately be a NOP because we won't select this # codepath whenever we used the surrogate `ones_like`. x = array_ops.where(math_ops.logical_or(is_too_small, is_too_large), array_ops.ones_like(x), x) y = x + math_ops.log(-math_ops.expm1(-x)) # == log(expm1(x)) return array_ops.where(is_too_small, too_small_value, array_ops.where(is_too_large, too_large_value, y)) # TODO(b/35290280): Add unit-tests. def dimension_size(x, axis): """Returns the size of a specific dimension.""" # Since tf.gather isn't "constant-in, constant-out", we must first check the # static shape or fallback to dynamic shape. s = tensor_shape.dimension_value( x.shape.with_rank_at_least(np.abs(axis))[axis]) if s is not None: return s return array_ops.shape(x)[axis] def process_quadrature_grid_and_probs( quadrature_grid_and_probs, dtype, validate_args, name=None): """Validates quadrature grid, probs or computes them as necessary. Args: quadrature_grid_and_probs: Python pair of `float`-like `Tensor`s representing the sample points and the corresponding (possibly normalized) weight. When `None`, defaults to: `np.polynomial.hermite.hermgauss(deg=8)`. dtype: The expected `dtype` of `grid` and `probs`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. name: Python `str` name prefixed to Ops created by this class. Returns: quadrature_grid_and_probs: Python pair of `float`-like `Tensor`s representing the sample points and the corresponding (possibly normalized) weight. Raises: ValueError: if `quadrature_grid_and_probs is not None` and `len(quadrature_grid_and_probs[0]) != len(quadrature_grid_and_probs[1])` """ with ops.name_scope(name, "process_quadrature_grid_and_probs", [quadrature_grid_and_probs]): if quadrature_grid_and_probs is None: grid, probs = np.polynomial.hermite.hermgauss(deg=8) grid = grid.astype(dtype.as_numpy_dtype) probs = probs.astype(dtype.as_numpy_dtype) probs /= np.linalg.norm(probs, ord=1, keepdims=True) grid = ops.convert_to_tensor(grid, name="grid", dtype=dtype) probs = ops.convert_to_tensor(probs, name="probs", dtype=dtype) return grid, probs grid, probs = tuple(quadrature_grid_and_probs) grid = ops.convert_to_tensor(grid, name="grid", dtype=dtype) probs = ops.convert_to_tensor(probs, name="unnormalized_probs", dtype=dtype) probs /= linalg_ops.norm(probs, ord=1, axis=-1, keepdims=True, name="probs") def _static_event_size(x): """Returns the static size of a specific dimension or `None`.""" return tensor_shape.dimension_value(x.shape.with_rank_at_least(1)[-1]) m, n = _static_event_size(probs), _static_event_size(grid) if m is not None and n is not None: if m != n: raise ValueError("`quadrature_grid_and_probs` must be a `tuple` of " "same-length zero-th-dimension `Tensor`s " "(saw lengths {}, {})".format(m, n)) elif validate_args: assertions = [ check_ops.assert_equal( dimension_size(probs, axis=-1), dimension_size(grid, axis=-1), message=("`quadrature_grid_and_probs` must be a `tuple` of " "same-length zero-th-dimension `Tensor`s")), ] with ops.control_dependencies(assertions): grid = array_ops.identity(grid) probs = array_ops.identity(probs) return grid, probs def pad(x, axis, front=False, back=False, value=0, count=1, name=None): """Pads `value` to the front and/or back of a `Tensor` dim, `count` times. Args: x: `Tensor` input. axis: Scalar `int`-like `Tensor` representing the single dimension to pad. (Negative indexing is supported.) front: Python `bool`; if `True` the beginning of the `axis` dimension is padded with `value`, `count` times. If `False` no front padding is made. back: Python `bool`; if `True` the end of the `axis` dimension is padded with `value`, `count` times. If `False` no end padding is made. value: Scalar `int`-like `Tensor` representing the actual value added to the front and/or back of the `axis` dimension of `x`. count: Scalar `int`-like `Tensor` representing number of elements added to the front and/or back of the `axis` dimension of `x`. E.g., if `front = back = True` then `2 * count` elements are added. name: Python `str` name prefixed to Ops created by this function. Returns: pad: The padded version of input `x`. Raises: ValueError: if both `front` and `back` are `False`. TypeError: if `count` is not `int`-like. """ with ops.name_scope(name, "pad", [x, value, count]): x = ops.convert_to_tensor(x, name="x") value = ops.convert_to_tensor(value, dtype=x.dtype, name="value") count = ops.convert_to_tensor(count, name="count") if not count.dtype.is_integer: raise TypeError("`count.dtype` (`{}`) must be `int`-like.".format( count.dtype.name)) if not front and not back: raise ValueError("At least one of `front`, `back` must be `True`.") ndims = (x.shape.ndims if x.shape.ndims is not None else array_ops.rank(x, name="ndims")) axis = ops.convert_to_tensor(axis, name="axis") axis_ = tensor_util.constant_value(axis) if axis_ is not None: axis = axis_ if axis < 0: axis = ndims + axis count_ = tensor_util.constant_value(count) if axis_ >= 0 or x.shape.ndims is not None: head = x.shape[:axis] middle = tensor_shape.TensorShape( None if count_ is None else (tensor_shape.dimension_at_index( x.shape, axis) + count_ * (front + back))) tail = x.shape[axis+1:] final_shape = head.concatenate(middle.concatenate(tail)) else: final_shape = None else: axis = array_ops.where(axis < 0, ndims + axis, axis) final_shape = None x = array_ops.pad( x, paddings=array_ops.one_hot( indices=array_ops.stack([axis if front else -1, axis if back else -1]), depth=ndims, axis=0, on_value=count, dtype=dtypes.int32), constant_values=value) if final_shape is not None: x.set_shape(final_shape) return x def parent_frame_arguments(): """Returns parent frame arguments. When called inside a function, returns a dictionary with the caller's function arguments. These are positional arguments and keyword arguments (**kwargs), while variable arguments (*varargs) are excluded. When called at global scope, this will return an empty dictionary, since there are no arguments. WARNING: If caller function argument names are overloaded before invoking this method, then values will reflect the overloaded value. For this reason, we recommend calling `parent_frame_arguments` at the beginning of the function. """ # All arguments and the names used for *varargs, and **kwargs arg_names, variable_arg_name, keyword_arg_name, local_vars = ( tf_inspect._inspect.getargvalues( # pylint: disable=protected-access # Get the first frame of the caller of this method. tf_inspect._inspect.stack()[1][0])) # pylint: disable=protected-access # Remove the *varargs, and flatten the **kwargs. Both are # nested lists. local_vars.pop(variable_arg_name, {}) keyword_args = local_vars.pop(keyword_arg_name, {}) final_args = {} # Copy over arguments and their values. In general, local_vars # may contain more than just the arguments, since this method # can be called anywhere in a function. for arg_name in arg_names: final_args[arg_name] = local_vars.pop(arg_name) final_args.update(keyword_args) return final_args class AppendDocstring(object): """Helper class to promote private subclass docstring to public counterpart. Example: ```python class TransformedDistribution(Distribution): @distribution_util.AppendDocstring( additional_note="A special note!", kwargs_dict={"foo": "An extra arg."}) def _prob(self, y, foo=None): pass ``` In this case, the `AppendDocstring` decorator appends the `additional_note` to the docstring of `prob` (not `_prob`) and adds a new `kwargs` section with each dictionary item as a bullet-point. For a more detailed example, see `TransformedDistribution`. """ def __init__(self, additional_note="", kwargs_dict=None): """Initializes the AppendDocstring object. Args: additional_note: Python string added as additional docstring to public version of function. kwargs_dict: Python string/string dictionary representing specific kwargs expanded from the **kwargs input. Raises: ValueError: if kwargs_dict.key contains whitespace. ValueError: if kwargs_dict.value contains newlines. """ self._additional_note = additional_note if kwargs_dict: bullets = [] for key in sorted(kwargs_dict.keys()): value = kwargs_dict[key] if any(x.isspace() for x in key): raise ValueError( "Parameter name \"%s\" contains whitespace." % key) value = value.lstrip() if "\n" in value: raise ValueError( "Parameter description for \"%s\" contains newlines." % key) bullets.append("* `%s`: %s" % (key, value)) self._additional_note += ("\n\n##### `kwargs`:\n\n" + "\n".join(bullets)) def __call__(self, fn): @functools.wraps(fn) def _fn(*args, **kwargs): return fn(*args, **kwargs) if _fn.__doc__ is None: _fn.__doc__ = self._additional_note else: _fn.__doc__ += "\n%s" % self._additional_note return _fn
jbedorf/tensorflow
tensorflow/python/ops/distributions/util.py
Python
apache-2.0
54,998
0.005364
#!/usr/bin/env python import os import sys ## A name of directory containing 'path:...' file ## You can download them using 'make-wget_pathway.sh' script dir_name = sys.argv[1] f_summary = open('%s.summary'%dir_name,'w') f_genes = open('%s.genes'%dir_name,'w') f_compounds = open('%s.compounds'%dir_name,'w') gene_total = [] for filename in os.listdir( dir_name ): if( not filename.startswith('path:') ): continue #sys.stderr.write('Read %s ... '%filename) path_id = '' path_name = '' gene_list = [] comp_list = [] prev_tag = '' f = open(os.path.join(dir_name,filename),'r') for line in f: tmp_tag = line[:11].strip() if( tmp_tag == 'ENTRY' ): path_id = line.strip().split()[1] if( tmp_tag == 'NAME' ): path_name = line[11:].split(' - ')[0].strip() if( tmp_tag == 'COMPOUND' ): comp_list.append( line[11:].strip().split()[0] ) f_compounds.write('path:%s\t%s\n'%(path_id,line[11:].strip())) elif( tmp_tag == '' and prev_tag == 'COMPOUND' ): comp_list.append( line[11:].strip().split()[0] ) f_compounds.write('path:%s\t%s\n'%(path_id,line[11:].strip())) elif( tmp_tag == 'GENE' ): gene_list.append( line[11:].strip().split()[0] ) f_genes.write('path:%s\t%s\n'%(path_id,line[11:].strip())) #print line[11:].strip() elif( tmp_tag == '' and prev_tag == 'GENE' ): gene_list.append( line[11:].strip().split()[0] ) f_genes.write('path:%s\t%s\n'%(path_id,line[11:].strip())) #print line[11:].strip() if( tmp_tag != '' ): prev_tag = tmp_tag f.close() if( len(gene_list) == 0 ): sys.stderr.write('//SKIP// %s(%d) %s\n'%(path_id, len(gene_list), path_name)) continue f_summary.write('path:%s\t%s\t%d\t%d\n'%(path_id, path_name, len(gene_list), len(comp_list))) f_summary.close() f_genes.close() f_compounds.close()
taejoonlab/taejoonlab-toolbox
KEGG/make-pathway2list.py
Python
gpl-3.0
2,013
0.027322
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA 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. # # SPDX-License-Identifier: Apache-2.0 import re import argparse import json import functools from utils import parse_raw_timing, merged_dict # ============================================================================= NUMBER_RE = re.compile(r'\d+$') def get_sdf_type(type): """ Returns a SDF timing type for the given type plus information whether it is sequential or not. Returns None, None if the type is unknown """ # Known keywords and their SDF counterparts seq_keywords = { "Setup": "setup", "Hold": "hold", "Recov": "recovery", "Remov": "removal", } comb_keywords = { "Prop": "iopath", } # Sequential if type in seq_keywords: return seq_keywords[type], True # Combinational if type in comb_keywords: return comb_keywords[type], False # Unknown return None, None def parse_logical_names(phy_type, log_names, cell_pins): """ Parses logical cell names. Extracts the cell name, input pin name and output pin name. Uses dumped library cell definitions to achive that since a logical name string uses "_" as a separator and "_" can also occur in cell/pin name. Returns a list of tuples with (cell_name, src_pin, dst_pin) """ log_cells = [] # Process logical names that should correspond to bel timings for log_name in log_names.split(","): # Since both cell and pin names may also contain "_" the # logical name is split iteratively. # The timing type is the first, it has to equal the timing # type of the speed model if not log_name.startswith(phy_type): continue log_name = log_name[len(phy_type) + 1:] # Find the cell name in the library and strip it for c in cell_pins: if log_name.startswith(c): log_cell = c log_name = log_name[len(c) + 1:] break else: continue log_pins = cell_pins[log_cell] # Find the input pin in the library and strip it for p in log_pins: if log_name.startswith(p): log_src = p log_name = log_name[len(p) + 1:] break else: continue # Find the output pin in the library and strip it for p in log_pins: if log_name == p: log_dst = p break else: continue # Append log_cells.append(( log_cell, log_src, log_dst, )) return log_cells def read_raw_timings(fin, cell_pins): """ Reads and parses raw timings, converts them into data used for SDF generation. """ REGEX_CFG = re.compile(r".*__CFG([0-9]+)$") def inner(): raw = list(parse_raw_timing(fin)) for slice, site_name, bel_name, speed_model, properties in raw: # Check if we have a bel timing # TODO: There are other naming conventions for eg. BRAM and DSP if not speed_model.startswith("bel_"): continue # Get timings from properties timings = [(k, properties[k]) for k in [ "DELAY", "FAST_MAX", "FAST_MIN", "SLOW_MAX", "SLOW_MIN", ]] # Get edge from the model name if "RISING" in speed_model: edge = "rising" elif "FALLING" in speed_model: edge = "falling" else: # Supposedly means either edge edge = None # Get configuration. Look for "__CFG<n>" # FIXME: How to correlate that with a configuration name ? match = REGEX_CFG.match(speed_model) if match is not None: cfg = match.group(1) else: cfg = None # Process physical names for the timing model. These should # correspond to site timings phy_names = properties["NAME"].split(",") for phy_name in phy_names: # Extract data from the name. Each name field should hava the # format: "<type>_<bel>_<site>_<src_pin>_<dst_pin>". The split # has to be done in complex way as the bel name may have "_" # within. phy_type, phy_name = phy_name.split("_", maxsplit=1) if 'URAM288' in phy_name: uram_info = speed_model.split("__") site = 'URAM288' bel = uram_info[1] phy_src = uram_info[2] phy_dst = uram_info[3] else: phy_name, phy_src, phy_dst = phy_name.rsplit( "_", maxsplit=2) bel_site = phy_name.rsplit("_", maxsplit=1) if len(bel_site) == 2: bel, site = bel_site else: continue sdf_type, is_seq = get_sdf_type(phy_type) if sdf_type is None: continue # Process logical names that should correspond to bel timings log_cells = parse_logical_names( phy_type, properties["NAME_LOGICAL"], cell_pins) # If we have log cells then yield them for log_cell, log_src, log_dst in log_cells: # Format cell type cell_type = log_cell if edge is not None: cell_type += "_{}_{}".format(log_src, edge) # Format cell location location = "{}/{}".format(site, bel) # Yield stuff key = (site_name, location, cell_type, speed_model) yield (*key, "type"), cell_type.upper() yield (*key, "location"), location.upper() yield (*key, "model"), speed_model if is_seq: yield (*key, "clock"), log_src.upper() yield (*key, "input"), log_dst.upper() else: yield (*key, "input"), log_src.upper() yield (*key, "output"), log_dst.upper() if is_seq: yield (*key, "sequential"), sdf_type for t, v in timings: yield (*key, t), v # We don't have any logical cells, stick to the bel # # TODO: This can be modified so we always dump timing for the # bel regardless of if we can decode logical cells. This way # we may have SDFs with both bels and logical cells. if not len(log_cells): # Format cell type cell_type = bel if cfg is not None: cell_type += "_CFG{}".format(cfg) if edge is not None: cell_type += "_{}_{}".format(phy_src, edge) # Format cell location location = "{}/{}".format(site, bel) # Yield stuff key = (site_name, location, cell_type, speed_model) yield (*key, "type"), cell_type.upper() yield (*key, "location"), location.upper() yield (*key, "model"), speed_model if is_seq: yield (*key, "clock"), phy_src.upper() yield (*key, "input"), phy_dst.upper() else: yield (*key, "input"), phy_src.upper() yield (*key, "output"), phy_dst.upper() if is_seq: yield (*key, "sequential"), sdf_type for t, v in timings: yield (*key, t), v return merged_dict(inner()) def read_cell_pins(pins_file): """ Read definitions of library cell pins as extracted from Vivado """ def inner(): with open(pins_file, 'r') as f: for line in f: raw_pins = line.split() loc = 0 num_cells = int(raw_pins[loc]) loc += 1 for cell in range(num_cells): cell_name = raw_pins[loc] num_pins = int(raw_pins[loc + 1]) loc += 2 for pin in range(num_pins): pin_name = raw_pins[loc] loc += 1 yield cell_name, pin_name cell_pins = {} for cell_name, pin_name in inner(): if cell_name not in cell_pins: cell_pins[cell_name] = [] cell_pins[cell_name].append(pin_name) return cell_pins def main(): parser = argparse.ArgumentParser() parser.add_argument('--timings', type=str, help='Raw timing input file') parser.add_argument('--json', type=str, help='json output file') parser.add_argument( '--cellpins', type=str, help='Library cell pins input file') parser.add_argument( '--debug', action="store_true", help='Enable debug json dumps') args = parser.parse_args() cell_pins = read_cell_pins(args.cellpins) if args.debug: with open("debug_cells.json", 'w') as fp: json.dump(cell_pins, fp, indent=4, sort_keys=True) timings = read_raw_timings(args.timings, cell_pins) with open(args.json, 'w') as fp: json.dump(timings, fp, indent=4, sort_keys=True) if __name__ == '__main__': main()
SymbiFlow/prjuray
fuzzers/007-timing/bel/tim2json.py
Python
isc
10,507
0
from SamplingAccuracyEvaluation import SamplingAlgorithm as SA from SamplingAccuracyEvaluation import AccuracyEvaluation as AE from SamplingAccuracyEvaluation import PrintGraph as PG from SamplingAccuracyEvaluation import StatisticalCalculation as SC import operator def populationListGenerate(filePath, target): print('Generate Population List') populationList = [] populationFile = open(filePath, 'r') while True: line = populationFile.readline() if not line: break line_data = line.split(',') populationList.append(line_data[target]) populationFile.close() return populationList def calculateScore(evalList): score = 0 for i in range(len(evalList)): if i == 0: score = score + abs(evalList[i])/4 else: score = score + abs(evalList[i])/3 return score def run(windowSize, sampleSize, filePath, target=0): print('############## Sampling Accuracy Evaluation ##############') count = 1 numOfTrials = 1 jSDPieceCount = 20 pAAPieceCount = 20 print('Window Size: ' ,windowSize) print('Sample Size: ' ,sampleSize) print('JSD Piece Count: ' ,jSDPieceCount) print('PAA Piece Count: ' ,pAAPieceCount) populationList = populationListGenerate(filePath, target) windowList = [] accuracyMeasureCount = 3 evalDic = {} reservoirEvalList = [0.0 for _ in range(accuracyMeasureCount)] hashEvalList = [0.0 for _ in range(accuracyMeasureCount)] priorityEvalList = [0.0 for _ in range(accuracyMeasureCount)] print() for data in populationList: windowList.append(data) if count == windowSize: print('################## ' + str(numOfTrials) + ' Evaluation Start ####################') # if numOfTrials == 1: PG.printGraph(windowList, 'Population', numOfTrials) print() print(str(numOfTrials)+'_ReservoirSampling') sampleList = SA.sortedReservoirSam(sampleSize, windowList) tempEvalList = AE.run(windowList, sampleList, jSDPieceCount, pAAPieceCount) SC.sumPerIndex(reservoirEvalList, tempEvalList) # if numOfTrials == 1: PG.printGraph(sampleList, 'Reservoir', numOfTrials) print() print(str(numOfTrials)+'_HashSampling') sampleList = SA.hashSam(sampleSize, windowList) tempEvalList = AE.run(windowList, sampleList, jSDPieceCount, pAAPieceCount) SC.sumPerIndex(hashEvalList, tempEvalList) # if numOfTrials == 1: PG.printGraph(sampleList, 'Hash', numOfTrials) print() print(str(numOfTrials)+'_PrioritySampling') sampleList = SA.sortedPrioritySam(sampleSize, windowList) tempEvalList = AE.run(windowList, sampleList, jSDPieceCount, pAAPieceCount) SC.sumPerIndex(priorityEvalList, tempEvalList) # if numOfTrials == 1: PG.printGraph(sampleList, 'Priority', numOfTrials) print() numOfTrials = numOfTrials + 1 count = 0 windowList = [] count = count + 1 for i in range(accuracyMeasureCount): reservoirEvalList[i] = reservoirEvalList[i] / numOfTrials hashEvalList[i] = hashEvalList[i] / numOfTrials priorityEvalList[i] = priorityEvalList[i] / numOfTrials evalDic['RESERVOIR_SAMPLING'] = calculateScore(reservoirEvalList) evalDic['HASH_SAMPLING'] = calculateScore(hashEvalList) evalDic['PRIORITY_SAMPLING'] = calculateScore(priorityEvalList) sortedEvalList = sorted(evalDic.items(), key = operator.itemgetter(1)) return sortedEvalList[0][0]
dke-knu/i2am
i2am-app/AlgorithmSelectionEngine/SamplingAccuracyEvaluation/SamplingAccuracyEvaluation.py
Python
apache-2.0
3,665
0.006276
# OpenShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor 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. # # OpenShot Video Editor 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 OpenShot Video Editor. If not, see <http://www.gnu.org/licenses/>. # Import Blender's python API. This only works when the script is being # run from the context of Blender. Blender contains it's own version of Python # with this library pre-installed. import bpy # Load a font def load_font(font_path): """ Load a new TTF font into Blender, and return the font object """ # get the original list of fonts (before we add a new one) original_fonts = bpy.data.fonts.keys() # load new font bpy.ops.font.open(filepath=font_path) # get the new list of fonts (after we added a new one) for font_name in bpy.data.fonts.keys(): if font_name not in original_fonts: return bpy.data.fonts[font_name] # no new font was added return None # Debug Info: # ./blender -b test.blend -P demo.py # -b = background mode # -P = run a Python script within the context of the project file # Init all of the variables needed by this script. Because Blender executes # this script, OpenShot will inject a dictionary of the required parameters # before this script is executed. params = { 'title' : 'Oh Yeah! OpenShot!', 'extrude' : 0.1, 'bevel_depth' : 0.02, 'spacemode' : 'CENTER', 'text_size' : 1.5, 'width' : 1.0, 'fontname' : 'Bfont', 'color' : [0.8,0.8,0.8], 'alpha' : 1.0, 'alpha_mode' : 'TRANSPARENT', 'output_path' : '/tmp/', 'fps' : 24, 'quality' : 90, 'file_format' : 'PNG', 'color_mode' : 'RGBA', 'horizon_color' : [0.57, 0.57, 0.57], 'resolution_x' : 1920, 'resolution_y' : 1080, 'resolution_percentage' : 100, 'start_frame' : 20, 'end_frame' : 25, 'animation' : True, } #INJECT_PARAMS_HERE # The remainder of this script will modify the current Blender .blend project # file, and adjust the settings. The .blend file is specified in the XML file # that defines this template in OpenShot. #---------------------------------------------------------------------------- # Modify Text / Curve settings #print (bpy.data.curves.keys()) text_object = bpy.data.curves["Title"] text_object.extrude = params["extrude"] text_object.bevel_depth = params["bevel_depth"] text_object.body = params["title"] text_object.align = params["spacemode"] text_object.size = params["text_size"] text_object.space_character = params["width"] # Get font object font = None if params["fontname"] != "Bfont": # Add font so it's available to Blender font = load_font(params["fontname"]) else: # Get default font font = bpy.data.fonts["Bfont"] text_object.font = font text_object = bpy.data.curves["Subtitle"] text_object.extrude = params["extrude"] text_object.bevel_depth = params["bevel_depth"] text_object.body = params["sub_title"] text_object.align = params["spacemode"] text_object.size = params["text_size"] text_object.space_character = params["width"] # set the font text_object.font = font # Change the material settings (color, alpha, etc...) material_object = bpy.data.materials["Text"] material_object.diffuse_color = params["diffuse_color"] material_object.specular_color = params["specular_color"] material_object.specular_intensity = params["specular_intensity"] material_object.alpha = params["alpha"] # Set the render options. It is important that these are set # to the same values as the current OpenShot project. These # params are automatically set by OpenShot bpy.context.scene.render.filepath = params["output_path"] bpy.context.scene.render.fps = params["fps"] #bpy.context.scene.render.quality = params["quality"] try: bpy.context.scene.render.file_format = params["file_format"] bpy.context.scene.render.color_mode = params["color_mode"] except: bpy.context.scene.render.image_settings.file_format = params["file_format"] bpy.context.scene.render.image_settings.color_mode = params["color_mode"] try: bpy.context.scene.render.alpha_mode = params["alpha_mode"] except: pass bpy.data.worlds[0].horizon_color = params["horizon_color"] bpy.context.scene.render.resolution_x = params["resolution_x"] bpy.context.scene.render.resolution_y = params["resolution_y"] bpy.context.scene.render.resolution_percentage = params["resolution_percentage"] bpy.context.scene.frame_start = params["start_frame"] bpy.context.scene.frame_end = params["end_frame"] # Animation Speed (use Blender's time remapping to slow or speed up animation) animation_speed = int(params["animation_speed"]) # time remapping multiplier new_length = int(params["end_frame"]) * animation_speed # new length (in frames) bpy.context.scene.frame_end = new_length bpy.context.scene.render.frame_map_old = 1 bpy.context.scene.render.frame_map_new = animation_speed if params["start_frame"] == params["end_frame"]: bpy.context.scene.frame_start = params["end_frame"] bpy.context.scene.frame_end = params["end_frame"] # Render the current animation to the params["output_path"] folder bpy.ops.render.render(animation=params["animation"])
XXLRay/libreshot
libreshot/blender/scripts/blinds.py
Python
gpl-3.0
5,718
0.019237
""" Django settings for pyanalysis project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import sys import os from path import path import dj_database_url # Normally you should not import ANYTHING from Django directly # into your settings, but ImproperlyConfigured is an exception. from django.core.exceptions import ImproperlyConfigured def get_env_setting(setting, default=None): """ Get the environment setting or return exception """ if default is not None: return os.environ.get(setting, default) else: try: return os.environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg) ########## PATH CONFIGURATION # Absolute filesystem path to the django site folder SITE_ROOT = path(__file__).abspath().realpath().dirname().parent # Absolute path to the top-level project folder PROJECT_ROOT = SITE_ROOT.parent # Site name: SITE_NAME = SITE_ROOT.basename() # Id for the Sites framework SITE_ID = 1 ########## END PATH CONFIGURATION ########## DEBUG CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = bool(get_env_setting('DEBUG', False)) # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug TEMPLATE_DEBUG = DEBUG # Is this a development instance? Set this to True on development/master # instances and False on stage/prod. DEV = False DEBUG_DB = bool(get_env_setting('DEBUG_DB', False)) ########## END DEBUG CONFIGURATION ########## DATABASE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': dj_database_url.config(default='sqlite:///%s' % (PROJECT_ROOT / 'development.sqlite')) } # enable utf8mb4 on mysql if DATABASES['default']['ENGINE'] == 'django.db.backends.mysql': # enable utf8mb4 on mysql DATABASES['default']['OPTIONS'] = { 'charset': 'utf8mb4', 'init_command': 'SET storage_engine=INNODB', } ########## END DATABASE CONFIGURATION ########## CACHE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#caches CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } if get_env_setting('MEMCACHED_LOCATION', '') is not '': CACHES['default'] = { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': get_env_setting('MEMCACHED_LOCATION'), 'PREFIX': SITE_NAME + ':', } ########## END CACHE CONFIGURATION ########## GENERAL CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone TIME_ZONE = 'UTC' # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = 'en-us' # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n USE_I18N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n USE_L10N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz USE_TZ = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGIN_REDIRECT_URL LOGIN_REDIRECT_URL = "/" ########## END GENERAL CONFIGURATION ########## MEDIA CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = (SITE_ROOT / 'media').normpath() # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' ########## END MEDIA CONFIGURATION ########## STATIC FILE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = get_env_setting('STATIC_ROOT', (PROJECT_ROOT / 'assets').normpath()) if not isinstance(STATIC_ROOT, path): STATIC_ROOT = path(STATIC_ROOT) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( (SITE_ROOT / 'static').normpath(), ) # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) ########## END STATIC FILE CONFIGURATION ########## FIXTURE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS FIXTURE_DIRS = ( (SITE_ROOT / 'fixtures').normpath(), ) ########## END FIXTURE CONFIGURATION ########## SECRET CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = get_env_setting('SECRET_KEY', 'secret') ########## END SECRET CONFIGURATION ########## TEST CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#test-runner TEST_RUNNER = 'django.test.runner.DiscoverRunner' ########## END TEST CONFIGURATION ########## TEMPLATE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.media', 'django.core.context_processors.request', 'django.core.context_processors.i18n', 'django.core.context_processors.static', 'django.core.context_processors.csrf', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'pyanalysis.apps.base.context_processors.google_analytics', ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs TEMPLATE_DIRS = ( (SITE_ROOT / 'templates').normpath(), ) ########## END TEMPLATE CONFIGURATION ########## MIDDLEWARE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes MIDDLEWARE_CLASSES = ( # Default Django middleware. 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ########## END MIDDLEWARE CONFIGURATION ########## URL CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf ROOT_URLCONF = '%s.urls' % SITE_NAME ########## END URL CONFIGURATION ########## APP CONFIGURATION DJANGO_APPS = ( # Default Django apps: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Utilities 'django_extensions', 'widget_tweaks', ) # Apps specific for this project go here. LOCAL_APPS = ( 'pyanalysis.apps.base', 'pyanalysis.apps.api', 'pyanalysis.apps.corpus', 'pyanalysis.apps.importer', 'pyanalysis.apps.enhance', ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS ########## END APP CONFIGURATION ########## LOGGING CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGS_ROOT = get_env_setting('LOGS_ROOT', PROJECT_ROOT / 'logs') if not isinstance(LOGS_ROOT, path): LOGS_ROOT = path(LOGS_ROOT) if not LOGS_ROOT.exists(): LOGS_ROOT.mkdir() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { # logging handler that outputs log messages to terminal 'class': 'logging.StreamHandler', 'level': 'DEBUG', }, 'db_handler': { 'class': 'logging.FileHandler', 'filename': LOGS_ROOT / 'django.db.log', 'level': 'DEBUG', }, }, 'loggers': { 'pyanalysis': { 'handlers': ['console'], 'level': 'WARNING', }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', }, } } if DEBUG: LOGGING['loggers']['pyanalysis']['level'] = 'DEBUG' if DEBUG_DB: LOGGING['loggers']['django.db'] = { 'handlers': ['db_handler'], 'level': 'DEBUG', 'propagate': False, } ########## END LOGGING CONFIGURATION ########## WSGI CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME ########## END WSGI CONFIGURATION ########## TOOLBAR CONFIGURATION # See: http://south.readthedocs.org/en/latest/installation.html#configuring-your-django-installation if bool(get_env_setting('DEBUG_TOOLBAR', False)): INSTALLED_APPS += ( # Database migration helpers: 'debug_toolbar', ) # Only show the debug toolbar to users with the superuser flag. def custom_show_toolbar(request): return DEBUG or request.user.is_superuser DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TOOLBAR_CALLBACK': '%s.settings.common.custom_show_toolbar' % SITE_NAME, 'HIDE_DJANGO_SQL': True, 'TAG': 'body', 'SHOW_TEMPLATE_CONTEXT': True, 'ENABLE_STACKTRACES': True, } DEBUG_TOOLBAR_PATCH_SETTINGS = True # http://django-debug-toolbar.readthedocs.org/en/latest/installation.html INTERNAL_IPS = tuple(s.strip() for s in get_env_setting('INTERNAL_IPS', '127.0.0.1').split(',')) ########## END TOOLBAR CONFIGURATION ########## COMPRESSOR CONFIGURATION # See: http://django-compressor.readthedocs.org/en/latest/quickstart/ INSTALLED_APPS += ( 'compressor', ) def find_node_bin(package_name='less', bin_name='lessc'): p = PROJECT_ROOT / 'node_modules' / '.bin' / bin_name if p.exists(): return p p = PROJECT_ROOT / 'node_modules' / package_name / 'bin' / bin_name if p.exists(): return "node %s" % p return bin_name # global install BIN_COFFEE = find_node_bin('coffee-script', 'coffee') BIN_COFFEE_COMMAND = '%s --compile --stdio' % BIN_COFFEE BIN_LESSC = find_node_bin('less', 'lessc') # The relative-urls flag is necessary since we are moving less files around. BIN_LESSC_COMMAND = '%s --relative-urls {infile} {outfile}' % BIN_LESSC COMPRESS_PRECOMPILERS = ( ('text/coffeescript', BIN_COFFEE_COMMAND), # this adds the CssAbsoluteFilter to the less filter ('text/less', 'pyanalysis.precompilers.LessFilter'), ) # Don't actually compress the js if get_env_setting('DEBUG_JS', False): COMPRESS_JS_FILTERS = [] COMPRESS_ROOT = STATIC_ROOT COMPRESS_OUTPUT_DIR = 'CACHE' ########## END COMPRESSOR CONFIGURATION ######### REST FRAMEWORK INSTALLED_APPS += ( 'rest_framework', ) REST_FRAMEWORK = { 'VIEW_DESCRIPTION_FUNCTION': 'pyanalysis.apps.api.drf.get_view_description', } ######### END REST FRAMEWORK ######### ANGULAR JS CONFIG INSTALLED_APPS += ( 'djangular', ) ######### END ANGULAR CONFIG ######### DJANGO DOCS INSTALLED_APPS += ( 'docs', ) DOCS_ROOT = PROJECT_ROOT / 'docs' / '_build' / 'html' DOCS_ACCESS = 'staff' ######### END DJANGO DOCS ######### TWITTER SETTINGS TWITTER_CONSUMER_KEY = get_env_setting('TWITTER_CONSUMER_KEY', '') TWITTER_CONSUMER_SECRET = get_env_setting('TWITTER_CONSUMER_SECRET', '') TWITTER_ACCESS_TOKEN = get_env_setting('TWITTER_ACCESS_TOKEN', '') TWITTER_ACCESS_TOKEN_SECRET = get_env_setting('TWITTER_ACCESS_TOKEN_SECRET', '') ######### END TWITTER SETTINGS ######### DIMENSION SETTINGS QUANTITATIVE_DIMENSION_BINS = 50 ######### END DIMENSION SETTINGS
nanchenchen/script-analysis
pyanalysis/settings/common.py
Python
mit
12,572
0.00517
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2011-2013 Martijn Kaijser # # 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 xbmc import xbmcaddon ### get addon info __addon__ = xbmcaddon.Addon(id='script.artwork.downloader') __addonid__ = __addon__.getAddonInfo('id') __addonname__ = __addon__.getAddonInfo('name') __author__ = __addon__.getAddonInfo('author') __version__ = __addon__.getAddonInfo('version') __addonpath__ = __addon__.getAddonInfo('path') __addonprofile__= xbmc.translatePath(__addon__.getAddonInfo('profile')).decode('utf-8') __icon__ = __addon__.getAddonInfo('icon') __localize__ = __addon__.getLocalizedString
SMALLplayer/smallplayer-image-creator
storage/.xbmc/addons/script.artwork.downloader/lib/common.py
Python
gpl-2.0
1,305
0.008429
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from . import note
ddico/odoo
addons/note/controllers/__init__.py
Python
agpl-3.0
118
0.008475
import unittest from mopidy_tunein import Extension class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn("[tunein]", config) self.assertIn("enabled = true", config) def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() self.assertIn("timeout", schema) self.assertIn("filter", schema)
kingosticks/mopidy-tunein
tests/test_extension.py
Python
apache-2.0
483
0
#!/usr/bin/python # -*- coding: utf-8 -*- import re COST_AUTO = 5 class Appartment(object): """Appartment class consists of features that have all appartments""" def __init__(self, address, metro, transportation, rooms, space, price, floor, addInfo): super(Appartment, self).__init__() self.address = self.setAddress(address) self.metro = self.setMetro(metro) self.transportation = self.setTransportation(transportation) self.rooms = self.setRooms(rooms) self.space = self.setSpace(space) self.price = self.setPrice(price) self.floor = self.setFloor(floor) self.addInfo = self.setAddInfo(addInfo) # Getter methods def getAddress(self): return self.address def getMetro(self): return self.metro def getTransportation(self): return self.transportation def getRooms(self): return self.rooms def getSpace(self): return self.space def getPrice(self): return self.price def getFloor(self): return self.floor def getAddInfo(self): return self.addInfo # Setter methods def setAddress(self, address): if (type(address) is str) or (type(address) is unicode): self.address = address else: print "Can't set proper address, type is not string" self.address = None return self.address def setMetro(self, metro): if (type(metro) is str) or (type(metro) is unicode): self.metro = metro else: print "Can't set metro, type is not string" self.metro = None return self.metro def setTransportation(self, transportation): if type(transportation) is dict: self.transportation = transportation elif (type(transportation) is str) or (type(transportation) is unicode): time = re.search(u'\d+', transportation) auto = re.search(u'авто', transportation) foot = re.search(u'пешком', transportation) if time and auto: time = int(time.group()) d = {} d['auto'] = time self.transportation = d elif time and foot: time = int(time.group()) d = {} d['foot'] = time self.transportation = d else: self.transportation = None return self.transportation def setRooms(self, rooms): if type(rooms) is int: self.rooms = rooms elif (type(rooms) is str) or (type(rooms) is unicode): room = re.search(u'\d', rooms) if room: room = int(room.group()) self.rooms = room else: print "error, no match" self.rooms = None else: print "type error, current type is " + type(rooms) self.rooms = None return self.rooms def setSpace(self, space): if type(space) is dict: self.space = space elif type(space) is list: d = {} for typo in space: if re.search(u'кухня', typo): area = re.search(u'\d+', typo) area = int(area.group()) d['kitchen'] = area elif re.search(u'жилая', typo): area = re.search(u'\d+', typo) area = int(area.group()) d['dwelling'] = area elif re.search(u'общая', typo): area = re.search(u'\d+', typo) area = int(area.group()) d['full'] = area elif typo == "NULL": pass else: print "Error, no matching typo's. Current typo is " + typo self.space = d else: print "Error with setting space" self.space = None return self.space def setPrice(self, price): if (type(price) is int) or (type(price) is float): print "type is " + str(type(price)) self.price = int(price) elif (type(price) is str) or (type(price) is unicode): price = price.replace(u',', '') price = re.search(u'^\d+', price) if price: self.price = int(price.group()) else: print "No match of price in string" self.price = None else: print "Type error, current type is " + str(type(price)) self.price = None return self.price def setFloor(self, floor): if type(floor) is tuple: self.floor = floor elif (type(floor) is str) or (type(floor) is unicode): floor = floor.split("/") if len(floor) == 2: floor = (int(floor[0]), int(floor[1])) self.floor = floor else: print "length of floor array is not 2, len = " + len(floor) self.floor = None else: print "Type error, current type is " + type(floor) self.floor = None return self.floor def setAddInfo(self, addInfo): if type(addInfo) is list: self.addInfo = addInfo elif (type(addInfo) is str) or (type(addInfo) is unicode): addInfo = addInfo.split('|') self.addInfo = addInfo else: print "Type error, current type is " + type(addInfo) self.addInfo = None return self.addInfo # Helper methods to preprocess data def preprocessData1(self): line = [] address = self.address if address: line.append(address) metro = self.metro if metro: line.append(metro) transportation = self.transportation if transportation: if 'auto' in transportation: line.append(str(COST_AUTO*transportation['auto'])) elif 'foot' in transportation: line.append(str(transportation['foot'])) else: print "no line about transportation" rooms = self.rooms if rooms: line.append(str(rooms)) space = self.space if space: if 'kitchen' in space: line.append(str(space['kitchen'])) if 'dwelling' in space: line.append(str(space['dwelling'])) if 'full' in space: line.append(str(space['full'])) price = self.price if price: line.append(str(price)) floor = self.floor if floor and floor[1]!=0: num = round(float(floor[0])/float(floor[1]), 2) line.append(str(num)) return line
leanton/cianParser
appartment.py
Python
mit
5,447
0.035596
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from projects.models import Project User = get_user_model() class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('user') parser.add_argument('name', nargs='+') parser.add_argument('--description', nargs='*', default='') def handle(self, *args, **options): name = ' '.join(options['name']) description = ' '.join(options['description']) u = User.objects.get(username=options['user']) p = Project.objects.create(user=u, name=name, description=description) p.save() self.stdout.write(str(p.pk))
XeryusTC/projman
functional_tests/management/commands/create_project.py
Python
mit
728
0.001374
# -*- coding: utf-8 -*- import traceback from datetime import timedelta from django.core import mail from django.core.mail import EmailMultiAlternatives, mail_admins from django.core.management.base import BaseCommand from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from django.contrib.sites.models import Site from django.conf import settings from django.utils import translation from django.utils import timezone from cert.models import Attendee class Command(BaseCommand): help = u'Send certificate e-mails' def get_email(self, attendee): translation.activate(settings.LANGUAGE_CODE) subject = _(u'Certificado de participação | PUG-PE') from_email = settings.DEFAULT_FROM_EMAIL ctx = { 'site': Site.objects.get_current().domain, 'event': attendee.event, 'attendee': attendee, } text_content = render_to_string('cert/cert_email.txt', ctx) html_content = render_to_string('cert/cert_email.html', ctx) msg = EmailMultiAlternatives( subject, text_content, from_email, [attendee.email], ) msg.attach_alternative(html_content, "text/html") return msg def handle(self, *args, **options): connection = mail.get_connection() num_emails = 0 attendees = Attendee.objects.filter(sent_date__isnull=True) # Evitar envio para eventos muito antigos attendees = attendees.filter( pub_date__gte=timezone.now() - timedelta(days=10), ) for attendee in attendees: msg = self.get_email(attendee) try: num_emails += connection.send_messages([msg]) except Exception as exc: subject = _(u'PUG-PE: Problema envio certificado') body = 'except: '.format(exc) body += traceback.format_exc() mail_admins(subject, body) else: attendee.sent_date = timezone.now() attendee.save() self.stdout.write( unicode(_(u'Foram enviados {0} emails\n'.format(num_emails))), )
pugpe/pugpe
apps/cert/management/commands/send_certificates.py
Python
mit
2,215
0.000904
import sys import glob def read_fileb(filename, mode='rb'): f = open(filename, mode) try: return f.read() finally: f.close() def write_fileb(filename, value, mode='wb'): f = open(filename, mode) try: f.write(value) finally: f.close() for filename in glob.glob(sys.argv[1]): data1 = read_fileb(filename) write_fileb(filename + '.bak2', data1) data2lines = read_fileb(filename).strip().split('\n') data2 = '\n'.join([line.rstrip( ).replace('\t', ' ' * 2) for line in data2lines]) + '\n' write_fileb(filename, data2) print filename, len(data1) - len(data2)
pouyana/teireader
webui/scripts/fixws.py
Python
mit
646
0.001548
from hypothesis.utils.conventions import not_set def accept(f): def complex_numbers(): return f() return complex_numbers
keybar/keybar
.hypothesis/eval_source/hypothesis_temporary_module_f921b2988402df61d5f91622b67a9e50eddd05fc.py
Python
bsd-3-clause
138
0.007246
# # Created by DraX on 2005.08.08 # # Updated by ElgarL on 28.09.2005 # print "importing village master data: Talking Island Village ...done" import sys from net.sf.l2j.gameserver.model.quest import State from net.sf.l2j.gameserver.model.quest import QuestState from net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest GRAND_MASTER_BITZ = 7026 class Quest (JQuest) : def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr) def onEvent (self,event,st): htmltext = "No Quest" if event == "7026-01.htm": htmltext = event if event == "7026-02.htm": htmltext = event if event == "7026-03.htm": htmltext = event if event == "7026-04.htm": htmltext = event if event == "7026-05.htm": htmltext = event if event == "7026-06.htm": htmltext = event if event == "7026-07.htm": htmltext = event return htmltext def onTalk (Self,npc,st): npcId = npc.getNpcId() Race = st.getPlayer().getRace() pcId = st.getPlayer().getClassId().getId() # Humans got accepted if npcId == GRAND_MASTER_BITZ and Race in [Race.human]: #fighter if pcId == 0x00: htmltext = "7026-01.htm" #warrior, knight, rogue if pcId == 0x01 or pcId == 0x04 or pcId == 0x07: htmltext = "7026-08.htm" #warlord, paladin, treasureHunter if pcId == 0x03 or pcId == 0x05 or pcId == 0x08: htmltext = "7026-09.htm" #gladiator, darkAvenger, hawkeye if pcId == 0x02 or pcId == 0x06 or pcId == 0x09: htmltext = "7026-09.htm" #mage, wizard, cleric]: if pcId == 0x0a or pcId == 0x0b or pcId == 0x0f: htmltext = "7026-10.htm" #sorceror, necromancer, warlock, bishop, prophet if pcId == 0x0c or pcId == 0x0d or pcId == 0x0e or pcId == 0x10 or pcId == 0x11: htmltext = "7026-10.htm" st.setState(STARTED) return htmltext # All other Races must be out if npcId == GRAND_MASTER_BITZ and Race in [Race.dwarf, Race.darkelf, Race.elf, Race.orc]: st.setState(COMPLETED) st.exitQuest(1) return "7026-10.htm" QUEST = Quest(7026,"7026_bitz_occupation_change","village_master") CREATED = State('Start', QUEST) STARTED = State('Started', QUEST) COMPLETED = State('Completed', QUEST) QUEST.setInitialState(CREATED) QUEST.addStartNpc(7026) STARTED.addTalkId(7026)
Barrog/C4-Datapack
data/jscript/village_master/7026_bitz_occupation_change/__init__.py
Python
gpl-2.0
2,377
0.03618
#!/usr/bin/env python """ Backup all your organization's repositories, private or otherwise. """ import argparse import base64 import contextlib import json import os import sys import urllib2 from collections import namedtuple from urllib import urlencode from urllib import quote API_BASE = 'https://api.github.com/' REPO_TYPE_CHOICES = ('all', 'public', 'private', 'forks', 'sources', 'member') @contextlib.contextmanager def chdir(dirname=None): curdir = os.getcwd() try: if dirname is not None: os.chdir(dirname) yield finally: os.chdir(curdir) class Helpers(object): def __init__(self, args): self.args = args def exec_cmd(self, command): """ Executes an external command taking into account errors and logging. """ print "Executing command: %s" % self.redact(command) resp = os.system(command) if resp != 0: raise Exception(self.redact("Command [%s] failed (%s)" % (command, resp))) def https_url_with_auth(self, base_url): _, suffix = base_url.split('https://') return 'https://%s:%s@%s' % (quote(self.args.username), quote(self.args.password), suffix) def redact(self, s): if hasattr(self.args, 'password'): s = s.replace(self.args.password, 'REDACTED') if hasattr(self.args, 'username'): s = s.replace(self.args.username, 'REDACTED') return s Pagination = namedtuple('Pagination', 'first prev next last') def get_pagination(raw_link_header): link_map = {} for link, rel in (lh.split(';') for lh in raw_link_header.split(',')): link_map[rel.split('=')[1].strip('"')] = link.strip(' <>') return Pagination(*(link_map.get(f) for f in Pagination._fields)) def add_https_basic_auth(request, username, password): base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) def get_repos(org, repo_type, access_token=None, username=None, password=None, per_page=25): """ Paginates through all of the repositories using github's Link header. https://developer.github.com/v3/#link-header """ url = API_BASE + 'orgs/%s/repos?' % org qs_params = {'type': repo_type, 'per_page': per_page} if access_token: qs_params.update({'access_token': args.access_token}) url += urlencode(qs_params) request = urllib2.Request(url) elif username and password: url += urlencode(qs_params) request = urllib2.Request(url) add_https_basic_auth(request, username, password) else: raise ValueError('unworkable combination of authentication inputs') response = urllib2.urlopen(request) try: pagination = get_pagination(response.headers['Link']) except KeyError: print 'no Link header, nothing to paginate through.' pagination = Pagination(None, None, None, None) repos = json.loads(response.read()) for r in repos: if not r.get('archived'): yield r # so, this isn't the DRYest code ;-) while pagination.next: request = urllib2.Request(pagination.next) if username and password: add_https_basic_auth(request, username, password) response = urllib2.urlopen(request) pagination = get_pagination(response.headers['Link']) repos = json.loads(response.read()) for r in repos: if not r.get('archived'): yield r # Github API call, can authenticate via access token, or username and password # git cloning/pulling, can authenticate via ssh key, or username & password via https def repocsv(string): """ >>> repocsv('org1/repo1, org2/repo2,org3/repo3 ,org4/repo4') ['org1/repo1', 'org2/repo2', 'org3/repo3', 'org4/repo4'] """ try: repos = [r.strip() for r in string.split(',')] return set(repos) except Exception as exc: raise argparse.ArgumentTypeError(exc.message) if __name__ == '__main__': parser = argparse.ArgumentParser(description='backup github repositories for an organization') subparsers = parser.add_subparsers(dest='authtype') # uses an access token to fetch repositories names from github's API, # but then assumes you have SSH keys setup for cloning/pulling ssh_parser = subparsers.add_parser('ssh', help='use ssh for cloning/pulling, and use access token for github api access') ssh_parser.add_argument('-d', '--dir', type=str, dest='directory', required=True, help='full or relative path to store backed up repositories') ssh_parser.add_argument('-o', '--org', type=str, required=True, help='github organization name') ssh_parser.add_argument('-t', '--type', type=str, dest='rtype', nargs='?', default='all', choices=REPO_TYPE_CHOICES, help='repository types to backup') ssh_parser.add_argument('-a', '--access-token', type=str, help='personal access token or oauth access token') ssh_parser.add_argument('-f', '--forks', action='store_true', help='add this arg if you want to backup fork repositories also') ssh_parser.add_argument('-i', '--ignore-list', type=repocsv, default=set(), help='add repos you dont want to fetch/index, e.g. --ignore-list org1/repo1,org2/repo2') # uses a username and password for fetching repositories names from # github's API, and uses same username and password for # cloning/updating via HTTPS as well. # # note: you can also use your personal access token as a password for https # basic auth when talking to github's api or cloning https_parser = subparsers.add_parser('https', help='use https for cloning/pulling, and use username and password (https basic auth) for github api access. note that github also allows using a personal access token as a password via this method') https_parser.add_argument('-d', '--dir', type=str, dest='directory', required=True, help='full or relative path to store backed up repositories') https_parser.add_argument('-o', '--org', type=str, required=True, help='github organization name') https_parser.add_argument('-t', '--type', type=str, dest='rtype', nargs='?', default='all', choices=REPO_TYPE_CHOICES, help='repository types to backup') https_parser.add_argument('-u', '--username', dest='username', type=str, required=True, help='github username') https_parser.add_argument('-p', '--password', dest='password', type=str, required=True, help='github password or github personal access token') https_parser.add_argument('-f', '--forks', action='store_true', help='add this arg if you want to backup fork repositories also') https_parser.add_argument('-i', '--ignore-list', type=repocsv, default=set(), help='add repos you dont want to fetch/index, e.g. --ignore-list org1/repo1,org2/repo2') args = parser.parse_args() if not os.path.exists(args.directory): os.makedirs(args.directory) if args.authtype == 'ssh': org_repos = get_repos(args.org, args.rtype, args.access_token) else: org_repos = get_repos(args.org, args.rtype, username=args.username, password=args.password) h = Helpers(args) for repo in org_repos: # skip ignored repos if repo['full_name'] in args.ignore_list: print 'skipping ignored repository %s' % repo['full_name'] continue # skip forks unless asked not to if not args.forks and repo['fork']: print 'skipping fork repository %s' % repo['full_name'] continue destdir = os.path.join(args.directory, repo['name']) if args.authtype == 'ssh': repo_path = repo['ssh_url'] else: repo_path = h.https_url_with_auth(repo['clone_url']) if os.path.exists(destdir): # pull in new commits to an already tracked repository print '*** updating %s... ***' % h.redact(repo_path) with chdir(destdir): try: h.exec_cmd('git pull origin %s' % repo['default_branch']) continue except Exception as e: print 'error: %s (repo=%s); will re-clone!' % (e, repo['name']) # clone the repo fresh, deleting if it already existed print '*** backing up %s... ***' % h.redact(repo_path) try: h.exec_cmd('rm -rf %s && git clone %s %s' % (destdir, repo_path, destdir)) except Exception as e: print 'error: %s' % e
sproutsocial/botanist
packages/github_backup.py
Python
mit
8,574
0.003032
# dev/py/upax3/upax3/ftlog.py """ Fault-tolerant log for a Upax node. """ import os import re # import sys from collections import Container, Sized from xlattice import (HashTypes, check_hashtype, # u, SHA1_HEX_NONE, SHA2_HEX_NONE, SHA3_HEX_NONE, BLAKE2B_HEX_NONE) from upax import UpaxError from upax.node import check_hex_node_id_160, check_hex_node_id_256 __all__ = ['ATEXT', 'AT_FREE', 'PATH_RE', 'BODY_LINE_1_RE', 'BODY_LINE_256_RE', 'IGNORABLE_RE', # classes 'Log', 'BoundLog', 'LogEntry', 'Reader', 'FileReader', 'StringReader', ] # ------------------------------------------------------------------- # CLASS LOG AND SUBCLASSES # ------------------------------------------------------------------- # Take care: this pattern is used in xlmfilter, possibly elsewhere # this is RFC2822's atext; *,+,?,- are escaped; needs to be enclosed in []+ ATEXT = r"[a-z0-9!#$%&'\*\+/=\?^_`{|}~\-]+" AT_FREE = ATEXT + r'(?:\.' + ATEXT + r')*' # this permits an RFC2822 message ID but is a little less restrictive PATH_PAT = AT_FREE + r'(?:@' + AT_FREE + ')?' PATH_RE = re.compile(PATH_PAT, re.I) BODY_LINE_1_PAT =\ r'^(\d+) ([0-9a-f]{40}) ([0-9a-f]{40}) "([^"]*)" (%s)$' % PATH_PAT BODY_LINE_1_RE = re.compile(BODY_LINE_1_PAT, re.I) BODY_LINE_256_PAT =\ r'^(\d+) ([0-9a-f]{64}) ([0-9a-f]{64}) "([^"]*)" (%s)$' % PATH_PAT BODY_LINE_256_RE = re.compile(BODY_LINE_256_PAT, re.I) IGNORABLE_PAT = '(^ *$)|^ *#' IGNORABLE_RE = re.compile(IGNORABLE_PAT) class Log(Container, Sized): """a fault-tolerant log""" def __init__(self, reader, hashtype): self._hashtype = hashtype (timestamp, prev_log_hash, prev_master, entries, index) = reader.read() self._timestamp = timestamp # seconds from epoch self._prev_hash = prev_log_hash # SHA1/3 hash of previous Log if hashtype == HashTypes.SHA1: check_hex_node_id_160(self._prev_hash) else: check_hex_node_id_256(self._prev_hash) self._prev_master = prev_master # nodeID of master writing prev log if hashtype == HashTypes.SHA1: check_hex_node_id_160(self._prev_master) else: check_hex_node_id_256(self._prev_master) self._entries = entries # a list self._index = index # a map, hash => entry def __contains__(self, key): """ Return whether this key is in the Log. """ return key in self._index def __len__(self): """ Return the length of this Log. """ return len(self._entries) def __str__(self): """used for serialization, so includes newline""" # first line if self._hashtype == HashTypes.SHA1: fmt = "%013u %40s %40s\n" else: fmt = "%013u %64s %64s\n" ret = fmt % (self._timestamp, self._prev_hash, self._prev_master) # list of entries for entry in self._entries: ret += str(entry) # woefully inefficient :-) return ret def add_entry(self, tstamp, key, node_id, src, path): """ Create a LogEntry with the given timestamp, key, nodeID, src, and path. If the LogEntry is already present in the Log, return a reference to the existing LogEntry. Otherwise, add the LogEntry to the list and index it by key. """ entry = LogEntry(tstamp, key, node_id, src, path) if key in self._index: existing = self._index[key] if entry == existing: return existing # silently ignore duplicates self._entries.append(entry) # increases size of list self._index[key] = entry # overwrites any earlier duplicates return entry def get_entry(self, key): """ Given a key, return the corresponding LogEntry or None. """ if key not in self._index: return None return self._index[key] @property def entries(self): """ Return the list of LogEntries. """ return self._entries @property def index(self): """ Return the index by key into the list of LogEntries. """ return self._index @property def prev_hash(self): """ Return the content hash of the previous Log. """ return self._prev_hash @property def prev_master(self): """ Return the ID of the master of the previous Log. """ return self._prev_master @property def timestamp(self): """ Return the timestamp for this Log. """ return self._timestamp class BoundLog(Log): """ A fult tolerant log bound to a file. """ def __init__(self, reader, hashtype=HashTypes.SHA2, u_path=None, base_name='L'): super(). __init__(reader, hashtype) self.fd_ = None self.is_open = False # for appending overwriting = False if u_path: self.u_path = u_path self.base_name = base_name overwriting = True else: if isinstance(reader, FileReader): self.u_path = reader.u_path self.base_name = reader.base_name overwriting = False else: msg = "no target uPath/baseName specified" raise UpaxError(msg) self.path_to_log = "%s/%s" % (self.u_path, self.base_name) if overwriting: with open(self.path_to_log, 'w') as file: log_contents = super(BoundLog, self).__str__() file.write(log_contents) file.close() self.fd_ = open(self.path_to_log, 'a') self.is_open = True def add_entry(self, tstamp, key, node_id, src, path): if not self.is_open: msg = "log file %s is not open for appending" % self.path_to_log raise UpaxError(msg) # XXX NEED TO THINK ABOUT THE ORDER OF OPERATIONS HERE entry = super( BoundLog, self).add_entry(tstamp, key, node_id, src, path) stringified = str(entry) self.fd_.write(stringified) return entry def flush(self): """ Flush the log. This should write the contents of any internal buffers to disk, but no particular behavior is guaranteed. """ self.fd_.flush() def close(self): """ Close the log. """ self.fd_.close() self.is_open = False # ------------------------------------------------------------------- class LogEntry(): """ The entry made upon adding a file to the Upax content-keyed data store. This consists of a timestamp; an SHA content key, the hash of the contents of the file, the NodeID identifying the contributor, its source (which may be a program name, and a UNIX/POSIX path associated with the file. The path will normally be relative. """ __slots__ = ['_timestamp', '_key', '_node_id', '_src', '_path', ] def __init__(self, timestamp, key, node_id, source, pathToDoc): self._timestamp = timestamp # seconds from epoch if key is None: raise UpaxError('LogEntry key may not be None') hashtype = len(key) == 40 self._key = key # 40 or 64 hex digits, content hash if hashtype == HashTypes.SHA1: check_hex_node_id_160(self._key) else: check_hex_node_id_256(self._key) if node_id is None: raise UpaxError('LogEntry nodeID may not be None') self._node_id = node_id # 40/64 digits, node providing entry # XXX This is questionable. Why can't a node with a SHA1 id store # a datum with a SHA3 key? if hashtype == HashTypes.SHA1: check_hex_node_id_160(self._node_id) else: check_hex_node_id_256(self._node_id) self._src = source # tool or person responsible self._path = pathToDoc # file name @property def key(self): """ Return the 40- or 64-byte SHA hash associated with the entry. This is an SHA content hash. """ return self._key @property def node_id(self): """ Return the 40- or 64-byte NodeID associated with the entry. """ return self._node_id @property def path(self): """ Return the POSIX path associated with the LogEntry. """ return self._path @property def src(self): """ Return the 'src' associated with the LogEntry. """ return self._src @property def timestamp(self): """ Return the time at which the LogEntry was created. """ return self._timestamp @property def hashtype(self): """ XXX WRONG should return key length, allowing 64 or 40. """ return len(self._key) == 40 # used in serialization, so newlines are intended def __str__(self): if self.hashtype == HashTypes.SHA1: fmt = '%013u %40s %40s "%s" %s\n' else: fmt = '%013u %64s %64s "%s" %s\n' return fmt % (self._timestamp, self._key, self._node_id, self._src, self._path) def __eq__(self, other): return isinstance(other, LogEntry) and\ self._timestamp == other.timestamp and\ self._key == other.key and\ self._node_id == other.node_id and\ self._src == other.src and\ self._path == other.path def __ne__(self, other): return not self.__eq__(other) def equals(self, other): """ The function usualy known as __eq__. XXX DEPRECATED """ return self.__eq__(other) # ------------------------------------------------------------------- # CLASS READER AND SUBCLASSES # ------------------------------------------------------------------- class Reader(object): """ Would prefer to be able to handle this through something like a Java Reader, so that we could test with a StringReader but then use a FileReader in production. If it is a file, file.readlines(sizeHint) supposedly has very good preformance for larger sizeHint, say 100KB It appears that lines returned need to be rstripped, which wastefully requires copying For our purposes, string input can just be split on newlines, which has the benefit of effectively chomping at the same time """ # __slots__ = ['_entries', '_index', '_lines', '_hashtype', # 'FIRST_LINE_RE', ] def __init__(self, lines, hashtype): check_hashtype(hashtype) self._hashtype = hashtype if hashtype == HashTypes.SHA1: first_line_pat = r'^(\d{13}) ([0-9a-f]{40}) ([0-9a-f]{40})$' else: first_line_pat = r'^(\d{13}) ([0-9a-f]{64}) ([0-9a-f]{64})$' self.first_line_re = re.compile(first_line_pat, re.I) # XXX verify that argument is an array of strings self._lines = lines ndx_last = len(self._lines) - 1 # strip newline from last line if present if ndx_last >= 1: self._lines[ndx_last] = self._lines[ndx_last].rstrip('\n') # Entries are a collection, a list. We also need a dictionary # that accesses each log entry using its hash. self._entries = [] # the empty list self._index = dict() # mapping hash => entry @property def hashtype(self): """ Return the type of SHA hash used. """ return self._hashtype def read(self): """ The first line contains timestamp, hash, nodeID for previous Log. Succeeding lines look like timestamp hash nodeID src path In both cases timestamp is an unsigned int, the number of milliseconds since the epoch. It can be printed with %13u. The current value (April 2011) is about 1.3 trillion (1301961973000). """ first_line = None if self._lines: first_line = self._lines[0] if first_line: match = re.match(self.first_line_re, first_line) if not match: print("NO MATCH, FIRST LINE; hashtype = %s" % self.hashtype) print((" FIRST LINE: '%s'" % first_line)) raise UpaxError("no match on first line; giving up") timestamp = int(match.group(1)) prev_log_hash = match.group(2) prev_master = match.group(3) del self._lines[0] # so we can cleanly iterate else: # no first line timestamp = 0 if self._hashtype == HashTypes.SHA1: prev_log_hash = SHA1_HEX_NONE prev_master = SHA1_HEX_NONE elif self._hashtype == HashTypes.SHA2: prev_log_hash = SHA2_HEX_NONE prev_master = SHA2_HEX_NONE elif self._hashtype == HashTypes.SHA3: prev_log_hash = SHA3_HEX_NONE prev_master = SHA3_HEX_NONE elif self._hashtype == HashTypes.BLAKE2B: prev_log_hash = BLAKE2B_HEX_NONE prev_master = BLAKE2B_HEX_NONE else: raise NotImplementedError entries = [] index = dict() for line in self._lines: # Read each successive line, creating an entry for each and # indexing each. Ignore blank lines and those beginning with # a hash ('#') match = re.match(IGNORABLE_RE, line) if match: continue if self._hashtype == HashTypes.SHA1: match = re.match(BODY_LINE_1_RE, line) else: match = re.match(BODY_LINE_256_RE, line) if match: tstamp = int(match.group(1)) key = match.group(2) node_id = match.group(3) src = match.group(4) path = match.group(5) # constructor should catch invalid fields entry = LogEntry(tstamp, key, node_id, src, path) entries.append(entry) index[key] = entry else: msg = "not a valid log entry line: '%s'" % line raise UpaxError(msg) return (timestamp, prev_log_hash, prev_master, entries, index) # ------------------------------------------------------------------- class FileReader(Reader): """ Accept uPath and optionally log file name, read entire file into a string array, pass to Reader. """ __slots__ = ['_u_path', '_base_name', '_log_file', ] # XXX CHECK ORDER OF ARGUMENTS def __init__(self, u_path, hashtype=False, base_name="L"): if not os.path.exists(u_path): raise UpaxError("no such directory %s" % u_path) self._u_path = u_path self._base_name = base_name self._log_file = "%s/%s" % (self._u_path, base_name) with open(self._log_file, 'r') as file: contents = file.read() lines = contents.split('\n') super(FileReader, self).__init__(lines, hashtype) @property def base_name(self): """ Return the base name of the log file. """ return self._base_name @property def log_file(self): """ Return the path to the log file. """ return self._log_file @property def u_path(self): """ Return the path to uDir, the content-keyed store. """ return self._u_path # ------------------------------------------------------------------- class StringReader(Reader): """ Accept a (big) string, convert to a string array, pass to Reader """ def __init__(self, bigString, hashtype=False): # split on newlines lines = bigString.split('\n') super().__init__(lines, hashtype)
jddixon/upax_py
src/upax/ftlog.py
Python
mit
16,036
0
#!/usr/bin/env python import sys import re from helpers import * PROGRAM_USAGE = """ SeqAn invalid identifiers detection script. USAGE: invalid_identifiers.py BASE_PATH BASE_PATH is the root path of all the folders to be searched. This script generates a list of invalid identifiers found in the code base, paired with their suggested replacement string in the format ``"old: new"``, one identifier per line. The result is written to the standard output. """.strip() INVALID_IDENTIFIER = re.compile(r'\b_[A-Z_]\w*\b') REPLACEMENT_ID = re.compile(r'\b(__?)(\w*)\b') # The following IDs are exempted from replacement since they are either defined # by some compiler (-specific library) or are solely used within a string. VALID_IDENTIFIERS = map( lambda rx: re.compile(rx), [ '___+', '^__$', '_N', '_L', '_H', '__u?int64(_t)?', '_A123456', '__OPTIMIZE__', '__gnu_cxx', '_Resize_String', # will be done manually '_Fill_String', # '_Transcript_', '_Confidence_99', '_PARSER_H', '_POSIX_TIMERS', '__GNUC_MINOR__', '_S_IREAD', '_S_IWRITE', '_O_BINARY', '_O_CREAT', '_O_RDONLY', '_O_RDWR', '_O_TEMPORARY', '_O_TRUNC', '_O_WRONLY', '_KMER_H', '_MSC_EXTENSIONS', '_GLIBCXX_PARALLEL', '_FILE_OFFSET_BITS', '_POSIX_SYNCHRONIZED_IO', '__cplusplus', '__(force)?inline(__)?', '__alignof(__)?', '__attribute__', '__GLOBAL__', '_DELETIONS____', '_INSERTS______', '_REPLACEMENTS_', '__int128', '__SSE2__', '__m128i', '__VA_ARGS__', '__FILE__', '__LINE__', '__GET_OPT_H__', '_OPENMP', '__SINIX__', '__sgi', '__BEOS__', '__aix__', '__ICC', '__WATCOMC__', '__ADSPBLACKFIN__', '_BEOS', '__SUNPRO_CC?', '__tru64', '__FreeBSD__', '__ultrix', '__OPENBSD', '_MPRAS', '_HAIKU', '_SGI_COMPILER_VERSION', '_POSIX_C_SOURCE', '_XOPEN_SOURCE', '__OpenBSD__', '__AIX__', '__ADSP21000__', '__HAIKU__', '__riscos__', '__hpux', '__HP_aCC', '__riscos', '__hpua', '__GNUC__', '_ULTRIX', '_SCO_SV', '__DECCXX', '_XENIX', '__sgi__', '_WIN32', '__PGI', '__QNX__', '__APPLE__', '__AIX', '_SGI', '_AIX', '__XENIX__', '__INTEL_COMPILER', '__osf', '__linux__', '__sinix__', '__bsdos__', '__ADSPTS__', '__sun', '__sinix', '__NetBSD', '__FreeBSD', '__osf__', '__ultrix__', '__COMPILER_VER__', '__COMO__', '__linux', '__UNIX_SV__', '__HAIKU', '__WIN32__', '__NetBSD__', '__CYGWIN__', '_COMPILER_VERSION', '__BORLANDC__', '__TRU64__', '__MINGW32__', '__aix', '__BeOS', '__QNXNTO__', '__hpux__', '__IBMCPP__', '__IAR_SYSTEMS_ICC__', '__18CXX', '__HP_cc', '__SUNPRO_C', '__DECC', '__IBMC__', '_MSC_VER' ]) def valid(id): """ Returns whether the given ``id`` is in fact valid and shouldn't be replaced. """ return any(VALID_ID.match(id) for VALID_ID in VALID_IDENTIFIERS) def find_all(file): """ Returns all invalid identifiers found in a given ``file``. """ f = open(file, 'r') result = [] for line in f: matches = INVALID_IDENTIFIER.findall(line) invalids = [match for match in matches if not valid(match)] result += invalids return result def replacement(orig): """ Returns the replacement string for a given invalid identifier. """ return REPLACEMENT_ID.sub(r'\2\1', orig) def generate_replacements(ids): """ Generates a dictionary of replacement strings for a list of invalid identifiers. """ return dict([(original, replacement(original)) for original in ids]) def main(): if len(sys.argv) != 2: print >>sys.stderr, 'ERROR: Invalid number of arguments.' print >>sys.stderr, PROGRAM_USAGE return 1 results = {} project_path = sys.argv[1] for file in all_files(project_path): results[file] = set(find_all(file)) all_ids = set() for ids in results.values(): all_ids |= ids replacements = generate_replacements(all_ids) for id in sorted(all_ids): print '%s: %s' % (id, replacements[id]) #for file in sorted(results.keys()): # for id in results[file]: # print '%s: %s' % (file, id) return 0 if __name__ == '__main__': sys.exit(main())
bkahlert/seqan-research
raw/workshop13/workshop2013-data-20130926/trunk/misc/renaming/invalid_identifiers.py
Python
mit
5,253
0.002094
# Foris - web administration interface for OpenWrt based on NETCONF # Copyright (C) 2017 CZ.NIC, z.s.p.o. <http://www.nic.cz> # # 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/>. from .base import BaseConfigHandler __all__ = ["BaseConfigHandler"]
CZ-NIC/foris
foris/config_handlers/__init__.py
Python
gpl-3.0
833
0