prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>HIDManagerTest.java<|end_file_name|><|fim▁begin|>package com.cibuddy.hid.test;
import com.codeminders.hidapi.ClassPathLibraryLoader;
import com.codeminders.hidapi.HIDDeviceInfo;
import com.codeminders.hidapi.HIDManager;
import java.io.IOException;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
<|fim▁hole|> *
* @author Mirko Jahn <[email protected]>
* @version 1.0
*/
@Ignore
public class HIDManagerTest {
/**
* Loads the native libraries before the test execution.
* @since 1.0
*/
@BeforeClass
public static void beforeEverything() {
// load the native libraries automatically (only once per JVM instance)
ClassPathLibraryLoader.loadNativeHIDLibrary();
}
/**
* Test how many devices are found if run twice.
*
* Listing all devices twice and checking if the lists are identical. If not,
* most likely one device is still occupied by the first request (Windows is
* supposed to behave like that in some cases). You might as well have just
* removed/added the HID device during the test run.
*
* @throws IOException in case access to the driver was not possible
* @throws InterruptedException
*/
@Test
public void testListDevices() throws IOException, InterruptedException {
HIDManager manager = HIDManager.getInstance();
HIDDeviceInfo[] firstRun = printDevices(manager);
System.out.println("Second run: Checking for HID devices again...");
HIDDeviceInfo[] secondRun = printDevices(manager);
Assert.assertArrayEquals("The list of found HID devices is NOT equal. Make sure you didn't connect/disconnect a device while running the test",
firstRun,
secondRun);
manager.release();
}
/**
* Main method, just printing all connected devices.
*
* @param args - not used.
*/
private static HIDDeviceInfo[] printDevices(HIDManager manager) throws IOException{
HIDDeviceInfo[] devs = manager.listDevices();
System.out.println("HID Devices:\n\n");
for(int i=0;i<devs.length;i++)
{
System.out.println(""+i+".\t"+devs[i]);
System.out.println("---------------------------------------------\n");
}
System.gc();
return devs;
}
}<|fim▁end|>
|
/**
* A simple test to see if the native libraries could be loaded.
|
<|file_name|>ViewDoctorActivity.java<|end_file_name|><|fim▁begin|>package com.faravy.icare;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.faravy.database.DoctorDataSource;
import com.faravy.modelclass.Doctor;
public class ViewDoctorActivity extends Activity {
Doctor mDoctor;
DoctorDataSource mDataSource;
TextView mEtName;
TextView mEtDetail;
TextView mEtDate;
TextView mEtPhone;
TextView mEtEmail;
String mID = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_doctor);
ActionBar ab = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#0080FF"));
ab.setBackgroundDrawable(colorDrawable);
mEtName = (TextView) findViewById(R.id.addName);
mEtDetail = (TextView) findViewById(R.id.addDetails);
mEtDate = (TextView) findViewById(R.id.addAppointment);
mEtPhone = (TextView) findViewById(R.id.addPhone);
mEtEmail = (TextView) findViewById(R.id.addEmail);
<|fim▁hole|>
String name = mDoctor.getmName();
String detail = mDoctor.getmDetails();
String date = mDoctor.getmAppoinment();
String phone = mDoctor.getmPhone();
String email = mDoctor.getmEmail();
mEtName.setText(name);
mEtDetail.setText(detail);
mEtDate.setText(date);
mEtPhone.setText(phone);
mEtEmail.setText(email);
}
public void makeCall(View v) {
String number = mEtPhone.getText().toString().trim();
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
+ number));
startActivity(callIntent);
}
public void sendSms(View v) {
String number = mEtPhone.getText().toString().trim();
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:"
+ number));
startActivity(smsIntent);
}
public void sendEmail(View v) {
String email = mEtEmail.getText().toString();
/*Intent emailIntent = new Intent(Intent.ACTION_SEND,
Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, email);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
startActivity(Intent.createChooser(emailIntent, "Send mail..."));*/
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", email, null));
startActivity(Intent.createChooser(intent, "Send email..."));
}
public void addToContact(View v) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME,
mEtName.getText().toString()) // Name of the
// person
.build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, mEtPhone.getText().toString()) // Number
// of
// the
// person
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of
// mobile
// number
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getApplicationContext(),
"Successfully Contract Added !!!!!!!", Toast.LENGTH_LONG)
.show();
} catch (RemoteException e) {
// error
} catch (OperationApplicationException e) {
// error
}
Intent contacts = new Intent(Intent.ACTION_VIEW,
ContactsContract.Contacts.CONTENT_URI);
startActivity(contacts);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_doctor, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}<|fim▁end|>
|
Intent mActivityIntent = getIntent();
mID = mActivityIntent.getStringExtra("mId");
mDataSource = new DoctorDataSource(this);
mDoctor = mDataSource.singleDoctor(mID);
|
<|file_name|>jquery,mmenu.addon-template.js<|end_file_name|><|fim▁begin|>/*
* jQuery mmenu {ADDON} add-on
* mmenu.frebsite.nl
*
* Copyright (c) Fred Heusschen
*/
(function( $ ) {
var _PLUGIN_ = 'mmenu',
_ADDON_ = '{ADDON}';
$[ _PLUGIN_ ].addons[ _ADDON_ ] = {
// setup: fired once per menu
setup: function()
{
var that = this,
opts = this.opts[ _ADDON_ ],
conf = this.conf[ _ADDON_ ];
glbl = $[ _PLUGIN_ ].glbl;
// Extend shorthand options
if ( typeof opts != 'object' )
{
opts = {};
}
opts = this.opts[ _ADDON_ ] = $.extend( true, {}, $[ _PLUGIN_ ].defaults[ _ADDON_ ], opts );
// Extend shorthand configuration
if ( typeof conf != 'object' )
{
conf = {};
}
conf = this.conf[ _ADDON_ ] = $.extend( true, {}, $[ _PLUGIN_ ].configuration[ _ADDON_ ], conf );
// Add methods to api
// this._api = $.merge( this._api, [ 'fn1', 'fn2' ] );
// Bind functions to update
// this.bind( 'update', function() {} );
// this.bind( 'initPanels', function() {} );
// this.bind( 'initPage', function() {} );
},
// add: fired once per page load
add: function()
{<|fim▁hole|> _d = $[ _PLUGIN_ ]._d;
_e = $[ _PLUGIN_ ]._e;
// ...Add classnames, data and events
},
// clickAnchor: prevents default behavior when clicking an anchor
clickAnchor: function( $a, inMenu )
{
// if ( $a.is( '.CLASSNAME' ) )
// {
// return true;
// }
// return false;
}
};
// Default options and configuration
$[ _PLUGIN_ ].defaults[ _ADDON_ ] = {
// ...
};
$[ _PLUGIN_ ].configuration.classNames[ _ADDON_ ] = {
// ...
};
var _c, _d, _e, glbl;
})( jQuery );<|fim▁end|>
|
_c = $[ _PLUGIN_ ]._c;
|
<|file_name|>main.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "mainwindow.h"
//! [0]
int main(int argc, char *argv[])
//! [0] //! [1]
{
QApplication app(argc, argv);
QString locale = QLocale::system().name();<|fim▁hole|> translator.load(QString("arrowpad_") + locale);
app.installTranslator(&translator);
//! [1] //! [3]
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}<|fim▁end|>
|
//! [2]
QTranslator translator;
//! [2] //! [3]
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>export { authentication } from './authentication'
export { authorization } from './authorization'<|fim▁hole|><|fim▁end|>
|
export { errorHandler } from './error-handler'
export { logRequest } from './log-request'
export { validate } from './validator'
export { responseTime } from './response-time'
|
<|file_name|>increment.py<|end_file_name|><|fim▁begin|>import ConfigParser
from .settings import SECTIONS, CONFIG
config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
"""
Read max ids of the last downloads
:param users: A list of users
Return a dictionary mapping users to ids
"""
since_ids = {}
for user in users:
if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1
return since_ids
def set_max_ids(max_ids):
"""
Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids
"""
config.read(CONFIG)<|fim▁hole|> config.write(f)
def remove_since_id(user):
if config.has_option(SECTIONS['INCREMENTS'], user):
config.remove_option(SECTIONS['INCREMENTS'], user)
with open(CONFIG, 'w') as f:
config.write(f)<|fim▁end|>
|
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f:
|
<|file_name|>emailer_plugin.py<|end_file_name|><|fim▁begin|>from gi.repository import Gtk
import gourmet.gtk_extras.dialog_extras as de
from gourmet.plugin import RecDisplayModule, UIPlugin, MainPlugin, ToolPlugin
from .recipe_emailer import RecipeEmailer
from gettext import gettext as _
class EmailRecipePlugin (MainPlugin, UIPlugin):
ui_string = '''
<menubar name="RecipeIndexMenuBar">
<menu name="Tools" action="Tools">
<placeholder name="StandaloneTool">
<menuitem action="EmailRecipes"/>
</placeholder>
</menu>
</menubar>
'''
def setup_action_groups (self):
self.actionGroup = Gtk.ActionGroup(name='RecipeEmailerActionGroup')<|fim▁hole|> None,_('Email all selected recipes (or all recipes if no recipes are selected'),self.email_selected),
])
self.action_groups.append(self.actionGroup)
def activate (self, pluggable):
self.rg = self.pluggable = pluggable
self.add_to_uimanager(pluggable.ui_manager)
def get_selected_recs (self):
recs = self.rg.get_selected_recs_from_rec_tree()
if not recs:
recs = self.rd.fetch_all(self.rd.recipe_table, deleted=False, sort_by=[('title',1)])
return recs
def email_selected (self, *args):
recs = self.get_selected_recs()
l = len(recs)
if l > 20:
if not de.getBoolean(
title=_('Email recipes'),
# only called for l>20, so fancy gettext methods
# shouldn't be necessary if my knowledge of
# linguistics serves me
sublabel=_('Do you really want to email all %s selected recipes?')%l,
custom_yes=_('Yes, e_mail them'),
cancel=False,
):
return
re = RecipeEmailer(recs)
re.send_email_with_attachments()<|fim▁end|>
|
self.actionGroup.add_actions([
('EmailRecipes',None,_('Email recipes'),
|
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import json
import httplib
from conpaas.core import https
def _check(response):
code, body = response
if code != httplib.OK: raise Exception('Received http response code %d' % (code))
data = json.loads(body)
if data['error']: raise Exception(data['error'])
else: return data['result']
def check_agent_process(host, port):
method = 'check_agent_process'<|fim▁hole|> method = 'startup'
return _check(https.client.jsonrpc_post(host, port, '/', method))
def get_helloworld(host, port):
method = 'get_helloworld'
return _check(https.client.jsonrpc_get(host, port, '/', method))<|fim▁end|>
|
return _check(https.client.jsonrpc_get(host, port, '/', method))
def startup(host, port):
|
<|file_name|>test_url.cpp<|end_file_name|><|fim▁begin|>#include "test_url.hpp"
#include <oonet/http/url.hpp>
namespace oonet
{
namespace test
{
test_url test_url_inst;
bool test_url::TestUrlParamCtor::operator()()
{ http::url_params a;
if (!a.list().empty())
return false;
if (!a.full().empty())
return false;
return true;
}
bool test_url::TestUrlParamParseCtor::operator()()
{
// Test some parsing
http::url_params a("b=124");
if (a.full() != "b=124")
return false;
if (a.list().size() != 1)
return false;
if (a.begin()->first != "b")
return false;
if (a.begin()->second != "124")
return false;
http::url_params b("250402kfoe=sdfgklsjdflgkjsdfg90sdfug09sdfugoj");
if (b.full() != "250402kfoe=sdfgklsjdflgkjsdfg90sdfug09sdfugoj")
return false;
if (b.list().size() != 1)
return false;
if (b.begin()->first != "250402kfoe")
return false;
if (b.begin()->second != "sdfgklsjdflgkjsdfg90sdfug09sdfugoj")
return false;
// No value
http::url_params c("dsfklgjsdkflgjsdf");
if (c.full() != "dsfklgjsdkflgjsdf")
return false;
if (c.list().size() != 1)
return false;
if (c.begin()->first != "dsfklgjsdkflgjsdf")
return false;
if (c.begin()->second != "")
return false;
// Embended =
<|fim▁hole|> if (d.list().size() != 1)
return false;
if (d.begin()->first != "dsfklgjsdkflgjsdf")
return false;
if (d.begin()->second != "123=123")
return false;
return true;
}
bool test_url::TestUrlParamCopyCtor::operator()()
{ http::url_params a("kaka=lola");
http::url_params b(a);
if (b.list().size() != 1)
return false;
if (b.begin()->first != "kaka")
return false;
if (b.begin()->second != "lola")
return false;
return true;
}
bool test_url::TestUrlParamCopyOperator::operator()()
{ http::url_params a("kaka=lola");
http::url_params b;
b = a;
if (b.list().size() != 1)
return false;
if (b.begin()->first != "kaka")
return false;
if (b.begin()->second != "lola")
return false;
return true;
}
bool test_url::TestUrlParamParse::operator()()
{ http::url_params a;
// Test 100k parsings
for(long i = 0;i < 100000; i++)
a.parse("fofo=lola");
if (a.list().size() != 1)
return false;
if (a.begin()->first != "fofo")
return false;
if (a.begin()->second != "lola")
return false; return true;
}
bool test_url::TestUrlCtor::operator()()
{ http::url a;
if (a.full() != "")
return false;
if (a.host_port() != "")
return false;
if (a.host() != "")
return false;
if (a.port() != "")
return false;
if (a.resource() != "")
return false;
if (a.path() != "")
return false;
if (a.parameters().full() != "")
return false;
return true;
}
bool test_url::TestUrlCtorString::operator()()
{ http::url a = http::url("http://www.gogla.gr/test1?par=1&par2=3");
if (a.full() != "http://www.gogla.gr/test1?par=1&par2=3")
return false;
if (a.scheme() != "http")
return false;
if (a.host_port() != "www.gogla.gr")
return false;
if (a.host() != "www.gogla.gr")
return false;
if (a.port() != "")
return false;
if (a.resource() != "/test1?par=1&par2=3")
return false;
if (a.path() != "/test1")
return false;
if (a.parameters().list().size() != 2)
return false;
return true;
}
bool test_url::TestCopyCtor::operator()()
{ http::url b = http::url("http://www.gogla.gr/test1?par=1&par2=3");
http::url a(b);
if (a.full() != "http://www.gogla.gr/test1?par=1&par2=3")
return false;
if (a.scheme() != "http")
return false;
if (a.host_port() != "www.gogla.gr")
return false;
if (a.host() != "www.gogla.gr")
return false;
if (a.port() != "")
return false;
if (a.resource() != "/test1?par=1&par2=3")
return false;
if (a.path() != "/test1")
return false;
if (a.parameters().list().size() != 2)
return false;
return true;
}
bool test_url::TestCopyOperatorUrl::operator()()
{ http::url b = http::url("http://www.gogla.gr/test1?par=1&par2=3");
http::url a;
a = b;
if (a.full() != "http://www.gogla.gr/test1?par=1&par2=3")
return false;
if (a.scheme() != "http")
return false;
if (a.host_port() != "www.gogla.gr")
return false;
if (a.host() != "www.gogla.gr")
return false;
if (a.port() != "")
return false;
if (a.resource() != "/test1?par=1&par2=3")
return false;
if (a.path() != "/test1")
return false;
if (a.parameters().list().size() != 2)
return false;
return true;
}
bool test_url::TestFind::operator()()
{ http::url b = http::url("http://www.gogla.gr/test1?par=1&par2=3");
http::url_params::const_iterator par_it;
if ((par_it = b.parameters().find("par")) == b.parameters().end())
return false;
if ((par_it->first != "par") || (par_it->second != "1"))
return false;
if ((par_it = b.parameters().find("par2")) == b.parameters().end())
return false;
if ((par_it->first != "par2") || (par_it->second != "3"))
return false;
if ((par_it = b.parameters().find("par3")) != b.parameters().end())
return false;
return true;
}
bool test_url::TestSplit3Wrong1::operator()()
{ http::url b("http:/lolalosadfadsf");
return false;
}
bool test_url::TestSplit3Wrong2::operator()()
{ http::url b("http//lolalosadfadsf");
return false;
}
bool test_url::TestSplit3Speed::operator()()
{ http::url b;
for(long i = 0;i < 10000;i++)
b = http::url("http://www.google.com:43/sadf.sf?asdfasd%");
if (b.scheme() != "http")
return false;
if (b.host_port() != "www.google.com:43")
return false;
if (b.resource() != "/sadf.sf?asdfasd%")
return false;
return true;
}
bool test_url::TestSplit3Quality::operator()()
{ http::url b;
string scheme, host, resource;
b = http::url("http://www.google.com:43/sadf.sf?asdfasd%");
if (b.scheme() != "http")
return false;
if (b.host_port() != "www.google.com:43")
return false;
if (b.resource() != "/sadf.sf?asdfasd%")
return false;
b = http::url("http://:www.goo:gle.com:43//////");
if (b.scheme() != "http")
return false;
if (b.host_port() != ":www.goo:gle.com:43")
return false;
if (b.resource() != "//////")
return false;
b = http::url("http://");
if (b.scheme() != "http")
return false;
if (b.host_port() != "")
return false;
if (b.resource() != "")
return false;
b = http::url("http:///");
if (b.scheme() != "http")
return false;
if (b.host_port() != "")
return false;
if (b.resource() != "/")
return false;
return true;
}
bool test_url::TestSplit4Wrong1::operator()()
{ http::url b("http:://lolal:/osadfadsf");
return false;
}
bool test_url::TestSplit4Quality::operator()()
{ http::url b;
b = http::url("http://asdfasD:12/");
if (b.scheme() != "http")
return false;
if (b.host() != "asdfasD")
return false;
if (b.port() != "12")
return false;
if (b.resource() != "/")
return false;
b = http::url("http://asdfa:sD:12/");
if (b.scheme() != "http")
return false;
if (b.host() != "asdfa")
return false;
if (b.port() != "sD:12")
return false;
if (b.resource() != "/")
return false;
b = http::url("http://www/12:32");
if (b.scheme() != "http")
return false;
if (b.host() != "www")
return false;
if (b.port() != "")
return false;
if (b.resource() != "/12:32")
return false;
b = http::url("http://");
if (b.scheme() != "http")
return false;
if (b.host() != "")
return false;
if (b.port() != "")
return false;
if (b.resource() != "")
return false;
b = http::url("http:///");
if (b.scheme() != "http")
return false;
if (b.host() != "")
return false;
if (b.port() != "")
return false;
if (b.resource() != "/")
return false;
b = http::url("http:///:");
if (b.scheme() != "http")
return false;
if (b.host() != "")
return false;
if (b.port() != "")
return false;
if (b.resource() != "/:")
return false;
return true;
}
bool test_url::TestSplit4Speed::operator()()
{ http::url b;
for(long i = 0;i < 10000;i++)
b = http::url("http://www.google.com:43/sadf.sf?asdfasd%");
if (b.scheme() != "http")
return false;
if (b.host() != "www.google.com")
return false;
if (b.port() != "43")
return false;
if (b.resource() != "/sadf.sf?asdfasd%")
return false;
return true;
}
bool test_url::TestSplit5Wrong1::operator()()
{ http::url b("http///lolal:/osadfadsf?");
return false;
}
bool test_url::TestSplit5Quality::operator()()
{ http::url b;
b = http::url("http://?");
if (b.scheme() != "http")
return false;
if (b.host() != "?")
return false;
if (b.port() != "")
return false;
if (b.path() != "")
return false;
if (b.parameters().list().size() != 0)
return false;
b = http::url("http:///?");
if (b.scheme() != "http")
return false;
if (b.host() != "")
return false;
if (b.port() != "")
return false;
if (b.path() != "/")
return false;
if (b.parameters().list().size() != 0)
return false;
b = http::url("http:///?a");
if (b.scheme() != "http")
return false;
if (b.host() != "")
return false;
if (b.port() != "")
return false;
if (b.path() != "/")
return false;
if (b.parameters().list().size() != 1)
return false;
if (b.parameters().list()[0].first != "a")
return false;
if (b.parameters().list()[0].second != "")
return false;
b = http::url("http:///??a");
if (b.scheme() != "http")
return false;
if (b.host() != "")
return false;
if (b.port() != "")
return false;
if (b.path() != "/")
return false;
if (b.parameters().list().size() != 1)
return false;
if (b.parameters().list()[0].first != "?a")
return false;
if (b.parameters().list()[0].second != "")
return false;
b = http::url("http:///?&a");
if (b.scheme() != "http")
return false;
if (b.host() != "")
return false;
if (b.port() != "")
return false;
if (b.path() != "/")
return false;
if (b.parameters().list().size() != 1)
return false;
if (b.parameters().list()[0].first != "a")
return false;
if (b.parameters().list()[0].second != "")
return false;
b = http::url("http://localhost:8080/dqp_calculator?ac=12&br=3&ts=4&ku=5&rl=6&session=134521611");
if (b.scheme() != "http")
return false;
if (b.host() != "localhost")
return false;
if (b.port() != "8080")
return false;
if (b.path() != "/dqp_calculator")
return false;
if (b.parameters().list().size() != 6)
return false;
if (b.parameters().list()[0].first != "ac")
return false;
if (b.parameters().list()[0].second != "12")
return false;
if (b.parameters().list()[1].first != "br")
return false;
if (b.parameters().list()[1].second != "3")
return false;
if (b.parameters().list()[2].first != "ts")
return false;
if (b.parameters().list()[2].second != "4")
return false;
if (b.parameters().list()[3].first != "ku")
return false;
if (b.parameters().list()[3].second != "5")
return false;
if (b.parameters().list()[4].first != "rl")
return false;
if (b.parameters().list()[4].second != "6")
return false;
if (b.parameters().list()[5].first != "session")
return false;
if (b.parameters().list()[5].second != "134521611")
return false;
return true;
}
bool test_url::TestSplit5Speed::operator()()
{ http::url b;
for(long i = 0;i < 10000;i++)
b = http::url("http://www.google.com:43/sadf.sf?asdfasd%");
if (b.scheme() != "http")
return false;
if (b.host() != "www.google.com")
return false;
if (b.port() != "43")
return false;
if (b.path() != "/sadf.sf")
return false;
if (b.parameters().list().size() != 1)
return false;
if (b.parameters().list()[0].first != "asdfasd%")
return false;
if (b.parameters().list()[0].second != "")
return false;
return true;
}
} // !test namespace
}; // !oonet namespace<|fim▁end|>
|
http::url_params d("dsfklgjsdkflgjsdf=123=123");
if (d.full() != "dsfklgjsdkflgjsdf=123=123")
return false;
|
<|file_name|>elf64.rs<|end_file_name|><|fim▁begin|>use core::fmt;
use core::iter::Iterator;
use ::kern::console::LogLevel::*;
pub const SIZEOF_IDENT: usize = 16;
pub const SIZEOF_EHDR: usize = 64;
pub const ELFCLASS: u8 = ELFCLASS64;
#[repr(C)]<|fim▁hole|> pub e_ident: [u8; SIZEOF_IDENT],
/// Object file type
pub e_type: u16,
/// Architecture
pub e_machine: u16,
/// Object file version
pub e_version: u32,
/// Entry point virtual address
pub e_entry: u64,
/// Program header table file offset
pub e_phoff: u64,
/// Section header table file offset
pub e_shoff: u64,
/// Processor-specific flags
pub e_flags: u32,
/// ELF header size in bytes
pub e_ehsize: u16,
/// Program header table entry size
pub e_phentsize: u16,
/// Program header table entry count
pub e_phnum: u16,
/// Section header table entry size
pub e_shentsize: u16,
/// Section header table entry count
pub e_shnum: u16,
/// Section header string table index
pub e_shstrndx: u16,
}
impl fmt::Debug for Header {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "e_ident: {:?} e_type: {} e_machine: 0x{:x} e_version: 0x{:x} e_entry: 0x{:x} \
e_phoff: 0x{:x} e_shoff: 0x{:x} e_flags: {:x} e_ehsize: {} e_phentsize: {} \
e_phnum: {} e_shentsize: {} e_shnum: {} e_shstrndx: {}",
self.e_ident,
et_to_str(self.e_type),
self.e_machine,
self.e_version,
self.e_entry,
self.e_phoff,
self.e_shoff,
self.e_flags,
self.e_ehsize,
self.e_phentsize,
self.e_phnum,
self.e_shentsize,
self.e_shnum,
self.e_shstrndx)
}
}
/// No file type.
pub const ET_NONE: u16 = 0;
/// Relocatable file.
pub const ET_REL: u16 = 1;
/// Executable file.
pub const ET_EXEC: u16 = 2;
/// Shared object file.
pub const ET_DYN: u16 = 3;
/// Core file.
pub const ET_CORE: u16 = 4;
/// Number of defined types.
pub const ET_NUM: u16 = 5;
/// The ELF magic number.
pub const ELFMAG: &'static [u8; 4] = b"\x7FELF";
/// Sizeof ELF magic number.
pub const SELFMAG: usize = 4;
/// File class byte index.
pub const EI_CLASS: usize = 4;
/// Invalid class.
pub const ELFCLASSNONE: u8 = 0;
/// 32-bit objects.
pub const ELFCLASS32: u8 = 1;
/// 64-bit objects.
pub const ELFCLASS64: u8 = 2;
/// ELF class number.
pub const ELFCLASSNUM: u8 = 3;
/// Convert an ET value to their associated string.
#[inline]
pub fn et_to_str(et: u16) -> &'static str {
match et {
ET_NONE => "NONE",
ET_REL => "REL",
ET_EXEC => "EXEC",
ET_DYN => "DYN",
ET_CORE => "CORE",
ET_NUM => "NUM",
_ => "UNKNOWN_ET",
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub struct ProgramHeader {
/// Segment type
pub p_type: u32,
/// Segment flags
pub p_flags: u32,
/// Segment file offset
pub p_offset: u64,
/// Segment virtual address
pub p_vaddr: u64,
/// Segment physical address
pub p_paddr: u64,
/// Segment size in file
pub p_filesz: u64,
/// Segment size in memory
pub p_memsz: u64,
/// Segment alignment
pub p_align: u64,
}
pub const SIZEOF_PHDR: usize = 56;
/// Program header table entry unused
pub const PT_NULL: u32 = 0;
/// Loadable program segment
pub const PT_LOAD: u32 = 1;
/// Dynamic linking information
pub const PT_DYNAMIC: u32 = 2;
/// Program interpreter
pub const PT_INTERP: u32 = 3;
/// Auxiliary information
pub const PT_NOTE: u32 = 4;
/// Reserved
pub const PT_SHLIB: u32 = 5;
/// Entry for header table itself
pub const PT_PHDR: u32 = 6;
/// Thread-local storage segment
pub const PT_TLS: u32 = 7;
/// Number of defined types
pub const PT_NUM: u32 = 8;
/// Start of OS-specific
pub const PT_LOOS: u32 = 0x60000000;
/// GCC .eh_frame_hdr segment
pub const PT_GNU_EH_FRAME: u32 = 0x6474e550;
/// Indicates stack executability
pub const PT_GNU_STACK: u32 = 0x6474e551;
/// Read-only after relocation
pub const PT_GNU_RELRO: u32 = 0x6474e552;
/// Sun Specific segment
pub const PT_LOSUNW: u32 = 0x6ffffffa;
/// Sun Specific segment
pub const PT_SUNWBSS: u32 = 0x6ffffffa;
/// Stack segment
pub const PT_SUNWSTACK: u32 = 0x6ffffffb;
/// End of OS-specific
pub const PT_HISUNW: u32 = 0x6fffffff;
/// End of OS-specific
pub const PT_HIOS: u32 = 0x6fffffff;
/// Start of processor-specific
pub const PT_LOPROC: u32 = 0x70000000;
/// ARM unwind segment
pub const PT_ARM_EXIDX: u32 = 0x70000001;
/// End of processor-specific
pub const PT_HIPROC: u32 = 0x7fffffff;
/// Segment is executable
pub const PF_X: u32 = 1 << 0;
/// Segment is writable
pub const PF_W: u32 = 1 << 1;
/// Segment is readable
pub const PF_R: u32 = 1 << 2;
pub struct ProgramHeaderIter<'a> {
data: &'a [u8],
header: &'a Header,
next: usize
}
pub struct Elf64<'a> {
pub header: &'a Header,
pub data: &'a [u8]
}
impl<'a> Elf64<'a> {
pub unsafe fn from(bytes: &'a [u8]) -> Elf64<'a> {
let h = &*(bytes.as_ptr() as *const Header);
Elf64 {
data: bytes,
header: h,
}
}
pub fn program_headers(&self) -> ProgramHeaderIter<'a> {
ProgramHeaderIter {
data: self.data,
header: self.header,
next: 0
}
}
}
impl<'a> Iterator for ProgramHeaderIter<'a> {
type Item = &'a ProgramHeader;
fn next(&mut self) -> Option<Self::Item> {
if self.next < self.header.e_phnum as usize {
let program = unsafe {
&*(self.data.as_ptr().offset(
self.header.e_phoff as isize +
self.header.e_phentsize as isize * self.next as isize)
as *const ProgramHeader)
};
self.next += 1;
Some(program)
} else {
None
}
}
}<|fim▁end|>
|
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Header {
/// Magic number and other info
|
<|file_name|>docker_info_test.go<|end_file_name|><|fim▁begin|>package appui
import (
"testing"
"github.com/moncho/dry/mocks"
)
var expectedDockerInfoWithSwarm = ` <blue>Docker Host:</> <yellow>dry.io</> <blue>Docker Version:</> <yellow>1.0</> <blue>Hostname:</> <yellow>test</> <blue>Swarm:</> <yellow>active</>
<blue>Cert Path:</> <yellow></> <blue>APIVersion:</> <yellow>1.27</> <blue>CPU:</> <yellow>2</> <blue>Node role:</> <yellow>manager</>
<blue>Verify Certificate:</> <yellow>false</> <blue>OS/Arch/Kernel:</> <yellow>dry/amd64/42</> <blue>Memory:</> <yellow>1KiB</> <blue>Nodes:</> <yellow>0</>
`
var expectedDockerInfoNoSwarm = ` <blue>Docker Host:</> <yellow>dry.io</> <blue>Docker Version:</> <yellow>1.0</> <blue>Hostname:</> <yellow>test</> <blue>Swarm:</> <yellow>inactive</>
<blue>Cert Path:</> <yellow></> <blue>APIVersion:</> <yellow>1.27</> <blue>CPU:</> <yellow>2</>
<blue>Verify Certificate:</> <yellow>false</> <blue>OS/Arch/Kernel:</> <yellow>dry/amd64/42</> <blue>Memory:</> <yellow>1KiB</>
`
func TestDockerInfo(t *testing.T) {
daemon := &mocks.DockerDaemonMock{}
di := NewDockerInfo(daemon)
if di == nil {
t.Error("Docker info widget is nil")
}
content := di.Buffer()
if content.Area.Dy() != di.GetHeight() {
t.Error("Docker info widget does not have the expected height")
}
<|fim▁hole|> t.Errorf("Docker info widget does not have the expected content: %v", content.CellMap)
}
}
func TestNoSwarmDockerInfoContent(t *testing.T) {
daemon := &mocks.DockerDaemonMock{}
di := dockerInfo(daemon)
if di == "" {
t.Error("Docker info is empty")
}
if di != expectedDockerInfoNoSwarm {
t.Errorf("Docker info output does not match. Expected: \n'%q'\n, got: \n'%q'", expectedDockerInfoNoSwarm, di)
}
}
func TestSwarmDockerInfoContent(t *testing.T) {
daemon := &mocks.SwarmDockerDaemon{}
di := dockerInfo(daemon)
if di == "" {
t.Error("Docker info is empty")
}
if di != expectedDockerInfoWithSwarm {
t.Errorf("Docker info output does not match. Expected: \n'%q'\n, got: \n'%q'", expectedDockerInfoWithSwarm, di)
}
}<|fim▁end|>
|
if len(content.CellMap) == 0 {
|
<|file_name|>getgit.component.ts<|end_file_name|><|fim▁begin|>angular.module('component').component('getGit', {
template: `<|fim▁hole|> <h1>GIT : Repro</h1>
<div class="controller" >
<div git-repro="user : 'gaetanV',repositories :'angular_directive',branch:'master',path:'angular1/directive/gitRepro.directive.js'" > </div>
</div>
</section>
`,
});<|fim▁end|>
|
<section>
|
<|file_name|>wordpress.js<|end_file_name|><|fim▁begin|>import fs from 'fs';
import path from 'path';
import Wxr from 'wxr';
import Base from './base';
const NOT_SAFE_IN_XML = /[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm;
export default class extends Base {
constructor(...args) {
super(...args);
this.outputFile = path.join(think.RUNTIME_PATH, 'output_wordpress.xml');
}
async run() {
let importer = new Wxr();
let posts = await this.getPosts();
for(let post of posts) {
post.content = post.content.replace(NOT_SAFE_IN_XML, '');
post.summary = post.summary.replace(NOT_SAFE_IN_XML, '');
importer.addPost({
id: post.id,
title: post.title,
date: think.datetime(post.create_time),
contentEncoded: post.content,
excerptEncoded: post.summary,
categories: post.cate
})
}
let cateList = await this.model('cate').select();
for(let cate of cateList) {
importer.addCategory({
id: cate.id,
title: cate.name,<|fim▁hole|>
try {
fs.writeFileSync(
this.outputFile,
importer.stringify()
)
return this.outputFile;
} catch (e) {
throw new Error(e);
}
}
}<|fim▁end|>
|
slug: cate.pathname
});
}
|
<|file_name|>bitmap_font.rs<|end_file_name|><|fim▁begin|>use std::collections::HashMap;
use std::old_io::{File};
use xml::Element;
///
/// Representation of a bitmap font, generated with a tool like
/// [BMFont](http://www.angelcode.com/products/bmfont/)
///
/// A BitmapFont describes a bitmap font texture, providing a mapping from character
/// codes to a rectangular area within a corresponding font texture that contains a
/// bitmap representation for that character code.
///
/// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information.
///
pub struct BitmapFont {
pub scale_w: u8,
pub scale_h: u8,
pub characters: HashMap<char, BitmapCharacter>
}
#[derive(Debug)]
#[derive(Default)]
pub struct BitmapCharacter {<|fim▁hole|> pub y: u8,
pub width: u8,
pub height: u8,
pub xoffset: u8,
pub yoffset: u8,
pub xadvance: u8,
}
impl BitmapFont {
///
/// Constructs a BitmapFont for the xml configuration file at the given path
///
/// Expects file format like:
///
/// ```xml
/// <font>
/// <common scaleW="128" scaleH="128" ... />
/// <chars count="95">
/// <char id="32" x="2" y="2" width="0" height="0" xoffset="0" yoffset="14" xadvance="16" ... />
/// ...
/// </chars>
/// ```
///
/// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information.
///
pub fn from_path(path: &Path) -> Result<BitmapFont, &'static str> {
let mut file = match File::open(path) {
Ok(file) => file,
Err(_) => return Err("Failed to open font file at path.")
};
let xml_string = match file.read_to_string() {
Ok(file_string) => file_string,
Err(_) => return Err("Failed to read font file.")
};
BitmapFont::from_string(&xml_string[..])
}
///
/// Constructs a BitmapFont from the given string
///
/// Expects string format like:
///
/// ```xml
/// <font>
/// <common scaleW="128" scaleH="128" ... />
/// <chars count="95">
/// <char id="32" x="2" y="2" width="0" height="0" xoffset="0" yoffset="14" xadvance="16" ... />
/// ...
/// </chars>
/// ```
///
/// See http://www.angelcode.com/products/bmfont/doc/file_format.html for more information.
///
///
pub fn from_string(xml_string: &str) -> Result<BitmapFont, &'static str> {
match xml_string.parse() {
Ok(xml_root) => {
BitmapFont::from_xml_document(&xml_root)
},
Err(_) => Err("Error while parsing font document."),
}
}
///
/// Constructs a BitmapFont for the given root xml element
///
fn from_xml_document(xml_root: &Element) -> Result<BitmapFont, &'static str> {
let chars_element = match xml_root.get_child("chars", None) {
Some(chars_element) => chars_element,
None => return Err("Missing <chars> element"),
};
let common_element = match xml_root.get_child("common", None) {
Some(e) => e,
None => return Err("Missing <common> element"),
};
let mut bitmap_font = BitmapFont{
characters: HashMap::new(),
scale_w: get_attribute(&common_element, "scaleW"),
scale_h: get_attribute(&common_element, "scaleH"),
};
for char_elem in chars_element.get_children("char", None).iter() {
let character = BitmapCharacter {
x: get_attribute(char_elem, "x"),
y: get_attribute(char_elem, "y"),
width: get_attribute(char_elem, "width"),
height: get_attribute(char_elem, "height"),
xoffset: get_attribute(char_elem, "xoffset"),
yoffset: get_attribute(char_elem, "yoffset"),
xadvance: get_attribute(char_elem, "xadvance"),
};
let id = get_attribute(char_elem, "id");
bitmap_font.characters.insert(id as char, character);
}
Ok(bitmap_font)
}
}
///
/// Get a u8 value for for the attribute name on the given element,
/// defaulting to 0 if attribute unavaiable or failing to parse
///
fn get_attribute(element: &Element, name: &str) -> u8 {
match element.get_attribute(name, None) {
Some(value_string) => match value_string.parse() {
Ok(value) => value,
Err(_) => 0,
},
None => 0
}
}<|fim▁end|>
|
pub x: u8,
|
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
from distutils.core import setup, Extension
from distutils.util import get_platform
import shutil
import os, sys
def buil_all():<|fim▁hole|> packages=['miasm2',
'miasm2/arch',
'miasm2/arch/x86',
'miasm2/arch/arm',
'miasm2/arch/aarch64',
'miasm2/arch/msp430',
'miasm2/arch/sh4',
'miasm2/arch/mips32',
'miasm2/core',
'miasm2/expression',
'miasm2/ir',
'miasm2/ir/translators',
'miasm2/analysis',
'miasm2/os_dep',
'miasm2/jitter',
'miasm2/jitter/arch',
'miasm2/jitter/loader',
]
ext_modules_no_tcc = [
Extension("miasm2.jitter.VmMngr",
["miasm2/jitter/vm_mngr.c",
"miasm2/jitter/vm_mngr_py.c"]),
Extension("miasm2.jitter.arch.JitCore_x86",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_x86.c"]),
Extension("miasm2.jitter.arch.JitCore_arm",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_arm.c"]),
Extension("miasm2.jitter.arch.JitCore_aarch64",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_aarch64.c"]),
Extension("miasm2.jitter.arch.JitCore_msp430",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_msp430.c"]),
Extension("miasm2.jitter.arch.JitCore_mips32",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_mips32.c"]),
Extension("miasm2.jitter.Jitgcc",
["miasm2/jitter/Jitgcc.c"]),
Extension("miasm2.jitter.Jitllvm",
["miasm2/jitter/Jitllvm.c"]),
]
ext_modules_all = [
Extension("miasm2.jitter.VmMngr",
["miasm2/jitter/vm_mngr.c",
"miasm2/jitter/vm_mngr_py.c"]),
Extension("miasm2.jitter.arch.JitCore_x86",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_x86.c"]),
Extension("miasm2.jitter.arch.JitCore_arm",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_arm.c"]),
Extension("miasm2.jitter.arch.JitCore_aarch64",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_aarch64.c"]),
Extension("miasm2.jitter.arch.JitCore_msp430",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_msp430.c"]),
Extension("miasm2.jitter.arch.JitCore_mips32",
["miasm2/jitter/JitCore.c",
"miasm2/jitter/vm_mngr.c",
"miasm2/jitter/arch/JitCore_mips32.c"]),
Extension("miasm2.jitter.Jitllvm",
["miasm2/jitter/Jitllvm.c"]),
Extension("miasm2.jitter.Jitgcc",
["miasm2/jitter/Jitgcc.c"]),
Extension("miasm2.jitter.Jittcc",
["miasm2/jitter/Jittcc.c"],
libraries=["tcc"])
]
print 'building'
build_ok = False
for name, ext_modules in [('all', ext_modules_all),
('notcc', ext_modules_no_tcc)]:
print 'build with', repr(name)
try:
s = setup(
name = 'Miasm',
version = '2.0',
packages = packages,
package_data = {'miasm2':['jitter/*.h',
'jitter/arch/*.h',]},
ext_modules = ext_modules,
# Metadata
author = 'Fabrice Desclaux',
author_email = '[email protected]',
description = 'Machine code manipulation library',
license = 'GPLv2',
# keywords = '',
# url = '',
)
except SystemExit, e:
print repr(e)
continue
build_ok = True
break
if not build_ok:
raise ValueError('Unable to build Miasm!')
print 'build', name
if name == 'notcc':
print
print "*"*80
print "Warning: TCC is not properly installed,"
print "Miasm will be installed without TCC Jitter"
print "Etheir install TCC or use LLVM jitter"
print "*"*80
print
# we copy libraries from build dir to current miasm directory
build_base = None
if 'build' in s.command_options:
if 'build_base' in s.command_options['build']:
build_base = s.command_options['build']['build_base']
if build_base is None:
build_base = "build"
plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
build_base = os.path.join('build','lib' + plat_specifier)
print build_base
def buil_no_tcc():
setup(
name = 'Miasm',
version = '2.0',
packages=['miasm2', 'miasm2/tools',
'miasm2/expression', 'miasm2/graph', 'miasm2/arch',
'miasm2/core', 'miasm2/tools/emul_lib' ],
package_data = {'miasm2':['tools/emul_lib/*.h']},
# data_files = [('toto', ['miasm2/tools/emul_lib/queue.h'])],
# Metadata
author = 'Fabrice Desclaux',
author_email = '[email protected]',
description = 'Machine code manipulation library',
license = 'GPLv2',
# keywords = '',
# url = '',
)
def try_build():
buil_all()
"""
try:
buil_all()
return
except:
print "WARNING cannot build with libtcc!, trying without it"
print "Miasm will not be able to emulate code"
buil_no_tcc()
"""
try_build()<|fim▁end|>
| |
<|file_name|>tools.py<|end_file_name|><|fim▁begin|>import sys
import inspect
import os
import numpy as np
import time
import timeit
import collections
import subprocess
from qtools.qtpy import QtCore, QtGui
from qtools.utils import get_application, show_window
from functools import wraps
from galry import log_debug, log_info, log_warn
from collections import OrderedDict as ordict
# try importing numexpr
try:
import numexpr
except:
numexpr = None
__all__ = [
'get_application',
'get_intermediate_classes',
'show_window',
'run_all_scripts',
'enforce_dtype',
'FpsCounter',
'ordict',
]
def hsv_to_rgb(hsv):
"""
convert hsv values in a numpy array to rgb values
both input and output arrays have shape (M,N,3)
"""
h = hsv[:, :, 0]
s = hsv[:, :, 1]
v = hsv[:, :, 2]
r = np.empty_like(h)
g = np.empty_like(h)
b = np.empty_like(h)
i = (h * 6.0).astype(np.int)
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
idx = i % 6 == 0
r[idx] = v[idx]
g[idx] = t[idx]
b[idx] = p[idx]
idx = i == 1<|fim▁hole|>
idx = i == 2
r[idx] = p[idx]
g[idx] = v[idx]
b[idx] = t[idx]
idx = i == 3
r[idx] = p[idx]
g[idx] = q[idx]
b[idx] = v[idx]
idx = i == 4
r[idx] = t[idx]
g[idx] = p[idx]
b[idx] = v[idx]
idx = i == 5
r[idx] = v[idx]
g[idx] = p[idx]
b[idx] = q[idx]
idx = s == 0
r[idx] = v[idx]
g[idx] = v[idx]
b[idx] = v[idx]
rgb = np.empty_like(hsv)
rgb[:, :, 0] = r
rgb[:, :, 1] = g
rgb[:, :, 2] = b
return rgb
def get_intermediate_classes(cls, baseclass):
"""Return all intermediate classes in the OO hierarchy between a base
class and a child class."""
classes = inspect.getmro(cls)
classes = [c for c in classes if issubclass(c, baseclass)]
return classes
def run_all_scripts(dir=".", autodestruct=True, condition=None, ignore=[]):
"""Run all scripts successively."""
if condition is None:
condition = lambda file: file.endswith(".py") and not file.startswith("_")
os.chdir(dir)
files = sorted([file for file in os.listdir(dir) if condition(file)])
for file in files:
if file in ignore:
continue
print "Running %s..." % file
args = ["python", file]
if autodestruct:
args += ["autodestruct"]
subprocess.call(args)
print "Done!"
print
def enforce_dtype(arr, dtype, msg=""):
"""Force the dtype of a Numpy array."""
if isinstance(arr, np.ndarray):
if arr.dtype is not np.dtype(dtype):
log_debug("enforcing dtype for array %s %s" % (str(arr.dtype), msg))
return np.array(arr, dtype)
return arr
def memoize(func):
"""Decorator for memoizing a function."""
cache = {}
@wraps(func)
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
def nid(x):
"""Return the address of an array data, used to check whether two arrays
refer to the same data in memory."""
return x.__array_interface__['data'][0]
class FpsCounter(object):
"""Count FPS."""
# memory for the FPS counter
maxlen = 10
def __init__(self, maxlen=None):
if maxlen is None:
maxlen = self.maxlen
self.times = collections.deque(maxlen=maxlen)
self.fps = 0.
self.delta = 0.
def tick(self):
"""Record the current time stamp.
To be called by paintGL().
"""
self.times.append(timeit.default_timer())
def get_fps(self):
"""Return the current FPS."""
if len(self.times) >= 2:
dif = np.diff(self.times)
fps = 1. / dif.min()
# if the FPS crosses 500, do not update it
if fps <= 500:
self.fps = fps
return self.fps
else:
return 0.<|fim▁end|>
|
r[idx] = q[idx]
g[idx] = v[idx]
b[idx] = p[idx]
|
<|file_name|>SimpleAccess3.py<|end_file_name|><|fim▁begin|>import sdms
server = { 'HOST' : 'localhost',
'PORT' : '2506',
'USER' : 'SYSTEM',
'PASSWORD' : 'VerySecret' }
conn = sdms.SDMSConnectionOpenV2(server, server['USER'], server['PASSWORD'], "Simple Access Example")
try:
if 'ERROR' in conn:
print(str(conn))
exit(1)
except:
pass
stmt = "LIST SESSIONS;"
result = sdms.SDMSCommandWithSoc(conn, stmt)
if 'ERROR' in result:
print(str(result['ERROR']))
else:
for row in result['DATA']['TABLE']:
print("{0:3} {1:8} {2:32} {3:9} {4:15} {5:>15} {6}".format(\
str(row['THIS']), \
str(row['UID']), \
str(row['USER']), \<|fim▁hole|> str(row['TYPE']), \
str(row['START']), \
str(row['IP']), \
str(row['INFORMATION'])))
conn.close()<|fim▁end|>
| |
<|file_name|>object.rs<|end_file_name|><|fim▁begin|>use libc::c_void;
use llvm_sys::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef};
use cbox::CBox;
use std::fmt;
use std::iter::Iterator;
use std::marker::PhantomData;
use std::mem;
use super::buffer::MemoryBuffer;
use super::util;
/// An external object file that has been parsed by LLVM.
pub struct ObjectFile {
obj: LLVMObjectFileRef,
}
native_ref!(ObjectFile, obj: LLVMObjectFileRef);
impl ObjectFile {
/// Parse the object file at the path given, or return an error string if an error occurs.
pub fn read(path: &str) -> Result<ObjectFile, CBox<str>> {
let buf = try!(MemoryBuffer::new_from_file(path));
unsafe {
let ptr = object::LLVMCreateObjectFile(buf.as_ptr());
if ptr.is_null() {
Err(CBox::from("unknown error"))
} else {
Ok(ptr.into())
}
}
}
/// Iterate through the symbols in this object file.
pub fn symbols(&self) -> Symbols {
Symbols {
iter: unsafe { object::LLVMGetSymbols(self.obj) },
marker: PhantomData,
}
}
}
pub struct Symbols<'a> {
iter: LLVMSymbolIteratorRef,
marker: PhantomData<&'a ()>,
}
impl<'a> Iterator for Symbols<'a> {
type Item = Symbol<'a>;
fn next(&mut self) -> Option<Symbol<'a>> {
unsafe {
let name = util::to_str(object::LLVMGetSymbolName(self.iter) as *mut i8);
let size = object::LLVMGetSymbolSize(self.iter) as usize;
let address = object::LLVMGetSymbolAddress(self.iter) as usize;
Some(Symbol {
name: name,
address: mem::transmute(address),
size: size,
})
}
}
}
impl<'a> Drop for Symbols<'a> {
fn drop(&mut self) {
unsafe { object::LLVMDisposeSymbolIterator(self.iter) }
}
}
pub struct Symbol<'a> {
/// The name of this symbol.
pub name: &'a str,
/// The address that this symbol is at.
pub address: *const c_void,<|fim▁hole|> fn clone(&self) -> Symbol<'a> {
*self
}
}
impl<'a> fmt::Debug for Symbol<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{} - {}", self.name, self.size)
}
}
impl<'a> Symbol<'a> {
/// Get the pointer for this symbol.
pub unsafe fn get<T>(self) -> &'a T {
mem::transmute(self.address)
}
}<|fim▁end|>
|
pub size: usize,
}
impl<'a> Copy for Symbol<'a> {}
impl<'a> Clone for Symbol<'a> {
|
<|file_name|>vector.rs<|end_file_name|><|fim▁begin|>use std::ops::Add;
use std::ops::Sub;
use std::ops::Mul;
use std::ops::Div;
use std::cmp::PartialEq;
#[derive(Debug)]
pub struct Vector2 {
pub x:f64
, pub y:f64
}
impl Vector2 {
/* constructors*/
///
/// Returns zero vector
///
pub fn default() -> Vector2 {
Vector2{
x: 0.0,
y: 0.0,
}
}
///
/// Returns vector{x,y}
///
pub fn new(x:f64, y:f64) -> Vector2 {
Vector2{
x: x,
y: y,
}<|fim▁hole|> }
///
/// Returns the squared length of this vector
///
pub fn sqr_magnitude(&self) -> f64 {
(self.x * self.x) + (self.y * self.y)
}
///
/// Returns the length of this vector
///
pub fn magnitude(&self) -> f64 {
self.sqr_magnitude().sqrt()
}
///
/// Returns vector with a magnitude of 1
///
pub fn normalize(&self) -> Vector2 {
let magnitude = self.magnitude();
if magnitude.abs() < EPSILON {
Vector2::default()
}
else {
Vector2{ x: (self.x / self.magnitude())
, y: (self.y / self.magnitude())
}
}
}
}
///
/// Overrides '+' operator
/// Example
/// let a = Vector{1.0 ,0.2}
/// let b = Vector{1.5,-0.5}
/// let c = a + b
/// or
/// let c = b + a
///
impl Add for Vector2{
type Output = Vector2;
fn add(self, rhs: Vector2) -> Self::Output {
Vector2{ x: (self.x + rhs.x), y: (self.y + rhs.y) }
}
}
///
/// Overrides '-' operator
/// subtracts vector
/// if a and b are vector then you
/// can:
/// a - b or b - a
///
impl Sub for Vector2{
type Output = Vector2;
fn sub(self, rhs: Vector2) -> Self::Output {
Vector2{ x: (self.x - rhs.x), y: (self.y - rhs.y) }
}
}
///
/// Overrides '*' operator
/// multiplies vector by value(component-wise)
/// for Vector{x,y} * Scalar = Vector{Scalar * x ,Scalar * y}
///
impl Mul<f64> for Vector2{
type Output = Vector2;
fn mul(self, rhs: f64) -> Self::Output {
Vector2{ x: (self.x * rhs), y: (self.y * rhs) }
}
}
///
/// Overrides '*' operator
/// multiplies vector by value(component-wise)
/// for Scalar * Vector{x,y} = Vector{Scalar * x ,Scalar * y}
///
impl Mul<Vector2> for f64{
type Output = Vector2;
fn mul(self, rhs: Vector2) -> Self::Output {
Vector2{ x: (self * rhs.x), y: (self * rhs.y) }
}
}
///
/// Overrides '/' operator
/// Divide vector by value(component-wise)
/// Vector{x,y} / scalar = Vector{x/scalar, y/scalar}
///
impl Div<f64> for Vector2{
type Output = Vector2;
fn div(self, rhs: f64) -> Self::Output {
Vector2{ x: (self.x / rhs), y: (self.y / rhs) }
}
}
///
/// Overrides '/' operator
/// Divide scalar by vector
/// scalar / Vector{x, y} => Vector{scalar/x, scalar/y}
///
impl Div<Vector2> for f64{
type Output = Vector2;
fn div(self, rhs: Vector2) -> Self::Output {
Vector2{ x: (self / rhs.x), y: (self / rhs.y) }
}
}
///
/// Overrides '==' operator
/// Compare vectors like A == B or B == A
///
impl PartialEq for Vector2{
fn eq(&self, other: &Vector2) -> bool {
(self.x == other.x) && (self.y == other.y)
}
fn ne(&self, other: &Vector2) -> bool {
(self.x != other.x) || (self.y != other.y)
}
}
///
/// Shorthand for writing Vector2{ x: -1.0, y: 0.0 }
///
pub const LEFT: Vector2 = Vector2{ x: -1.0, y: 0.0 };
///
/// Shorthand for writing Vector2{ x: 0.0, y: 1.0 }
///
pub const UP: Vector2 = Vector2{ x: 0.0, y: 1.0 };
///
/// Shorthand for writing Vector2{ x: 1.0, y: 0.0 }
///
pub const RIGHT: Vector2 = Vector2{ x: 1.0, y: 0.0 };
///
/// Shorthand for writing Vector2{ x: 0.0, y: -1.0 }
///
pub const DOWN: Vector2 = Vector2{ x: 0.0, y: -1.0 };
///
/// Shorthand for writing Vector2{ x: 0.0, y: 0.0 }
///
pub const ZERO: Vector2 = Vector2{ x: 0.0, y: 0.0 };
///
/// Shorthand for writing Vector2{ x: 1.0, y: 1.0 }
///
pub const ONE: Vector2 = Vector2{ x: 1.0, y: 1.0 };
///
/// for float comparison
/// `abs(a - b) < eps`
///
const EPSILON:f64 = 1e-10;
///
/// Multiplies two vectors component-wise
///
pub fn scale(a : Vector2, b:Vector2) -> Vector2 {
Vector2{ x: (a.x * b.x), y: (a.y * b.y) }
}
///
/// Returns a vector that is made from the largest components of two vectors
///
pub fn max(lhs:Vector2, rhs:Vector2) -> Vector2 {
Vector2{
x: (if lhs.x > rhs.x {lhs.x} else {rhs.x})
, y: (if lhs.y > rhs.y {lhs.y} else {rhs.y})
}
}
///
/// Returns a vector that is made from the smallest components of two vectors
///
pub fn min(lhs: Vector2, rhs:Vector2) -> Vector2 {
Vector2{
x: (if lhs.x < rhs.x {lhs.x} else {rhs.x})
, y: (if lhs.y < rhs.y {lhs.y} else {rhs.y})
}
}
///
/// Dot Product of two vectors.
///
pub fn dot(lhs:Vector2, rhs:Vector2) -> f64 {
lhs.x * rhs.x + lhs.y * rhs.y
}
///
/// Reflects a vector off the vector defined by a normal.
///
pub fn reflect(vector:Vector2, normal:Vector2) -> Vector2 {
let val = 2.0 * ((vector.x * normal.x) + (vector.y * normal.y));
Vector2{ x: (vector.x - (normal.x * val))
, y: (vector.y - (normal.y * val))
}
}
///
/// Returns the distance between a and b.
///
pub fn distance(a:Vector2, b:Vector2) -> f64 {
let x = a.x - b.x;
let y = a.y - b.y;
(x*x + y*y).sqrt()
}
///
/// Returns the squared distance between a and b.
///
pub fn distance_squared(a:Vector2, b:Vector2) -> f64{
let x = a.x - b.x;
let y = a.y - b.y;
(x*x + y*y)
}
///
/// Return true if vectors A and B are orthogonal.
/// Two vectors `a` and `b` are said to be orthogonal
/// if their direction are right angles; that's,
/// the scalar product `a * b` is 0
///
pub fn are_orthogonal(a:Vector2, b:Vector2) -> bool {
dot(a,b).abs() < EPSILON
}
///
/// Two vectors are said to be parallel if they have
/// the same or opposite direction or if one of
/// them is the zero vector
///
pub fn are_parallel(a:Vector2, b:Vector2) -> bool{
let dot = dot(a.normalize(), b.normalize());
println!("dot is {}", dot);
(dot.abs() - 1.0).abs() < EPSILON || (dot.abs() + 1.0).abs() < EPSILON || dot.abs() < EPSILON
}
///
/// Return true if vectors A and B are codirectional.
///
pub fn are_codirectional(a:Vector2, b:Vector2) -> bool {
(dot(a.normalize(), b.normalize()).abs() - 1.0).abs() < EPSILON
}
///
/// Linearly interpolates between vector `a` and vector `b` by `t`
/// when `t = 1` returns `b`
/// when `t = 0` returns `a`
/// when `t = 0.5` returns midpoint
///
pub fn lerp(a:Vector2, b:Vector2, t:f64) -> Vector2 {
let t_clamped = float_clamp01(t);
Vector2{
x: (a.x + (b.x - a.x) * t_clamped),
y: (a.y + (b.y - a.y) * t_clamped)
}
}
///
/// Linearly interpolates between vector `a` and vector `b` by `t`
///
pub fn lerp_unclamped(a:Vector2, b:Vector2, t:f64) -> Vector2 {
Vector2{
x: (a.x + (b.x - a.x) * t),
y: (a.y + (b.y - a.y) * t)
}
}
///
/// Clamps a value between a minimum float and maximum float value
///
pub fn float_clamp(value:f64, min:f64, max:f64) -> f64{
if value < min
{min}
else if value > max
{max}
else
{value}
}
///
/// Clamps a value between 0 and 1 and returns value
///
pub fn float_clamp01(value:f64) -> f64{
if value < 0.0
{0.0}
else if value > 1.0
{1.0}
else
{value}
}
///
/// testing private functions
///
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn float_clamp_test_it_returns_max() {
let value = 11.0;
let min = 0.0;
let max = 10.0;
let result = float_clamp(value,min,max);
assert_eq!(result, max);
}
#[test]
fn float_clamp_test_it_returns_min() {
let value = -5.0;
let min = 0.0;
let max = 10.0;
let result = float_clamp(value,min,max);
assert_eq!(result, min);
}
#[test]
fn float_clamp_test_it_returns_value() {
let value = 1.0;
let min = 0.0;
let max = 10.0;
let result = float_clamp(value,min,max);
assert_eq!(result, value);
}
#[test]
fn float_clamp01_test_it_returns_max() {
let value = 2.0;
let result = float_clamp01(value);
assert_eq!(result, 1.0);
}
#[test]
fn float_clamp01_test_it_returns_min() {
let value = -5.0;
let result = float_clamp01(value);
assert_eq!(result, 0.0);
}
#[test]
fn float_clamp01_test_it_returns_value() {
let value = 0.10;
let result = float_clamp01(value);
assert_eq!(result, value);
}
}<|fim▁end|>
| |
<|file_name|>crypto.go<|end_file_name|><|fim▁begin|>package pusher<|fim▁hole|> // "crypto/md5"
"crypto/sha256"
"encoding/hex"
"strings"
)
func hmacSignature(toSign, secret string) string {
return hex.EncodeToString(hmacBytes([]byte(toSign), []byte(secret)))
}
func hmacBytes(toSign, secret []byte) []byte {
_authSignature := hmac.New(sha256.New, secret)
_authSignature.Write(toSign)
return _authSignature.Sum(nil)
}
func createAuthString(key, secret, stringToSign string) string {
authSignature := hmacSignature(stringToSign, secret)
return strings.Join([]string{key, authSignature}, ":")
}<|fim▁end|>
|
import (
"crypto/hmac"
|
<|file_name|>issue-14901.rs<|end_file_name|><|fim▁begin|>// check-pass
pub trait Reader {}
enum Wrapper<'a> {
WrapReader(&'a (dyn Reader + 'a))
}
trait Wrap<'a> {<|fim▁hole|>}
impl<'a, R: Reader> Wrap<'a> for &'a mut R {
fn wrap(self) -> Wrapper<'a> {
Wrapper::WrapReader(self as &'a mut dyn Reader)
}
}
pub fn main() {}<|fim▁end|>
|
fn wrap(self) -> Wrapper<'a>;
|
<|file_name|>message.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use crossbeam_channel::{Receiver, Sender};
use euclid::default::{Point2D, Rect};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg::constellation_msg::{BackgroundHangMonitorRegister, BrowsingContextId, PipelineId};
use net_traits::image_cache::ImageCache;
use profile_traits::mem::ReportsChan;
use script_traits::Painter;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg};
use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData};
use servo_arc::Arc as ServoArc;
use servo_atoms::Atom;<|fim▁hole|>use style::context::QuirksMode;
use style::dom::OpaqueNode;
use style::properties::PropertyId;
use style::selector_parser::PseudoElement;
use style::stylesheets::Stylesheet;
/// Asynchronous messages that script can send to layout.
pub enum Msg {
/// Adds the given stylesheet to the document. The second stylesheet is the
/// insertion point (if it exists, the sheet needs to be inserted before
/// it).
AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>),
/// Removes a stylesheet from the document.
RemoveStylesheet(ServoArc<Stylesheet>),
/// Change the quirks mode.
SetQuirksMode(QuirksMode),
/// Requests a reflow.
Reflow(ScriptReflow),
/// Get an RPC interface.
GetRPC(Sender<Box<dyn LayoutRPC + Send>>),
/// Requests that the layout thread render the next frame of all animations.
TickAnimations,
/// Updates layout's timer for animation testing from script.
///
/// The inner field is the number of *milliseconds* to advance, and the bool
/// field is whether animations should be force-ticked.
AdvanceClockMs(i32, bool),
/// Destroys layout data associated with a DOM node.
///
/// TODO(pcwalton): Maybe think about batching to avoid message traffic.
ReapStyleAndLayoutData(OpaqueStyleAndLayoutData),
/// Requests that the layout thread measure its memory usage. The resulting reports are sent back
/// via the supplied channel.
CollectReports(ReportsChan),
/// Requests that the layout thread enter a quiescent state in which no more messages are
/// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
/// this happens.
PrepareToExit(Sender<()>),
/// Requests that the layout thread immediately shut down. There must be no more nodes left after
/// this, or layout will crash.
ExitNow,
/// Get the last epoch counter for this layout thread.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending;
/// false otherwise).
GetWebFontLoadState(IpcSender<bool>),
/// Creates a new layout thread.
///
/// This basically exists to keep the script-layout dependency one-way.
CreateLayoutThread(LayoutThreadInit),
/// Set the final Url.
SetFinalUrl(ServoUrl),
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetScrollStates(Vec<ScrollState>),
/// Tells layout about a single new scrolling offset from the script. The rest will
/// remain untouched and layout won't forward this back to script.
UpdateScrollStateFromScript(ScrollState),
/// Tells layout that script has added some paint worklet modules.
RegisterPaint(Atom, Vec<Atom>, Box<dyn Painter>),
/// Send to layout the precise time when the navigation started.
SetNavigationStart(u64),
/// Request the current number of animations that are running.
GetRunningAnimations(IpcSender<usize>),
}
#[derive(Debug, PartialEq)]
pub enum NodesFromPointQueryType {
All,
Topmost,
}
#[derive(Debug, PartialEq)]
pub enum QueryMsg {
ContentBoxQuery(OpaqueNode),
ContentBoxesQuery(OpaqueNode),
NodeGeometryQuery(OpaqueNode),
NodeScrollGeometryQuery(OpaqueNode),
OffsetParentQuery(OpaqueNode),
TextIndexQuery(OpaqueNode, Point2D<f32>),
NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType),
// FIXME(nox): The following queries use the TrustedNodeAddress to
// access actual DOM nodes, but those values can be constructed from
// garbage values such as `0xdeadbeef as *const _`, this is unsound.
NodeScrollIdQuery(TrustedNodeAddress),
ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId),
StyleQuery(TrustedNodeAddress),
ElementInnerTextQuery(TrustedNodeAddress),
InnerWindowDimensionsQuery(BrowsingContextId),
}
/// Any query to perform with this reflow.
#[derive(Debug, PartialEq)]
pub enum ReflowGoal {
Full,
TickAnimations,
LayoutQuery(QueryMsg, u64),
}
impl ReflowGoal {
/// Returns true if the given ReflowQuery needs a full, up-to-date display list to
/// be present or false if it only needs stacking-relative positions.
pub fn needs_display_list(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match *querymsg {
QueryMsg::NodesFromPointQuery(..) |
QueryMsg::TextIndexQuery(..) |
QueryMsg::InnerWindowDimensionsQuery(_) |
QueryMsg::ElementInnerTextQuery(_) => true,
QueryMsg::ContentBoxQuery(_) |
QueryMsg::ContentBoxesQuery(_) |
QueryMsg::NodeGeometryQuery(_) |
QueryMsg::NodeScrollGeometryQuery(_) |
QueryMsg::NodeScrollIdQuery(_) |
QueryMsg::ResolvedStyleQuery(..) |
QueryMsg::OffsetParentQuery(_) |
QueryMsg::StyleQuery(_) => false,
},
}
}
/// Returns true if the given ReflowQuery needs its display list send to WebRender or
/// false if a layout_thread display list is sufficient.
pub fn needs_display(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match *querymsg {
QueryMsg::NodesFromPointQuery(..) |
QueryMsg::TextIndexQuery(..) |
QueryMsg::ElementInnerTextQuery(_) => true,
QueryMsg::ContentBoxQuery(_) |
QueryMsg::ContentBoxesQuery(_) |
QueryMsg::NodeGeometryQuery(_) |
QueryMsg::NodeScrollGeometryQuery(_) |
QueryMsg::NodeScrollIdQuery(_) |
QueryMsg::ResolvedStyleQuery(..) |
QueryMsg::OffsetParentQuery(_) |
QueryMsg::InnerWindowDimensionsQuery(_) |
QueryMsg::StyleQuery(_) => false,
},
}
}
}
/// Information needed for a reflow.
pub struct Reflow {
/// A clipping rectangle for the page, an enlarged rectangle containing the viewport.
pub page_clip_rect: Rect<Au>,
}
/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Default)]
pub struct ReflowComplete {
/// The list of images that were encountered that are in progress.
pub pending_images: Vec<PendingImage>,
/// The list of nodes that initiated a CSS transition.
pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>,
}
/// Information needed for a script-initiated reflow.
pub struct ScriptReflow {
/// General reflow data.
pub reflow_info: Reflow,
/// The document node.
pub document: TrustedNodeAddress,
/// Whether the document's stylesheets have changed since the last script reflow.
pub stylesheets_changed: bool,
/// The current window size.
pub window_size: WindowSizeData,
/// The channel that we send a notification to.
pub script_join_chan: Sender<ReflowComplete>,
/// The goal of this reflow.
pub reflow_goal: ReflowGoal,
/// The number of objects in the dom #10110
pub dom_count: u32,
}
pub struct LayoutThreadInit {
pub id: PipelineId,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
pub constellation_chan: IpcSender<ConstellationMsg>,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub image_cache: Arc<dyn ImageCache>,
pub paint_time_metrics: PaintTimeMetrics,
pub layout_is_busy: Arc<AtomicBool>,
pub window_size: WindowSizeData,
}<|fim▁end|>
|
use servo_url::ServoUrl;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
|
<|file_name|>Wire.cpp<|end_file_name|><|fim▁begin|>/*
TwoWire.cpp - TWI/I2C library for Wiring & Arduino
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 2012 by Todd Krein ([email protected]) to implement repeated starts
*/
extern "C" {
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "twi.h"
}
#include "Wire.h"
// Initialize Class Variables //////////////////////////////////////////////////
uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;
uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;
uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);
// Constructors ////////////////////////////////////////////////////////////////
TwoWire::TwoWire()
{
}
// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(void)
{
rxBufferIndex = 0;
rxBufferLength = 0;
txBufferIndex = 0;
txBufferLength = 0;
twi_init();
}
void TwoWire::begin(uint8_t address)
{
twi_setAddress(address);
twi_attachSlaveTxEvent(onRequestService);
twi_attachSlaveRxEvent(onReceiveService);
begin();
}
void TwoWire::begin(int address)
{
begin((uint8_t)address);
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
{
// clamp to buffer length
if(quantity > BUFFER_LENGTH){
quantity = BUFFER_LENGTH;
}
// perform blocking read into buffer
uint8_t read = twi_readFrom(address, rxBuffer, quantity, sendStop);
// set rx buffer iterator vars
rxBufferIndex = 0;
rxBufferLength = read;
return read;
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true);
}
uint8_t TwoWire::requestFrom(int address, int quantity)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true);
}
uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)sendStop);
}
void TwoWire::beginTransmission(uint8_t address)
{
// indicate that we are transmitting
transmitting = 1;
// set address of targeted slave
txAddress = address;
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
}
void TwoWire::beginTransmission(int address)
{
beginTransmission((uint8_t)address);
}
//
// Originally, 'endTransmission' was an f(void) function.
// It has been modified to take one parameter indicating
// whether or not a STOP should be performed on the bus.
// Calling endTransmission(false) allows a sketch to
// perform a repeated start.
//
// WARNING: Nothing in the library keeps track of whether
// the bus tenure has been properly ended with a STOP. It
// is very possible to leave the bus in a hung state if
// no call to endTransmission(true) is made. Some I2C
// devices will behave oddly if they do not see a STOP.
//
uint8_t TwoWire::endTransmission(uint8_t sendStop)
{
// transmit buffer (blocking)
int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1, sendStop);
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
// indicate that we are done transmitting
transmitting = 0;
return ret;
}
// This provides backwards compatibility with the original
// definition, and expected behaviour, of endTransmission
//
uint8_t TwoWire::endTransmission(void)
{
return endTransmission(true);
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
size_t TwoWire::write(uint8_t data)
{
if(transmitting){
// in master transmitter mode
// don't bother if buffer is full
if(txBufferLength >= BUFFER_LENGTH){
setWriteError();
return 0;
}
// put byte in tx buffer
txBuffer[txBufferIndex] = data;
++txBufferIndex;
// update amount in buffer
txBufferLength = txBufferIndex;
}else{
// in slave send mode
// reply to master
twi_transmit(&data, 1);
}
return 1;
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
size_t TwoWire::write(const uint8_t *data, size_t quantity)
{
if(transmitting){
// in master transmitter mode
for(size_t i = 0; i < quantity; ++i){
write(data[i]);
}
}else{
// in slave send mode
// reply to master
twi_transmit(data, quantity);
}
return quantity;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::available(void)
{
return rxBufferLength - rxBufferIndex;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::read(void)
{
int value = -1;
// get each successive byte on each call
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
++rxBufferIndex;
}
return value;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::peek(void)
{
int value = -1;
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
}
return value;
}
void TwoWire::flush(void)
{
// XXX: to be implemented.
}
// behind the scenes function that is called when data is received
void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
{
// don't bother if user hasn't registered a callback
if(!user_onReceive){
return;
}
// don't bother if rx buffer is in use by a master requestFrom() op
// i know this drops data, but it allows for slight stupidity
// meaning, they may not have read all the master requestFrom() data yet
if(rxBufferIndex < rxBufferLength){
return;
}
// copy twi rx buffer into local read buffer
// this enables new reads to happen in parallel
for(uint8_t i = 0; i < numBytes; ++i){
rxBuffer[i] = inBytes[i];
}
// set rx iterator vars
rxBufferIndex = 0;
rxBufferLength = numBytes;<|fim▁hole|> user_onReceive(numBytes);
}
// behind the scenes function that is called when data is requested
void TwoWire::onRequestService(void)
{
// don't bother if user hasn't registered a callback
if(!user_onRequest){
return;
}
// reset tx buffer iterator vars
// !!! this will kill any pending pre-master sendTo() activity
txBufferIndex = 0;
txBufferLength = 0;
// alert user program
user_onRequest();
}
// sets function called on slave write
void TwoWire::onReceive( void (*function)(int) )
{
user_onReceive = function;
}
// sets function called on slave read
void TwoWire::onRequest( void (*function)(void) )
{
user_onRequest = function;
}
// Preinstantiate Objects //////////////////////////////////////////////////////
TwoWire Wire = TwoWire();<|fim▁end|>
|
// alert user program
|
<|file_name|>qgssourcefieldsproperties.cpp<|end_file_name|><|fim▁begin|>/***************************************************************************
qgssourcefieldsproperties.cpp
---------------------
begin : July 2017
copyright : (C) 2017 by David Signer
email : david at opengis dot ch
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "qgssourcefieldsproperties.h"
#include "qgsvectorlayer.h"
#include "qgsproject.h"
QgsSourceFieldsProperties::QgsSourceFieldsProperties( QgsVectorLayer *layer, QWidget *parent )
: QWidget( parent )
, mLayer( layer )
{
if ( !layer )
return;
setupUi( this );
layout()->setContentsMargins( 0, 0, 0, 0 );
layout()->setMargin( 0 );
//button appearance
mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) );
mDeleteAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) );
mToggleEditingButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionToggleEditing.svg" ) ) );
mCalculateFieldButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCalculateField.svg" ) ) );
//button signals
connect( mToggleEditingButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::toggleEditing );
connect( mAddAttributeButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::addAttributeClicked );
connect( mDeleteAttributeButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::deleteAttributeClicked );
connect( mCalculateFieldButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::calculateFieldClicked );
//slots
connect( mLayer, &QgsVectorLayer::editingStarted, this, &QgsSourceFieldsProperties::editingToggled );
connect( mLayer, &QgsVectorLayer::editingStopped, this, &QgsSourceFieldsProperties::editingToggled );
connect( mLayer, &QgsVectorLayer::attributeAdded, this, &QgsSourceFieldsProperties::attributeAdded );
connect( mLayer, &QgsVectorLayer::attributeDeleted, this, &QgsSourceFieldsProperties::attributeDeleted );
//field list appearance
mFieldsList->setColumnCount( AttrColCount );
mFieldsList->setSelectionBehavior( QAbstractItemView::SelectRows );
mFieldsList->setDragDropMode( QAbstractItemView::DragOnly );
mFieldsList->setHorizontalHeaderItem( AttrIdCol, new QTableWidgetItem( tr( "Id" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrNameCol, new QTableWidgetItem( tr( "Name" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrTypeCol, new QTableWidgetItem( tr( "Type" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrTypeNameCol, new QTableWidgetItem( tr( "Type name" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrLengthCol, new QTableWidgetItem( tr( "Length" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrPrecCol, new QTableWidgetItem( tr( "Precision" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrCommentCol, new QTableWidgetItem( tr( "Comment" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrWMSCol, new QTableWidgetItem( QStringLiteral( "WMS" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrWFSCol, new QTableWidgetItem( QStringLiteral( "WFS" ) ) );
mFieldsList->setHorizontalHeaderItem( AttrAliasCol, new QTableWidgetItem( tr( "Alias" ) ) );
mFieldsList->setSortingEnabled( true );
mFieldsList->sortByColumn( 0, Qt::AscendingOrder );
mFieldsList->setSelectionBehavior( QAbstractItemView::SelectRows );
mFieldsList->setSelectionMode( QAbstractItemView::ExtendedSelection );
mFieldsList->verticalHeader()->hide();
//load buttons and field list
updateButtons();
}
void QgsSourceFieldsProperties::init()
{
loadRows();
}
void QgsSourceFieldsProperties::loadRows()
{
disconnect( mFieldsList, &QTableWidget::cellChanged, this, &QgsSourceFieldsProperties::attributesListCellChanged );
const QgsFields &fields = mLayer->fields();
mIndexedWidgets.clear();
mFieldsList->setRowCount( 0 );
for ( int i = 0; i < fields.count(); ++i )
attributeAdded( i );
mFieldsList->resizeColumnsToContents();
connect( mFieldsList, &QTableWidget::cellChanged, this, &QgsSourceFieldsProperties::attributesListCellChanged );
connect( mFieldsList, &QTableWidget::cellPressed, this, &QgsSourceFieldsProperties::attributesListCellPressed );
<|fim▁hole|>}
void QgsSourceFieldsProperties::updateFieldRenamingStatus()
{
bool canRenameFields = mLayer->isEditable() && ( mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::RenameAttributes ) && !mLayer->readOnly();
for ( int row = 0; row < mFieldsList->rowCount(); ++row )
{
if ( canRenameFields )
mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() | Qt::ItemIsEditable );
else
mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() & ~Qt::ItemIsEditable );
}
}
void QgsSourceFieldsProperties::updateExpression()
{
QToolButton *btn = qobject_cast<QToolButton *>( sender() );
Q_ASSERT( btn );
int index = btn->property( "Index" ).toInt();
const QString exp = mLayer->expressionField( index );
QgsExpressionContext context;
context << QgsExpressionContextUtils::globalScope()
<< QgsExpressionContextUtils::projectScope( QgsProject::instance() );
QgsExpressionBuilderDialog dlg( mLayer, exp, nullptr, QStringLiteral( "generic" ), context );
if ( dlg.exec() )
{
mLayer->updateExpressionField( index, dlg.expressionText() );
loadRows();
}
}
void QgsSourceFieldsProperties::attributeAdded( int idx )
{
bool sorted = mFieldsList->isSortingEnabled();
if ( sorted )
mFieldsList->setSortingEnabled( false );
const QgsFields &fields = mLayer->fields();
int row = mFieldsList->rowCount();
mFieldsList->insertRow( row );
setRow( row, idx, fields.at( idx ) );
mFieldsList->setCurrentCell( row, idx );
//in case there are rows following, there is increased the id to the correct ones
for ( int i = idx + 1; i < mIndexedWidgets.count(); i++ )
mIndexedWidgets.at( i )->setData( Qt::DisplayRole, i );
if ( sorted )
mFieldsList->setSortingEnabled( true );
for ( int i = 0; i < mFieldsList->columnCount(); i++ )
{
switch ( mLayer->fields().fieldOrigin( idx ) )
{
case QgsFields::OriginExpression:
if ( i == 7 ) continue;
mFieldsList->item( row, i )->setBackgroundColor( QColor( 200, 200, 255 ) );
break;
case QgsFields::OriginJoin:
mFieldsList->item( row, i )->setBackgroundColor( QColor( 200, 255, 200 ) );
break;
default:
mFieldsList->item( row, i )->setBackgroundColor( QColor( 255, 255, 200 ) );
break;
}
}
}
void QgsSourceFieldsProperties::attributeDeleted( int idx )
{
mFieldsList->removeRow( mIndexedWidgets.at( idx )->row() );
mIndexedWidgets.removeAt( idx );
for ( int i = idx; i < mIndexedWidgets.count(); i++ )
{
mIndexedWidgets.at( i )->setData( Qt::DisplayRole, i );
}
}
void QgsSourceFieldsProperties::setRow( int row, int idx, const QgsField &field )
{
QTableWidgetItem *dataItem = new QTableWidgetItem();
dataItem->setData( Qt::DisplayRole, idx );
switch ( mLayer->fields().fieldOrigin( idx ) )
{
case QgsFields::OriginExpression:
dataItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) );
break;
case QgsFields::OriginJoin:
dataItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/join.svg" ) ) );
break;
default:
dataItem->setIcon( mLayer->fields().iconForField( idx ) );
break;
}
mFieldsList->setItem( row, AttrIdCol, dataItem );
mIndexedWidgets.insert( idx, mFieldsList->item( row, 0 ) );
mFieldsList->setItem( row, AttrNameCol, new QTableWidgetItem( field.name() ) );
mFieldsList->setItem( row, AttrAliasCol, new QTableWidgetItem( field.alias() ) );
mFieldsList->setItem( row, AttrTypeCol, new QTableWidgetItem( QVariant::typeToName( field.type() ) ) );
mFieldsList->setItem( row, AttrTypeNameCol, new QTableWidgetItem( field.typeName() ) );
mFieldsList->setItem( row, AttrLengthCol, new QTableWidgetItem( QString::number( field.length() ) ) );
mFieldsList->setItem( row, AttrPrecCol, new QTableWidgetItem( QString::number( field.precision() ) ) );
if ( mLayer->fields().fieldOrigin( idx ) == QgsFields::OriginExpression )
{
QWidget *expressionWidget = new QWidget;
expressionWidget->setLayout( new QHBoxLayout );
QToolButton *editExpressionButton = new QToolButton;
editExpressionButton->setProperty( "Index", idx );
editExpressionButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) );
connect( editExpressionButton, &QAbstractButton::clicked, this, &QgsSourceFieldsProperties::updateExpression );
expressionWidget->layout()->setContentsMargins( 0, 0, 0, 0 );
expressionWidget->layout()->addWidget( editExpressionButton );
expressionWidget->layout()->addWidget( new QLabel( mLayer->expressionField( idx ) ) );
expressionWidget->setStyleSheet( "background-color: rgb( 200, 200, 255 )" );
mFieldsList->setCellWidget( row, AttrCommentCol, expressionWidget );
}
else
{
mFieldsList->setItem( row, AttrCommentCol, new QTableWidgetItem( field.comment() ) );
}
QList<int> notEditableCols = QList<int>()
<< AttrIdCol
<< AttrNameCol
<< AttrAliasCol
<< AttrTypeCol
<< AttrTypeNameCol
<< AttrLengthCol
<< AttrPrecCol
<< AttrCommentCol;
Q_FOREACH ( int i, notEditableCols )
{
if ( notEditableCols[i] != AttrCommentCol || mLayer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression )
mFieldsList->item( row, i )->setFlags( mFieldsList->item( row, i )->flags() & ~Qt::ItemIsEditable );
if ( notEditableCols[i] == AttrAliasCol )
mFieldsList->item( row, i )->setToolTip( tr( "Edit alias in the Form config tab" ) );
}
bool canRenameFields = mLayer->isEditable() && ( mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::RenameAttributes ) && !mLayer->readOnly();
if ( canRenameFields )
mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() | Qt::ItemIsEditable );
else
mFieldsList->item( row, AttrNameCol )->setFlags( mFieldsList->item( row, AttrNameCol )->flags() & ~Qt::ItemIsEditable );
//published WMS/WFS attributes
QTableWidgetItem *wmsAttrItem = new QTableWidgetItem();
wmsAttrItem->setCheckState( mLayer->excludeAttributesWms().contains( field.name() ) ? Qt::Unchecked : Qt::Checked );
wmsAttrItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable );
mFieldsList->setItem( row, AttrWMSCol, wmsAttrItem );
QTableWidgetItem *wfsAttrItem = new QTableWidgetItem();
wfsAttrItem->setCheckState( mLayer->excludeAttributesWfs().contains( field.name() ) ? Qt::Unchecked : Qt::Checked );
wfsAttrItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable );
mFieldsList->setItem( row, AttrWFSCol, wfsAttrItem );
}
bool QgsSourceFieldsProperties::addAttribute( const QgsField &field )
{
QgsDebugMsg( "inserting attribute " + field.name() + " of type " + field.typeName() );
mLayer->beginEditCommand( tr( "Added attribute" ) );
if ( mLayer->addAttribute( field ) )
{
mLayer->endEditCommand();
return true;
}
else
{
mLayer->destroyEditCommand();
QMessageBox::critical( this, tr( "Add Field" ), tr( "Failed to add field '%1' of type '%2'. Is the field name unique?" ).arg( field.name(), field.typeName() ) );
return false;
}
}
void QgsSourceFieldsProperties::apply()
{
QSet<QString> excludeAttributesWMS, excludeAttributesWFS;
for ( int i = 0; i < mFieldsList->rowCount(); i++ )
{
if ( mFieldsList->item( i, AttrWMSCol )->checkState() == Qt::Unchecked )
{
excludeAttributesWMS.insert( mFieldsList->item( i, AttrNameCol )->text() );
}
if ( mFieldsList->item( i, AttrWFSCol )->checkState() == Qt::Unchecked )
{
excludeAttributesWFS.insert( mFieldsList->item( i, AttrNameCol )->text() );
}
}
mLayer->setExcludeAttributesWms( excludeAttributesWMS );
mLayer->setExcludeAttributesWfs( excludeAttributesWFS );
}
//SLOTS
void QgsSourceFieldsProperties::editingToggled()
{
updateButtons();
updateFieldRenamingStatus();
}
void QgsSourceFieldsProperties::addAttributeClicked()
{
QgsAddAttrDialog dialog( mLayer, this );
if ( dialog.exec() == QDialog::Accepted )
{
addAttribute( dialog.field() );
loadRows();
}
}
void QgsSourceFieldsProperties::deleteAttributeClicked()
{
QSet<int> providerFields;
QSet<int> expressionFields;
Q_FOREACH ( QTableWidgetItem *item, mFieldsList->selectedItems() )
{
if ( item->column() == 0 )
{
int idx = mIndexedWidgets.indexOf( item );
if ( idx < 0 )
continue;
if ( mLayer->fields().fieldOrigin( idx ) == QgsFields::OriginExpression )
expressionFields << idx;
else
providerFields << idx;
}
}
if ( !expressionFields.isEmpty() )
mLayer->deleteAttributes( expressionFields.toList() );
if ( !providerFields.isEmpty() )
{
mLayer->beginEditCommand( tr( "Deleted attributes" ) );
if ( mLayer->deleteAttributes( providerFields.toList() ) )
mLayer->endEditCommand();
else
mLayer->destroyEditCommand();
}
}
void QgsSourceFieldsProperties::calculateFieldClicked()
{
if ( !mLayer )
{
return;
}
QgsFieldCalculator calc( mLayer, this );
if ( calc.exec() == QDialog::Accepted )
{
loadRows();
}
}
void QgsSourceFieldsProperties::attributesListCellChanged( int row, int column )
{
if ( column == AttrNameCol && mLayer && mLayer->isEditable() )
{
int idx = mIndexedWidgets.indexOf( mFieldsList->item( row, AttrIdCol ) );
QTableWidgetItem *nameItem = mFieldsList->item( row, column );
//avoiding that something will be changed, just because this is triggered by simple re-sorting
if ( !nameItem ||
nameItem->text().isEmpty() ||
!mLayer->fields().exists( idx ) ||
mLayer->fields().at( idx ).name() == nameItem->text()
)
return;
mLayer->beginEditCommand( tr( "Rename attribute" ) );
if ( mLayer->renameAttribute( idx, nameItem->text() ) )
{
mLayer->endEditCommand();
}
else
{
mLayer->destroyEditCommand();
QMessageBox::critical( this, tr( "Rename Field" ), tr( "Failed to rename field to '%1'. Is the field name unique?" ).arg( nameItem->text() ) );
}
}
}
void QgsSourceFieldsProperties::attributesListCellPressed( int /*row*/, int /*column*/ )
{
updateButtons();
}
//NICE FUNCTIONS
void QgsSourceFieldsProperties::updateButtons()
{
int cap = mLayer->dataProvider()->capabilities();
mToggleEditingButton->setEnabled( ( cap & QgsVectorDataProvider::ChangeAttributeValues ) && !mLayer->readOnly() );
if ( mLayer->isEditable() )
{
mDeleteAttributeButton->setEnabled( cap & QgsVectorDataProvider::DeleteAttributes );
mAddAttributeButton->setEnabled( cap & QgsVectorDataProvider::AddAttributes );
mToggleEditingButton->setChecked( true );
}
else
{
mToggleEditingButton->setChecked( false );
mAddAttributeButton->setEnabled( false );
// Enable delete button if items are selected
mDeleteAttributeButton->setEnabled( !mFieldsList->selectedItems().isEmpty() );
// and only if all selected items have their origin in an expression
Q_FOREACH ( QTableWidgetItem *item, mFieldsList->selectedItems() )
{
if ( item->column() == 0 )
{
int idx = mIndexedWidgets.indexOf( item );
if ( mLayer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression )
{
mDeleteAttributeButton->setEnabled( false );
break;
}
}
}
}
}<|fim▁end|>
|
updateButtons();
updateFieldRenamingStatus();
|
<|file_name|>archive.rs<|end_file_name|><|fim▁begin|>use rustc_data_structures::temp_dir::MaybeTempDir;<|fim▁hole|>use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname != unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test;
}
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool + 'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
}<|fim▁end|>
|
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
|
<|file_name|>custom_workflow.py<|end_file_name|><|fim▁begin|>from cloudify.workflows import ctx, parameters
ctx.logger.info(parameters.node_id)<|fim▁hole|>
for relationship in instance.relationships:
relationship.execute_source_operation('custom_lifecycle.custom_operation')<|fim▁end|>
|
instance = [n for n in ctx.node_instances
if n.node_id == parameters.node_id][0]
|
<|file_name|>List.spec.js<|end_file_name|><|fim▁begin|>const test = require('tape')
const sinon = require('sinon')
const helpers = require('../test/helpers')
const MockCrock = require('../test/MockCrock')
const bindFunc = helpers.bindFunc
const curry = require('./curry')
const _compose = curry(require('./compose'))
const isFunction = require('./isFunction')
const isObject = require('./isObject')
const isSameType = require('./isSameType')
const isString = require('./isString')
const unit = require('./_unit')
const fl = require('./flNames')
const Maybe = require('./Maybe')
const Pred = require('./Pred')
const constant = x => () => x
const identity = x => x
const applyTo =
x => fn => fn(x)
const List = require('./List')
test('List', t => {
const f = x => List(x).toArray()
t.ok(isFunction(List), 'is a function')
t.ok(isObject(List([])), 'returns an object')
t.equals(List([]).constructor, List, 'provides TypeRep on constructor')
t.ok(isFunction(List.of), 'provides an of function')
t.ok(isFunction(List.fromArray), 'provides a fromArray function')
t.ok(isFunction(List.type), 'provides a type function')
t.ok(isString(List['@@type']), 'provides a @@type string')
const err = /List: List must wrap something/
t.throws(List, err, 'throws with no parameters')
t.same(f(undefined), [ undefined ], 'wraps value in array when called with undefined')
t.same(f(null), [ null ], 'wraps value in array when called with null')
t.same(f(0), [ 0 ], 'wraps value in array when called with falsey number')
t.same(f(1), [ 1 ], 'wraps value in array when called with truthy number')
t.same(f(''), [ '' ], 'wraps value in array when called with falsey string')
t.same(f('string'), [ 'string' ], 'wraps value in array when called with truthy string')
t.same(f(false), [ false ], 'wraps value in array when called with false')
t.same(f(true), [ true ], 'wraps value in array when called with true')
t.same(f({}), [ {} ], 'wraps value in array when called with an Object')
t.same(f([ 1, 2, 3 ]), [ 1, 2, 3 ], 'Does not wrap an array, just uses it as the list')
t.end()
})
test('List fantasy-land api', t => {
const m = List('value')
t.ok(isFunction(List[fl.empty]), 'provides empty function on constructor')
t.ok(isFunction(List[fl.of]), 'provides of function on constructor')
t.ok(isFunction(m[fl.of]), 'provides of method on instance')
t.ok(isFunction(m[fl.empty]), 'provides empty method on instance')
t.ok(isFunction(m[fl.equals]), 'provides equals method on instance')
t.ok(isFunction(m[fl.concat]), 'provides concat method on instance')
t.ok(isFunction(m[fl.map]), 'provides map method on instance')
t.ok(isFunction(m[fl.chain]), 'provides chain method on instance')
t.ok(isFunction(m[fl.reduce]), 'provides reduce method on instance')
t.ok(isFunction(m[fl.filter]), 'provides filter method on instance')
t.end()
})
test('List @@implements', t => {
const f = List['@@implements']
t.equal(f('ap'), true, 'implements ap func')
t.equal(f('chain'), true, 'implements chain func')
t.equal(f('concat'), true, 'implements concat func')
t.equal(f('empty'), true, 'implements empty func')
t.equal(f('equals'), true, 'implements equals func')
t.equal(f('map'), true, 'implements map func')
t.equal(f('of'), true, 'implements of func')
t.equal(f('reduce'), true, 'implements reduce func')
t.equal(f('traverse'), true, 'implements traverse func')
t.end()
})
test('List fromArray', t => {
const fromArray = bindFunc(List.fromArray)
const err = /List.fromArray: Array required/
t.throws(fromArray(undefined), err, 'throws with undefined')
t.throws(fromArray(null), err, 'throws with null')
t.throws(fromArray(0), err, 'throws with falsey number')
t.throws(fromArray(1), err, 'throws with truthy number')
t.throws(fromArray(''), err, 'throws with falsey string')
t.throws(fromArray('string'), err, 'throws with truthy string')
t.throws(fromArray(false), err, 'throws with false')
t.throws(fromArray(true), err, 'throws with true')
t.throws(fromArray({}), err, 'throws with an object')
const data = [ [ 2, 1 ], 'a' ]
t.ok(isSameType(List, List.fromArray([ 0 ])), 'returns a List')
t.same(List.fromArray(data).valueOf(), data, 'wraps the value passed into List in an array')
t.end()
})
test('List inspect', t => {
const m = List([ 1, true, 'string' ])
t.ok(isFunction(m.inspect), 'provides an inpsect function')
t.equal(m.inspect, m.toString, 'toString is the same function as inspect')
t.equal(m.inspect(), 'List [ 1, true, "string" ]', 'returns inspect string')
t.end()
})
test('List type', t => {
const m = List([])
t.ok(isFunction(m.type), 'is a function')
t.equal(m.type, List.type, 'static and instance versions are the same')
t.equal(m.type(), 'List', 'returns List')
t.end()
})
test('List @@type', t => {
const m = List([])
t.equal(m['@@type'], List['@@type'], 'static and instance versions are the same')
t.equal(m['@@type'], 'crocks/List@4', 'returns crocks/List@4')
t.end()
})
test('List head', t => {
const empty = List.empty()
const one = List.of(1)
const two = List([ 2, 3 ])
t.ok(isFunction(two.head), 'Provides a head Function')
t.ok(isSameType(Maybe, empty.head()), 'empty List returns a Maybe')
t.ok(isSameType(Maybe, one.head()), 'one element List returns a Maybe')
t.ok(isSameType(Maybe, two.head()), 'two element List returns a Maybe')
t.equal(empty.head().option('Nothing'), 'Nothing', 'empty List returns a Nothing')
t.equal(one.head().option('Nothing'), 1, 'one element List returns a `Just 1`')
t.equal(two.head().option('Nothing'), 2, 'two element List returns a `Just 2`')
t.end()
})
test('List tail', t => {
const empty = List.empty()
const one = List.of(1)
const two = List([ 2, 3 ])
const three = List([ 4, 5, 6 ])
t.ok(isFunction(two.tail), 'Provides a tail Function')
t.equal(empty.tail().type(), Maybe.type(), 'empty List returns a Maybe')
t.equal(one.tail().type(), Maybe.type(), 'one element List returns a Maybe')
t.equal(two.tail().type(), Maybe.type(), 'two element List returns a Maybe')
t.equal(three.tail().type(), Maybe.type(), 'three element List returns a Maybe')
t.equal(empty.tail().option('Nothing'), 'Nothing', 'empty List returns a Nothing')
t.equal(one.tail().option('Nothing'), 'Nothing', 'one element List returns a `Just 1`')
t.equal(two.tail().option('Nothing').type(), 'List', 'two element List returns a `Just List`')
t.same(two.tail().option('Nothing').valueOf(), [ 3 ], 'two element Maybe List contains `[ 3 ]`')
t.equal(three.tail().option('Nothing').type(), 'List', 'three element List returns a `Just List`')
t.same(three.tail().option('Nothing').valueOf(), [ 5, 6 ], 'three element Maybe List contains `[ 5, 6 ]`')
t.end()
})
test('List cons', t => {
const list = List.of('guy')
const consed = list.cons('hello')
t.ok(isFunction(list.cons), 'provides a cons function')
t.notSame(list.valueOf(), consed.valueOf(), 'keeps old list intact')
t.same(consed.valueOf(), [ 'hello', 'guy' ], 'returns a list with the element pushed to front')
t.end()
})
test('List valueOf', t => {
const x = List([ 'some-thing', 34 ]).valueOf()
t.same(x, [ 'some-thing', 34 ], 'provides the wrapped array')
t.end()
})
test('List toArray', t => {
const data = [ 'some-thing', [ 'else', 43 ], 34 ]
const a = List(data).toArray()
t.same(a, data, 'provides the wrapped array')
t.end()
})
test('List equals functionality', t => {
const a = List([ 'a', 'b' ])
const b = List([ 'a', 'b' ])
const c = List([ '1', 'b' ])
const value = 'yep'
const nonList = { type: 'List...Not' }
t.equal(a.equals(c), false, 'returns false when 2 Lists are not equal')
t.equal(a.equals(b), true, 'returns true when 2 Lists are equal')
t.equal(a.equals(value), false, 'returns false when passed a simple value')
t.equal(a.equals(nonList), false, 'returns false when passed a non-List')
t.end()
})
test('List equals properties (Setoid)', t => {
const a = List([ 0, 'like' ])
const b = List([ 0, 'like' ])
const c = List([ 1, 'rainbow' ])
const d = List([ 'like', 0 ])
t.ok(isFunction(List([]).equals), 'provides an equals function')
t.equal(a.equals(a), true, 'reflexivity')
t.equal(a.equals(b), b.equals(a), 'symmetry (equal)')
t.equal(a.equals(c), c.equals(a), 'symmetry (!equal)')
t.equal(a.equals(b) && b.equals(d), a.equals(d), 'transitivity')
t.end()
})
test('List concat properties (Semigroup)', t => {
const a = List([ 1, '' ])
const b = List([ 0, null ])
const c = List([ true, 'string' ])
const left = a.concat(b).concat(c)
const right = a.concat(b.concat(c))
t.ok(isFunction(a.concat), 'provides a concat function')
t.same(left.valueOf(), right.valueOf(), 'associativity')
t.equal(a.concat(b).type(), a.type(), 'returns a List')
t.end()
})
test('List concat errors', t => {
const a = List([ 1, 2 ])
const notList = { type: constant('List...Not') }
const cat = bindFunc(a.concat)
const err = /List.concat: List required/
t.throws(cat(undefined), err, 'throws with undefined')
t.throws(cat(null), err, 'throws with null')
t.throws(cat(0), err, 'throws with falsey number')
t.throws(cat(1), err, 'throws with truthy number')
t.throws(cat(''), err, 'throws with falsey string')
t.throws(cat('string'), err, 'throws with truthy string')
t.throws(cat(false), err, 'throws with false')
t.throws(cat(true), err, 'throws with true')
t.throws(cat([]), err, 'throws with an array')
t.throws(cat({}), err, 'throws with an object')
t.throws(cat(notList), err, 'throws when passed non-List')
t.end()
})
test('List concat fantasy-land errors', t => {
const a = List([ 1, 2 ])
const notList = { type: constant('List...Not') }
const cat = bindFunc(a[fl.concat])
const err = /List.fantasy-land\/concat: List required/
t.throws(cat(undefined), err, 'throws with undefined')
t.throws(cat(null), err, 'throws with null')
t.throws(cat(0), err, 'throws with falsey number')
t.throws(cat(1), err, 'throws with truthy number')
t.throws(cat(''), err, 'throws with falsey string')
t.throws(cat('string'), err, 'throws with truthy string')
t.throws(cat(false), err, 'throws with false')
t.throws(cat(true), err, 'throws with true')
t.throws(cat([]), err, 'throws with an array')
t.throws(cat({}), err, 'throws with an object')
t.throws(cat(notList), err, 'throws when passed non-List')
t.end()
})
test('List concat functionality', t => {
const a = List([ 1, 2 ])
const b = List([ 3, 4 ])
t.same(a.concat(b).valueOf(), [ 1, 2, 3, 4 ], 'concats second to first')
t.same(b.concat(a).valueOf(), [ 3, 4, 1, 2 ], 'concats first to second')
t.end()
})
test('List empty properties (Monoid)', t => {
const m = List([ 1, 2 ])
t.ok(isFunction(m.concat), 'provides a concat function')
t.ok(isFunction(m.empty), 'provides an empty function')
const right = m.concat(m.empty())
const left = m.empty().concat(m)
t.same(right.valueOf(), m.valueOf(), 'right identity')
t.same(left.valueOf(), m.valueOf(), 'left identity')
t.end()
})
test('List empty functionality', t => {
const x = List([ 0, 1, true ]).empty()
t.equal(x.type(), 'List', 'provides a List')
t.same(x.valueOf(), [], 'provides an empty array')
t.end()
})
test('List reduce errors', t => {
const reduce = bindFunc(List([ 1, 2 ]).reduce)
const err = /List.reduce: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduce fantasy-land errors', t => {
const reduce = bindFunc(List([ 1, 2 ])[fl.reduce])
const err = /List.fantasy-land\/reduce: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduce functionality', t => {
const f = (y, x) => y + x
const m = List([ 1, 2, 3 ])
t.equal(m.reduce(f, 0), 6, 'reduces as expected with a neutral initial value')
t.equal(m.reduce(f, 10), 16, 'reduces as expected with a non-neutral initial value')
t.end()
})
test('List reduceRight errors', t => {
const reduce = bindFunc(List([ 1, 2 ]).reduceRight)
const err = /List.reduceRight: Function required for first argument/
t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument')
t.throws(reduce(null, 0), err, 'throws with null in the first argument')
t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument')
t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument')
t.throws(reduce('', 0), err, 'throws with falsey string in the first argument')
t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument')
t.throws(reduce(false, 0), err, 'throws with false in the first argument')
t.throws(reduce(true, 0), err, 'throws with true in the first argument')
t.throws(reduce({}, 0), err, 'throws with an object in the first argument')
t.throws(reduce([], 0), err, 'throws with an array in the first argument')
t.end()
})
test('List reduceRight functionality', t => {
const f = (y, x) => y.concat(x)
const m = List([ '1', '2', '3' ])
t.equal(m.reduceRight(f, '4'), '4321', 'reduces as expected')
t.end()
})
test('List fold errors', t => {
const f = bindFunc(x => List(x).fold())
const noSemi = /^TypeError: List.fold: List must contain Semigroups of the same type/
t.throws(f(undefined), noSemi, 'throws when contains single undefined')
t.throws(f(null), noSemi, 'throws when contains single null')
t.throws(f(0), noSemi, 'throws when contains single falsey number')
t.throws(f(1), noSemi, 'throws when contains single truthy number')
t.throws(f(false), noSemi, 'throws when contains single false')
t.throws(f(true), noSemi, 'throws when contains single true')
t.throws(f({}), noSemi, 'throws when contains a single object')
t.throws(f(unit), noSemi, 'throws when contains a single function')
const empty = /^TypeError: List.fold: List must contain at least one Semigroup/
t.throws(f([]), empty, 'throws when empty')
const diff = /^TypeError: List.fold: List must contain Semigroups of the same type/
t.throws(f([ [], '' ]), diff, 'throws when empty')
t.end()
})
test('List fold functionality', t => {
const f = x => List(x).fold()
t.same(f([ [ 1 ], [ 2 ] ]), [ 1, 2 ], 'combines and extracts semigroups')
t.equals(f('lucky'), 'lucky', 'extracts a single semigroup')
t.end()
})
test('List foldMap errors', t => {
const noFunc = bindFunc(fn => List([ 1 ]).foldMap(fn))
const funcErr = /^TypeError: List.foldMap: Semigroup returning function required/
t.throws(noFunc(undefined), funcErr, 'throws with undefined')
t.throws(noFunc(null), funcErr, 'throws with null')
t.throws(noFunc(0), funcErr, 'throws with falsey number')
t.throws(noFunc(1), funcErr, 'throws with truthy number')
t.throws(noFunc(false), funcErr, 'throws with false')
t.throws(noFunc(true), funcErr, 'throws with true')
t.throws(noFunc(''), funcErr, 'throws with falsey string')
t.throws(noFunc('string'), funcErr, 'throws with truthy string')
t.throws(noFunc({}), funcErr, 'throws with an object')
t.throws(noFunc([]), funcErr, 'throws with an array')
const fn = bindFunc(x => List(x).foldMap(identity))
const emptyErr = /^TypeError: List.foldMap: List must not be empty/
t.throws(fn([]), emptyErr, 'throws when passed an empty List')
const notSameSemi = /^TypeError: List.foldMap: Provided function must return Semigroups of the same type/
t.throws(fn([ 0 ]), notSameSemi, 'throws when function does not return a Semigroup')
t.throws(fn([ '', 0 ]), notSameSemi, 'throws when not all returned values are Semigroups')
t.throws(fn([ '', [] ]), notSameSemi, 'throws when different semigroups are returned')
t.end()
})
test('List foldMap functionality', t => {
const fold = xs =>
List(xs).foldMap(x => x.toString())
t.same(fold([ 1, 2 ]), '12', 'combines and extracts semigroups')
t.same(fold([ 3 ]), '3', 'extracts a single semigroup')
t.end()
})
test('List filter fantasy-land errors', t => {
const filter = bindFunc(List([ 0 ])[fl.filter])
const err = /List.fantasy-land\/filter: Pred or predicate function required/
t.throws(filter(undefined), err, 'throws with undefined')
t.throws(filter(null), err, 'throws with null')
t.throws(filter(0), err, 'throws with falsey number')
t.throws(filter(1), err, 'throws with truthy number')
t.throws(filter(''), err, 'throws with falsey string')
t.throws(filter('string'), err, 'throws with truthy string')
t.throws(filter(false), err, 'throws with false')
t.throws(filter(true), err, 'throws with true')
t.throws(filter([]), err, 'throws with an array')
t.throws(filter({}), err, 'throws with an object')
t.end()
})
test('List filter errors', t => {
const filter = bindFunc(List([ 0 ]).filter)
const err = /List.filter: Pred or predicate function required/
t.throws(filter(undefined), err, 'throws with undefined')
t.throws(filter(null), err, 'throws with null')
t.throws(filter(0), err, 'throws with falsey number')
t.throws(filter(1), err, 'throws with truthy number')
t.throws(filter(''), err, 'throws with falsey string')
t.throws(filter('string'), err, 'throws with truthy string')
t.throws(filter(false), err, 'throws with false')
t.throws(filter(true), err, 'throws with true')
t.throws(filter([]), err, 'throws with an array')
t.throws(filter({}), err, 'throws with an object')
t.end()
})
test('List filter functionality', t => {
const m = List([ 4, 5, 10, 34, 'string' ])
const bigNum = x => typeof x === 'number' && x > 10
const justStrings = x => typeof x === 'string'
const bigNumPred = Pred(bigNum)
const justStringsPred = Pred(justStrings)
t.same(m.filter(bigNum).valueOf(), [ 34 ], 'filters for bigNums with function')
t.same(m.filter(justStrings).valueOf(), [ 'string' ], 'filters for strings with function')
t.same(m.filter(bigNumPred).valueOf(), [ 34 ], 'filters for bigNums with Pred')
t.same(m.filter(justStringsPred).valueOf(), [ 'string' ], 'filters for strings with Pred')
t.end()
})
test('List filter properties (Filterable)', t => {
const m = List([ 2, 6, 10, 25, 9, 28 ])
const n = List([ 'string', 'party' ])
const isEven = x => x % 2 === 0
const isBig = x => x >= 10
const left = m.filter(x => isBig(x) && isEven(x)).valueOf()
const right = m.filter(isBig).filter(isEven).valueOf()
t.same(left, right , 'distributivity')
t.same(m.filter(() => true).valueOf(), m.valueOf(), 'identity')
t.same(m.filter(() => false).valueOf(), n.filter(() => false).valueOf(), 'annihilation')
t.end()
})
test('List reject errors', t => {
const reject = bindFunc(List([ 0 ]).reject)
const err = /List.reject: Pred or predicate function required/<|fim▁hole|> t.throws(reject(0), err, 'throws with falsey number')
t.throws(reject(1), err, 'throws with truthy number')
t.throws(reject(''), err, 'throws with falsey string')
t.throws(reject('string'), err, 'throws with truthy string')
t.throws(reject(false), err, 'throws with false')
t.throws(reject(true), err, 'throws with true')
t.throws(reject([]), err, 'throws with an array')
t.throws(reject({}), err, 'throws with an object')
t.end()
})
test('List reject functionality', t => {
const m = List([ 4, 5, 10, 34, 'string' ])
const bigNum = x => typeof x === 'number' && x > 10
const justStrings = x => typeof x === 'string'
const bigNumPred = Pred(bigNum)
const justStringsPred = Pred(justStrings)
t.same(m.reject(bigNum).valueOf(), [ 4, 5, 10, 'string' ], 'rejects bigNums with function')
t.same(m.reject(justStrings).valueOf(), [ 4, 5, 10, 34 ], 'rejects strings with function')
t.same(m.reject(bigNumPred).valueOf(), [ 4, 5, 10, 'string' ], 'rejects bigNums with Pred')
t.same(m.reject(justStringsPred).valueOf(), [ 4, 5, 10, 34 ], 'rejects strings with Pred')
t.end()
})
test('List map errors', t => {
const map = bindFunc(List([]).map)
const err = /List.map: Function required/
t.throws(map(undefined), err, 'throws with undefined')
t.throws(map(null), err, 'throws with null')
t.throws(map(0), err, 'throws with falsey number')
t.throws(map(1), err, 'throws with truthy number')
t.throws(map(''), err, 'throws with falsey string')
t.throws(map('string'), err, 'throws with truthy string')
t.throws(map(false), err, 'throws with false')
t.throws(map(true), err, 'throws with true')
t.throws(map([]), err, 'throws with an array')
t.throws(map({}), err, 'throws with an object')
t.doesNotThrow(map(unit), 'allows a function')
t.end()
})
test('List map fantasy-land errors', t => {
const map = bindFunc(List([])[fl.map])
const err = /List.fantasy-land\/map: Function required/
t.throws(map(undefined), err, 'throws with undefined')
t.throws(map(null), err, 'throws with null')
t.throws(map(0), err, 'throws with falsey number')
t.throws(map(1), err, 'throws with truthy number')
t.throws(map(''), err, 'throws with falsey string')
t.throws(map('string'), err, 'throws with truthy string')
t.throws(map(false), err, 'throws with false')
t.throws(map(true), err, 'throws with true')
t.throws(map([]), err, 'throws with an array')
t.throws(map({}), err, 'throws with an object')
t.doesNotThrow(map(unit), 'allows a function')
t.end()
})
test('List map functionality', t => {
const spy = sinon.spy(identity)
const xs = [ 42 ]
const m = List(xs).map(spy)
t.equal(m.type(), 'List', 'returns a List')
t.equal(spy.called, true, 'calls mapping function')
t.same(m.valueOf(), xs, 'returns the result of the map inside of new List')
t.end()
})
test('List map properties (Functor)', t => {
const m = List([ 49 ])
const f = x => x + 54
const g = x => x * 4
t.ok(isFunction(m.map), 'provides a map function')
t.same(m.map(identity).valueOf(), m.valueOf(), 'identity')
t.same(m.map(_compose(f, g)).valueOf(), m.map(g).map(f).valueOf(), 'composition')
t.end()
})
test('List ap errors', t => {
const left = bindFunc(x => List([ x ]).ap(List([ 0 ])))
const noFunc = /List.ap: Wrapped values must all be functions/
t.throws(left([ undefined ]), noFunc, 'throws when wrapped value is undefined')
t.throws(left([ null ]), noFunc, 'throws when wrapped value is null')
t.throws(left([ 0 ]), noFunc, 'throws when wrapped value is a falsey number')
t.throws(left([ 1 ]), noFunc, 'throws when wrapped value is a truthy number')
t.throws(left([ '' ]), noFunc, 'throws when wrapped value is a falsey string')
t.throws(left([ 'string' ]), noFunc, 'throws when wrapped value is a truthy string')
t.throws(left([ false ]), noFunc, 'throws when wrapped value is false')
t.throws(left([ true ]), noFunc, 'throws when wrapped value is true')
t.throws(left([ [] ]), noFunc, 'throws when wrapped value is an array')
t.throws(left([ {} ]), noFunc, 'throws when wrapped value is an object')
t.throws(left([ unit, 'string' ]), noFunc, 'throws when wrapped values are not all functions')
const ap = bindFunc(x => List([ unit ]).ap(x))
const noList = /List.ap: List required/
t.throws(ap(undefined), noList, 'throws with undefined')
t.throws(ap(null), noList, 'throws with null')
t.throws(ap(0), noList, 'throws with falsey number')
t.throws(ap(1), noList, 'throws with truthy number')
t.throws(ap(''), noList, 'throws with falsey string')
t.throws(ap('string'), noList, 'throws with truthy string')
t.throws(ap(false), noList, 'throws with false')
t.throws(ap(true), noList, 'throws with true')
t.throws(ap([]), noList, 'throws with an array')
t.throws(ap({}), noList, 'throws with an object')
t.end()
})
test('List ap properties (Apply)', t => {
const m = List([ identity ])
const a = m.map(_compose).ap(m).ap(m)
const b = m.ap(m.ap(m))
t.ok(isFunction(List([]).ap), 'provides an ap function')
t.ok(isFunction(List([]).map), 'implements the Functor spec')
t.same(a.ap(List([ 3 ])).valueOf(), b.ap(List([ 3 ])).valueOf(), 'composition')
t.end()
})
test('List of', t => {
t.equal(List.of, List([]).of, 'List.of is the same as the instance version')
t.equal(List.of(0).type(), 'List', 'returns a List')
t.same(List.of(0).valueOf(), [ 0 ], 'wraps the value passed into List in an array')
t.end()
})
test('List of properties (Applicative)', t => {
const m = List([ identity ])
t.ok(isFunction(List([]).of), 'provides an of function')
t.ok(isFunction(List([]).ap), 'implements the Apply spec')
t.same(m.ap(List([ 3 ])).valueOf(), [ 3 ], 'identity')
t.same(m.ap(List.of(3)).valueOf(), List.of(identity(3)).valueOf(), 'homomorphism')
const a = x => m.ap(List.of(x))
const b = x => List.of(applyTo(x)).ap(m)
t.same(a(3).valueOf(), b(3).valueOf(), 'interchange')
t.end()
})
test('List chain errors', t => {
const chain = bindFunc(List([ 0 ]).chain)
const bad = bindFunc(x => List.of(x).chain(identity))
const noFunc = /List.chain: Function required/
t.throws(chain(undefined), noFunc, 'throws with undefined')
t.throws(chain(null), noFunc, 'throws with null')
t.throws(chain(0), noFunc, 'throw with falsey number')
t.throws(chain(1), noFunc, 'throws with truthy number')
t.throws(chain(''), noFunc, 'throws with falsey string')
t.throws(chain('string'), noFunc, 'throws with truthy string')
t.throws(chain(false), noFunc, 'throws with false')
t.throws(chain(true), noFunc, 'throws with true')
t.throws(chain([]), noFunc, 'throws with an array')
t.throws(chain({}), noFunc, 'throws with an object')
const noList = /List.chain: Function must return a List/
t.throws(bad(undefined), noList, 'throws when function returns undefined')
t.throws(bad(null), noList, 'throws when function returns null')
t.throws(bad(0), noList, 'throws when function returns falsey number')
t.throws(bad(1), noList, 'throws when function returns truthy number')
t.throws(bad(''), noList, 'throws when function returns falsey string')
t.throws(bad('string'), noList, 'throws when function returns truthy string')
t.throws(bad(false), noList, 'throws when function returns false')
t.throws(bad(true), noList, 'throws when function returns true')
t.throws(bad([]), noList, 'throws when function returns an array')
t.throws(bad({}), noList, 'throws when function returns an object')
t.throws(bad(unit), noList, 'throws when function returns a function')
t.throws(bad(MockCrock), noList, 'throws when function a non-List ADT')
t.end()
})
test('List chain fantasy-land errors', t => {
const chain = bindFunc(List([ 0 ])[fl.chain])
const bad = bindFunc(x => List.of(x)[fl.chain](identity))
const noFunc = /List.fantasy-land\/chain: Function required/
t.throws(chain(undefined), noFunc, 'throws with undefined')
t.throws(chain(null), noFunc, 'throws with null')
t.throws(chain(0), noFunc, 'throw with falsey number')
t.throws(chain(1), noFunc, 'throws with truthy number')
t.throws(chain(''), noFunc, 'throws with falsey string')
t.throws(chain('string'), noFunc, 'throws with truthy string')
t.throws(chain(false), noFunc, 'throws with false')
t.throws(chain(true), noFunc, 'throws with true')
t.throws(chain([]), noFunc, 'throws with an array')
t.throws(chain({}), noFunc, 'throws with an object')
const noList = /List.fantasy-land\/chain: Function must return a List/
t.throws(bad(undefined), noList, 'throws when function returns undefined')
t.throws(bad(null), noList, 'throws when function returns null')
t.throws(bad(0), noList, 'throws when function returns falsey number')
t.throws(bad(1), noList, 'throws when function returns truthy number')
t.throws(bad(''), noList, 'throws when function returns falsey string')
t.throws(bad('string'), noList, 'throws when function returns truthy string')
t.throws(bad(false), noList, 'throws when function returns false')
t.throws(bad(true), noList, 'throws when function returns true')
t.throws(bad([]), noList, 'throws when function returns an array')
t.throws(bad({}), noList, 'throws when function returns an object')
t.throws(bad(unit), noList, 'throws when function returns a function')
t.throws(bad(MockCrock), noList, 'throws when function a non-List ADT')
t.end()
})
test('List chain properties (Chain)', t => {
t.ok(isFunction(List([]).chain), 'provides a chain function')
t.ok(isFunction(List([]).ap), 'implements the Apply spec')
const f = x => List.of(x + 2)
const g = x => List.of(x + 10)
const a = x => List.of(x).chain(f).chain(g)
const b = x => List.of(x).chain(y => f(y).chain(g))
t.same(a(10).valueOf(), b(10).valueOf(), 'assosiativity')
t.end()
})
test('List chain properties (Monad)', t => {
t.ok(isFunction(List([]).chain), 'implements the Chain spec')
t.ok(isFunction(List([]).of), 'implements the Applicative spec')
const f = x => List([ x ])
t.same(List.of(3).chain(f).valueOf(), f(3).valueOf(), 'left identity')
t.same(f(3).chain(List.of).valueOf(), f(3).valueOf(), 'right identity')
t.end()
})
test('List sequence errors', t => {
const seq = bindFunc(List.of(MockCrock(2)).sequence)
const seqBad = bindFunc(List.of(0).sequence)
const err = /List.sequence: Applicative TypeRep or Apply returning function required/
t.throws(seq(undefined), err, 'throws with undefined')
t.throws(seq(null), err, 'throws with null')
t.throws(seq(0), err, 'throws falsey with number')
t.throws(seq(1), err, 'throws truthy with number')
t.throws(seq(''), err, 'throws falsey with string')
t.throws(seq('string'), err, 'throws with truthy string')
t.throws(seq(false), err, 'throws with false')
t.throws(seq(true), err, 'throws with true')
t.throws(seq([]), err, 'throws with an array')
t.throws(seq({}), err, 'throws with an object')
const noAppl = /List.sequence: Must wrap Applys of the same type/
t.throws(seqBad(unit), noAppl, 'wrapping non-Apply throws')
t.end()
})
test('List sequence with Apply function', t => {
const x = 'string'
const fn = x => MockCrock(x)
const m = List.of(MockCrock(x)).sequence(fn)
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ x ], 'inner List contains original inner value')
const ar = x => [ x ]
const arM = List.of([ x ]).sequence(ar)
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ x ], 'inner List contains original inner value')
t.end()
})
test('List sequence with Applicative TypeRep', t => {
const x = 'string'
const m = List.of(MockCrock(x)).sequence(MockCrock)
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ x ], 'inner List contains original inner value')
const ar = List.of([ x ]).sequence(Array)
t.ok(isSameType(Array, ar), 'Provides an outer type of Array')
t.ok(isSameType(List, ar[0]), 'Provides an inner type of List')
t.same(ar[0].valueOf(), [ x ], 'inner List contains original inner value')
t.end()
})
test('List traverse errors', t => {
const trav = bindFunc(List.of(2).traverse)
const first = /List.traverse: Applicative TypeRep or Apply returning function required for first argument/
t.throws(trav(undefined, MockCrock), first, 'throws with undefined in first argument')
t.throws(trav(null, MockCrock), first, 'throws with null in first argument')
t.throws(trav(0, MockCrock), first, 'throws falsey with number in first argument')
t.throws(trav(1, MockCrock), first, 'throws truthy with number in first argument')
t.throws(trav('', MockCrock), first, 'throws falsey with string in first argument')
t.throws(trav('string', MockCrock), first, 'throws with truthy string in first argument')
t.throws(trav(false, MockCrock), first, 'throws with false in first argument')
t.throws(trav(true, MockCrock), first, 'throws with true in first argument')
t.throws(trav([], MockCrock), first, 'throws with an array in first argument')
t.throws(trav({}, MockCrock), first, 'throws with an object in first argument')
const second = /List.traverse: Apply returning functions required for second argument/
t.throws(trav(MockCrock, undefined), second, 'throws with undefined in second argument')
t.throws(trav(MockCrock, null), second, 'throws with null in second argument')
t.throws(trav(MockCrock, 0), second, 'throws falsey with number in second argument')
t.throws(trav(MockCrock, 1), second, 'throws truthy with number in second argument')
t.throws(trav(MockCrock, ''), second, 'throws falsey with string in second argument')
t.throws(trav(MockCrock, 'string'), second, 'throws with truthy string in second argument')
t.throws(trav(MockCrock, false), second, 'throws with false in second argument')
t.throws(trav(MockCrock, true), second, 'throws with true in second argument')
t.throws(trav(MockCrock, []), second, 'throws with an array in second argument')
t.throws(trav(MockCrock, {}), second, 'throws with an object in second argument')
const noAppl = /List.traverse: Both functions must return an Apply of the same type/
t.throws(trav(unit, MockCrock), noAppl, 'throws with non-Appicative returning function in first argument')
t.throws(trav(MockCrock, unit), noAppl, 'throws with non-Appicative returning function in second argument')
t.end()
})
test('List traverse with Apply function', t => {
const x = 'string'
const res = 'result'
const f = x => MockCrock(x)
const fn = m => constant(m(res))
const m = List.of(x).traverse(f, fn(MockCrock))
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ res ], 'inner List contains transformed value')
const ar = x => [ x ]
const arM = List.of(x).traverse(ar, fn(ar))
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ res ], 'inner List contains transformed value')
t.end()
})
test('List traverse with Applicative TypeRep', t => {
const x = 'string'
const res = 'result'
const fn = m => constant(m(res))
const m = List.of(x).traverse(MockCrock, fn(MockCrock))
t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock')
t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List')
t.same(m.valueOf().valueOf(), [ res ], 'inner List contains transformed value')
const ar = x => [ x ]
const arM = List.of(x).traverse(Array, fn(ar))
t.ok(isSameType(Array, arM), 'Provides an outer type of Array')
t.ok(isSameType(List, arM[0]), 'Provides an inner type of List')
t.same(arM[0].valueOf(), [ res ], 'inner List contains transformed value')
t.end()
})<|fim▁end|>
|
t.throws(reject(undefined), err, 'throws with undefined')
t.throws(reject(null), err, 'throws with null')
|
<|file_name|>travis_doc.py<|end_file_name|><|fim▁begin|>def function1():
"""
Return 1
"""
return 1<|fim▁hole|> Return 2
"""
return 2<|fim▁end|>
|
def function2():
"""
|
<|file_name|>IdeationStatusExtension.java<|end_file_name|><|fim▁begin|>package com.adobe.aem.scf.extensions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
<|fim▁hole|>import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceUtil;
import com.adobe.cq.social.forum.client.api.Post;
import com.adobe.cq.social.forum.client.endpoints.ForumOperationExtension;
import com.adobe.cq.social.scf.Operation;
import com.adobe.cq.social.scf.OperationException;
@Component(name = "Ideation Status Extension", immediate = true, metatype = true)
@Service
public class IdeationStatusExtension implements ForumOperationExtension {
@Override
public void afterAction(Operation op, Session sessionUsed, Post post, Map<String, Object> props)
throws OperationException {
// TODO Auto-generated method stub
}
@Override
public void beforeAction(Operation op, Session sessionUsed, Resource requestResource, Map<String, Object> props)
throws OperationException {
if (ResourceUtil.isA(requestResource, "acme/components/ideation/forum")) {
List<String> tags = new ArrayList<String>();
if (props.containsKey("tags")) {
final Object v = props.get("tags");
if (!(v instanceof String[])) {
if (v instanceof String) {
tags.add((String) v);
}
} else {
for (String t : (String[]) v) {
tags.add(t);
}
}
}
tags.add("acmeideas:new");
props.put("tags", tags.toArray(new String[]{}));
}
}
@Override
public String getName() {
return "ideation status";
}
@Override
public int getOrder() {
return 1;
}
@Override
public List<ForumOperation> getOperationsToHookInto() {
return Arrays.asList(ForumOperation.CREATE);
}
}<|fim▁end|>
|
import javax.jcr.Session;
import org.apache.felix.scr.annotations.Component;
|
<|file_name|>SingleThreadPortScan.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: S.H.
Version: 0.1
Date: 2015-01-17
Description:
Scan ip:
74.125.131.0/24
74.125.131.99-125
74.125.131.201
Only three format above.
Read ip form a ip.txt, and scan all port(or a list port).
"""
import os
import io
import socket
fileOpen = open("ip.txt", 'r')
fileTemp = open("temp.txt", 'a')
for line in fileOpen.readlines():
if line.find("-") != -1:
list = line[:line.index("-")]
ip = [int(a) for a in list.split(".")]
b = int(line[line.index("-")+1:])
for i in range(ip[3], b+1):
fileTemp.write(str(ip[0])+"."+str(ip[1])+"."+str(ip[2])+"."+str(i)+"\n")
elif line.find("/") != -1:
list = line[:line.index("/")]
ip = [int(a) for a in list.split(".")]
for i in range(256):
fileTemp.write(str(ip[0])+"."+str(ip[1])+"."+str(ip[2])+"."+str(i)+"\n")
else:
fileTemp.write(line)
fileTemp.close()<|fim▁hole|>
# print("process is here.")
f = open("temp.txt", 'r')
print("===Scan Staring===")
for line in f.readlines():
hostIP = socket.gethostbyname(line)
# print(hostIP)
# for port in range(65535):
portList = [80, 8080]
for port in portList:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((hostIP, port))
if result == 0:
print("Port {} is OPEN on:\t\t\t {}".format(port, hostIP))
else:
print("Port {} is NOT open on {}".format(port, hostIP))
sock.close()
f.close()
os.remove("temp.txt")
print("===Scan Complement===")<|fim▁end|>
|
fileOpen.close()
|
<|file_name|>Balance.hpp<|end_file_name|><|fim▁begin|>/*
* Balance.hpp
*
* Created on: Apr 24, 2014
* Author: f3r0x
*/
#ifndef BALANCE_HPP_
#define BALANCE_HPP_
// BalanceSheet
#include "SheetItem.hpp"
namespace bs {
class Balance {
private:
std::string name;
SheetItem assets;
SheetItem liabilities;
public:
Balance();
Balance(std::string name);
virtual ~Balance();
void init();
void print();<|fim▁hole|><|fim▁end|>
|
};
} /* namespace bs */
#endif /* BALANCE_HPP_ */
|
<|file_name|>block.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS block layout.
use layout::box::{RenderBox, RenderBoxUtils};
use layout::context::LayoutContext;
use layout::display_list_builder::{DisplayListBuilder, ExtraDisplayListData};
use layout::flow::{BlockFlowClass, FlowClass, FlowContext, FlowData, ImmutableFlowUtils};
use layout::flow;
use layout::model::{MaybeAuto, Specified, Auto};
use layout::float_context::{FloatContext, Invalid};
use std::cell::Cell;
use geom::point::Point2D;
use geom::size::Size2D;
use geom::rect::Rect;
use gfx::display_list::DisplayList;
use servo_util::geometry::{Au, to_frac_px};
use servo_util::geometry;
pub struct BlockFlow {
/// Data common to all flows.
base: FlowData,
/// The associated render box.
box: Option<@RenderBox>,
/// Whether this block flow is the root flow.
is_root: bool
}
impl BlockFlow {
pub fn new(base: FlowData) -> BlockFlow {
BlockFlow {
base: base,
box: None,
is_root: false
}
}
pub fn new_root(base: FlowData) -> BlockFlow {
BlockFlow {
base: base,
box: None,
is_root: true
}
}
pub fn teardown(&mut self) {
for box in self.box.iter() {
box.teardown();
}
self.box = None;
}
/// Computes left and right margins and width based on CSS 2.1 section 10.3.3.
/// Requires borders and padding to already be computed.
fn compute_horiz(&self,
width: MaybeAuto,
left_margin: MaybeAuto,
right_margin: MaybeAuto,
available_width: Au)
-> (Au, Au, Au) {
// If width is not 'auto', and width + margins > available_width, all 'auto' margins are
// treated as 0.
let (left_margin, right_margin) = match width {
Auto => (left_margin, right_margin),
Specified(width) => {
let left = left_margin.specified_or_zero();
let right = right_margin.specified_or_zero();
if((left + right + width) > available_width) {
(Specified(left), Specified(right))
} else {
(left_margin, right_margin)
}
}
};
//Invariant: left_margin_Au + width_Au + right_margin_Au == available_width
let (left_margin_Au, width_Au, right_margin_Au) = match (left_margin, width, right_margin) {
//If all have a computed value other than 'auto', the system is over-constrained and we need to discard a margin.
//if direction is ltr, ignore the specified right margin and solve for it. If it is rtl, ignore the specified
//left margin. FIXME(eatkinson): this assumes the direction is ltr
(Specified(margin_l), Specified(width), Specified(_margin_r)) => (margin_l, width, available_width - (margin_l + width )),
//If exactly one value is 'auto', solve for it
(Auto, Specified(width), Specified(margin_r)) => (available_width - (width + margin_r), width, margin_r),
(Specified(margin_l), Auto, Specified(margin_r)) => (margin_l, available_width - (margin_l + margin_r), margin_r),
(Specified(margin_l), Specified(width), Auto) => (margin_l, width, available_width - (margin_l + width)),
//If width is set to 'auto', any other 'auto' value becomes '0', and width is solved for
(Auto, Auto, Specified(margin_r)) => (Au::new(0), available_width - margin_r, margin_r),
(Specified(margin_l), Auto, Auto) => (margin_l, available_width - margin_l, Au::new(0)),
(Auto, Auto, Auto) => (Au::new(0), available_width, Au::new(0)),
//If left and right margins are auto, they become equal
(Auto, Specified(width), Auto) => {
let margin = (available_width - width).scale_by(0.5);
(margin, width, margin)
}
};
//return values in same order as params
(width_Au, left_margin_Au, right_margin_Au)
}
// inline(always) because this is only ever called by in-order or non-in-order top-level
// methods
#[inline(always)]
fn assign_height_block_base(&mut self, ctx: &mut LayoutContext, inorder: bool) {
let mut cur_y = Au::new(0);
let mut clearance = Au::new(0);
let mut top_offset = Au::new(0);
let mut bottom_offset = Au::new(0);
let mut left_offset = Au::new(0);
let mut float_ctx = Invalid;
for &box in self.box.iter() {
let base = box.base();
clearance = match base.clear() {
None => Au::new(0),
Some(clear) => {
self.base.floats_in.clearance(clear)
}
};
let mut model_ref = base.model.mutate();
let model = &mut model_ref.ptr;
top_offset = clearance + model.margin.top + model.border.top + model.padding.top;
cur_y = cur_y + top_offset;
bottom_offset = model.margin.bottom + model.border.bottom + model.padding.bottom;
left_offset = model.offset();
}
if inorder {
// Floats for blocks work like this:
// self.floats_in -> child[0].floats_in
// visit child[0]
// child[i-1].floats_out -> child[i].floats_in
// visit child[i]
// repeat until all children are visited.
// last_child.floats_out -> self.floats_out (done at the end of this method)
float_ctx = self.base.floats_in.translate(Point2D(-left_offset, -top_offset));
for kid in self.base.child_iter() {
flow::mut_base(*kid).floats_in = float_ctx.clone();
kid.assign_height_inorder(ctx);
float_ctx = flow::mut_base(*kid).floats_out.clone();
}
}
let mut collapsible = Au::new(0);
let mut collapsing = Au::new(0);
let mut margin_top = Au::new(0);
let mut margin_bottom = Au::new(0);
let mut top_margin_collapsible = false;
let mut bottom_margin_collapsible = false;
let mut first_in_flow = true;
for &box in self.box.iter() {
let base = box.base();
let mut model_ref = base.model.mutate();
let model = &mut model_ref.ptr;
if !self.is_root && model.border.top == Au::new(0) && model.padding.top == Au::new(0) {
collapsible = model.margin.top;
top_margin_collapsible = true;
}
if !self.is_root && model.border.bottom == Au::new(0) && model.padding.bottom == Au::new(0) {
bottom_margin_collapsible = true;
}
margin_top = model.margin.top;
margin_bottom = model.margin.bottom;
}
for kid in self.base.child_iter() {
kid.collapse_margins(top_margin_collapsible,
&mut first_in_flow,
&mut margin_top,
&mut top_offset,
&mut collapsing,
&mut collapsible);
let child_node = flow::mut_base(*kid);
cur_y = cur_y - collapsing;
child_node.position.origin.y = cur_y;
cur_y = cur_y + child_node.position.size.height;
}
// The bottom margin collapses with its last in-flow block-level child's bottom margin
// if the parent has no bottom boder, no bottom padding.
collapsing = if bottom_margin_collapsible {
if margin_bottom < collapsible {
margin_bottom = collapsible;
}
collapsible
} else {
Au::new(0)
};
// TODO: A box's own margins collapse if the 'min-height' property is zero, and it has neither
// top or bottom borders nor top or bottom padding, and it has a 'height' of either 0 or 'auto',
// and it does not contain a line box, and all of its in-flow children's margins (if any) collapse.
let mut height = if self.is_root {
Au::max(ctx.screen_size.size.height, cur_y)
} else {
cur_y - top_offset - collapsing
};
for &box in self.box.iter() {
let base = box.base();
let style = base.style();
let maybe_height = MaybeAuto::from_style(style.Box.height, Au::new(0));
let maybe_height = maybe_height.specified_or_zero();
height = geometry::max(height, maybe_height);
}
let mut noncontent_height = Au::new(0);
for box in self.box.iter() {
let base = box.base();
let mut model_ref = base.model.mutate();
let mut position_ref = base.position.mutate();
let (model, position) = (&mut model_ref.ptr, &mut position_ref.ptr);
// The associated box is the border box of this flow.
model.margin.top = margin_top;
model.margin.bottom = margin_bottom;
position.origin.y = clearance + model.margin.top;
noncontent_height = model.padding.top + model.padding.bottom + model.border.top +
model.border.bottom;
position.size.height = height + noncontent_height;
noncontent_height = noncontent_height + clearance + model.margin.top +
model.margin.bottom;
}
//TODO(eatkinson): compute heights using the 'height' property.
self.base.position.size.height = height + noncontent_height;
if inorder {
let extra_height = height - (cur_y - top_offset) + bottom_offset;
self.base.floats_out = float_ctx.translate(Point2D(left_offset, -extra_height));
} else {
self.base.floats_out = self.base.floats_in.clone();
}
}
pub fn build_display_list_block<E:ExtraDisplayListData>(
&mut self,
builder: &DisplayListBuilder,
dirty: &Rect<Au>,
list: &Cell<DisplayList<E>>)
-> bool {
if self.base.node.is_iframe_element() {
let x = self.base.abs_position.x + do self.box.map_default(Au::new(0)) |box| {
let model = box.base().model.get();
model.margin.left + model.border.left + model.padding.left
};
let y = self.base.abs_position.y + do self.box.map_default(Au::new(0)) |box| {
let model = box.base().model.get();
model.margin.top + model.border.top + model.padding.top
};
let w = self.base.position.size.width - do self.box.map_default(Au::new(0)) |box| {
box.base().model.get().noncontent_width()
};
let h = self.base.position.size.height - do self.box.map_default(Au::new(0)) |box| {
box.base().model.get().noncontent_height()
};
do self.base.node.with_mut_iframe_element |iframe_element| {
iframe_element.size.get_mut_ref().set_rect(Rect(Point2D(to_frac_px(x) as f32,
to_frac_px(y) as f32),
Size2D(to_frac_px(w) as f32,
to_frac_px(h) as f32)));
}
}
let abs_rect = Rect(self.base.abs_position, self.base.position.size);
if !abs_rect.intersects(dirty) {
return true;
}
debug!("build_display_list_block: adding display element");
// add box that starts block context
for box in self.box.iter() {
box.build_display_list(builder, dirty, &self.base.abs_position, list)
}
// TODO: handle any out-of-flow elements
let this_position = self.base.abs_position;
for child in self.base.child_iter() {
let child_base = flow::mut_base(*child);
child_base.abs_position = this_position + child_base.position.origin;
}
false
}
}
impl FlowContext for BlockFlow {
fn class(&self) -> FlowClass {
BlockFlowClass
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
self
}
/* Recursively (bottom-up) determine the context's preferred and
minimum widths. When called on this context, all child contexts
have had their min/pref widths set. This function must decide
min/pref widths based on child context widths and dimensions of
any boxes it is responsible for flowing. */
/* TODO: floats */
/* TODO: absolute contexts */
/* TODO: inline-blocks */
fn bubble_widths(&mut self, _: &mut LayoutContext) {
let mut min_width = Au::new(0);
let mut pref_width = Au::new(0);
let mut num_floats = 0;
/* find max width from child block contexts */
for child_ctx in self.base.child_iter() {
assert!(child_ctx.starts_block_flow() || child_ctx.starts_inline_flow());
let child_base = flow::mut_base(*child_ctx);
min_width = geometry::max(min_width, child_base.min_width);
pref_width = geometry::max(pref_width, child_base.pref_width);
num_floats = num_floats + child_base.num_floats;
}
/* if not an anonymous block context, add in block box's widths.
these widths will not include child elements, just padding etc. */
for box in self.box.iter() {
{
// Can compute border width here since it doesn't depend on anything.
let base = box.base();
base.model.mutate().ptr.compute_borders(base.style())
}
let (this_minimum_width, this_preferred_width) = box.minimum_and_preferred_widths();
min_width = min_width + this_minimum_width;
pref_width = pref_width + this_preferred_width;
}
self.base.min_width = min_width;
self.base.pref_width = pref_width;
self.base.num_floats = num_floats;
}
/// Recursively (top-down) determines the actual width of child contexts and boxes. When called
/// on this context, the context has had its width set by the parent context.
///
/// Dual boxes consume some width first, and the remainder is assigned to all child (block)
/// contexts.
fn assign_widths(&mut self, ctx: &mut LayoutContext) {
debug!("assign_widths_block: assigning width for flow {}", self.base.id);
if self.is_root {
debug!("Setting root position");
self.base.position.origin = Au::zero_point();
self.base.position.size.width = ctx.screen_size.size.width;
self.base.floats_in = FloatContext::new(self.base.num_floats);
self.base.is_inorder = false;
}
//position was set to the containing block by the flow's parent
let mut remaining_width = self.base.position.size.width;
let mut x_offset = Au::new(0);
for &box in self.box.iter() {
let base = box.base();
let style = base.style();
let mut model_ref = base.model.mutate();
let model = &mut model_ref.ptr;
// Can compute padding here since we know containing block width.
model.compute_padding(style, remaining_width);
// Margins are 0 right now so model.noncontent_width() is just borders + padding.
let available_width = remaining_width - model.noncontent_width();
// Top and bottom margins for blocks are 0 if auto.
let margin_top = MaybeAuto::from_style(style.Margin.margin_top,
remaining_width).specified_or_zero();
let margin_bottom = MaybeAuto::from_style(style.Margin.margin_bottom,
remaining_width).specified_or_zero();
let (width, margin_left, margin_right) =
(MaybeAuto::from_style(style.Box.width, remaining_width),<|fim▁hole|> let (width, margin_left, margin_right) = self.compute_horiz(width,
margin_left,
margin_right,
available_width);
model.margin.top = margin_top;
model.margin.right = margin_right;
model.margin.bottom = margin_bottom;
model.margin.left = margin_left;
x_offset = model.offset();
remaining_width = width;
//The associated box is the border box of this flow
let position_ref = base.position.mutate();
position_ref.ptr.origin.x = model.margin.left;
let padding_and_borders = model.padding.left + model.padding.right +
model.border.left + model.border.right;
position_ref.ptr.size.width = remaining_width + padding_and_borders;
}
let has_inorder_children = self.base.is_inorder || self.base.num_floats > 0;
for kid in self.base.child_iter() {
assert!(kid.starts_block_flow() || kid.starts_inline_flow());
let child_base = flow::mut_base(*kid);
child_base.position.origin.x = x_offset;
child_base.position.size.width = remaining_width;
child_base.is_inorder = has_inorder_children;
if !child_base.is_inorder {
child_base.floats_in = FloatContext::new(0);
}
}
}
fn assign_height_inorder(&mut self, ctx: &mut LayoutContext) {
debug!("assign_height_inorder: assigning height for block {}", self.base.id);
self.assign_height_block_base(ctx, true);
}
fn assign_height(&mut self, ctx: &mut LayoutContext) {
debug!("assign_height: assigning height for block {}", self.base.id);
// This is the only case in which a block flow can start an inorder
// subtraversal.
if self.is_root && self.base.num_floats > 0 {
self.assign_height_inorder(ctx);
return;
}
self.assign_height_block_base(ctx, false);
}
fn collapse_margins(&mut self,
top_margin_collapsible: bool,
first_in_flow: &mut bool,
margin_top: &mut Au,
top_offset: &mut Au,
collapsing: &mut Au,
collapsible: &mut Au) {
for &box in self.box.iter() {
let base = box.base();
let mut model_ref = base.model.mutate();
let model = &mut model_ref.ptr;
// The top margin collapses with its first in-flow block-level child's
// top margin if the parent has no top border, no top padding.
if *first_in_flow && top_margin_collapsible {
// If top-margin of parent is less than top-margin of its first child,
// the parent box goes down until its top is aligned with the child.
if *margin_top < model.margin.top {
// TODO: The position of child floats should be updated and this
// would influence clearance as well. See #725
let extra_margin = model.margin.top - *margin_top;
*top_offset = *top_offset + extra_margin;
*margin_top = model.margin.top;
}
}
// The bottom margin of an in-flow block-level element collapses
// with the top margin of its next in-flow block-level sibling.
*collapsing = geometry::min(model.margin.top, *collapsible);
*collapsible = model.margin.bottom;
}
*first_in_flow = false;
}
}<|fim▁end|>
|
MaybeAuto::from_style(style.Margin.margin_left, remaining_width),
MaybeAuto::from_style(style.Margin.margin_right, remaining_width));
|
<|file_name|>matrix.py<|end_file_name|><|fim▁begin|>from typing import Sequence
from numbers import Number
from tabulate import tabulate
class Matrix(Sequence):
def __init__(self, matrix: Sequence[Sequence[float]]):
assert (isinstance(matrix, Sequence) and
isinstance(matrix, Sequence)), "Wrong data"
self.__matrix = [[float(x) for x in row] for row in matrix]
@staticmethod
def one(rows: int, columns: int):
return [
[1 if i == j else 0 for j in range(columns)] for i in range(rows)
]
@staticmethod
def zero(rows: int, columns: int):
return [[0] * columns for _ in range(rows)]
def __repr__(self):
return 'Matrix({})'.format(self.__matrix)
def __str__(self):
return tabulate(self.__matrix)
def __len__(self):
return len(self.__matrix)
def __getitem__(self, item):
return self.__matrix.__getitem__(item)
def __iter__(self):
return iter(self.__matrix)
def __mul__(self, other):
assert isinstance(other, Sequence)
# Количество столбцов равно количеству строк / элементов
assert len(self.__matrix[0]) == len(other), "Wrong data"
if isinstance(other[0], Sequence):
return Matrix([
[
sum(self[i][k] * other[k][j] for k in range(len(other))) for j in range(len(other[0]))
] for i in range(len(self))
])
else:
return [
sum(x * y for x, y in zip(row, other)) for row in self
]
def __rmul__(self, other):
assert isinstance(other, Number)
return Matrix([
[other * x for x in row] for row in self.__matrix
])
def __add__(self, other):
# and all(len(other) == len(row) for row in other)), "Wrong data"
assert (isinstance(other, Sequence) and
isinstance(other[0], Sequence) and<|fim▁hole|> len(self) == len(other) and
len(self[0]) == len(other[0])), "Wrong data"
return Matrix([
[x + y for x, y in zip(r1, r2)] for r1, r2 in zip(self.__matrix, other)
])
def __neg__(self):
return Matrix([
[-x for x in row] for row in self.__matrix
])
def __sub__(self, other):
assert (isinstance(other, Sequence) and
isinstance(other[0], Sequence) and
all(len(other) == len(row) for row in other)), "Wrong data"
return Matrix([
[x - y for x, y in zip(r1, r2)] for r1, r2 in zip(self, other)
])
@property
def shape(self):
return len(self.__matrix), len(self.__matrix[0])
if __name__ == '__main__':
m = Matrix([[1, 2, 1], [2, 3, 0]])
a = Matrix([[1, 0, 0], [2, 1, 0], [1, 1, 0]])
# print(m, m.shape)
# print(a, a.shape)
print(m * a)<|fim▁end|>
| |
<|file_name|>rpcapi.py<|end_file_name|><|fim▁begin|># Copyright 2013, Red Hat, 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.
"""
Client side of the scheduler manager RPC API.
"""
from oslo.config import cfg
from oslo import messaging
from nova.objects import base as objects_base
from nova.openstack.common import jsonutils
from nova import rpc
rpcapi_opts = [
cfg.StrOpt('scheduler_topic',<|fim▁hole|>CONF = cfg.CONF
CONF.register_opts(rpcapi_opts)
rpcapi_cap_opt = cfg.StrOpt('scheduler',
help='Set a version cap for messages sent to scheduler services')
CONF.register_opt(rpcapi_cap_opt, 'upgrade_levels')
class SchedulerAPI(object):
'''Client side of the scheduler rpc API.
API version history:
1.0 - Initial version.
1.1 - Changes to prep_resize():
- remove instance_uuid, add instance
- remove instance_type_id, add instance_type
- remove topic, it was unused
1.2 - Remove topic from run_instance, it was unused
1.3 - Remove instance_id, add instance to live_migration
1.4 - Remove update_db from prep_resize
1.5 - Add reservations argument to prep_resize()
1.6 - Remove reservations argument to run_instance()
1.7 - Add create_volume() method, remove topic from live_migration()
2.0 - Remove 1.x backwards compat
2.1 - Add image_id to create_volume()
2.2 - Remove reservations argument to create_volume()
2.3 - Remove create_volume()
2.4 - Change update_service_capabilities()
- accepts a list of capabilities
2.5 - Add get_backdoor_port()
2.6 - Add select_hosts()
... Grizzly supports message version 2.6. So, any changes to existing
methods in 2.x after that point should be done such that they can
handle the version_cap being set to 2.6.
2.7 - Add select_destinations()
2.8 - Deprecate prep_resize() -- JUST KIDDING. It is still used
by the compute manager for retries.
2.9 - Added the legacy_bdm_in_spec parameter to run_instance()
... Havana supports message version 2.9. So, any changes to existing
methods in 2.x after that point should be done such that they can
handle the version_cap being set to 2.9.
... - Deprecated live_migration() call, moved to conductor
... - Deprecated select_hosts()
3.0 - Removed backwards compat
'''
VERSION_ALIASES = {
'grizzly': '2.6',
'havana': '2.9',
'icehouse': '3.0',
}
def __init__(self):
super(SchedulerAPI, self).__init__()
target = messaging.Target(topic=CONF.scheduler_topic, version='3.0')
version_cap = self.VERSION_ALIASES.get(CONF.upgrade_levels.scheduler,
CONF.upgrade_levels.scheduler)
serializer = objects_base.NovaObjectSerializer()
self.client = rpc.get_client(target, version_cap=version_cap,
serializer=serializer)
def select_destinations(self, ctxt, request_spec, filter_properties):
cctxt = self.client.prepare()
return cctxt.call(ctxt, 'select_destinations',
request_spec=request_spec, filter_properties=filter_properties)
def run_instance(self, ctxt, request_spec, admin_password,
injected_files, requested_networks, is_first_time,
filter_properties, legacy_bdm_in_spec=True):
msg_kwargs = {'request_spec': request_spec,
'admin_password': admin_password,
'injected_files': injected_files,
'requested_networks': requested_networks,
'is_first_time': is_first_time,
'filter_properties': filter_properties,
'legacy_bdm_in_spec': legacy_bdm_in_spec}
cctxt = self.client.prepare()
cctxt.cast(ctxt, 'run_instance', **msg_kwargs)
def prep_resize(self, ctxt, instance, instance_type, image,
request_spec, filter_properties, reservations):
instance_p = jsonutils.to_primitive(instance)
instance_type_p = jsonutils.to_primitive(instance_type)
reservations_p = jsonutils.to_primitive(reservations)
image_p = jsonutils.to_primitive(image)
cctxt = self.client.prepare()
cctxt.cast(ctxt, 'prep_resize',
instance=instance_p, instance_type=instance_type_p,
image=image_p, request_spec=request_spec,
filter_properties=filter_properties,
reservations=reservations_p)<|fim▁end|>
|
default='scheduler',
help='The topic scheduler nodes listen on'),
]
|
<|file_name|>config-form.js<|end_file_name|><|fim▁begin|>(function($) {
var FourthWallConfiguration = function() {
this.token = localStorage.getItem('token');
this.gitlab_host = localStorage.getItem('gitlab_host');
}
FourthWallConfiguration.prototype.save = function() {
localStorage.setItem('token', this.token);
localStorage.setItem('gitlab_host', this.gitlab_host);
$(this).trigger('updated');
}
var FourthWallConfigurationForm = function(form, config) {
this.form = form;
this.statusField = $('#form-status', form)
this.config = config;
this.form.submit(this.onSubmit.bind(this));
};<|fim▁hole|> };
FourthWallConfigurationForm.prototype.onSubmit = function(e) {
var values = this.form.serializeArray();
for( var i in values ) {
this.config[values[i].name] = values[i].value;
}
this.config.save();
this.updateStatus('Data saved!');
return false;
}
var FourthWallConfigurationDisplay = function(element) {
this.configurationList = element;
};
FourthWallConfigurationDisplay.prototype.display = function(config) {
var tokenValue = $('<li>').text('Token: ' + config.token);
var hostnameValue = $('<li>').text('Hostname: ' + config.gitlab_host);
this.configurationList.empty();
this.configurationList.append(tokenValue);
this.configurationList.append(hostnameValue);
};
$(document).ready(function() {
var form = $('#fourth-wall-config');
var savedValues = $('#saved-values');
var config = new FourthWallConfiguration();
var form = new FourthWallConfigurationForm(form, config);
var configDisplay = new FourthWallConfigurationDisplay(savedValues);
configDisplay.display(config);
$(config).on('updated', function() {
configDisplay.display(config);
});
});
})(jQuery);<|fim▁end|>
|
FourthWallConfigurationForm.prototype.updateStatus = function(string) {
this.statusField.text(string).show();
|
<|file_name|>res_users.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2014 OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import itertools
import logging
from functools import partial
from itertools import repeat
from lxml import etree
from lxml.builder import E
import openerp
from openerp import SUPERUSER_ID, models
from openerp import tools
import openerp.exceptions
from openerp.osv import fields, osv, expression
from openerp.tools.translate import _
from openerp.http import request
_logger = logging.getLogger(__name__)
#----------------------------------------------------------
# Basic res.groups and res.users
#----------------------------------------------------------
class res_groups(osv.osv):
_name = "res.groups"
_description = "Access Groups"
_rec_name = 'full_name'
_order = 'name'
def _get_full_name(self, cr, uid, ids, field, arg, context=None):
res = {}
for g in self.browse(cr, uid, ids, context):
if g.category_id:
res[g.id] = '%s / %s' % (g.category_id.name, g.name)
else:
res[g.id] = g.name
return res
def _search_group(self, cr, uid, obj, name, args, context=None):
operand = args[0][2]
operator = args[0][1]
lst = True
if isinstance(operand, bool):
domains = [[('name', operator, operand)], [('category_id.name', operator, operand)]]
if operator in expression.NEGATIVE_TERM_OPERATORS == (not operand):
return expression.AND(domains)
else:
return expression.OR(domains)
if isinstance(operand, basestring):
lst = False
operand = [operand]
where = []
for group in operand:
values = filter(bool, group.split('/'))
group_name = values.pop().strip()
category_name = values and '/'.join(values).strip() or group_name
group_domain = [('name', operator, lst and [group_name] or group_name)]
category_domain = [('category_id.name', operator, lst and [category_name] or category_name)]
if operator in expression.NEGATIVE_TERM_OPERATORS and not values:
category_domain = expression.OR([category_domain, [('category_id', '=', False)]])
if (operator in expression.NEGATIVE_TERM_OPERATORS) == (not values):
sub_where = expression.AND([group_domain, category_domain])
else:
sub_where = expression.OR([group_domain, category_domain])
if operator in expression.NEGATIVE_TERM_OPERATORS:
where = expression.AND([where, sub_where])
else:
where = expression.OR([where, sub_where])
return where
_columns = {
'name': fields.char('Name', required=True, translate=True),
'users': fields.many2many('res.users', 'res_groups_users_rel', 'gid', 'uid', 'Users'),
'model_access': fields.one2many('ir.model.access', 'group_id', 'Access Controls'),
'rule_groups': fields.many2many('ir.rule', 'rule_group_rel',
'group_id', 'rule_group_id', 'Rules', domain=[('global', '=', False)]),
'menu_access': fields.many2many('ir.ui.menu', 'ir_ui_menu_group_rel', 'gid', 'menu_id', 'Access Menu'),
'view_access': fields.many2many('ir.ui.view', 'ir_ui_view_group_rel', 'group_id', 'view_id', 'Views'),
'comment' : fields.text('Comment', size=250, translate=True),
'category_id': fields.many2one('ir.module.category', 'Application', select=True),
'full_name': fields.function(_get_full_name, type='char', string='Group Name', fnct_search=_search_group),
}
_sql_constraints = [
('name_uniq', 'unique (category_id, name)', 'The name of the group must be unique within an application!')
]
def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
# add explicit ordering if search is sorted on full_name
if order and order.startswith('full_name'):
ids = super(res_groups, self).search(cr, uid, args, context=context)
gs = self.browse(cr, uid, ids, context)
gs.sort(key=lambda g: g.full_name, reverse=order.endswith('DESC'))
gs = gs[offset:offset+limit] if limit else gs[offset:]
return map(int, gs)
return super(res_groups, self).search(cr, uid, args, offset, limit, order, context, count)
def copy(self, cr, uid, id, default=None, context=None):
group_name = self.read(cr, uid, [id], ['name'])[0]['name']
default.update({'name': _('%s (copy)')%group_name})
return super(res_groups, self).copy(cr, uid, id, default, context)
def write(self, cr, uid, ids, vals, context=None):
if 'name' in vals:
if vals['name'].startswith('-'):
raise osv.except_osv(_('Error'),
_('The name of the group can not start with "-"'))
res = super(res_groups, self).write(cr, uid, ids, vals, context=context)
self.pool['ir.model.access'].call_cache_clearing_methods(cr)
self.pool['res.users'].has_group.clear_cache(self.pool['res.users'])
return res
class res_users(osv.osv):
""" User class. A res.users record models an OpenERP user and is different
from an employee.
res.users class now inherits from res.partner. The partner model is
used to store the data related to the partner: lang, name, address,
avatar, ... The user model is now dedicated to technical data.
"""
__admin_ids = {}
_uid_cache = {}
_inherits = {
'res.partner': 'partner_id',
}
_name = "res.users"
_description = 'Users'
def _set_new_password(self, cr, uid, id, name, value, args, context=None):
if value is False:
# Do not update the password if no value is provided, ignore silently.
# For example web client submits False values for all empty fields.
return
if uid == id:
# To change their own password users must use the client-specific change password wizard,
# so that the new password is immediately used for further RPC requests, otherwise the user
# will face unexpected 'Access Denied' exceptions.
raise osv.except_osv(_('Operation Canceled'), _('Please use the change password wizard (in User Preferences or User menu) to change your own password.'))
self.write(cr, uid, id, {'password': value})
def _get_password(self, cr, uid, ids, arg, karg, context=None):
return dict.fromkeys(ids, '')
_columns = {
'id': fields.integer('ID'),
'login_date': fields.date('Latest connection', select=1, copy=False),
'partner_id': fields.many2one('res.partner', required=True,
string='Related Partner', ondelete='restrict',
help='Partner-related data of the user', auto_join=True),
'login': fields.char('Login', size=64, required=True,
help="Used to log into the system"),
'password': fields.char('Password', size=64, invisible=True, copy=False,
help="Keep empty if you don't want the user to be able to connect on the system."),
'new_password': fields.function(_get_password, type='char', size=64,
fnct_inv=_set_new_password, string='Set Password',
help="Specify a value only when creating a user or if you're "\
"changing the user's password, otherwise leave empty. After "\
"a change of password, the user has to login again."),
'signature': fields.html('Signature'),
'active': fields.boolean('Active'),
'action_id': fields.many2one('ir.actions.actions', 'Home Action', help="If specified, this action will be opened at log on for this user, in addition to the standard menu."),
'groups_id': fields.many2many('res.groups', 'res_groups_users_rel', 'uid', 'gid', 'Groups'),
# Special behavior for this field: res.company.search() will only return the companies
# available to the current user (should be the user's companies?), when the user_preference
# context is set.
'company_id': fields.many2one('res.company', 'Company', required=True,
help='The company this user is currently working for.', context={'user_preference': True}),
'company_ids':fields.many2many('res.company','res_company_users_rel','user_id','cid','Companies'),
}
# overridden inherited fields to bypass access rights, in case you have
# access to the user but not its corresponding partner
name = openerp.fields.Char(related='partner_id.name', inherited=True)
email = openerp.fields.Char(related='partner_id.email', inherited=True)
def on_change_login(self, cr, uid, ids, login, context=None):
if login and tools.single_email_re.match(login):
return {'value': {'email': login}}
return {}
def onchange_state(self, cr, uid, ids, state_id, context=None):
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool.get('res.partner').onchange_state(cr, uid, partner_ids, state_id, context=context)
def onchange_type(self, cr, uid, ids, is_company, context=None):
""" Wrapper on the user.partner onchange_type, because some calls to the
partner form view applied to the user may trigger the
partner.onchange_type method, but applied to the user object.
"""
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool['res.partner'].onchange_type(cr, uid, partner_ids, is_company, context=context)
def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
""" Wrapper on the user.partner onchange_address, because some calls to the
partner form view applied to the user may trigger the
partner.onchange_type method, but applied to the user object.
"""
partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context=context)]
return self.pool['res.partner'].onchange_address(cr, uid, partner_ids, use_parent_address, parent_id, context=context)
def _check_company(self, cr, uid, ids, context=None):
return all(((this.company_id in this.company_ids) or not this.company_ids) for this in self.browse(cr, uid, ids, context))
_constraints = [
(_check_company, 'The chosen company is not in the allowed companies for this user', ['company_id', 'company_ids']),
]
_sql_constraints = [
('login_key', 'UNIQUE (login)', 'You can not have two users with the same login !')
]
def _get_company(self,cr, uid, context=None, uid2=False):
if not uid2:
uid2 = uid
# Use read() to compute default company, and pass load=_classic_write to
# avoid useless name_get() calls. This will avoid prefetching fields
# while computing default values for new db columns, as the
# db backend may not be fully initialized yet.
user_data = self.pool['res.users'].read(cr, uid, uid2, ['company_id'],
context=context, load='_classic_write')
comp_id = user_data['company_id']
return comp_id or False
def _get_companies(self, cr, uid, context=None):
c = self._get_company(cr, uid, context)
if c:
return [c]
return False
def _get_group(self,cr, uid, context=None):
dataobj = self.pool.get('ir.model.data')
result = []
try:
dummy,group_id = dataobj.get_object_reference(cr, SUPERUSER_ID, 'base', 'group_user')
result.append(group_id)
dummy,group_id = dataobj.get_object_reference(cr, SUPERUSER_ID, 'base', 'group_partner_manager')
result.append(group_id)
except ValueError:
# If these groups does not exists anymore
pass
return result
def _get_default_image(self, cr, uid, context=None):
return self.pool['res.partner']._get_default_image(cr, uid, False, colorize=True, context=context)
_defaults = {
'password': '',
'active': True,
'customer': False,
'company_id': _get_company,
'company_ids': _get_companies,
'groups_id': _get_group,
'image': _get_default_image,
}
# User can write on a few of his own fields (but not his groups for example)
SELF_WRITEABLE_FIELDS = ['password', 'signature', 'action_id', 'company_id', 'email', 'name', 'image', 'image_medium', 'image_small', 'lang', 'tz']
# User can read a few of his own fields
SELF_READABLE_FIELDS = ['signature', 'company_id', 'login', 'email', 'name', 'image', 'image_medium', 'image_small', 'lang', 'tz', 'tz_offset', 'groups_id', 'partner_id', '__last_update']
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
def override_password(o):
if 'password' in o and ('id' not in o or o['id'] != uid):
o['password'] = '********'
return o
if fields and (ids == [uid] or ids == uid):
for key in fields:
if not (key in self.SELF_READABLE_FIELDS or key.startswith('context_')):
break
else:
# safe fields only, so we read as super-user to bypass access rights
uid = SUPERUSER_ID
result = super(res_users, self).read(cr, uid, ids, fields=fields, context=context, load=load)
canwrite = self.pool['ir.model.access'].check(cr, uid, 'res.users', 'write', False)
if not canwrite:
if isinstance(ids, (int, long)):
result = override_password(result)
else:
result = map(override_password, result)
return result
def create(self, cr, uid, vals, context=None):
user_id = super(res_users, self).create(cr, uid, vals, context=context)
user = self.browse(cr, uid, user_id, context=context)
if user.partner_id.company_id:
user.partner_id.write({'company_id': user.company_id.id})
return user_id
def write(self, cr, uid, ids, values, context=None):
if not hasattr(ids, '__iter__'):
ids = [ids]
if ids == [uid]:
for key in values.keys():
if not (key in self.SELF_WRITEABLE_FIELDS or key.startswith('context_')):
break
else:
if 'company_id' in values:
user = self.browse(cr, SUPERUSER_ID, uid, context=context)
if not (values['company_id'] in user.company_ids.ids):
del values['company_id']
uid = 1 # safe fields only, so we write as super-user to bypass access rights
res = super(res_users, self).write(cr, uid, ids, values, context=context)
if 'company_id' in values:
for user in self.browse(cr, uid, ids, context=context):
# if partner is global we keep it that way
if user.partner_id.company_id and user.partner_id.company_id.id != values['company_id']:
user.partner_id.write({'company_id': user.company_id.id})
# clear caches linked to the users
self.pool['ir.model.access'].call_cache_clearing_methods(cr)
clear = partial(self.pool['ir.rule'].clear_cache, cr)
map(clear, ids)
db = cr.dbname
if db in self._uid_cache:
for id in ids:
if id in self._uid_cache[db]:
del self._uid_cache[db][id]
self.context_get.clear_cache(self)
self.has_group.clear_cache(self)
return res
def unlink(self, cr, uid, ids, context=None):
if 1 in ids:
raise osv.except_osv(_('Can not remove root user!'), _('You can not remove the admin user as it is used internally for resources created by Odoo (updates, module installation, ...)'))
db = cr.dbname
if db in self._uid_cache:
for id in ids:
if id in self._uid_cache[db]:
del self._uid_cache[db][id]
return super(res_users, self).unlink(cr, uid, ids, context=context)
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
if not args:
args=[]
if not context:
context={}
ids = []
if name and operator in ['=', 'ilike']:
ids = self.search(cr, user, [('login','=',name)]+ args, limit=limit, context=context)
if not ids:
ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit, context=context)
return self.name_get(cr, user, ids, context=context)
def copy(self, cr, uid, id, default=None, context=None):
user2copy = self.read(cr, uid, [id], ['login','name'])[0]
default = dict(default or {})
if ('name' not in default) and ('partner_id' not in default):
default['name'] = _("%s (copy)") % user2copy['name']
if 'login' not in default:
default['login'] = _("%s (copy)") % user2copy['login']
return super(res_users, self).copy(cr, uid, id, default, context)
@tools.ormcache(skiparg=2)
def context_get(self, cr, uid, context=None):
user = self.browse(cr, SUPERUSER_ID, uid, context)
result = {}
for k in self._fields:
if k.startswith('context_'):
context_key = k[8:]
elif k in ['lang', 'tz']:
context_key = k
else:
context_key = False
if context_key:
res = getattr(user, k) or False
if isinstance(res, models.BaseModel):
res = res.id
result[context_key] = res or False
return result
def action_get(self, cr, uid, context=None):
dataobj = self.pool['ir.model.data']
data_id = dataobj._get_id(cr, SUPERUSER_ID, 'base', 'action_res_users_my')
return dataobj.browse(cr, uid, data_id, context=context).res_id
def check_super(self, passwd):
if passwd == tools.config['admin_passwd']:
return True
else:
raise openerp.exceptions.AccessDenied()
def check_credentials(self, cr, uid, password):
""" Override this method to plug additional authentication methods"""
res = self.search(cr, SUPERUSER_ID, [('id','=',uid),('password','=',password)])
if not res:
raise openerp.exceptions.AccessDenied()
def _login(self, db, login, password):
if not password:
return False
user_id = False
cr = self.pool.cursor()
try:
# autocommit: our single update request will be performed atomically.
# (In this way, there is no opportunity to have two transactions
# interleaving their cr.execute()..cr.commit() calls and have one
# of them rolled back due to a concurrent access.)
cr.autocommit(True)
# check if user exists
res = self.search(cr, SUPERUSER_ID, [('login','=',login)])
if res:
user_id = res[0]
# check credentials
self.check_credentials(cr, user_id, password)
# We effectively unconditionally write the res_users line.
# Even w/ autocommit there's a chance the user row will be locked,
# in which case we can't delay the login just for the purpose of
# update the last login date - hence we use FOR UPDATE NOWAIT to
# try to get the lock - fail-fast
# Failing to acquire the lock on the res_users row probably means
# another request is holding it. No big deal, we don't want to
# prevent/delay login in that case. It will also have been logged
# as a SQL error, if anyone cares.
try:
# NO KEY introduced in PostgreSQL 9.3 http://www.postgresql.org/docs/9.3/static/release-9-3.html#AEN115299
update_clause = 'NO KEY UPDATE' if cr._cnx.server_version >= 90300 else 'UPDATE'
cr.execute("SELECT id FROM res_users WHERE id=%%s FOR %s NOWAIT" % update_clause, (user_id,), log_exceptions=False)
cr.execute("UPDATE res_users SET login_date = now() AT TIME ZONE 'UTC' WHERE id=%s", (user_id,))
self.invalidate_cache(cr, user_id, ['login_date'], [user_id])
except Exception:
_logger.debug("Failed to update last_login for db:%s login:%s", db, login, exc_info=True)
except openerp.exceptions.AccessDenied:
_logger.info("Login failed for db:%s login:%s", db, login)
user_id = False
finally:
cr.close()
return user_id
def authenticate(self, db, login, password, user_agent_env):
"""Verifies and returns the user ID corresponding to the given
``login`` and ``password`` combination, or False if there was
no matching user.
:param str db: the database on which user is trying to authenticate
:param str login: username
:param str password: user password
:param dict user_agent_env: environment dictionary describing any
relevant environment attributes
"""
uid = self._login(db, login, password)
if uid == openerp.SUPERUSER_ID:
# Successfully logged in as admin!
# Attempt to guess the web base url...
if user_agent_env and user_agent_env.get('base_location'):
cr = self.pool.cursor()
try:
base = user_agent_env['base_location']
ICP = self.pool['ir.config_parameter']
if not ICP.get_param(cr, uid, 'web.base.url.freeze'):
ICP.set_param(cr, uid, 'web.base.url', base)
cr.commit()
except Exception:
_logger.exception("Failed to update web.base.url configuration parameter")
finally:
cr.close()
return uid
def check(self, db, uid, passwd):
"""Verifies that the given (uid, password) is authorized for the database ``db`` and
raise an exception if it is not."""
if not passwd:
# empty passwords disallowed for obvious security reasons
raise openerp.exceptions.AccessDenied()
if self._uid_cache.get(db, {}).get(uid) == passwd:
return
cr = self.pool.cursor()
try:
self.check_credentials(cr, uid, passwd)
if self._uid_cache.has_key(db):
self._uid_cache[db][uid] = passwd
else:
self._uid_cache[db] = {uid:passwd}
finally:
cr.close()
def change_password(self, cr, uid, old_passwd, new_passwd, context=None):
"""Change current user password. Old password must be provided explicitly
to prevent hijacking an existing user session, or for cases where the cleartext
password is not used to authenticate requests.
:return: True
:raise: openerp.exceptions.AccessDenied when old password is wrong
:raise: except_osv when new password is not set or empty
"""
self.check(cr.dbname, uid, old_passwd)
if new_passwd:
return self.write(cr, uid, uid, {'password': new_passwd})
raise osv.except_osv(_('Warning!'), _("Setting empty passwords is not allowed for security reasons!"))
def preference_save(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.client',
'tag': 'reload_context',
}
def preference_change_password(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.client',
'tag': 'change_password',
'target': 'new',
}
@tools.ormcache(skiparg=2)
def has_group(self, cr, uid, group_ext_id):
"""Checks whether user belongs to given group.
:param str group_ext_id: external ID (XML ID) of the group.
Must be provided in fully-qualified form (``module.ext_id``), as there
is no implicit module to use..
:return: True if the current user is a member of the group with the
given external ID (XML ID), else False.
"""
assert group_ext_id and '.' in group_ext_id, "External ID must be fully qualified"
module, ext_id = group_ext_id.split('.')
cr.execute("""SELECT 1 FROM res_groups_users_rel WHERE uid=%s AND gid IN
(SELECT res_id FROM ir_model_data WHERE module=%s AND name=%s)""",
(uid, module, ext_id))
return bool(cr.fetchone())
#----------------------------------------------------------
# Implied groups
#
# Extension of res.groups and res.users with a relation for "implied"
# or "inherited" groups. Once a user belongs to a group, it
# automatically belongs to the implied groups (transitively).
#----------------------------------------------------------
class cset(object):
""" A cset (constrained set) is a set of elements that may be constrained to
be a subset of other csets. Elements added to a cset are automatically
added to its supersets. Cycles in the subset constraints are supported.
"""
def __init__(self, xs):
self.supersets = set()
self.elements = set(xs)
def subsetof(self, other):
if other is not self:
self.supersets.add(other)
other.update(self.elements)
def update(self, xs):
xs = set(xs) - self.elements
if xs: # xs will eventually be empty in case of a cycle
self.elements.update(xs)
for s in self.supersets:
s.update(xs)
def __iter__(self):
return iter(self.elements)
concat = itertools.chain.from_iterable
class groups_implied(osv.osv):
_inherit = 'res.groups'
def _get_trans_implied(self, cr, uid, ids, field, arg, context=None):
"computes the transitive closure of relation implied_ids"
memo = {} # use a memo for performance and cycle avoidance
def computed_set(g):
if g not in memo:
memo[g] = cset(g.implied_ids)
for h in g.implied_ids:
computed_set(h).subsetof(memo[g])
return memo[g]
res = {}
for g in self.browse(cr, SUPERUSER_ID, ids, context):
res[g.id] = map(int, computed_set(g))
return res
_columns = {
'implied_ids': fields.many2many('res.groups', 'res_groups_implied_rel', 'gid', 'hid',
string='Inherits', help='Users of this group automatically inherit those groups'),
'trans_implied_ids': fields.function(_get_trans_implied,
type='many2many', relation='res.groups', string='Transitively inherits'),
}
def create(self, cr, uid, values, context=None):
users = values.pop('users', None)
gid = super(groups_implied, self).create(cr, uid, values, context)
if users:
# delegate addition of users to add implied groups
self.write(cr, uid, [gid], {'users': users}, context)
return gid
def write(self, cr, uid, ids, values, context=None):
res = super(groups_implied, self).write(cr, uid, ids, values, context)
if values.get('users') or values.get('implied_ids'):
# add all implied groups (to all users of each group)
for g in self.browse(cr, uid, ids, context=context):
gids = map(int, g.trans_implied_ids)
vals = {'users': [(4, u.id) for u in g.users]}
super(groups_implied, self).write(cr, uid, gids, vals, context)
return res
class users_implied(osv.osv):
_inherit = 'res.users'
def create(self, cr, uid, values, context=None):
groups = values.pop('groups_id', None)
user_id = super(users_implied, self).create(cr, uid, values, context)
if groups:
# delegate addition of groups to add implied groups
self.write(cr, uid, [user_id], {'groups_id': groups}, context)
self.pool['ir.ui.view'].clear_cache()
return user_id
def write(self, cr, uid, ids, values, context=None):
if not isinstance(ids,list):
ids = [ids]
res = super(users_implied, self).write(cr, uid, ids, values, context)
if values.get('groups_id'):
# add implied groups for all users
for user in self.browse(cr, uid, ids):
gs = set(concat(g.trans_implied_ids for g in user.groups_id))
vals = {'groups_id': [(4, g.id) for g in gs]}
super(users_implied, self).write(cr, uid, [user.id], vals, context)
self.pool['ir.ui.view'].clear_cache()
return res
#----------------------------------------------------------
# Vitrual checkbox and selection for res.user form view
#
# Extension of res.groups and res.users for the special groups view in the users
# form. This extension presents groups with selection and boolean widgets:
# - Groups are shown by application, with boolean and/or selection fields.
# Selection fields typically defines a role "Name" for the given application.
# - Uncategorized groups are presented as boolean fields and grouped in a
# section "Others".
#
# The user form view is modified by an inherited view (base.user_groups_view);
# the inherited view replaces the field 'groups_id' by a set of reified group
# fields (boolean or selection fields). The arch of that view is regenerated
# each time groups are changed.
#
# Naming conventions for reified groups fields:
# - boolean field 'in_group_ID' is True iff
# ID is in 'groups_id'
# - selection field 'sel_groups_ID1_..._IDk' is ID iff
# ID is in 'groups_id' and ID is maximal in the set {ID1, ..., IDk}
#----------------------------------------------------------
def name_boolean_group(id):
return 'in_group_' + str(id)
def name_selection_groups(ids):
return 'sel_groups_' + '_'.join(map(str, ids))
def is_boolean_group(name):
return name.startswith('in_group_')
def is_selection_groups(name):
return name.startswith('sel_groups_')
def is_reified_group(name):
return is_boolean_group(name) or is_selection_groups(name)
def get_boolean_group(name):
return int(name[9:])
def get_selection_groups(name):
return map(int, name[11:].split('_'))
def partition(f, xs):
"return a pair equivalent to (filter(f, xs), filter(lambda x: not f(x), xs))"
yes, nos = [], []
for x in xs:
(yes if f(x) else nos).append(x)
return yes, nos
def parse_m2m(commands):
"return a list of ids corresponding to a many2many value"
ids = []
for command in commands:
if isinstance(command, (tuple, list)):
if command[0] in (1, 4):
ids.append(command[2])
elif command[0] == 5:
ids = []
elif command[0] == 6:
ids = list(command[2])
else:
ids.append(command)
return ids
class groups_view(osv.osv):
_inherit = 'res.groups'
def create(self, cr, uid, values, context=None):
res = super(groups_view, self).create(cr, uid, values, context)
self.update_user_groups_view(cr, uid, context)
return res
def write(self, cr, uid, ids, values, context=None):
res = super(groups_view, self).write(cr, uid, ids, values, context)
self.update_user_groups_view(cr, uid, context)
return res
def unlink(self, cr, uid, ids, context=None):
res = super(groups_view, self).unlink(cr, uid, ids, context)
self.update_user_groups_view(cr, uid, context)
return res
def update_user_groups_view(self, cr, uid, context=None):
# the view with id 'base.user_groups_view' inherits the user form view,
# and introduces the reified group fields
# we have to try-catch this, because at first init the view does not exist
# but we are already creating some basic groups
view = self.pool['ir.model.data'].xmlid_to_object(cr, SUPERUSER_ID, 'base.user_groups_view', context=context)
if view and view.exists() and view._name == 'ir.ui.view':
xml1, xml2 = [], []
xml1.append(E.separator(string=_('Application'), colspan="4"))
for app, kind, gs in self.get_groups_by_application(cr, uid, context):
# hide groups in category 'Hidden' (except to group_no_one)
attrs = {'groups': 'base.group_no_one'} if app and app.xml_id == 'base.module_category_hidden' else {}
if kind == 'selection':
# application name with a selection field
field_name = name_selection_groups(map(int, gs))
xml1.append(E.field(name=field_name, **attrs))
xml1.append(E.newline())
else:
# application separator with boolean fields
app_name = app and app.name or _('Other')
xml2.append(E.separator(string=app_name, colspan="4", **attrs))
for g in gs:
field_name = name_boolean_group(g.id)
xml2.append(E.field(name=field_name, **attrs))
xml = E.field(*(xml1 + xml2), name="groups_id", position="replace")
xml.addprevious(etree.Comment("GENERATED AUTOMATICALLY BY GROUPS"))
xml_content = etree.tostring(xml, pretty_print=True, xml_declaration=True, encoding="utf-8")
view.write({'arch': xml_content})
return True
def get_application_groups(self, cr, uid, domain=None, context=None):
return self.search(cr, uid, domain or [])
def get_groups_by_application(self, cr, uid, context=None):
""" return all groups classified by application (module category), as a list of pairs:
[(app, kind, [group, ...]), ...],
where app and group are browse records, and kind is either 'boolean' or 'selection'.
Applications are given in sequence order. If kind is 'selection', the groups are
given in reverse implication order.
"""
def linearized(gs):
gs = set(gs)
# determine sequence order: a group should appear after its implied groups
order = dict.fromkeys(gs, 0)
for g in gs:
for h in gs.intersection(g.trans_implied_ids):
order[h] -= 1
# check whether order is total, i.e., sequence orders are distinct
if len(set(order.itervalues())) == len(gs):
return sorted(gs, key=lambda g: order[g])
return None
# classify all groups by application
gids = self.get_application_groups(cr, uid, context=context)
by_app, others = {}, []
for g in self.browse(cr, uid, gids, context):
if g.category_id:
by_app.setdefault(g.category_id, []).append(g)
else:
others.append(g)
# build the result
res = []
apps = sorted(by_app.iterkeys(), key=lambda a: a.sequence or 0)
for app in apps:
gs = linearized(by_app[app])
if gs:
res.append((app, 'selection', gs))
else:
res.append((app, 'boolean', by_app[app]))
if others:
res.append((False, 'boolean', others))
return res
class users_view(osv.osv):
_inherit = 'res.users'
def create(self, cr, uid, values, context=None):
values = self._remove_reified_groups(values)
return super(users_view, self).create(cr, uid, values, context)
def write(self, cr, uid, ids, values, context=None):
values = self._remove_reified_groups(values)
return super(users_view, self).write(cr, uid, ids, values, context)
def _remove_reified_groups(self, values):
""" return `values` without reified group fields """
add, rem = [], []
values1 = {}
for key, val in values.iteritems():
if is_boolean_group(key):
(add if val else rem).append(get_boolean_group(key))
elif is_selection_groups(key):
rem += get_selection_groups(key)
if val:
add.append(val)
else:
values1[key] = val
if 'groups_id' not in values and (add or rem):
# remove group ids in `rem` and add group ids in `add`
values1['groups_id'] = zip(repeat(3), rem) + zip(repeat(4), add)
return values1
def default_get(self, cr, uid, fields, context=None):
group_fields, fields = partition(is_reified_group, fields)
fields1 = (fields + ['groups_id']) if group_fields else fields
values = super(users_view, self).default_get(cr, uid, fields1, context)
self._add_reified_groups(group_fields, values)
# add "default_groups_ref" inside the context to set default value for group_id with xml values
if 'groups_id' in fields and isinstance(context.get("default_groups_ref"), list):
groups = []
ir_model_data = self.pool.get('ir.model.data')
for group_xml_id in context["default_groups_ref"]:
group_split = group_xml_id.split('.')
if len(group_split) != 2:
raise osv.except_osv(_('Invalid context value'), _('Invalid context default_groups_ref value (model.name_id) : "%s"') % group_xml_id)
try:
temp, group_id = ir_model_data.get_object_reference(cr, uid, group_split[0], group_split[1])
except ValueError:
group_id = False
groups += [group_id]
values['groups_id'] = groups
return values
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
# determine whether reified groups fields are required, and which ones
fields1 = fields or self.fields_get(cr, uid, context=context).keys()
group_fields, other_fields = partition(is_reified_group, fields1)
<|fim▁hole|> other_fields.append('groups_id')
drop_groups_id = True
else:
other_fields = fields
res = super(users_view, self).read(cr, uid, ids, other_fields, context=context, load=load)
# post-process result to add reified group fields
if group_fields:
for values in (res if isinstance(res, list) else [res]):
self._add_reified_groups(group_fields, values)
if drop_groups_id:
values.pop('groups_id', None)
return res
def _add_reified_groups(self, fields, values):
""" add the given reified group fields into `values` """
gids = set(parse_m2m(values.get('groups_id') or []))
for f in fields:
if is_boolean_group(f):
values[f] = get_boolean_group(f) in gids
elif is_selection_groups(f):
selected = [gid for gid in get_selection_groups(f) if gid in gids]
values[f] = selected and selected[-1] or False
def fields_get(self, cr, uid, allfields=None, context=None, write_access=True):
res = super(users_view, self).fields_get(cr, uid, allfields, context, write_access)
# add reified groups fields
for app, kind, gs in self.pool['res.groups'].get_groups_by_application(cr, uid, context):
if kind == 'selection':
# selection group field
tips = ['%s: %s' % (g.name, g.comment) for g in gs if g.comment]
res[name_selection_groups(map(int, gs))] = {
'type': 'selection',
'string': app and app.name or _('Other'),
'selection': [(False, '')] + [(g.id, g.name) for g in gs],
'help': '\n'.join(tips),
'exportable': False,
'selectable': False,
}
else:
# boolean group fields
for g in gs:
res[name_boolean_group(g.id)] = {
'type': 'boolean',
'string': g.name,
'help': g.comment,
'exportable': False,
'selectable': False,
}
return res
#----------------------------------------------------------
# change password wizard
#----------------------------------------------------------
class change_password_wizard(osv.TransientModel):
"""
A wizard to manage the change of users' passwords
"""
_name = "change.password.wizard"
_description = "Change Password Wizard"
_columns = {
'user_ids': fields.one2many('change.password.user', 'wizard_id', string='Users'),
}
def _default_user_ids(self, cr, uid, context=None):
if context is None:
context = {}
user_model = self.pool['res.users']
user_ids = context.get('active_model') == 'res.users' and context.get('active_ids') or []
return [
(0, 0, {'user_id': user.id, 'user_login': user.login})
for user in user_model.browse(cr, uid, user_ids, context=context)
]
_defaults = {
'user_ids': _default_user_ids,
}
def change_password_button(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids, context=context)[0]
need_reload = any(uid == user.user_id.id for user in wizard.user_ids)
line_ids = [user.id for user in wizard.user_ids]
self.pool.get('change.password.user').change_password_button(cr, uid, line_ids, context=context)
if need_reload:
return {
'type': 'ir.actions.client',
'tag': 'reload'
}
return {'type': 'ir.actions.act_window_close'}
class change_password_user(osv.TransientModel):
"""
A model to configure users in the change password wizard
"""
_name = 'change.password.user'
_description = 'Change Password Wizard User'
_columns = {
'wizard_id': fields.many2one('change.password.wizard', string='Wizard', required=True),
'user_id': fields.many2one('res.users', string='User', required=True),
'user_login': fields.char('User Login', readonly=True),
'new_passwd': fields.char('New Password'),
}
_defaults = {
'new_passwd': '',
}
def change_password_button(self, cr, uid, ids, context=None):
for line in self.browse(cr, uid, ids, context=context):
line.user_id.write({'password': line.new_passwd})
# don't keep temporary passwords in the database longer than necessary
self.write(cr, uid, ids, {'new_passwd': False}, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|>
|
# read regular fields (other_fields); add 'groups_id' if necessary
drop_groups_id = False
if group_fields and fields:
if 'groups_id' not in other_fields:
|
<|file_name|>Class_914.java<|end_file_name|><|fim▁begin|>package fr.javatronic.blog.massive.annotation1;<|fim▁hole|>
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_914 {
}<|fim▁end|>
| |
<|file_name|>SSHGEComputingElement.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File : SSHGEComputingElement.py
# Author : A.T. V.H.
########################################################################
""" Grid Engine Computing Element with remote job submission via ssh/scp and using site
shared area for the job proxy placement
"""
__RCSID__ = "092c1d9 (2011-06-02 15:20:46 +0200) atsareg <[email protected]>"
from DIRAC.Resources.Computing.SSHComputingElement import SSHComputingElement
from DIRAC.Core.Utilities.Pfn import pfnparse <|fim▁hole|>from DIRAC import S_OK
CE_NAME = 'SSHGE'
MANDATORY_PARAMETERS = [ 'Queue' ]
class SSHGEComputingElement( SSHComputingElement ):
""" The SUN Grid Engine interfacr
"""
#############################################################################
def __init__( self, ceUniqueID ):
""" Standard constructor.
"""
SSHComputingElement.__init__( self, ceUniqueID )
self.ceType = CE_NAME
self.controlScript = 'sgece'
self.mandatoryParameters = MANDATORY_PARAMETERS
def _getJobOutputFiles( self, jobID ):
""" Get output file names for the specific CE
"""
result = pfnparse( jobID )
if not result['OK']:
return result
jobStamp = result['Value']['FileName']
host = result['Value']['Host']
output = '%s/DIRACPilot.o%s' % ( self.batchOutput, jobStamp )
error = '%s/DIRACPilot.e%s' % ( self.batchError, jobStamp )
return S_OK( (jobStamp, host, output, error) )
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#<|fim▁end|>
| |
<|file_name|>38.rs<|end_file_name|><|fim▁begin|>#[derive(Debug)]
struct Structure(i32);
#[derive(Debug)]
struct Deep(Structure);<|fim▁hole|>
fn main() {
println!("{:?} months in a year.", 12);
println!("{1:?} {0:?} is the {actor:?} name.",
"Slater",
"Christian",
actor="actor's");
println!("Now {:?} will print!", Structure(3));
println!("Now {:?} will print!", Deep(Structure(7)));
}<|fim▁end|>
| |
<|file_name|>header.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use common;
use common::config;
pub struct TestProps {
// Lines that should be expected, in order, on standard out
error_patterns: ~[~str],
// Extra flags to pass to the compiler
compile_flags: Option<~str>,
// If present, the name of a file that this test should match when
// pretty-printed
pp_exact: Option<Path>,
// Modules from aux directory that should be compiled
aux_builds: ~[~str],
// Environment settings to use during execution
exec_env: ~[(~str,~str)],
// Commands to be given to the debugger, when testing debug info
debugger_cmds: ~[~str],
// Lines to check if they appear in the expected debugger output
check_lines: ~[~str],
}
// Load any test directives embedded in the file
pub fn load_props(testfile: &Path) -> TestProps {
let mut error_patterns = ~[];
let mut aux_builds = ~[];
let mut exec_env = ~[];
let mut compile_flags = None;
let mut pp_exact = None;
let mut debugger_cmds = ~[];
let mut check_lines = ~[];
for iter_header(testfile) |ln| {
match parse_error_pattern(ln) {
Some(ep) => error_patterns.push(ep),
None => ()
};
if compile_flags.is_none() {
compile_flags = parse_compile_flags(ln);
}
<|fim▁hole|>
match parse_aux_build(ln) {
Some(ab) => { aux_builds.push(ab); }
None => {}
}
match parse_exec_env(ln) {
Some(ee) => { exec_env.push(ee); }
None => {}
}
match parse_debugger_cmd(ln) {
Some(dc) => debugger_cmds.push(dc),
None => ()
};
match parse_check_line(ln) {
Some(cl) => check_lines.push(cl),
None => ()
};
};
return TestProps {
error_patterns: error_patterns,
compile_flags: compile_flags,
pp_exact: pp_exact,
aux_builds: aux_builds,
exec_env: exec_env,
debugger_cmds: debugger_cmds,
check_lines: check_lines
};
}
pub fn is_test_ignored(config: &config, testfile: &Path) -> bool {
for iter_header(testfile) |ln| {
if parse_name_directive(ln, ~"xfail-test") { return true; }
if parse_name_directive(ln, xfail_target()) { return true; }
if config.mode == common::mode_pretty &&
parse_name_directive(ln, ~"xfail-pretty") { return true; }
};
return false;
fn xfail_target() -> ~str {
~"xfail-" + str::to_owned(os::SYSNAME)
}
}
fn iter_header(testfile: &Path, it: &fn(~str) -> bool) -> bool {
let rdr = io::file_reader(testfile).get();
while !rdr.eof() {
let ln = rdr.read_line();
// Assume that any directives will be found before the first
// module or function. This doesn't seem to be an optimization
// with a warm page cache. Maybe with a cold one.
if str::starts_with(ln, ~"fn")
|| str::starts_with(ln, ~"mod") {
return false;
} else { if !(it(ln)) { return false; } }
}
return true;
}
fn parse_error_pattern(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"error-pattern")
}
fn parse_aux_build(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"aux-build")
}
fn parse_compile_flags(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"compile-flags")
}
fn parse_debugger_cmd(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"debugger")
}
fn parse_check_line(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"check")
}
fn parse_exec_env(line: &str) -> Option<(~str, ~str)> {
do parse_name_value_directive(line, ~"exec-env").map |nv| {
// nv is either FOO or FOO=BAR
let mut strs = ~[];
for str::each_splitn_char(*nv, '=', 1u) |s| { strs.push(s.to_owned()); }
match strs.len() {
1u => (strs.pop(), ~""),
2u => {
let end = strs.pop();
(strs.pop(), end)
}
n => fail!("Expected 1 or 2 strings, not %u", n)
}
}
}
fn parse_pp_exact(line: &str, testfile: &Path) -> Option<Path> {
match parse_name_value_directive(line, ~"pp-exact") {
Some(s) => Some(Path(s)),
None => {
if parse_name_directive(line, "pp-exact") {
Some(testfile.file_path())
} else {
None
}
}
}
}
fn parse_name_directive(line: &str, directive: &str) -> bool {
str::contains(line, directive)
}
fn parse_name_value_directive(line: &str,
directive: ~str) -> Option<~str> {
let keycolon = directive + ~":";
match str::find_str(line, keycolon) {
Some(colon) => {
let value = str::slice(line, colon + str::len(keycolon),
str::len(line)).to_owned();
debug!("%s: %s", directive, value);
Some(value)
}
None => None
}
}<|fim▁end|>
|
if pp_exact.is_none() {
pp_exact = parse_pp_exact(ln, testfile);
}
|
<|file_name|>scanner.rs<|end_file_name|><|fim▁begin|>use std::fmt;
use std::iter::{FusedIterator, IntoIterator};
use std::mem;
use std::sync::Arc;
use std::time::{Duration, Instant};
use bytes::{Bytes, BytesMut};
use futures::{Async, Future, Poll, Stream};
use krpc::Proxy;
use vec_map::{self, VecMap};
use backoff::Backoff;
use meta_cache::{Entry, Lookup, TableLocations};
use pb::tserver::{NewScanRequestPb, ScanRequestPb, ScanResponsePb, TabletServerService};
use pb::{ColumnPredicatePb, ColumnSchemaPb, ExpectField, RowwiseRowBlockPb};
use replica::{ReplicaRpc, Selection, Speculation};
use tablet::Tablet;
use Column;
use ColumnSelector;
use Error;
use Filter;
use Result;
use Row;
use ScannerId;
use Schema;
use TabletId;
#[derive(Clone)]
pub struct ScanBuilder {
table_schema: Schema,
table_locations: TableLocations,
projected_columns: Vec<usize>,
filters: VecMap<Filter>,
}
fn column_to_pb(column: &Column) -> ColumnSchemaPb {
ColumnSchemaPb {
name: column.name().to_owned(),
type_: column.data_type().to_pb(),
is_nullable: Some(column.is_nullable()),
..Default::default()
}
}
impl ScanBuilder {
pub(crate) fn new(table_schema: Schema, table_locations: TableLocations) -> ScanBuilder {
let num_columns = table_schema.columns().len();
let projected_columns = (0..num_columns).collect::<Vec<_>>();
ScanBuilder {
table_schema,
table_locations,
projected_columns,
filters: VecMap::new(),
}
}
pub fn select<I, C>(mut self, projected_columns: I) -> Result<ScanBuilder>
where
I: IntoIterator<Item = C>,
C: ColumnSelector,
{
self.projected_columns.clear();
for column_selector in projected_columns {
self.projected_columns
.push(column_selector.column_index(&self.table_schema)?);
}
Ok(self)
}
pub fn count(mut self) -> ScanBuilder {
self.projected_columns.clear();
self
}
/// Apply a filter to the scan.
///
/// When multiple filters are applied to the scan they combine conjunctively, i.e. using `AND`.
pub fn filter<C>(mut self, column: C, filter: Filter) -> Result<ScanBuilder>
where
C: ColumnSelector,
{
let idx = column.column_index(&self.table_schema)?;
let column = &self.table_schema.columns()[idx];
filter.check_type(column)?;
match self.filters.entry(idx) {
vec_map::Entry::Occupied(mut occupied) => {
let existing = mem::replace(occupied.get_mut(), Filter::none());
occupied.insert(existing.and(filter));
}
vec_map::Entry::Vacant(vacant) => {
vacant.insert(filter);
}
}
Ok(self)
}
pub fn build(self) -> Scan {
let ScanBuilder {
table_schema,
table_locations,
projected_columns,
filters,
} = self;
let mut columns = Vec::new();
for idx in projected_columns {
columns.push(table_schema.columns()[idx].clone());
}
let projected_schema = Schema::new(columns, 0);
let mut short_circuit = false;
let mut predicates = Vec::with_capacity(filters.len());
for (idx, filter) in filters {
if filter == Filter::None {
short_circuit = true;
} else if filter != Filter::All {
predicates.push(filter.into_pb(&table_schema.columns()[idx]));
}
}
let state = if short_circuit {
ScannerState::Finished
} else {
ScannerState::Lookup(table_locations.entry(&[]))
};
Scan {
projected_schema,
predicates,
table_locations,
state,
}
}
}
pub struct Scan {
projected_schema: Schema,
predicates: Vec<ColumnPredicatePb>,
table_locations: TableLocations,
state: ScannerState,
}
enum ScannerState {
Lookup(Lookup<Entry>),
Scan {
tablet: Arc<Tablet>,
tablet_scan: TabletScan,
},
Finished,
}
impl Scan {
fn new_scan_request(&self, tablet: TabletId) -> NewScanRequestPb {
NewScanRequestPb {
tablet_id: tablet.to_string().into_bytes(),
projected_columns: self
.projected_schema
.columns()
.iter()
.map(column_to_pb)
.collect(),
column_predicates: self.predicates.clone(),
..Default::default()
}
}
pub fn projected_schema(&self) -> &Schema {
&self.projected_schema
}
}
impl Stream for Scan {
type Item = RowBatch;
type Error = Error;
fn poll(&mut self) -> Poll<Option<RowBatch>, Error> {
trace!("Scan::poll");
loop {
match mem::replace(&mut self.state, ScannerState::Finished) {
ScannerState::Lookup(mut lookup) => match lookup.poll()? {
Async::Ready(Entry::Tablet(tablet)) => {
let tablet_scan = TabletScan::new(
self.projected_schema.clone(),
tablet.clone(),
self.new_scan_request(tablet.id()),
);
self.state = ScannerState::Scan {
tablet,
tablet_scan,
};
}
Async::Ready(Entry::NonCoveredRange { upper_bound, .. }) => {
if !upper_bound.is_empty() {
let lookup = self.table_locations.entry(&upper_bound);<|fim▁hole|> }
Async::NotReady => {
self.state = ScannerState::Lookup(lookup);
return Ok(Async::NotReady);
}
},
ScannerState::Scan {
tablet,
mut tablet_scan,
} => match tablet_scan.poll()? {
Async::Ready(Some(batch)) => {
self.state = ScannerState::Scan {
tablet,
tablet_scan,
};
return Ok(Async::Ready(Some(batch)));
}
Async::Ready(None) => if !tablet.upper_bound().is_empty() {
let lookup = self.table_locations.entry(tablet.upper_bound());
self.state = ScannerState::Lookup(lookup);
},
Async::NotReady => {
self.state = ScannerState::Scan {
tablet,
tablet_scan,
};
return Ok(Async::NotReady);
}
},
ScannerState::Finished => return Ok(Async::Ready(None)),
}
}
}
}
impl fmt::Debug for Scan {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Scan").finish()
}
}
pub struct RowBatch {
projected_schema: Schema,
len: usize,
data: Bytes,
_indirect_data: Bytes,
}
impl RowBatch {
fn new(
projected_schema: Schema,
block: &RowwiseRowBlockPb,
mut sidecars: Vec<BytesMut>,
) -> Result<RowBatch> {
trace!(
"RowBatch::new; block: {:?}, sidecars: {:?}",
block,
sidecars
);
let mut data = match block.rows_sidecar {
Some(idx) if idx < 0 => {
return Err(Error::Serialization(
"RowwiseRowBlockPb.row_sidecar is negative".to_string(),
))
}
Some(idx) => match sidecars.get_mut(idx as usize) {
Some(sidecar) => mem::replace(sidecar, BytesMut::new()),
None => {
return Err(Error::Serialization(
"ScanResponsePb does not include a row sidecar".to_string(),
))
}
},
None => {
return Err(Error::Serialization(
"RowwiseRowBlockPb does not include a row sidecar".to_string(),
))
}
};
let indirect_data = match block.indirect_data_sidecar {
Some(idx) if idx < 0 => {
return Err(Error::Serialization(
"RowwiseRowBlockPb.indirect_data_sidecar is negative".to_string(),
))
}
Some(idx) => match sidecars.get_mut(idx as usize) {
Some(sidecar) => mem::replace(sidecar, BytesMut::new()).freeze(),
None => {
return Err(Error::Serialization(
"ScanResponsePb does not include an indirect data sidecar".to_string(),
))
}
},
None => Bytes::new(),
};
let row_len = projected_schema.row_len()
+ projected_schema.has_nullable_columns() as usize * projected_schema.bitmap_len();
// Sanity check that the data length matches the number of rows returned.
let num_rows = block.num_rows() as usize;
match num_rows.checked_mul(row_len) {
Some(len) if len == data.len() => (),
Some(_) => {
return Err(Error::Serialization(format!(
"RowwiseRowBlockPb.num_rows does not match row_sidecar length; \
num_rows: {}, row_sidecar.len: {}, row_len: {}",
num_rows,
data.len(),
row_len
)));
}
None => {
return Err(Error::Serialization(format!(
"RowwiseRowBlockPb.num_rows is invalid: {}",
num_rows
)));
}
}
// Swizzle string and binary column pointers.
if !projected_schema.var_len_column_offsets().is_empty() {
for row in data.chunks_mut(row_len) {
for &offset in projected_schema.var_len_column_offsets() {
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
unsafe {
// TODO: sanity check the value length falls in the indirect data buf.
let ptr = row.as_mut_ptr().offset(offset as isize) as *mut u64;
let offset = ptr.read_unaligned().to_le();
*ptr = ((indirect_data.as_ptr() as u64) + offset).to_le();
}
}
}
}
Ok(RowBatch {
projected_schema,
len: block.num_rows() as usize,
data: data.freeze(),
_indirect_data: indirect_data,
})
}
pub fn num_rows(&self) -> usize {
self.len
}
pub fn projected_schema(&self) -> &Schema {
&self.projected_schema
}
}
impl<'a> IntoIterator for &'a RowBatch {
type Item = Row<'a>;
type IntoIter = RowBatchIter<'a>;
fn into_iter(self) -> RowBatchIter<'a> {
let projected_schema = &self.projected_schema;
let row_len = projected_schema.row_len()
+ projected_schema.has_nullable_columns() as usize * projected_schema.bitmap_len();
let iter = self.data.chunks(row_len);
RowBatchIter {
projected_schema: &self.projected_schema,
iter,
}
}
}
pub struct RowBatchIter<'a> {
projected_schema: &'a Schema,
iter: ::std::slice::Chunks<'a, u8>,
}
impl<'a> Iterator for RowBatchIter<'a> {
type Item = Row<'a>;
fn next(&mut self) -> Option<Row<'a>> {
self.iter
.next()
.map(|data| Row::contiguous(self.projected_schema.clone(), data))
}
}
impl<'a> ExactSizeIterator for RowBatchIter<'a> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl<'a> DoubleEndedIterator for RowBatchIter<'a> {
fn next_back(&mut self) -> Option<Row<'a>> {
self.iter
.next_back()
.map(|data| Row::contiguous(self.projected_schema.clone(), data))
}
}
// TODO: compile-time assert that Chunks is fused.
impl<'a> FusedIterator for RowBatchIter<'a> {}
enum TabletScan {
New {
projected_schema: Schema,
rpc: ReplicaRpc<Arc<Tablet>, ScanRequestPb, ScanResponsePb>,
},
Continue {
projected_schema: Schema,
scanner_id: ScannerId,
call_seq_id: u32,
rpc: ReplicaRpc<Proxy, ScanRequestPb, ScanResponsePb>,
},
Finished,
}
impl TabletScan {
fn new(
projected_schema: Schema,
tablet: Arc<Tablet>,
new_scan_request: NewScanRequestPb,
) -> TabletScan {
debug!("TabletScan::new; tablet: {:?}", &*tablet);
let mut request = ScanRequestPb::default();
request.new_scan_request = Some(new_scan_request);
let call =
TabletServerService::scan(Arc::new(request), Instant::now() + Duration::from_secs(60));
let rpc = ReplicaRpc::new(
tablet,
call,
Speculation::Staggered(Duration::from_millis(100)),
Selection::Closest,
Backoff::default(),
);
TabletScan::New {
projected_schema,
rpc,
}
}
fn cont(
projected_schema: Schema,
scanner_id: ScannerId,
call_seq_id: u32,
proxy: Proxy,
) -> TabletScan {
let mut request = ScanRequestPb::default();
request.scanner_id = Some(scanner_id.to_string().into_bytes());
request.call_seq_id = Some(call_seq_id);
let call =
TabletServerService::scan(Arc::new(request), Instant::now() + Duration::from_secs(60));
let rpc = ReplicaRpc::new(
proxy,
call,
Speculation::Full,
Selection::Closest,
Backoff::default(),
);
TabletScan::Continue {
projected_schema,
scanner_id,
call_seq_id,
rpc,
}
}
}
impl Stream for TabletScan {
type Item = RowBatch;
type Error = Error;
fn poll(&mut self) -> Poll<Option<RowBatch>, Error> {
trace!("TabletScan::poll");
match self {
TabletScan::New {
projected_schema,
rpc,
} => {
let (proxy, mut response, sidecars) = try_ready!(rpc.poll());
let batch = RowBatch::new(
projected_schema.clone(),
&response.data.take().unwrap_or_default(),
sidecars,
)?;
*self = if response.has_more_results() {
let scanner_id = ScannerId::parse_bytes(
&response
.scanner_id
.expect_field("ScanResponsePb", "scanner_id")?,
)?;
// NLL hack: these schema clones are nasty.
TabletScan::cont(projected_schema.clone(), scanner_id, 1, proxy)
} else {
TabletScan::Finished
};
Ok(Async::Ready(Some(batch)))
}
TabletScan::Continue {
projected_schema,
scanner_id,
call_seq_id,
rpc,
} => {
let (proxy, mut response, sidecars) = try_ready!(rpc.poll());
let batch = RowBatch::new(
projected_schema.clone(),
&response.data.take().unwrap_or_default(),
sidecars,
)?;
*self = if response.has_more_results() {
TabletScan::cont(
projected_schema.clone(),
*scanner_id,
*call_seq_id + 1,
proxy,
)
} else {
TabletScan::Finished
};
Ok(Async::Ready(Some(batch)))
}
TabletScan::Finished => Ok(Async::Ready(None)),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use mini_cluster::MiniCluster;
use Client;
use Column;
use DataType;
use Options;
use SchemaBuilder;
use TableBuilder;
use WriterConfig;
use env_logger;
use futures::future;
use tokio::runtime::current_thread::Runtime;
#[test]
fn count() {
let _ = env_logger::try_init();
let mut cluster = MiniCluster::default();
let mut runtime = Runtime::new().unwrap();
let mut client = runtime
.block_on(Client::new(cluster.master_addrs(), Options::default()))
.expect("client");
let schema = SchemaBuilder::new()
.add_column(Column::new("key", DataType::Int32).set_not_null())
.add_column(Column::new("val", DataType::Int32))
.set_primary_key(vec!["key"])
.build()
.unwrap();
let mut table_builder = TableBuilder::new("count", schema.clone());
table_builder.add_hash_partitions(vec!["key"], 4);
table_builder.set_num_replicas(1);
// TODO: don't wait for table creation in order to test retry logic.
let table_id = runtime
.block_on(client.create_table(table_builder))
.unwrap();
let table = runtime.block_on(client.open_table_by_id(table_id)).unwrap();
let mut writer = table.new_writer(WriterConfig::default());
let num_rows = 100i32;
// TODO: remove lazy once apply no longer polls.
runtime
.block_on(future::lazy::<_, Result<()>>(|| {
// Insert a bunch of values
for i in 0..num_rows {
let mut insert = table.schema().new_row();
insert.set("key", i).unwrap();
insert.set("val", i).unwrap();
writer.insert(insert);
}
Ok(())
})).unwrap();
runtime
.block_on(future::poll_fn(|| writer.poll_flush()))
.unwrap();
let scan: Scan = runtime
.block_on(::futures::future::lazy::<_, Result<Scan>>(|| {
Ok(table.scan_builder().count().build())
})).unwrap();
let batches: Vec<RowBatch> = runtime
.block_on(::futures::future::lazy(|| scan.collect()))
.unwrap();
assert_eq!(
num_rows as usize,
batches.into_iter().map(|batch| batch.len).sum()
);
}
#[test]
fn select() {
let _ = env_logger::try_init();
let mut cluster = MiniCluster::default();
let mut runtime = Runtime::new().unwrap();
let mut client = runtime
.block_on(Client::new(cluster.master_addrs(), Options::default()))
.expect("client");
let schema = SchemaBuilder::new()
.add_column(Column::new("key", DataType::Int32).set_not_null())
.add_column(Column::new("val", DataType::Int32))
.set_primary_key(vec!["key"])
.build()
.unwrap();
let mut table_builder = TableBuilder::new("count", schema.clone());
table_builder.add_hash_partitions(vec!["key"], 4);
table_builder.set_num_replicas(1);
// TODO: don't wait for table creation in order to test retry logic.
let table_id = runtime
.block_on(client.create_table(table_builder))
.unwrap();
let table = runtime.block_on(client.open_table_by_id(table_id)).unwrap();
let mut writer = table.new_writer(WriterConfig::default());
let num_rows = 10i32;
// TODO: remove lazy once apply no longer polls.
runtime
.block_on(future::lazy::<_, Result<()>>(|| {
// Insert a bunch of values
for i in 0..num_rows {
let mut insert = table.schema().new_row();
insert.set("key", i).unwrap();
insert.set("val", i).unwrap();
writer.insert(insert);
}
Ok(())
})).unwrap();
runtime
.block_on(future::poll_fn(|| writer.poll_flush()))
.unwrap();
let scan: Scan = runtime
.block_on(::futures::future::lazy::<_, Result<Scan>>(|| {
Ok(table.scan_builder().build())
})).unwrap();
let batches = runtime
.block_on(::futures::future::lazy(|| scan.collect()))
.unwrap();
let mut rows = Vec::new();
for batch in batches {
for row in batch.into_iter() {
rows.push((
row.get::<_, i32>("key").unwrap(),
row.get::<_, i32>("val").unwrap(),
));
}
}
rows.sort();
let expected = (0..num_rows).map(|i| (i, i)).collect::<Vec<_>>();
assert_eq!(rows, expected);
}
#[test]
fn filter() {
let _ = env_logger::try_init();
let mut cluster = MiniCluster::default();
let mut runtime = Runtime::new().unwrap();
let mut client = runtime
.block_on(Client::new(cluster.master_addrs(), Options::default()))
.expect("client");
let schema = SchemaBuilder::new()
.add_column(Column::new("key", DataType::Int32).set_not_null())
.add_column(Column::new("val", DataType::Int32))
.set_primary_key(vec!["key"])
.build()
.unwrap();
let mut table_builder = TableBuilder::new("count", schema.clone());
table_builder.add_hash_partitions(vec!["key"], 4);
table_builder.set_num_replicas(1);
// TODO: don't wait for table creation in order to test retry logic.
let table_id = runtime
.block_on(client.create_table(table_builder))
.unwrap();
let table = runtime.block_on(client.open_table_by_id(table_id)).unwrap();
let mut writer = table.new_writer(WriterConfig::default());
let num_rows = 10i32;
// TODO: remove lazy once apply no longer polls.
runtime
.block_on(future::lazy::<_, Result<()>>(|| {
// Insert a bunch of values
for i in 0..num_rows {
let mut insert = table.schema().new_row();
insert.set("key", i).unwrap();
insert.set("val", i).unwrap();
writer.insert(insert);
}
Ok(())
})).unwrap();
runtime
.block_on(future::poll_fn(|| writer.poll_flush()))
.unwrap();
let scan: Scan = runtime
.block_on(::futures::future::lazy::<_, Result<Scan>>(|| {
Ok(table
.scan_builder()
.filter("key", Filter::range(5i32..))?
.build())
})).unwrap();
let batches = runtime
.block_on(::futures::future::lazy(|| scan.collect()))
.unwrap();
let mut rows = Vec::new();
for batch in batches {
for row in batch.into_iter() {
rows.push((
row.get::<_, i32>("key").unwrap(),
row.get::<_, i32>("val").unwrap(),
));
}
}
rows.sort();
let expected = (0..num_rows)
.filter(|&i| i >= 5)
.map(|i| (i, i))
.collect::<Vec<_>>();
assert_eq!(rows, expected);
}
}<|fim▁end|>
|
self.state = ScannerState::Lookup(lookup);
}
|
<|file_name|>pages.py<|end_file_name|><|fim▁begin|># ############################################################################
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2019 Université catholique de Louvain (http://www.uclouvain.be)
#
# 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.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
# ############################################################################
import pypom
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from features.pages.common import CommonPageMixin
from features.fields.fields import InputField, SelectField, ButtonField
class SearchEntityPage(CommonPageMixin, pypom.Page):
URL_TEMPLATE = '/entities/'
acronym = InputField(By.ID, 'id_acronym')
title = InputField(By.ID, 'id_title')
entity_type = SelectField(By.ID, "id_entity_type")
search = ButtonField(By.ID, "bt_submit_entity_search")
def find_acronym_in_table(self, row: int = 1):
return self.find_element(By.ID, 'td_entity_%d' % row).text
class SearchOrganizationPage(CommonPageMixin, pypom.Page):
URL_TEMPLATE = '/organizations/'
acronym = InputField(By.ID, 'id_acronym')
name = InputField(By.ID, 'id_name')
type = SelectField(By.ID, "id_type")
search = ButtonField(By.ID, "bt_submit_organization_search")
def find_acronym_in_table(self, row: int = 1):
return self.find_element(By.ID, 'td_organization_%d' % row).text
class SearchStudentPage(CommonPageMixin, pypom.Page):
URL_TEMPLATE = '/students/'
registration_id = InputField(By.ID, 'id_registration_id')
name = InputField(By.ID, 'id_name')
search = ButtonField(By.ID, "bt_submit_student_search")
def find_registration_id_in_table(self, row: int = 1):
return self.find_element(By.ID, 'td_student_%d' % row).text
def find_name_in_table(self):
names = []
row = 1
last = False<|fim▁hole|>
row += 1
except NoSuchElementException as e:
return names
return names<|fim▁end|>
|
while not last:
try:
elt = self.find_element(By.ID, 'spn_student_name_%d' % row)
names.append(elt.text)
|
<|file_name|>jsonmaking.py<|end_file_name|><|fim▁begin|>import json, random, time, sys
"""
Creating a random JSON object based on lists of info and random numbers
to assign the index
"""
##Directory
input_file = "test.json"
###Success message takes the file_name and operation type (ie. written, closed)
def process_message(outcome, file_name, operation_type):
print "*******%s File: %s %s *******" % (outcome, file_name, operation_type)
##Open file
try:
open_file=open(input_file, 'w')
print "File opened"
except:
print "Error opening "+input_file
##Random chooser-random number picker function to be used over and over, but needs to be created before called
##To keep everything clean it's listed before the others funtions so that they maybe listed in order of the dictionary keys
def random_chooser(start,end):
return random.randrange(start,end)
<|fim▁hole|>doctors_name=["Dr_K", "Dr. Pepper", "Dr. Lector", "Dr. Seus", "Dr Dre", "Dr. Phill", "Dr. Glass"]
special_notes_list=["No more doctors available for the weekend", "All offices closed for Labor Day", "Offices closed till Monday for Christmas",
"No Dr. on call Saturdays", "No Dr. on call Fridays", "No Dr. on call Mondays", "No Dr. on call Wednesdays" ,"No Dr. on call Tuesdays",
"Office closed for snow"]
dates=["1/17/2013","12/02/2011", "11/08/2012", "4/1/2010", "5/23/2011","1/15/2013","12/02/2010", "12/08/2012", "6/1/2010", "7/23/2011"]
first_name=["Bob", "Peter", "Jim", "Gerry", "Jean", "Robert", "Susan", "Mary", "Jo", "Brian"]
last_name=["Cameron", "Bender", "Neutron", "Simmons", "Jackson", "Smith", "Gardner", "Crocker","Black", "White"]
from_place=["Fort Worth","Plano","Houston","Little Rock","Detroit","Memphis", "Dallas","Arlington","Jenks","Chicago","Tulsa", "Boise", "Desmoins", "Minnieapolis", "St. Louis"]
check_list=["5647","7610","1230","3210","6543","9874","1324","3215","5897","6546","5968","6540"]
content_list=["Nice to see you!", "This is a content message", "This is another content message" ,"This is a test message to verify that the content is coming through",
"This is the content you are looking for","Content is magically here","Some content","Test content for your viewing pleasure",
"This is a test of the call_manager content system","Testing...testing...1...2...3!","Testing...testing...4...5...6!"]
##Keys for the dictionary
messages_info_keys = ["date_and_time", "caller_name", "from", "call_back_number", "call_back_ext", "check_number", "content"]
##Random pick of date from list dates
def date_picker():
picked_date=random_chooser(1,len(dates))
new_date=dates[picked_date]
return new_date
##creates a full name from lists first_name and last_name
def pick_your_name():
first=random_chooser(1,len(first_name))
last=random_chooser(1,10)
combo_name =first_name[first]+" "+last_name[last]
return combo_name
##Random pick of location from list from_place
def random_place():
picked_place=random_chooser(1,len(from_place))
place=from_place[picked_place]
return place
##Random number generator with randint from the random module
def random_number_maker(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return random.randint(range_start, range_end)
##combines a group of random numbers to resemble a phone number
def random_phone_number():
return "%s-%s-%s" %(str(random_number_maker(3)), str(random_number_maker(3)), str(random_number_maker(4)))
##call_back_ext picker, uses random number to generate number
def random_ext():
extension_maker=random_chooser(111,999)
return extension_maker
## not needed using random phone number generator
#call_back=[1,65,3,5,7,88]
##Random check number picker from list check_list
def check():
check_picker=random_chooser(1,10)
check=check_list[check_picker]
#=[1,2,3,5,6,8,98]
return check
##Random content picker from list content_list
def content():
content_picker=random_chooser(1,len(content_list))
content=content_list[content_picker]
return content
##Generates a random number of message items
def messages_list_random_maker():
x=0
lister_maker=[]
while(x<random_chooser(1,20)):
messages_info_values = [date_picker(),pick_your_name(),random_place(),random_phone_number(),random_ext(),check(), content()]
messages_info_list = dict(zip(messages_info_keys, messages_info_values))
lister_maker.append(messages_info_list)
x=x+1
return lister_maker
##dictionaries of info
account_info_dict = {"home_number":random_phone_number(), "cell_number":random_phone_number()}
messages_info_dict = {"home_number":random_phone_number(), "cell_number":random_phone_number()}
##Main area that puts everything together
doctors_list=[]
for name in doctors_name:
random_number=random.randrange(0,10)
special_notes_random_number=random.randrange(0,len(special_notes_list))
special_notes=special_notes_list[special_notes_random_number]
acct_number=random_number_maker(4)
ticket_number = abs(random_number-10)+1
duration_of_call = abs(random_number-10)+1
listerine = messages_list_random_maker()
account_info_dict = {"home_number":random_phone_number(), "cell_number":random_phone_number()}
doctors_list.append({"doctors_name":name, "special_notes":special_notes, "acct_number":acct_number,
"ticket_number":ticket_number, "duration_of_call":duration_of_call, "call_status": "ringing", "account_info": account_info_dict,
"messages":listerine})
##Dumps the dict to a jason object
jasoner=json.dumps(doctors_list)
#print jasoner
##Count up percentage of completion
for i in range(100):
print "\r", str(i)+"%"
time.sleep(.025)
print "\r"
##Write file
try:
open_file.write(jasoner)
process_message("SUCCESS", input_file, "Written")
except:
process_message("FAILURE" , input_file, "Not Written")
##Close file
try:
open_file.close()
process_message("SUCCESS", input_file, "Closed")
except:
process_message("FAILURE" , input_file, "Not Closed")<|fim▁end|>
|
##Lists of info
|
<|file_name|>blake2s_test.go<|end_file_name|><|fim▁begin|>// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package blake2s
import (
"bytes"
"encoding"
"encoding/hex"
"fmt"
"testing"
)
func TestHashes(t *testing.T) {
defer func(sse2, ssse3, sse4 bool) {
useSSE2, useSSSE3, useSSE4 = sse2, ssse3, sse4
}(useSSE2, useSSSE3, useSSE4)
if useSSE4 {
t.Log("SSE4 version")
testHashes(t)
testHashes128(t)
useSSE4 = false
}
if useSSSE3 {
t.Log("SSSE3 version")
testHashes(t)
testHashes128(t)
useSSSE3 = false
}
if useSSE2 {
t.Log("SSE2 version")
testHashes(t)
testHashes128(t)
useSSE2 = false
}
t.Log("generic version")
testHashes(t)
testHashes128(t)
}
func TestHashes2X(t *testing.T) {
defer func(sse2, ssse3, sse4 bool) {
useSSE2, useSSSE3, useSSE4 = sse2, ssse3, sse4
}(useSSE2, useSSSE3, useSSE4)
if useSSE4 {
t.Log("SSE4 version")
testHashes2X(t)
useSSE4 = false
}
if useSSSE3 {
t.Log("SSSE3 version")
testHashes2X(t)
useSSSE3 = false
}
if useSSE2 {
t.Log("SSE2 version")
testHashes2X(t)
useSSE2 = false
}
t.Log("generic version")
testHashes2X(t)
}
func TestMarshal(t *testing.T) {
input := make([]byte, 255)
for i := range input {
input[i] = byte(i)
}
for i := 0; i < 256; i++ {
h, err := New256(nil)
if err != nil {
t.Fatalf("len(input)=%d: error from New256(nil): %v", i, err)
}
h2, err := New256(nil)
if err != nil {
t.Fatalf("len(input)=%d: error from New256(nil): %v", i, err)
}
h.Write(input[:i/2])
halfstate, err := h.(encoding.BinaryMarshaler).MarshalBinary()
if err != nil {
t.Fatalf("len(input)=%d: could not marshal: %v", i, err)
}
err = h2.(encoding.BinaryUnmarshaler).UnmarshalBinary(halfstate)
if err != nil {
t.Fatalf("len(input)=%d: could not unmarshal: %v", i, err)
}
h.Write(input[i/2 : i])
sum := h.Sum(nil)
h2.Write(input[i/2 : i])
sum2 := h2.Sum(nil)
if !bytes.Equal(sum, sum2) {
t.Fatalf("len(input)=%d: results do not match; sum = %v, sum2 = %v", i, sum, sum2)
}
h3, err := New256(nil)
if err != nil {
t.Fatalf("len(input)=%d: error from New256(nil): %v", i, err)
}
h3.Write(input[:i])
sum3 := h3.Sum(nil)
if !bytes.Equal(sum, sum3) {
t.Fatalf("len(input)=%d: sum = %v, want %v", i, sum, sum3)
}
}
}
func testHashes(t *testing.T) {
key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
input := make([]byte, 255)
for i := range input {
input[i] = byte(i)
}
for i, expectedHex := range hashes {
h, err := New256(key)
if err != nil {
t.Fatalf("#%d: error from New256: %v", i, err)
}
h.Write(input[:i])
sum := h.Sum(nil)
if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex {
t.Fatalf("#%d (single write): got %s, wanted %s", i, gotHex, expectedHex)
}
h.Reset()
for j := 0; j < i; j++ {
h.Write(input[j : j+1])
}
sum = h.Sum(sum[:0])
if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex {
t.Fatalf("#%d (byte-by-byte): got %s, wanted %s", i, gotHex, expectedHex)
}
}
}
func testHashes128(t *testing.T) {
key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
input := make([]byte, 255)
for i := range input {
input[i] = byte(i)
}
for i, expectedHex := range hashes128 {
h, err := New128(key)
if err != nil {
t.Fatalf("#%d: error from New128: %v", i, err)
}
h.Write(input[:i])
sum := h.Sum(nil)
if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex {
t.Fatalf("#%d (single write): got %s, wanted %s", i, gotHex, expectedHex)
}
h.Reset()
for j := 0; j < i; j++ {
h.Write(input[j : j+1])
}
sum = h.Sum(sum[:0])
if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex {
t.Fatalf("#%d (byte-by-byte): got %s, wanted %s", i, gotHex, expectedHex)
}
}
}
func testHashes2X(t *testing.T) {
key, _ := hex.DecodeString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
input := make([]byte, 256)
for i := range input {
input[i] = byte(i)
}
for i, expectedHex := range hashes2X {
length := uint16(len(expectedHex) / 2)
sum := make([]byte, int(length))
h, err := NewXOF(length, key)
if err != nil {
t.Fatalf("#%d: error from NewXOF: %v", i, err)
}
if _, err := h.Write(input); err != nil {
t.Fatalf("#%d (single write): error from Write: %v", i, err)
}
if _, err := h.Read(sum); err != nil {
t.Fatalf("#%d (single write): error from Read: %v", i, err)
}
if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex {
t.Fatalf("#%d (single write): got %s, wanted %s", i, gotHex, expectedHex)
}
h.Reset()
for j := 0; j < len(input); j++ {
h.Write(input[j : j+1])
}
for j := 0; j < len(sum); j++ {
h = h.Clone()
if _, err := h.Read(sum[j : j+1]); err != nil {
t.Fatalf("#%d (byte-by-byte) - Read %d: error from Read: %v", i, j, err)
}
}
if gotHex := fmt.Sprintf("%x", sum); gotHex != expectedHex {
t.Fatalf("#%d (byte-by-byte): got %s, wanted %s", i, gotHex, expectedHex)
}
}
h, err := NewXOF(OutputLengthUnknown, key)
if err != nil {
t.Fatalf("#unknown length: error from NewXOF: %v", err)
}
if _, err := h.Write(input); err != nil {
t.Fatalf("#unknown length: error from Write: %v", err)
}
var result [64]byte
if n, err := h.Read(result[:]); err != nil {
t.Fatalf("#unknown length: error from Read: %v", err)
} else if n != len(result) {
t.Fatalf("#unknown length: Read returned %d bytes, want %d", n, len(result))
}
const expected = "2a9a6977d915a2c4dd07dbcafe1918bf1682e56d9c8e567ecd19bfd7cd93528833c764d12b34a5e2a219c9fd463dab45e972c5574d73f45de5b2e23af72530d8"
if fmt.Sprintf("%x", result) != expected {
t.Fatalf("#unknown length: bad result %x, wanted %s", result, expected)
}
}
// Benchmarks
func benchmarkSum(b *testing.B, size int) {
data := make([]byte, size)
b.SetBytes(int64(size))
b.ResetTimer()
for i := 0; i < b.N; i++ {
Sum256(data)
}
}
func benchmarkWrite(b *testing.B, size int) {
data := make([]byte, size)
h, _ := New256(nil)
b.SetBytes(int64(size))
b.ResetTimer()
for i := 0; i < b.N; i++ {
h.Write(data)
}
}
func BenchmarkWrite64(b *testing.B) { benchmarkWrite(b, 64) }
func BenchmarkWrite1K(b *testing.B) { benchmarkWrite(b, 1024) }
func BenchmarkSum64(b *testing.B) { benchmarkSum(b, 64) }
func BenchmarkSum1K(b *testing.B) { benchmarkSum(b, 1024) }
// hashes is taken from https://blake2.net/blake2s-test.txt
var hashes = []string{
"48a8997da407876b3d79c0d92325ad3b89cbb754d86ab71aee047ad345fd2c49",
"40d15fee7c328830166ac3f918650f807e7e01e177258cdc0a39b11f598066f1",
"6bb71300644cd3991b26ccd4d274acd1adeab8b1d7914546c1198bbe9fc9d803",
"1d220dbe2ee134661fdf6d9e74b41704710556f2f6e5a091b227697445dbea6b",
"f6c3fbadb4cc687a0064a5be6e791bec63b868ad62fba61b3757ef9ca52e05b2",
"49c1f21188dfd769aea0e911dd6b41f14dab109d2b85977aa3088b5c707e8598",
"fdd8993dcd43f696d44f3cea0ff35345234ec8ee083eb3cada017c7f78c17143",
"e6c8125637438d0905b749f46560ac89fd471cf8692e28fab982f73f019b83a9",
"19fc8ca6979d60e6edd3b4541e2f967ced740df6ec1eaebbfe813832e96b2974",
"a6ad777ce881b52bb5a4421ab6cdd2dfba13e963652d4d6d122aee46548c14a7",
"f5c4b2ba1a00781b13aba0425242c69cb1552f3f71a9a3bb22b4a6b4277b46dd",
"e33c4c9bd0cc7e45c80e65c77fa5997fec7002738541509e68a9423891e822a3",
"fba16169b2c3ee105be6e1e650e5cbf40746b6753d036ab55179014ad7ef6651",
"f5c4bec6d62fc608bf41cc115f16d61c7efd3ff6c65692bbe0afffb1fede7475",
"a4862e76db847f05ba17ede5da4e7f91b5925cf1ad4ba12732c3995742a5cd6e",
"65f4b860cd15b38ef814a1a804314a55be953caa65fd758ad989ff34a41c1eea",
"19ba234f0a4f38637d1839f9d9f76ad91c8522307143c97d5f93f69274cec9a7",
"1a67186ca4a5cb8e65fca0e2ecbc5ddc14ae381bb8bffeb9e0a103449e3ef03c",
"afbea317b5a2e89c0bd90ccf5d7fd0ed57fe585e4be3271b0a6bf0f5786b0f26",
"f1b01558ce541262f5ec34299d6fb4090009e3434be2f49105cf46af4d2d4124",
"13a0a0c86335635eaa74ca2d5d488c797bbb4f47dc07105015ed6a1f3309efce",
"1580afeebebb346f94d59fe62da0b79237ead7b1491f5667a90e45edf6ca8b03",
"20be1a875b38c573dd7faaa0de489d655c11efb6a552698e07a2d331b5f655c3",
"be1fe3c4c04018c54c4a0f6b9a2ed3c53abe3a9f76b4d26de56fc9ae95059a99",
"e3e3ace537eb3edd8463d9ad3582e13cf86533ffde43d668dd2e93bbdbd7195a",
"110c50c0bf2c6e7aeb7e435d92d132ab6655168e78a2decdec3330777684d9c1",
"e9ba8f505c9c80c08666a701f3367e6cc665f34b22e73c3c0417eb1c2206082f",
"26cd66fca02379c76df12317052bcafd6cd8c3a7b890d805f36c49989782433a",
"213f3596d6e3a5d0e9932cd2159146015e2abc949f4729ee2632fe1edb78d337",
"1015d70108e03be1c702fe97253607d14aee591f2413ea6787427b6459ff219a",
"3ca989de10cfe609909472c8d35610805b2f977734cf652cc64b3bfc882d5d89",
"b6156f72d380ee9ea6acd190464f2307a5c179ef01fd71f99f2d0f7a57360aea",
"c03bc642b20959cbe133a0303e0c1abff3e31ec8e1a328ec8565c36decff5265",
"2c3e08176f760c6264c3a2cd66fec6c3d78de43fc192457b2a4a660a1e0eb22b",
"f738c02f3c1b190c512b1a32deabf353728e0e9ab034490e3c3409946a97aeec",
"8b1880df301cc963418811088964839287ff7fe31c49ea6ebd9e48bdeee497c5",
"1e75cb21c60989020375f1a7a242839f0b0b68973a4c2a05cf7555ed5aaec4c1",
"62bf8a9c32a5bccf290b6c474d75b2a2a4093f1a9e27139433a8f2b3bce7b8d7",
"166c8350d3173b5e702b783dfd33c66ee0432742e9b92b997fd23c60dc6756ca",
"044a14d822a90cacf2f5a101428adc8f4109386ccb158bf905c8618b8ee24ec3",
"387d397ea43a994be84d2d544afbe481a2000f55252696bba2c50c8ebd101347",
"56f8ccf1f86409b46ce36166ae9165138441577589db08cbc5f66ca29743b9fd",
"9706c092b04d91f53dff91fa37b7493d28b576b5d710469df79401662236fc03",
"877968686c068ce2f7e2adcff68bf8748edf3cf862cfb4d3947a3106958054e3",
"8817e5719879acf7024787eccdb271035566cfa333e049407c0178ccc57a5b9f",
"8938249e4b50cadaccdf5b18621326cbb15253e33a20f5636e995d72478de472",
"f164abba4963a44d107257e3232d90aca5e66a1408248c51741e991db5227756",
"d05563e2b1cba0c4a2a1e8bde3a1a0d9f5b40c85a070d6f5fb21066ead5d0601",
"03fbb16384f0a3866f4c3117877666efbf124597564b293d4aab0d269fabddfa",
"5fa8486ac0e52964d1881bbe338eb54be2f719549224892057b4da04ba8b3475",
"cdfabcee46911111236a31708b2539d71fc211d9b09c0d8530a11e1dbf6eed01",
"4f82de03b9504793b82a07a0bdcdff314d759e7b62d26b784946b0d36f916f52",
"259ec7f173bcc76a0994c967b4f5f024c56057fb79c965c4fae41875f06a0e4c",
"193cc8e7c3e08bb30f5437aa27ade1f142369b246a675b2383e6da9b49a9809e",
"5c10896f0e2856b2a2eee0fe4a2c1633565d18f0e93e1fab26c373e8f829654d",
"f16012d93f28851a1eb989f5d0b43f3f39ca73c9a62d5181bff237536bd348c3",
"2966b3cfae1e44ea996dc5d686cf25fa053fb6f67201b9e46eade85d0ad6b806",
"ddb8782485e900bc60bcf4c33a6fd585680cc683d516efa03eb9985fad8715fb",
"4c4d6e71aea05786413148fc7a786b0ecaf582cff1209f5a809fba8504ce662c",
"fb4c5e86d7b2229b99b8ba6d94c247ef964aa3a2bae8edc77569f28dbbff2d4e",
"e94f526de9019633ecd54ac6120f23958d7718f1e7717bf329211a4faeed4e6d",
"cbd6660a10db3f23f7a03d4b9d4044c7932b2801ac89d60bc9eb92d65a46c2a0",
"8818bbd3db4dc123b25cbba5f54c2bc4b3fcf9bf7d7a7709f4ae588b267c4ece",
"c65382513f07460da39833cb666c5ed82e61b9e998f4b0c4287cee56c3cc9bcd",
"8975b0577fd35566d750b362b0897a26c399136df07bababbde6203ff2954ed4",
"21fe0ceb0052be7fb0f004187cacd7de67fa6eb0938d927677f2398c132317a8",
"2ef73f3c26f12d93889f3c78b6a66c1d52b649dc9e856e2c172ea7c58ac2b5e3",
"388a3cd56d73867abb5f8401492b6e2681eb69851e767fd84210a56076fb3dd3",
"af533e022fc9439e4e3cb838ecd18692232adf6fe9839526d3c3dd1b71910b1a",
"751c09d41a9343882a81cd13ee40818d12eb44c6c7f40df16e4aea8fab91972a",
"5b73ddb68d9d2b0aa265a07988d6b88ae9aac582af83032f8a9b21a2e1b7bf18",
"3da29126c7c5d7f43e64242a79feaa4ef3459cdeccc898ed59a97f6ec93b9dab",
"566dc920293da5cb4fe0aa8abda8bbf56f552313bff19046641e3615c1e3ed3f",
"4115bea02f73f97f629e5c5590720c01e7e449ae2a6697d4d2783321303692f9",
"4ce08f4762468a7670012164878d68340c52a35e66c1884d5c864889abc96677",
"81ea0b7804124e0c22ea5fc71104a2afcb52a1fa816f3ecb7dcb5d9dea1786d0",
"fe362733b05f6bedaf9379d7f7936ede209b1f8323c3922549d9e73681b5db7b",
"eff37d30dfd20359be4e73fdf40d27734b3df90a97a55ed745297294ca85d09f",
"172ffc67153d12e0ca76a8b6cd5d4731885b39ce0cac93a8972a18006c8b8baf",
"c47957f1cc88e83ef9445839709a480a036bed5f88ac0fcc8e1e703ffaac132c",
"30f3548370cfdceda5c37b569b6175e799eef1a62aaa943245ae7669c227a7b5",
"c95dcb3cf1f27d0eef2f25d2413870904a877c4a56c2de1e83e2bc2ae2e46821",
"d5d0b5d705434cd46b185749f66bfb5836dcdf6ee549a2b7a4aee7f58007caaf",
"bbc124a712f15d07c300e05b668389a439c91777f721f8320c1c9078066d2c7e",
"a451b48c35a6c7854cfaae60262e76990816382ac0667e5a5c9e1b46c4342ddf",
"b0d150fb55e778d01147f0b5d89d99ecb20ff07e5e6760d6b645eb5b654c622b",
"34f737c0ab219951eee89a9f8dac299c9d4c38f33fa494c5c6eefc92b6db08bc",
"1a62cc3a00800dcbd99891080c1e098458193a8cc9f970ea99fbeff00318c289",
"cfce55ebafc840d7ae48281c7fd57ec8b482d4b704437495495ac414cf4a374b",
"6746facf71146d999dabd05d093ae586648d1ee28e72617b99d0f0086e1e45bf",
"571ced283b3f23b4e750bf12a2caf1781847bd890e43603cdc5976102b7bb11b",
"cfcb765b048e35022c5d089d26e85a36b005a2b80493d03a144e09f409b6afd1",
"4050c7a27705bb27f42089b299f3cbe5054ead68727e8ef9318ce6f25cd6f31d",
"184070bd5d265fbdc142cd1c5cd0d7e414e70369a266d627c8fba84fa5e84c34",
"9edda9a4443902a9588c0d0ccc62b930218479a6841e6fe7d43003f04b1fd643",
"e412feef7908324a6da1841629f35d3d358642019310ec57c614836b63d30763",
"1a2b8edff3f9acc1554fcbae3cf1d6298c6462e22e5eb0259684f835012bd13f",
"288c4ad9b9409762ea07c24a41f04f69a7d74bee2d95435374bde946d7241c7b",
"805691bb286748cfb591d3aebe7e6f4e4dc6e2808c65143cc004e4eb6fd09d43",
"d4ac8d3a0afc6cfa7b460ae3001baeb36dadb37da07d2e8ac91822df348aed3d",
"c376617014d20158bced3d3ba552b6eccf84e62aa3eb650e90029c84d13eea69",
"c41f09f43cecae7293d6007ca0a357087d5ae59be500c1cd5b289ee810c7b082",
"03d1ced1fba5c39155c44b7765cb760c78708dcfc80b0bd8ade3a56da8830b29",
"09bde6f152218dc92c41d7f45387e63e5869d807ec70b821405dbd884b7fcf4b",
"71c9036e18179b90b37d39e9f05eb89cc5fc341fd7c477d0d7493285faca08a4",
"5916833ebb05cd919ca7fe83b692d3205bef72392b2cf6bb0a6d43f994f95f11",
"f63aab3ec641b3b024964c2b437c04f6043c4c7e0279239995401958f86bbe54",
"f172b180bfb09740493120b6326cbdc561e477def9bbcfd28cc8c1c5e3379a31",
"cb9b89cc18381dd9141ade588654d4e6a231d5bf49d4d59ac27d869cbe100cf3",
"7bd8815046fdd810a923e1984aaebdcdf84d87c8992d68b5eeb460f93eb3c8d7",
"607be66862fd08ee5b19facac09dfdbcd40c312101d66e6ebd2b841f1b9a9325",
"9fe03bbe69ab1834f5219b0da88a08b30a66c5913f0151963c360560db0387b3",
"90a83585717b75f0e9b725e055eeeeb9e7a028ea7e6cbc07b20917ec0363e38c",
"336ea0530f4a7469126e0218587ebbde3358a0b31c29d200f7dc7eb15c6aadd8",
"a79e76dc0abca4396f0747cd7b748df913007626b1d659da0c1f78b9303d01a3",
"44e78a773756e0951519504d7038d28d0213a37e0ce375371757bc996311e3b8",
"77ac012a3f754dcfeab5eb996be9cd2d1f96111b6e49f3994df181f28569d825",
"ce5a10db6fccdaf140aaa4ded6250a9c06e9222bc9f9f3658a4aff935f2b9f3a",
"ecc203a7fe2be4abd55bb53e6e673572e0078da8cd375ef430cc97f9f80083af",
"14a5186de9d7a18b0412b8563e51cc5433840b4a129a8ff963b33a3c4afe8ebb",
"13f8ef95cb86e6a638931c8e107673eb76ba10d7c2cd70b9d9920bbeed929409",
"0b338f4ee12f2dfcb78713377941e0b0632152581d1332516e4a2cab1942cca4",
"eaab0ec37b3b8ab796e9f57238de14a264a076f3887d86e29bb5906db5a00e02",
"23cb68b8c0e6dc26dc27766ddc0a13a99438fd55617aa4095d8f969720c872df",
"091d8ee30d6f2968d46b687dd65292665742de0bb83dcc0004c72ce10007a549",
"7f507abc6d19ba00c065a876ec5657868882d18a221bc46c7a6912541f5bc7ba",
"a0607c24e14e8c223db0d70b4d30ee88014d603f437e9e02aa7dafa3cdfbad94",
"ddbfea75cc467882eb3483ce5e2e756a4f4701b76b445519e89f22d60fa86e06",
"0c311f38c35a4fb90d651c289d486856cd1413df9b0677f53ece2cd9e477c60a",
"46a73a8dd3e70f59d3942c01df599def783c9da82fd83222cd662b53dce7dbdf",
"ad038ff9b14de84a801e4e621ce5df029dd93520d0c2fa38bff176a8b1d1698c",
"ab70c5dfbd1ea817fed0cd067293abf319e5d7901c2141d5d99b23f03a38e748",
"1fffda67932b73c8ecaf009a3491a026953babfe1f663b0697c3c4ae8b2e7dcb",
"b0d2cc19472dd57f2b17efc03c8d58c2283dbb19da572f7755855aa9794317a0",
"a0d19a6ee33979c325510e276622df41f71583d07501b87071129a0ad94732a5",
"724642a7032d1062b89e52bea34b75df7d8fe772d9fe3c93ddf3c4545ab5a99b",
"ade5eaa7e61f672d587ea03dae7d7b55229c01d06bc0a5701436cbd18366a626",
"013b31ebd228fcdda51fabb03bb02d60ac20ca215aafa83bdd855e3755a35f0b",
"332ed40bb10dde3c954a75d7b8999d4b26a1c063c1dc6e32c1d91bab7bbb7d16",
"c7a197b3a05b566bcc9facd20e441d6f6c2860ac9651cd51d6b9d2cdeeea0390",
"bd9cf64ea8953c037108e6f654914f3958b68e29c16700dc184d94a21708ff60",
"8835b0ac021151df716474ce27ce4d3c15f0b2dab48003cf3f3efd0945106b9a",
"3bfefa3301aa55c080190cffda8eae51d9af488b4c1f24c3d9a75242fd8ea01d",
"08284d14993cd47d53ebaecf0df0478cc182c89c00e1859c84851686ddf2c1b7",
"1ed7ef9f04c2ac8db6a864db131087f27065098e69c3fe78718d9b947f4a39d0",
"c161f2dcd57e9c1439b31a9dd43d8f3d7dd8f0eb7cfac6fb25a0f28e306f0661",
"c01969ad34c52caf3dc4d80d19735c29731ac6e7a92085ab9250c48dea48a3fc",
"1720b3655619d2a52b3521ae0e49e345cb3389ebd6208acaf9f13fdacca8be49",
"756288361c83e24c617cf95c905b22d017cdc86f0bf1d658f4756c7379873b7f",
"e7d0eda3452693b752abcda1b55e276f82698f5f1605403eff830bea0071a394",
"2c82ecaa6b84803e044af63118afe544687cb6e6c7df49ed762dfd7c8693a1bc",
"6136cbf4b441056fa1e2722498125d6ded45e17b52143959c7f4d4e395218ac2",
"721d3245aafef27f6a624f47954b6c255079526ffa25e9ff77e5dcff473b1597",
"9dd2fbd8cef16c353c0ac21191d509eb28dd9e3e0d8cea5d26ca839393851c3a",
"b2394ceacdebf21bf9df2ced98e58f1c3a4bbbff660dd900f62202d6785cc46e",
"57089f222749ad7871765f062b114f43ba20ec56422a8b1e3f87192c0ea718c6",
"e49a9459961cd33cdf4aae1b1078a5dea7c040e0fea340c93a724872fc4af806",
"ede67f720effd2ca9c88994152d0201dee6b0a2d2c077aca6dae29f73f8b6309",
"e0f434bf22e3088039c21f719ffc67f0f2cb5e98a7a0194c76e96bf4e8e17e61",
"277c04e2853484a4eba910ad336d01b477b67cc200c59f3c8d77eef8494f29cd",
"156d5747d0c99c7f27097d7b7e002b2e185cb72d8dd7eb424a0321528161219f",
"20ddd1ed9b1ca803946d64a83ae4659da67fba7a1a3eddb1e103c0f5e03e3a2c",
"f0af604d3dabbf9a0f2a7d3dda6bd38bba72c6d09be494fcef713ff10189b6e6",
"9802bb87def4cc10c4a5fd49aa58dfe2f3fddb46b4708814ead81d23ba95139b",
"4f8ce1e51d2fe7f24043a904d898ebfc91975418753413aa099b795ecb35cedb",
"bddc6514d7ee6ace0a4ac1d0e068112288cbcf560454642705630177cba608bd",
"d635994f6291517b0281ffdd496afa862712e5b3c4e52e4cd5fdae8c0e72fb08",
"878d9ca600cf87e769cc305c1b35255186615a73a0da613b5f1c98dbf81283ea",
"a64ebe5dc185de9fdde7607b6998702eb23456184957307d2fa72e87a47702d6",
"ce50eab7b5eb52bdc9ad8e5a480ab780ca9320e44360b1fe37e03f2f7ad7de01",
"eeddb7c0db6e30abe66d79e327511e61fcebbc29f159b40a86b046ecf0513823",
"787fc93440c1ec96b5ad01c16cf77916a1405f9426356ec921d8dff3ea63b7e0",
"7f0d5eab47eefda696c0bf0fbf86ab216fce461e9303aba6ac374120e890e8df",
"b68004b42f14ad029f4c2e03b1d5eb76d57160e26476d21131bef20ada7d27f4",
"b0c4eb18ae250b51a41382ead92d0dc7455f9379fc9884428e4770608db0faec",
"f92b7a870c059f4d46464c824ec96355140bdce681322cc3a992ff103e3fea52",
"5364312614813398cc525d4c4e146edeb371265fba19133a2c3d2159298a1742",
"f6620e68d37fb2af5000fc28e23b832297ecd8bce99e8be4d04e85309e3d3374",
"5316a27969d7fe04ff27b283961bffc3bf5dfb32fb6a89d101c6c3b1937c2871",
"81d1664fdf3cb33c24eebac0bd64244b77c4abea90bbe8b5ee0b2aafcf2d6a53",
"345782f295b0880352e924a0467b5fbc3e8f3bfbc3c7e48b67091fb5e80a9442",
"794111ea6cd65e311f74ee41d476cb632ce1e4b051dc1d9e9d061a19e1d0bb49",
"2a85daf6138816b99bf8d08ba2114b7ab07975a78420c1a3b06a777c22dd8bcb",
"89b0d5f289ec16401a069a960d0b093e625da3cf41ee29b59b930c5820145455",
"d0fdcb543943fc27d20864f52181471b942cc77ca675bcb30df31d358ef7b1eb",
"b17ea8d77063c709d4dc6b879413c343e3790e9e62ca85b7900b086f6b75c672",
"e71a3e2c274db842d92114f217e2c0eac8b45093fdfd9df4ca7162394862d501",
"c0476759ab7aa333234f6b44f5fd858390ec23694c622cb986e769c78edd733e",
"9ab8eabb1416434d85391341d56993c55458167d4418b19a0f2ad8b79a83a75b",
"7992d0bbb15e23826f443e00505d68d3ed7372995a5c3e498654102fbcd0964e",
"c021b30085151435df33b007ccecc69df1269f39ba25092bed59d932ac0fdc28",
"91a25ec0ec0d9a567f89c4bfe1a65a0e432d07064b4190e27dfb81901fd3139b",
"5950d39a23e1545f301270aa1a12f2e6c453776e4d6355de425cc153f9818867",
"d79f14720c610af179a3765d4b7c0968f977962dbf655b521272b6f1e194488e",
"e9531bfc8b02995aeaa75ba27031fadbcbf4a0dab8961d9296cd7e84d25d6006",
"34e9c26a01d7f16181b454a9d1623c233cb99d31c694656e9413aca3e918692f",
"d9d7422f437bd439ddd4d883dae2a08350173414be78155133fff1964c3d7972",
"4aee0c7aaf075414ff1793ead7eaca601775c615dbd60b640b0a9f0ce505d435",
"6bfdd15459c83b99f096bfb49ee87b063d69c1974c6928acfcfb4099f8c4ef67",
"9fd1c408fd75c336193a2a14d94f6af5adf050b80387b4b010fb29f4cc72707c",
"13c88480a5d00d6c8c7ad2110d76a82d9b70f4fa6696d4e5dd42a066dcaf9920",
"820e725ee25fe8fd3a8d5abe4c46c3ba889de6fa9191aa22ba67d5705421542b",
"32d93a0eb02f42fbbcaf2bad0085b282e46046a4df7ad10657c9d6476375b93e",
"adc5187905b1669cd8ec9c721e1953786b9d89a9bae30780f1e1eab24a00523c",
"e90756ff7f9ad810b239a10ced2cf9b2284354c1f8c7e0accc2461dc796d6e89",
"1251f76e56978481875359801db589a0b22f86d8d634dc04506f322ed78f17e8",
"3afa899fd980e73ecb7f4d8b8f291dc9af796bc65d27f974c6f193c9191a09fd",
"aa305be26e5deddc3c1010cbc213f95f051c785c5b431e6a7cd048f161787528",
"8ea1884ff32e9d10f039b407d0d44e7e670abd884aeee0fb757ae94eaa97373d",
"d482b2155d4dec6b4736a1f1617b53aaa37310277d3fef0c37ad41768fc235b4",
"4d413971387e7a8898a8dc2a27500778539ea214a2dfe9b3d7e8ebdce5cf3db3",
"696e5d46e6c57e8796e4735d08916e0b7929b3cf298c296d22e9d3019653371c",
"1f5647c1d3b088228885865c8940908bf40d1a8272821973b160008e7a3ce2eb",
"b6e76c330f021a5bda65875010b0edf09126c0f510ea849048192003aef4c61c",
"3cd952a0beada41abb424ce47f94b42be64e1ffb0fd0782276807946d0d0bc55",
"98d92677439b41b7bb513312afb92bcc8ee968b2e3b238cecb9b0f34c9bb63d0",
"ecbca2cf08ae57d517ad16158a32bfa7dc0382eaeda128e91886734c24a0b29d",
"942cc7c0b52e2b16a4b89fa4fc7e0bf609e29a08c1a8543452b77c7bfd11bb28",
"8a065d8b61a0dffb170d5627735a76b0e9506037808cba16c345007c9f79cf8f",
"1b9fa19714659c78ff413871849215361029ac802b1cbcd54e408bd87287f81f",
"8dab071bcd6c7292a9ef727b4ae0d86713301da8618d9a48adce55f303a869a1",
"8253e3e7c7b684b9cb2beb014ce330ff3d99d17abbdbabe4f4d674ded53ffc6b",
"f195f321e9e3d6bd7d074504dd2ab0e6241f92e784b1aa271ff648b1cab6d7f6",
"27e4cc72090f241266476a7c09495f2db153d5bcbd761903ef79275ec56b2ed8",
"899c2405788e25b99a1846355e646d77cf400083415f7dc5afe69d6e17c00023",
"a59b78c4905744076bfee894de707d4f120b5c6893ea0400297d0bb834727632",
"59dc78b105649707a2bb4419c48f005400d3973de3736610230435b10424b24f",
"c0149d1d7e7a6353a6d906efe728f2f329fe14a4149a3ea77609bc42b975ddfa",
"a32f241474a6c16932e9243be0cf09bcdc7e0ca0e7a6a1b9b1a0f01e41502377",
"b239b2e4f81841361c1339f68e2c359f929af9ad9f34e01aab4631ad6d5500b0",
"85fb419c7002a3e0b4b6ea093b4c1ac6936645b65dac5ac15a8528b7b94c1754",
"9619720625f190b93a3fad186ab314189633c0d3a01e6f9bc8c4a8f82f383dbf",
"7d620d90fe69fa469a6538388970a1aa09bb48a2d59b347b97e8ce71f48c7f46",
"294383568596fb37c75bbacd979c5ff6f20a556bf8879cc72924855df9b8240e",
"16b18ab314359c2b833c1c6986d48c55a9fc97cde9a3c1f10a3177140f73f738",
"8cbbdd14bc33f04cf45813e4a153a273d36adad5ce71f499eeb87fb8ac63b729",
"69c9a498db174ecaefcc5a3ac9fdedf0f813a5bec727f1e775babdec7718816e",
"b462c3be40448f1d4f80626254e535b08bc9cdcff599a768578d4b2881a8e3f0",
"553e9d9c5f360ac0b74a7d44e5a391dad4ced03e0c24183b7e8ecabdf1715a64",
"7a7c55a56fa9ae51e655e01975d8a6ff4ae9e4b486fcbe4eac044588f245ebea",
"2afdf3c82abc4867f5de111286c2b3be7d6e48657ba923cfbf101a6dfcf9db9a",
"41037d2edcdce0c49b7fb4a6aa0999ca66976c7483afe631d4eda283144f6dfc",
"c4466f8497ca2eeb4583a0b08e9d9ac74395709fda109d24f2e4462196779c5d",
"75f609338aa67d969a2ae2a2362b2da9d77c695dfd1df7224a6901db932c3364",
"68606ceb989d5488fc7cf649f3d7c272ef055da1a93faecd55fe06f6967098ca",
"44346bdeb7e052f6255048f0d9b42c425bab9c3dd24168212c3ecf1ebf34e6ae",
"8e9cf6e1f366471f2ac7d2ee9b5e6266fda71f8f2e4109f2237ed5f8813fc718",
"84bbeb8406d250951f8c1b3e86a7c010082921833dfd9555a2f909b1086eb4b8",
"ee666f3eef0f7e2a9c222958c97eaf35f51ced393d714485ab09a069340fdf88",
"c153d34a65c47b4a62c5cacf24010975d0356b2f32c8f5da530d338816ad5de6",
"9fc5450109e1b779f6c7ae79d56c27635c8dd426c5a9d54e2578db989b8c3b4e",
"d12bf3732ef4af5c22fa90356af8fc50fcb40f8f2ea5c8594737a3b3d5abdbd7",
"11030b9289bba5af65260672ab6fee88b87420acef4a1789a2073b7ec2f2a09e",
"69cb192b8444005c8c0ceb12c846860768188cda0aec27a9c8a55cdee2123632",
"db444c15597b5f1a03d1f9edd16e4a9f43a667cc275175dfa2b704e3bb1a9b83",
"3fb735061abc519dfe979e54c1ee5bfad0a9d858b3315bad34bde999efd724dd",
}
var hashes128 = []string{
"9536f9b267655743dee97b8a670f9f53",
"13bacfb85b48a1223c595f8c1e7e82cb",
"d47a9b1645e2feae501cd5fe44ce6333",
"1e2a79436a7796a3e9826bfedf07659f",
"7640360ed3c4f3054dba79a21dda66b7",
"d1207ac2bf5ac84fc9ef016da5a46a86",
"3123987871e59305ece3125abfc0099a",
"cf9e072ad522f2cda2d825218086731c",
"95d22870392efe2846b12b6e8e84efbb",
"7d63c30e2d51333f245601b038c0b93b",
"ed608b98e13976bdf4bedc63fa35e443",
"ed704b5cd1abf8e0dd67a6ac667a3fa5",
"77dc70109827dc74c70fd26cba379ae5",
"d2bf34508b07825ee934f33958f4560e",
"a340baa7b8a93a6e658adef42e78eeb7",
"b85c5ceaecbe9a251eac76f6932ba395",
"246519722001f6e8e97a2183f5985e53",
"5bce5aa0b7c6cac2ecf6406183cd779a",
"13408f1647c02f6efd0047ad8344f695",
"a63970f196760aa36cb965ab62f0e0fa",
"bc26f48421dd99fd45e15e736d3e7dac",
"4c6f70f9e3237cde918afb52d26f1823",
"45ed610cfbc37db80c4bf0eef14ae8d6",
"87c4c150705ea5078209ec008200539c",
"54de21f5e0e6f2afe04daeb822b6931e",
"9732a04e505064e19de3d542e7e71631",
"d2bd27e95531d6957eef511c4ba64ad4",
"7a36c9f70dcc7c3063b547101a5f6c35",
"322007d1a44c4257bc7903b183305529",
"dbcc9a09f412290ca2e0d53dfd142ddb",
"df12ed43b8e53a56db20e0f83764002c",
"d114cc11e7d5b33a360c45f18d4c7c6e",
"c43b5e836af88620a8a71b1652cb8640",
"9491c653e8867ed73c1b4ac6b5a9bb4d",
"06d0e988df94ada6c6f9f36f588ab7c5",
"561efad2480e93262c8eeaa3677615c4",
"ba8ffc702e5adc93503045eca8702312",
"5782be6ccdc78c8425285e85de8ccdc6",
"aa1c4393e4c07b53ea6e2b5b1e970771",
"42a229dc50e52271c51e8666023ebc1e",
"53706110e919f84de7f8d6c7f0e7b831",
"fc5ac8ee39cc1dd1424391323e2901bd",
"bed27b62ff66cac2fbb68193c727106a",
"cd5e689b96d0b9ea7e08dac36f7b211e",
"0b4c7f604eba058d18e322c6e1baf173",
"eb838227fdfad09a27f0f8413120675d",
"3149cf9d19a7fd529e6154a8b4c3b3ad",
"ca1e20126df930fd5fb7afe4422191e5",
"b23398f910599f3c09b6549fa81bcb46",
"27fb17c11b34fa5d8b5afe5ee3321ead",
"0f665f5f04cf2d46b7fead1a1f328158",
"8f068be73b3681f99f3b282e3c02bba5",
"ba189bbd13808dcf4e002a4dd21660d5",
"2732dcd1b16668ae6ab6a61595d0d62a",
"d410ccdd059f0e02b472ec9ec54bdd3c",
"b2eaa07b055b3a03a399971327f7e8c2",
"2e8a225655e9f99b69c60dc8b4d8e566",
"4eb55416c853f2152e67f8a224133cec",
"49552403790d8de0505a8e317a443687",
"7f2747cd41f56942752e868212c7d5ac",
"02a28f10e193b430df7112d2d98cf759",
"d4213404a9f1cf759017747cf5958270",
"faa34884344f9c65e944882db8476d34",
"ece382a8bd5018f1de5da44b72cea75b",
"f1efa90d2547036841ecd3627fafbc36",
"811ff8686d23a435ecbd0bdafcd27b1b",
"b21beea9c7385f657a76558530438721",
"9cb969da4f1b4fc5b13bf78fe366f0c4",
"8850d16d7b614d3268ccfa009d33c7fc",
"aa98a2b6176ea86415b9aff3268c6f6d",
"ec3e1efa5ed195eff667e16b1af1e39e",
"e40787dca57411d2630db2de699beb08",
"554835890735babd06318de23d31e78a",
"493957feecddc302ee2bb2086b6ebfd3",
"f6069709ad5b0139163717e9ce1114ab",
"ba5ed386098da284484b211555505a01",
"9244c8dfad8cbb68c118fa51465b3ae4",
"51e309a5008eb1f5185e5cc007cfb36f",
"6ce9ff712121b4f6087955f4911eafd4",
"59b51d8dcda031218ccdd7c760828155",
"0012878767a3d4f1c8194458cf1f8832",
"82900708afd5b6582dc16f008c655edd",
"21302c7e39b5a4cdf1d6f86b4f00c9b4",
"e894c7431591eab8d1ce0fe2aa1f01df",
"b67e1c40ee9d988226d605621854d955",
"6237bdafa34137cbbec6be43ea9bd22c",
"4172a8e19b0dcb09b978bb9eff7af52b",
"5714abb55bd4448a5a6ad09fbd872fdf",
"7ce1700bef423e1f958a94a77a94d44a",
"3742ec50cded528527775833453e0b26",
"5d41b135724c7c9c689495324b162f18",
"85c523333c6442c202e9e6e0f1185f93",
"5c71f5222d40ff5d90e7570e71ab2d30",
"6e18912e83d012efb4c66250ced6f0d9",
"4add4448c2e35e0b138a0bac7b4b1775",
"c0376c6bc5e7b8b9d2108ec25d2aab53",
"f72261d5ed156765c977751c8a13fcc1",
"cff4156c48614b6ceed3dd6b9058f17e",
"36bfb513f76c15f514bcb593419835aa",
"166bf48c6bffaf8291e6fdf63854bef4",
"0b67d33f8b859c3157fbabd9e6e47ed0",
"e4da659ca76c88e73a9f9f10f3d51789",
"33c1ae2a86b3f51c0642e6ed5b5aa1f1",
"27469b56aca2334449c1cf4970dcd969",
"b7117b2e363378aa0901b0d6a9f6ddc0",
"a9578233b09e5cd5231943fdb12cd90d",
"486d7d75253598b716a068243c1c3e89",
"66f6b02d682b78ffdc85e9ec86852489",
"38a07b9a4b228fbcc305476e4d2e05d2",
"aedb61c7970e7d05bf9002dae3c6858c",
"c03ef441f7dd30fdb61ad2d4d8e4c7da",
"7f45cc1eea9a00cb6aeb2dd748361190",
"a59538b358459132e55160899e47bd65",
"137010fef72364411820c3fbed15c8df",
"d8362b93fc504500dbd33ac74e1b4d70",
"a7e49f12c8f47e3b29cf8c0889b0a9c8",
"072e94ffbfc684bd8ab2a1b9dade2fd5",
"5ab438584bd2229e452052e002631a5f",
"f233d14221097baef57d3ec205c9e086",
"3a95db000c4a8ff98dc5c89631a7f162",
"0544f18c2994ab4ddf1728f66041ff16",
"0bc02116c60a3cc331928d6c9d3ba37e",
"b189dca6cb5b813c74200834fba97f29",
"ac8aaab075b4a5bc24419da239212650",
"1e9f19323dc71c29ae99c479dc7e8df9",
"12d944c3fa7caa1b3d62adfc492274dd",
"b4c68f1fffe8f0030e9b18aad8c9dc96",
"25887fab1422700d7fa3edc0b20206e2",
"8c09f698d03eaf88abf69f8147865ef6",
"5c363ae42a5bec26fbc5e996428d9bd7",
"7fdfc2e854fbb3928150d5e3abcf56d6",
"f0c944023f714df115f9e4f25bcdb89b",
"6d19534b4c332741c8ddd79a9644de2d",
"32595eb23764fbfc2ee7822649f74a12",
"5a51391aab33c8d575019b6e76ae052a",
"98b861ce2c620f10f913af5d704a5afd",
"b7fe2fc8b77fb1ce434f8465c7ddf793",
"0e8406e0cf8e9cc840668ece2a0fc64e",
"b89922db99c58f6a128ccffe19b6ce60",
"e1be9af665f0932b77d7f5631a511db7",
"74b96f20f58de8dc9ff5e31f91828523",
"36a4cfef5a2a7d8548db6710e50b3009",
"007e95e8d3b91948a1dedb91f75de76b",
"a87a702ce08f5745edf765bfcd5fbe0d",
"847e69a388a749a9c507354d0dddfe09",
"07176eefbc107a78f058f3d424ca6a54",
"ad7e80682333b68296f6cb2b4a8e446d",
"53c4aba43896ae422e5de5b9edbd46bf",
"33bd6c20ca2a7ab916d6e98003c6c5f8",
"060d088ea94aa093f9981a79df1dfcc8",
"5617b214b9df08d4f11e58f5e76d9a56",
"ca3a60ee85bd971e1daf9f7db059d909",
"cd2b7754505d8c884eddf736f1ec613e",
"f496163b252f1439e7e113ba2ecabd8e",
"5719c7dcf9d9f756d6213354acb7d5cf",
"6f7dd40b245c54411e7a9be83ae5701c",
"c8994dd9fdeb077a45ea04a30358b637",
"4b1184f1e35458c1c747817d527a252f",
"fc7df674afeac7a3fd994183f4c67a74",
"4f68e05ce4dcc533acf9c7c01d95711e",
"d4ebc59e918400720035dfc88e0c486a",
"d3105dd6fa123e543b0b3a6e0eeaea9e",
"874196128ed443f5bdb2800ca048fcad",
"01645f134978dc8f9cf0abc93b53780e",
"5b8b64caa257873a0ffd47c981ef6c3f",
"4ee208fc50ba0a6e65c5b58cec44c923",
"53f409a52427b3b7ffabb057ca088428",
"c1d6cd616f5341a93d921e356e5887a9",
"e85c20fea67fa7320dc23379181183c8",
"7912b6409489df001b7372bc94aebde7",
"e559f761ec866a87f1f331767fafc60f",
"20a6f5a36bc37043d977ed7708465ef8",
"6a72f526965ab120826640dd784c6cc4",
"bf486d92ad68e87c613689dd370d001b",
"d339fd0eb35edf3abd6419c8d857acaf",
"9521cd7f32306d969ddabc4e6a617f52",
"a1cd9f3e81520842f3cf6cc301cb0021",
"18e879b6f154492d593edd3f4554e237",
"66e2329c1f5137589e051592587e521e",
"e899566dd6c3e82cbc83958e69feb590",
"8a4b41d7c47e4e80659d77b4e4bfc9ae",
"f1944f6fcfc17803405a1101998c57dd",
"f6bcec07567b4f72851b307139656b18",
"22e7bb256918fe9924dce9093e2d8a27",
"dd25b925815fe7b50b7079f5f65a3970",
"0457f10f299acf0c230dd4007612e58f",
"ecb420c19efd93814fae2964d69b54af",
"14eb47b06dff685d88751c6e32789db4",
"e8f072dbb50d1ab6654aa162604a892d",
"69cff9c62092332f03a166c7b0034469",
"d3619f98970b798ca32c6c14cd25af91",
"2246d423774ee9d51a551e89c0539d9e",
"75e5d1a1e374a04a699247dad827b6cf",
"6d087dd1d4cd15bf47db07c7a96b1db8",
"967e4c055ac51b4b2a3e506cebd5826f",
"7417aa79247e473401bfa92a25b62e2a",
"24f3f4956da34b5c533d9a551ccd7b16",
"0c40382de693a5304e2331eb951cc962",
"9436f949d51b347db5c8e6258dafaaac",
"d2084297fe84c4ba6e04e4fb73d734fe",
"42a6f8ff590af21b512e9e088257aa34",
"c484ad06b1cdb3a54f3f6464a7a2a6fd",
"1b8ac860f5ceb4365400a201ed2917aa",
"c43eadabbe7b7473f3f837fc52650f54",
"0e5d3205406126b1f838875deb150d6a",
"6bf4946f8ec8a9c417f50cd1e67565be",
"42f09a2522314799c95b3fc121a0e3e8",
"06b8f1487f691a3f7c3f74e133d55870",
"1a70a65fb4f314dcf6a31451a9d2704f",
"7d4acdd0823279fd28a1e48b49a04669",
"09545cc8822a5dfc93bbab708fd69174",
"efc063db625013a83c9a426d39a9bddb",
"213bbf89b3f5be0ffdb14854bbcb2588",
"b69624d89fe2774df9a6f43695d755d4",
"c0f9ff9ded82bd73c512e365a894774d",
"d1b68507ed89c17ead6f69012982db71",
"14cf16db04648978e35c44850855d1b0",
"9f254d4eccab74cd91d694df863650a8",
"8f8946e2967baa4a814d36ff01d20813",
"6b9dc4d24ecba166cb2915d7a6cba43b",
"eb35a80418a0042b850e294db7898d4d",
"f55f925d280c637d54055c9df088ef5f",
"f48427a04f67e33f3ba0a17f7c9704a7",
"4a9f5bfcc0321aea2eced896cee65894",
"8723a67d1a1df90f1cef96e6fe81e702",
"c166c343ee25998f80bad4067960d3fd",
"dab67288d16702e676a040fd42344d73",
"c8e9e0d80841eb2c116dd14c180e006c",
"92294f546bacf0dea9042c93ecba8b34",
"013705b1502b37369ad22fe8237d444e",
"9b97f8837d5f2ebab0768fc9a6446b93",
"7e7e5236b05ec35f89edf8bf655498e7",
"7be8f2362c174c776fb9432fe93bf259",
"2422e80420276d2df5702c6470879b01",
"df645795db778bcce23bbe819a76ba48",
"3f97a4ac87dfc58761cda1782d749074",
"50e3f45df21ebfa1b706b9c0a1c245a8",
"7879541c7ff612c7ddf17cb8f7260183",
"67f6542b903b7ba1945eba1a85ee6b1c",
"b34b73d36ab6234b8d3f5494d251138e",
"0aea139641fdba59ab1103479a96e05f",
"02776815a87b8ba878453666d42afe3c",
"5929ab0a90459ebac5a16e2fb37c847e",
"c244def5b20ce0468f2b5012d04ac7fd",
"12116add6fefce36ed8a0aeccce9b6d3",
"3cd743841e9d8b878f34d91b793b4fad",
"45e87510cf5705262185f46905fae35f",
"276047016b0bfb501b2d4fc748165793",
"ddd245df5a799417d350bd7f4e0b0b7e",
"d34d917a54a2983f3fdbc4b14caae382",
"7730fbc09d0c1fb1939a8fc436f6b995",
"eb4899ef257a1711cc9270a19702e5b5",
"8a30932014bce35bba620895d374df7a",
"1924aabf9c50aa00bee5e1f95b5d9e12",
"1758d6f8b982aec9fbe50f20e3082b46",
"cd075928ab7e6883e697fe7fd3ac43ee",
}
// hashes2X is taken from
// https://github.com/BLAKE2/BLAKE2/blob/master/testvectors/blake2-kat.json
var hashes2X = []string{
"0e",
"5196",
"ad6bad",
"d8e4b32f",
"8eb89056f3",
"410497c2ed72",
"f0de771b375c90",
"8662db8685033611",
"9ef9f1eed88a3f52ca",
"08225082df0d2b0a815e",
"0f6e84a17439f1bc97c299",
"895ec39c78d3556cefdbfabc",
"2b396b3fa90ab556079a79b44d",
"abae26501c4c1d6123c0f2289111",
"bca098df9099b3f785a37ba40fce5f",
"19b827f054b67a120f11efb0d690be70",
"b88d32a338fd60b58570fda228a121113b",
"3f30143af1cad33f9b794576e078cc79062e",
"ffddb58d9aa8d38086fcdae07e6653e8f31dfc",
"abb99c2e74a74556919040ca0cd857c95ec985e9",
"71f13f89af55ba936f8a7188ee93d2e8fb0cf2a720",
"99734fdf0eef4838a7515426f4c59b800854e2fcdc1c",
"579b1652aa1f5779d2b0e61868af856855020bdd44d7a7",
"1383d4ab4a6d8672b4075d421a159f69380ff47e4bb518d5",
"d3fa1412712dbbab71d4c6265dc1585c8dcc73380cf807f76a",
"1d57868a71e7245667780455d9aaa9e0683baf08fbaf946091c2",
"ef80418fe7049c6251ed7960a6b0e9def0da2749781994b24593a0",
"ef91cb81e4bfb50231e89475e251e2ef2fde59357551cd227588b63f",
"d7f398a5d21c3139cff0562a84f154b6953c7bc18a5f4b60491c196b6d",
"0a2abc6d38f30aef253579a4088c5b9aec64391f37d576eb06a300c193a5",
"02dd758fa23113a14fd94830e50e0f6b86faec4e551e808b0ca8d00fef2a15",<|fim▁hole|> "02de8ffa5b9c748164f99ed9d678b02e53f4ae88fb26c6d94a8cefc328725a692eae78c2",
"348a61a0136436136910262ad67ef20644b32c15456d5fad6b1679386d0bea87cc1a2e2b5e",
"24c32966c803434d48d2283482ee8f404f598cf7a17961748125d2ed1da987039b1ce00f2ba7",
"bd07cb16121d3b47adf03b96c41c947beadc01e40548e0d0773e61780d48d33a0e2a675ca681a6",
"a35844e34c20b4b9371b6c52fac412afe5d80a4c1e40aa3a0e5a729dc3d41c2c3719d096f616f0ba",
"6df1efbb4567747fe98d218935612f8835852dde2ce3dec767792d7f1d876cdae0056fef085245449d",
"48d6094af78bd38d8f4b39c54279b80ef617bc6ad21def0b2c62113b656c5d6a55aea2e3fde94a254b92",
"cd6e684759d2f19083164712c2aca0038442efb5b646594396b1fccdbd21203290f44cfdecca0373b3801b",
"155dfbf26103c8354362663677fa27d0e1ce3487a821a2a7171014c1bd5dd071f4974df272b1374765b8f2e1",
"15b11067f311efa4ee813dbca48d690dc92780656bc4d4c56510523190a240180867c829a8b8b9844175a8aa23",
"9bc27953a17fb84d5eabe95b4ea6bc03ea450274abccfb6f3938ded8560fb59662459a11a86b0e0f32fbea6bb1f8",
"03b78fb0b34fb8662accdf350a6be75ace9789653ee4375d351e871f6a98ac5e782ca4b4a717665d25e49a5ae25d81",
"687e9a6fda6e2ce0e40e4d30fef38c31e3513d2892bbe85c991fc3715947e42bc49bcd079a40ed061c2c3665efe555ab",
"f3886027d2049a8909e26545bd202d6a6fa2a6f815d31c7d520f705a81fa606dd695369c37aee4fa77dc645e9b05813ceb",
"e4a412ccd20b97797d91ccc286904fcd17c5afe8bed0618f1af333c052c473cd327637d951c32e4af047106036a3bc8c1c45",
"92f4b8c240a28b6238bc2eabadaf2ff3c4bfe0e6c61268ace6aebdeb0691450caea4287db8b329bde96af8cdb8a0fe2f57ef2d",
"e506834b3445e1a9a9b7bae844e91e0834512a06c0dc75fa4604e3b903c4e23616f2e0c78b5cc496660b4a13064bb1138edef4ff",
"27031955a40d8dbd1591f26e3c26e367a3c68f8204a396c6a4ba34b89672896d11276966a42bd516716f35ed63e442e116dbcf35da",
"646b1635c68d2328dddd5ac26eb9877c24c28390a45753a65044c3136ae2fe4fb40d09bf555271646d3dceb1ab1b7c8d8e421f553f94",
"f6171f8d833743bdee7cc8f8b29c38614e1d2d8d6a5fff68bec2c0f4dd463d7941ff5c368e2683d8f1dc97119bde2b73ca412718bc8cb1",
"45db1c478b040aa2e23fb4427017079810775c62abe737e82ec0ef8dcd0fc51f521f29fe6412fff7eac9beb7bcf75f483f3f8b971e42454b",
"500dab14687db3ca3dde9304af5f54194b37bdf475628af46b07bfbf6bc2b64ecef284b17f9d1d9be41794699bc0e76c2878b3a55730f7142d",
"31bba2efc7b3f415c3f031d4c06bb590ae40085ad157370af30238e03e25a359c9e133212ed34b7a006f839173b577e7015a87fdff2270fafddb",
"0600b3fb4b5e1ed0c8b2698ac1d9905e67e027390764821f963ad8d2b33cbc378b9c25c3ee422992d22b760222ed5697be0576d73938ae9d634ed7",
"4c0ca4f177d132594a4c613bad68da24c564efa3b4da0d0a903f26534a2e09f8d799d10e78f48ccdb0203954a36c5cf1bf24c076632c2b022b041200",
"97aacf2e1b013677b2e14084f097cb1e64d7b3fa36f097e189d86dc4a263bcc46817cd1ee6ff0c7ccd9acef63201cdc0e36254e19204a7388643bb571f",
"71fd6846ce7adb0843d6063546a16b79b54ad6c0f018a479a45817624fa221f63525084860559d1a0679c8d89a80701c62743ec2da8419d503f8f0cd7946",
"f73dfb046def3362d6de36077dae2cee2587fe95fe0800548bb7d99737897096ba59052e0dadcc1fb0ccb5535391875328637a0376a43a4d89366758dfe3e2",
"ec470d0aa932c78c5bcf86203ec0014314114765fa679c3daef214f883a17e1b4ca12f44433772a6e4ef685c904b2fc35586c6bd88f325b965968b06d808d73f",
"cf601753ffa09fe48a8a84c37769991e96290e200bbaf1910c57760f989bd0c72e6128e294528ee861ad7eee70d589de3cf4a0c35f7197e1925a64d0133628d87d",
"f15413f7d6fc54bb55829f698da92ee42fcf58dde1aa1bd07d438ecdc32ad6bf2bcdbecc99f18ed43e81b33065af5a4ca29960ae50553e610c0bbf4153d580e73dbb",
"84b1738adb9757fb9402ef7113581291136184d7ae35fe0b6a738da6acb0889d4d5bac7a957024e3709fa80c77d3859871ed1aa25cf488e438a2d24cfadce6008761dd",
"e02814bb81f250c1835a05108396b74c7878e737654bb83155e241774d04e639bbc571b413cd9349092f926c8a149a53cd33e9b63f370b6d460e504199d2e7d849db6cbe",
"aeee4a789956ec0913592c30ce4f9c544894da77ba447c84df3be2c869100e4df8f7e316445d844b31c3209abcc912f647735fd4a7136c2f35c6fda5b2e6708f5ca951b2b0",
"8cfd11ca385de3c843de84c830d59278fe79b70fb5ddbfbfc1ddefeb22c329ef2f607d1d1abbd1cd0d0cc7c5d3ed922add76aadca0d2f57b66cb16c582b6f18f60aee2f7509b",
"852e5ce2047d8d8b42b4c7e4987b95d23e8026a202d4567951bbbd23111e389fe33a736318546a914d2bddedfbf53846036ad9e35f29318b1f96e33eba08f071d6dc665149feb6",
"f225c23164979d0d13874a90ee291627e4f61a672a5578506fd3d65a12cb48a182f78350dc24c637b2f3950dc4882a5c1d5d5bad551c6f3e0093aa87e962bea51566af3791d52d65",
"5f33864d882455f8ef046aed64e2d1691e5c1555e333b0852750592e6f00d3b5ec941d0c00e99629612795d5870cf93c984b45e4464ba072a34903b400a42824ac13da28c7c1cb1959",
"7baaee7c3eb68c18c5ae1d45ba381803de34e36a52e2d7ccc9d48a297273c4d8644b473195bc23005f7a4f5ca790b1fa11f6a96e585e635513f11745dd97a69c1222204ab28d3c7735df",
"d0a2a3fc450ef9af7ae982041feb2842901026467d87839c33b4a9e081ea63d5be60ae99ca6e42393ded45255b8f42886f87ba0310572d9f0d8b5a07ff4b6bae1f30559a844983cc568560",
"3aa4164462b3e7044c35b08b047b924790f6d5c520b1df4305b5d41f4717e81f0cd4bccb9a5a6594773832b8707443adde4047caaed2293f92234df257df54ed275a9658fab483d0576d33a9",
"c8b4239fd7f1b893d978268f77f6505b5775d89090374322d40083b0f4c437423f670ca213f7fe05c61069725da2561646eefaea597ac48e293fbad44c2872046857e56d04a426a84008cefd71",
"f94839a7024c0a16971271b6727c081770110c957b1f2e03be03d2200b565cf8240f2873b0426042aaea996a1784fadb2b27f23bc1a521b4f7320dfbed86cd38d75141365ba9b443defc0a3b4078",
"8af934fdc8b3376ca09bdd89f9057ed38b656bff96a8f8a3038d456a265689ca32036670cb01469cc6e958cc4a46f1e80d700ae56659828a65c0456b8e55f28f255bc86ce48e44377bf1f9970b617d",
"ada572989e42f0e38c1f7c22b46bb52a84df8f7b3b773c9f17a5823e59a9725248d703efb4cb011abc9474e8e711666ed3cfa60db48480a8160615dfabad761bc0eb843d2e46299c59b61a15b4422fdf",
"b11f1ea52a7e4bd2a5cf1e234b7c9eb909fb45860080f0a6bdb5517a37b5b7cd90f3a9e2297f995e96c293189b807a7bf6e7633bebbc36674544db5f18dd33020aeaf50ee832efe4d3d053873fd31ce3b9",
"e54b006cd96c43d19787c1ab1e08ea0f8922bdb7142e748212e7912a1f2c0a4fad1b9f5209c30960b8b83ef4960e929b155a8a48c8fb7ce4326915950cede6b98a96b6f1ecb12715b713985dacd1c1180413",
"ee2c2f31a414ccd8f6a790f55e09155fd50aac2a878f9014f6c6035cae9186f90cdef0b7adf3e207c3d24ddfba8cd321b2e9228b02a1182b6973da6698071fce8cc0a23a7bf0d5aefd21ab1b8dc7818549bba3",
"6d6810793bad6c7efe8fd56cac04a0fb8717a44c09cbfaebce196a80ac318c79ca5c2db54fee8191ee2d305b690a92bd9e2c947a3c29342a93ac05796484638787a184e4525e82aeb9afa2f9480caebb91014c51",
"91e4694366cff84854872667fd168d2d42eca9070cdc92fca9936e8361e7266931f418450d098a42686241d08024dd72f0024d22ba644bd414245e78608942321ff61860ba1245f83c88592dc7995c49c0c53aa8a9",
"608aa620a5cf145f4477694407ccd8faa3182465b29ae98d96a42f7409434c21e4671bcae079f6871a09d8f2965e4926a9b08277d32f9dd6a474e3a9fb232f27fc4235df9c02abf67f7e540ca9ddc270ee91b23a5b57",
"c14f75e92f75f4356ab01c8792af13383e7fef2ffb3064de55e8da0a50511fea364ccd8140134872adccad197228319260a7b77b67a39677a0dcdcadfb750333ac8e032121e278bdcdbed5e452dae0416011186d9ebf29",
"03fcb9f6e1f058091b11351e775184ff2cd1f31ee846c6ea8efd49dd344f4af473f92eb44eba8a019776f77bb24e294aa9f962b39feecf7c59d46f1a606f89b1e81c2715ac9aa252e9ce941d091ffb99bb52404961794cf8",
"11e189b1d90fcfe8111c79c5351d826f5ec15a602af3b71d50bc7ed813f36c9a682520984ae911669d3c3036223a53176794c7e17929efab2b1c5b500f24f8c83d3db5d1029c5714c6fd34eb800a913985c218071677b9885c",
"69f8f5db3ab0321a708ab2f4234645dade6bfda495851dbe7257f2b72e3e8378b9fa8120bc836b737a675271e519b4712d2b56b359e0f2234ba7552dd4828b939e0542e729878ac1f81b6ce14cb573e76af3a6aa227f95b2350e",
"be734d78fae92cacb009cc400e023086bc3a3a10e8ca7cb4d553ea85314f51383660b8508e8477af60baf7e07c04cc9e094690ae12c73e5f089763201b4b48d664b94b4f5820bd1540f4a84100fdf8fce7f6466aa5d5c34fcbab45",
"d61b77032403f9b6ea5ad2b760eb0157545e37f1712ec44d7926ccf130e8fc0fe8e9b15570a6214c3899a074811486182b250dc97ebdd3b61403614d935cd0a61c0899f31b0e49b81c8a9a4fe8409822c470aacfde229d965dd62f51",
"c31bd548e36d5fae95ed8fa6e807642711c897f0fcc3b0d00bd317ed2bca73412064618c6a84a61c71bce3e963333b0266a5656571dcc4ba8a8c9d84af4bdb445c34a7aef445b15d77698e0b13c436c928cc7fa7acd5f68867e8132993",
"9903b8adab803d085b634bfae2e109dd247a7d6249f203403216d9f7410c36142df8fa56fb4d6f78136eef5817bad5ea3608439bb19336628c37d42db16ab2df8018b773baedafb77278a50926370b48bd81710203c7abc7b4043f9a1751",
"4dadaf0d6a96022c8ce40d48f460526d9956da33260e1770315ead420da75b122c762762aa3ddc1aef9070ff2298b2304cf90443318b17183b60778f3859b141053e5827decfff27ff106a48cfdb0371d0ef614fc7400e860b676df3176d1a",
"314dda800f2f494ca9c9678f178940d2284cb29c51cb01ca2019a9bede0cdc50f8ecf2a77e238b884867e78e691461a66100b38f374c4ccac80309641533a3217eca7e6b9a9af01c026201f0afaec5a61629a59eb530c3cb81934b0cb5b45eae",
"4658b7500951f75c84e4509d74047ca621009835c0152f03c9f96ca73beb29608c44390ba4473323e621284be872bdb72175628780113e470036265d11dfcb284ac04604e667f1e4c1d357a411d3100d4d9f84a14a6fabd1e3f4de0ac81af50179",
"491f877592837e7912f16b73ee1fb06f4633d854a5723e156978f48ec48fbd8b5e863c24d838ff95fa865155d07e5513df42c8bb7706f8e3806b705866475c0ac04bbe5aa4b91b7dc373e82153483b1b03304a1a791b058926c1becd069509cbf46e",
"231034720c719ab31f7c146a702a971f5943b70086b80a2a3eb928fa9380b7a1ad8773bfd0739142d2ad6e19819765ca54f92db5f16c1df5fa4b445c266215a92527bd4ef50ed277b9a21aee3fb7a8128c14ce084f53eac878a7a660b7c011eb1a33c5",
"3366860c77804fe0b4f368b02bb5b0d150821d957e3ba37842da9fc8d336e9d702c8446ecafbd19d79b868702f32405853bc17695873a7306e0ce4573cd9ac0b7fc7dd35534d7635198d152a1802f7d8d6a4bb07600fcdaacfaa1c3f40a09bc02e974c99",
"ccbbbe621f910a95835f5f8d74b21e13f8a4b03f72f91f37b5c7e995aa3cd5539508d5e234e77a4668a42c239b2d13ef0e55ecf85142055e3f8a7e46320e21324a6b88e6c823ac04b485125c2aa59b61476481208f92ea4dd330cb18777c1cf0df7cd07893",
"87faf0e49e7e5ab66ee3147921f8817867fe637d4ab694c33ee8009c759e7d707f44c69c1b9754e2b4f8f47b25f51cd01de7273f548f4952e8efc4d9044c6ea72d1d5857e0ffeb3f44b0c88cb67683401cfb2f1d17f0ca5696641bef28d7579f68d9d066d968",
"38c876a007ec727c92e2503990c4d9407cea2271026aee88cd7b16c4396f00cc4b760576adf2d683713a3f6063cc13ecd7e4f3b6148ad914ca89f34d1375aa4c8e2033f1315153189507bfd116b07fc4bc14f751bbbb0e752f621153ae8df4d68491a22430b309",
"87d636a33dbd9ad81ecd6f3569e418bf8a972f97c5644787b99c361195231a72455a121dd7b3254d6ff80101a0a1e2b1eb1ca4866bd23063fe007310c88c4a2ab3b49f14755cd0ee0e5ffa2fd0d2c0ea41d89e67a27a8f6c94b134ba8d361491b3c20bacac3d226b",
"b021af793badbb857f9a353e320450c44c1030fce3885e6b271bcc02e6af65fdc5be4dc483ff44bd5d539ed1e7eb7efe3001252e92a87df8227ace601047e101c871d29302b3cb6c6f4639078afc81c4c0f4c2e04688612ecf3f7be1d58ea92894a5dab49b949f2089",
"c5c1f2fbf2c8504a686b615278fc6221858d401b7fe790b75fb6bca6885cdd128e9142bf925471ee126f9e62d984de1c30c9c677eff5fdbd5eb0fa4ef3bff6a831056cea20fd61cf44d56ffc5bda0e8472ecdc67946d63c40db4ba882bc4dfa16d8ddac600570b9b6bf3",
"88f8cc0daeaeaea7ab0520a311dff91b1fd9a7a3ec778c333422c9f3eb0bc183acc80dfefb17a5ac5f95c490693c45666ec69234919b83244003191bad837aa2a237daeb427e07b9e7aa6ca94b1db03d54ee8f4fe8d0802cb14a6599005eb6326eefe5008d9098d40aa851",
"2eb6b1a58e7fe39ff915ac84c2f21a22432c4f0d260380a3f993310af048b11647f95d23adf8a746500833ee4e467fb52ea9f1039519fa58bcb0f1d0151558147b3c92b83730aba0e20eeeea2b75f3ff3ad79f2f8a46cbbadb114a52e32f018342aeeaf827e03ad6d583bbce",
"3ba7dcd16a98be1df6b904457709b906cbf8d39516ef107006c0bf363db79f91aaae033466624d30858e61c2c368599963e49f22446e4473aa0df06e9c734e183a941510d540536377072334910e9cef56bc66c12df310ecd4b9dc14207439c1da0ac08bdd9be9f2c840df207e",
"a34a7926324ea96867dac6f0dba51d753268e497b1c4f272918c7eb0e34120be65b7b5ba044d583141ec3ea16fcedae6197116b16562fb0706a89dc8efd3ba173ccd0fd7d84d480e0a3dda3b580c326aa1caca623879b0fb91e7d173998889da704eda6495023b5ad4c9ad406298",
"5ef97d80b90d5c716322d9ba645a0e1b7a403968258a7d43d310320f60f96235f50e9f22cac0ad239636521fa0607d2f471051b505b371d88778c46fe6787d47a91a5bec4e3900fe6ed22918226fc9fbb3f70ee733c369420612b76b5f55988d757c891d7005d17ee55783fe506202",
"140d2c08dae0553f6a49585fd5c217796279152b2e100ebde6812d6e5f6b862b2a3a484aed4d6226197e511be2d7f05f55a916e32534ddcb81bdcf499c3f44f526eb515cc3b6fa4c4039ad251253241f541558bba7413ca29318a414179048a054104e433c674ca2d4b3a4c181878727",
"29fdfc1e859b001ee104d107216b5299a792d26b2418e823e0381fa390380d654e4a0a0720ba5ff59b2ff22d8c4e013284f980911dcfec7f0dca2f89867f311ced1ac8a14d669ef1114504a5b7626f67b22ecd86469800f1575543b72ab1d4c5c10ee08f06159a4a3e1ae09937f12aa173",
"52dfb643832a598a10786a430fc484d6370a05356ee61c80a101dbbcfac75847fba78e27e537cc4eb918eb5ab40b968d0fb23506fee2ad37e12fb7534fb55a9e50902b69ceb78d51db449cbe2d1fc0a8c0022d8a82e2182b0a059035e5f6c4f4cc90278518e178becfbea814f317f9e7c051",
"d32f69c6a8ee00ca83b82eaf82e312fbb00d9b2f6202412a1ffc6890b4509bbbeda4c4a90e8f7bca37e7fd82bd23307e2342d27aa10039a83da55e84ce273822740510e4ec239d73c52b0cbc245ad523af961994f19db225212bf4cc160f68a84760233952a8e09f2c963be9bb1d71ca4bb265",
"d1e603a46aa49ee1a9ded63918f80feca5fc22fb45f659fd837ff79be5ad7faf0bbd9c4ba91628ee293b478a7e6a7bd433fa265c20e5941b9ea7edc906055ce9799cbb06d0b33ae7ed7f4b918cc082c3d4a1ac317a4acec175a73cc3eeb7cb97d96d24133a29c19375c57f3a4105519846dd14d4",
"b45ac88fac2e8d8f5a4a90930cd7523730733369af9e39bf1ffb833c01108952198301f4619f04b9c399fef04c214bad3358999967c474b67a7c06457a1d61f9466489ed5c0c64c6cdc83027386d6263491d18e81ae8d68ca4e396a71207adaaa60997d0dca867065e68852e6dba9669b62dc7672b",
"d5f2893edd67f8a4b5245a616039ffe459d50e3d103ad4675102028f2c497ea69bf52fa62cd9e84f30ae2ea40449302932bbb0a5e426a054f166fdbe92c744314cc0a0aa58bbc3a8739f7e099961219ec208a8d01c1ae8a2a2b06534bf822aaa00ca96218e430f0389c69c7f3fd195e128c38d484ff6",
"37279a76e79f33f8b52f29358841db9ec2e03cc86d09a335f5a35c0a31a1db3e9c4eb7b1d1b978332f47f8c3e5409d4e443e1d15342a316f442e3bfa151f6a0d216df2443d80cbcf12c101c51f2946d81161583218584640f4f9c10de3bb3f4772bd3a0f4a365f444777456b913592719818afb26472b6",
"a46d252a0addf504ad2541e7d992cbed58a22ea5679980fb0df072d37540a77dd0a1448bdb7f172da7da19d6e4180a29356ecb2a8b5199b59a24e7028bb4521f3281313d2c00da9e1d284972ab6527066e9d508d68094c6aa03537226ef19c28d47f91dddebfcc796ec4221642ddf9de5b80b3b90c22d9e7",
"060c18d8b57b5e6572dee194c69e265c2743a48d4185a802eaa8d4dbd4c66c9ff725c93667f1fb816418f18c5f9be55e38b7718a9250bc06284bd834c7bd6dfcd11a97c14779ac539629bcd6e15b5fca3466d14fe60d8671af0fb8b080218703bc1c21563b8f640fde0304a3f4aeb9ec0482f880b5be0daa74",
"8f2f42bc01acca20d36054ec81272da60580a9a5414697e0bdb4e44a4ab18b8e690c8056d32f6eaaf9ee08f3448f1f23b9844cf33fb4a93cba5e8157b00b2179d18b6aa7215ae4e9dc9ad52484ad4bfb3688fc80565ddb246dd6db8f0937e01b0d2f2e2a64ad87e03c2a4ad74af5ab97976379445b96404f1d71",
"ccb9e524051cca0578aa1cb437116a01c400338f371f9e57525214ad5143b9c3416897eae8e584ce79347297071f67041f921cbc381c2be0b310b8004d039c7cc08cb8ff30ef83c3db413f3fb9c799e31cd930f64da1592ec980cc19830b2a448594cb12a61fc7a229e9c59fe1d66179772865894afd068f0942e5",
"3eb5dc42172022ab7d0bc465a3c725b2d82ee8d9844b396913ceb8a885323dbbbf9ef4ed549724cc96d451ea1d1d44a8175a75f2a7d44bb8bfc2c2dffed00db0328cfde52bf9171f4025770abbe59b3aefd8151c480bafa09f613955fd571e5d8c0d4936c670d182cf119c068d420ded12af694d63cd5aef2f4f6f71",
"20ea77e58e41337ad63f149ed962a8210b6efa3747fe9bea317c4b48f9641f7145b7906ed020a7ae7d2ee59435392edc32aee7eff978a661375af723fbd440dd84e4a152f2e6ef66f4ab1046b22c77ac52717de721dfe39aa8ba8cd5da27baca00cc1fffe12c52382f0ee83ad1418f4c6a122effaf7471e1e125d7e7ba",
"95c662b835171fa23f948c3c3ed27bab9b3c367bbfe267fe65f8037a35b50cd7fc6030bfce4000425ef646c34793f0762635ae70487a0216ef7428da622be895d1b6040423246511c2370d6876a5c5d2df8bbd48fb14f787b632ad2c1f5a927fdf36bc493c1c8606accfa52de33258669f7d2d73c9c81119591c8ea2b0ef",
"f708a230675d83299cc43167a771602d52fa37cbc068ef9128ef60d186e5d98efb8c98798da619d2011bf4673214f4a4c82e4b11156f6292f6e676d5b84dc1b81e7cc811b0d37310ac58da1bfcb339f6ba689d80dd876b82d131e03f450c6c9f15c3a3b3d4db43c273c94ed1d1bd6d369c4d30256ff80ea626bda56a6b94ea",
"f8417766ce86b275f2b7fec49da832ab9bf9cb6fdfe1b916979ae5b69176d7e0293f8d34cb55cf2b4264a8d671370cb595c419c1a3ce5b8afa642208481333522005fbe48cdc700e47b29254b79f685e1e91e7e34121784f53bd6a7d9fb6369571bba992c54316a54e309bbc2d488e9f4233d51d72a0dd8845772377f2c0feb9",
"3479e04efa2318afc441931a7d0134abc2f04227239fa5a6ae40f25189da1f1f313732026631969d3761aea0c478528b129808955be429136eeff003779dd0b8757e3b802bdff0f5f957e19278eabad72764aa74d469231e935f4c80040462ab56094e4a69a82346b3aeb075e73a8e30318e46fdaec0a42f17ccf5b592fb800613",
"03df0e061fa2ae63b42f94a1ba387661760deaab3ec8ffabcaff20eeed8d0717d8d09a0eafd9bde04e97b9501ac0c6f4255331f787d16054873f0673a3b42ce23b75a3b38c1ebcc04306d086c57a79d6095d8ce78e082a66c9efca7c2650c1046c6e0bbce0b2cba27c3824333e50e046e2a7703d3328ab3b82c9d6a51bc99b9516ff",
"76b488b801932932beefffdd8c19cf5b4632306e69e37e6a837e9a20c8e073bcadd5640549faa4972ebd7ee55cb2425b74cb041a52dd401b1a531beb6dfb23c4cfe74bc84f034156c8f55050ca93236eb73c4e2595d9fbf93dc49e1ec9a31705359732dda73f737ec4274e5c82626dc4ec929e5e2c7a2f5f5fb666181922bd8be575e3",
"ff17f6ef13abc0426b03d309dc6e8eeb822300f7b87eff4f9c44140a424098fd2aef860e5646066d22f5e8ed1e82a459c9b9ad7b9d5978c29718e17bff4eeefd1a80ba48108b551e62cd8be919e29edea8fbd5a96dfc97d01058d226105cfcdec0fba5d70769039c77be10bd182bd67f431e4b48b3345f534f08a4beb49628515d3e0b67",
"95b9d7b5b88431445ec80df511d4d106db2da75a2ba201484f90699157e5954d31a19f34d8f11524c1dabd88b9c3adcdba0520b2bdc8485def670409d1cd3707ff5f3e9dffe1bca56a23f254bf24770e2e636755f215814c8e897a062fd84c9f3f3fd62d16c6672a2578db26f65851b2c9f50e0f42685733a12dd9828cee198eb7c835b066",
"010e2192db21f3d49f96ba542b9977588025d823fc941c1c02d982eae87fb58c200b70b88d41bbe8ab0b0e8d6e0f14f7da03fde25e10148887d698289d2f686fa1408501422e1250af6b63e8bb30aac23dcdec4bba9c517361dff6dff5e6c6d9adcf42e1606e451b0004de10d90f0aed30dd853a7143e9e3f9256a1e638793713013ebee79d5",
"02aaf6b569e8e5b703ff5f28ccb6b89bf879b7311ea7f1a25edd372db62de8e000219afc1ad67e7909cc2f7c714c6fc63ba341062cebf24780980899950afc35cef38086ee88991e3002ae17c07fd8a16a49a8a90fc5540be0956dff95390c3d37629949de99920d93096eb35cf0427f75a6561cf68326e129dbeffb8772bfdce245d320f922ae",
"70752b3f18713e2f533246a2a46e38a83cc36dfccec07c1030b5204cba4432700735a8cee538b078d281a2d0262110381c5815a112bb84404f55af91652bd17502dd75e4910e062943d8a736ae3eecdfdd8e3f83e0a5e2ddeeff0ccbdadaddc95391310fc657a59724f7e6560c37dc1d5bb5db40170190f04a274c864ade9687c0f6a2a48283177a",
"01f3c1333b44077c518cc594d0fb90c37651fb7b2442e71fc0a5611097f1cf7bcfaf11c8e0ac1b1cab54afba15bb9332df6bc64d8032368e3f686c8324b0114e0979dad78a5ccd3fff88bbe89eef89c4be586ca092addef552ed33224e85d8c2f4fba85ac7735f34b6aa5ae5299154f861a9fb83046b0e8fca4db32c1343e02676f283975f43c086cf",
"509283ebc99ff8d87902fa00e2d2a6fa239e335fb840dbd0fdbab6ed2d95e8275402523f7ce9a2fabd4b6c9b533288fbe914bde84365a204711d0977a7d698f4614385984dd4c137e4820035dd6737da364edff1bb62283e87a8c7ae8637314fe9b5777ec4ec21276dafedb2ad5ee1aa0ac99e34a6c01c055c8a239fd28681607f65143082cd4553c529",
"c17e417e876db4e123c631f7136b8a85bfd6ce66a69180d0cd5ecfd6f037bb1c7bd7908d51f2c485bf9e92c0e1799ee5f6ab834ee481f5eb1a8020205adb4d0f90126d4e7c2c859c5a5f644bdfa9c649ff4f168e834de6f9769429732099d46d0af506ab86c6fd92175159bbc05c75db8e1fa867e6030d64250008d64c857c47caec3dc8b2ffb384d0193e",
"950988fbe9d62a66f5f2c492bc8dc944a78eb3796ec37ba94b6a81a9d402ccad03cd8497fff74c5f4a03081c5fecec48574fecb21c1de261332c23108195d3f6a96ff8e433a1a30eda53dd5bb414973334f8cde5510ff759f7c17046cbb5acd8e8c4a6eecf2a9121ec3fc4b22c4daa72678194ce809024cd45c4ebb9ccdb6f854205cdb624f0787480d8034d",
"552a212c403b473741da8e9c7b916d5e5e9bcc9949021ae1ca1ed46b7d4a98addbb604d9fff56175b7e0367db26c9635fa7813653dc8d610befdd09ec41e99b192a716106f4299eec8b940863e5a59cf26cdc2cd0c3017f9b4f215812bed15f69e77edf672178e13c55580982f01fcc2fa131ec3d736a55d56504c545f4be50fee83f1263e4d3f3c877cc6242c",
"b00c4283dd3d9cd26e44bd97cede6c771cb14f2571b51cfdaae4309560ffd165da025a1bbd31096c3aa8286e2d6dcc3e681b8d01f2c5064ea26dfd0b5156b7a7f5d1e046c5bd1628f8fdae24b03bdf7cf7366900cc013a8cbed9d7f5937c914b08f8c27683b956e1279812d04288515333fc6aba3684dde2292951f0610649d90fe61606630fc6a4cd383649252c",
"f6e79457bb6d0884dd223be2cf5ae412a1ed425f1e4012f75951b096aea3b9f3581f9013bcae1aff2d3fc1e5c7e06f24af6d53c2c5c238b71c71cc670b05a7ee5204400026a5c4e5ddec3ad96771e49fae4b0f75ec58049ad9d972e5749a32d90f847f1ed2a1bab83db181e541cf5c8adb6b29ecc64dc25add491d408d3eb3ddcb013de7f5ffb6de9dd7ff300a5fc6",
"fe1d71e1d5efa3f712d23216ee8ee9139e66bd648b83efc02cdb4d45a28cf36759ff190a84d14d9471477abefb5aea4111110336143dd80cf81e02f268120cc07d746538f968e9876bff8358d390f5b8e7eafa61ecd236cedaf276bd61865fdd3424988201dcdeda2e3e0c33c9e3b3670125dd1049106cc6df5695fb2dca443233ff440f265bbff055483bac1e859b83",
"4c80163562872a965dedd8725652906156ada6e9d999027d96f49289edb92f9ef043e9d7c3377e091b27f85275499454af32317535997fb4aaeaf93565ad481ff7d45d2abddd4df4b60f71a6923ec30496c6ae534dc5427107ab4c5e656a322c7ab058d4c13ec0ebafa76576560697ac98f84aa4a554f98ec87134c0d7dca9184cf70412a324aac91823c0aca02537d197",
"fdd58c5ffe88665beb7073c8f4c22472f4bc9390cdd27a42622ca55978b000ab7579f795d4de0dfcaf521b8268980ef1d20277b07567985c0fd5030784ad6c32541ac24e99ab706105a2255fc32935c0fce6fdad9bb224d94ae4eae2a3ff08836618a3adf193630647bce1952b69da4de360f59da303519278bfd39b733cf66820a5e9e971b702f45998b69a0889f4bec8ec",
"ff38b15aba3794e2c81d88003e045ac6cbfc9f4833cdf896cefd8ac0c88674727ad9a9fcb9ef36574deea480e6f6e8691c8390ad73b8ea0eb3665c914b0d886546948e67d7987eea248b5feb52346ffdd965d5c835144c3bc63daf325e74b11267e32e58a914ae4521a668839d9445fececa49c5fba41f9e171698bbc7c6c97fa163a377a96456958d6e1d74f91ada56a30df8",
"f048c19328d60b4e59ed76940415b2c84c23883198bba5699efb0a1774ad5da6d15390c7b55d77d66f37448fe08107f42a5336408d5322f4b630e3275865fc66dccab39f6e13fabc133e5a441fe352d81c7cd9a25f145a6e2e2417d3b0bbc79eafcd7ad688c02011fd268dd44ac3f4f87b37a84a46fd9e9975962fba92c9a3486deb0c45f6a2e044df4bb79f0feeea432c5008b0",
"1b3e5fe6f113cce28a6f8d6f7809d3cec398cabffe9ff2ff10a7fec29a4ee4b54186063fd5307a2be393c9ecd75a37620bdb94c9c18da69b658579676ec90351d10dc33a7cb3b75798b1234f9f684d4a73a0fab2df3d5d6fdb1c1b1514d0935c1f2dd21486f91c2595b2f8f8a500ff443b9305270fb6f3da7961d9316d4ed6a135a31c4a3611d40e6585bbb34f498cd5b9a5d92676",
"740db337baa12b16897f17a85fa5685acc85e48338867f8ac9c0198dd650f5dfa7c17725c1262c72207e365c8aa45ffaab6470a0e5afefbfc3bb702a9766064f28cc8b796878dfdd3ca9d0216c14941438fc541fb5be0a13d29a996c5c985db4f630df067a5626db5dcd8df3a2bff17dc446e46e4079b8815da4318cb228c7722684e2a795a0ca56f500ea51951a6a385385d886f678",
"1465f2d578d167faa017fe8f763ce3cc8dc1e8371d774ed2a8803f12585296ee71a1f2253dd16b717a81f91f0f3641018a0111182b4e65d884b0a3d0292631ad807cdccc88bdeecb476e76f72b5246a630aff6e2401fa9570f85acb73ccb4e19ef04a932a03d7b7985dbe1e5bb410df517fe362321469e6f8b0e0cef6c31d7aa8ec06aa220620d66cc0e133fdee963589b12320fc9678e",
"80c051952fa6f3ef6af0f1759ec3e83c8eb91abee1de360bfa09e74b05af2475a0dbf8f9135aa25892919bbe0515898cfb6f88abc9e1891f2b2180bb97370f578973d55c13c35edb22ed80647c2a7e2884d1ccb2dc2f92d7b6ec5843ade13a608a31190ce965bde97161c4d4af1d91ca9962053f9aa51865bdf04fc23fa35a6fc3c8e888941263a26ed66c2dd0b29b2325dfbd1227c5091c",
"9c1e2a1aed6406052eed12b4495365f2f80e9c9645473f3549b607f20910bcd16dc3a4b173ac8d128129cdb7c76ebbc8e9a2a1ba0d822c66b367e790a69ac71f0a60ed4bff0e979148e3f3ee6607c76dbc572ee5ff17c27e4b52adebb4bedddff517f591a1977299c7cb01106f1453b098d29848ba3751c816215bb0d090c50f9e445b41b2c49d4eec83b92ce6c269ce835fd279e7cbbb5e47",
"466abda8944d0329d2975c0f2e2afc901f117887af301881f63b714f49a2f692fa63a8871fc0b301fe8573dc9b2689880cd8969e5072c57671e0633b041481dab25e65c9de404af033a11a8070c8ab70ca6d465318501afdd9940c7efbe1bb6d49581c222fad251dba4ee0a98efe22a3c4f74da05844523b30bbad6b080ac8df70a02da80bc9d477dfb869adb211e209a316d5dd1fd89a6b8f8e",
"0e89a873e07799ba9372fc95d483193bd91a1ee6cc186374b51c8e4d1f40dd3d30e08f7feecfffbea5395d480ee588a294b96304b04f1ee7bbf6200cc8876395d1db3ac813e1019bb68d27204e514fe4a61ad2cbd1782dca0e38b5538c5390bca626c5895b745cfca5dac636fd4f37fed9014ab46ae1156c7789bbcbb956ff7ee5ce9effa560731d26783dc6ae8bddd53a5d28133614d0ddeddd9c",
"fdde2b80bc7a577ef0a6c03e59512bd5b62c265d860b75416ef0ce374d544cbb4e3a5dbd31e3b43e82975090c28bc77d1bdec907aeceb5d1c8b71375b6d631b84a46153f5f1d195bfcb2af6f597a9cdc83782c5bbbb58c5188a87ebf375eee5212fa52523820a83106e8ecd52bedd60d95cd646159774389c07e1adcaa6b6f649408f33399ec6e507d61659696b3dd249996892d5986b654d94ff337",
"f5d7d66929afcdff04de30e83f248e69e89604daea782e1d82d8032e91a95c1d6fb2f5578f79b51be4397e4cd7cbc608ce143fdddbc6fb6c43ffdd394a7df0124353b919aeeac025f3eb11ff246c3b9657c1a947fc534ce48e18feffada8797037c6bc7e2d9a9e2e019fe65627b3feb28e446473e3bd413047a2587f0be6a103403cb3c33fdc212dca14d8e386aa511c22308e632f5f9528dbabaf2deb",
"332990a8dba55f977bc814436cf386ebbf10cb487a5f6ce83e13741bac670c6810284fbbe4e303547ef411e964fae82854e8c13cf56979b89ecfedd337aad78260060122d13dfbbf8497acb2066ed89e30a1d5c11008bd4d145b5ec353956310536304d8b8bba0793baec6d8f3ff49718a56e6694f8122078265cf5731d9ba61292c1219a1affb3679576d4998290aba3684a205c3469d40761a5c4e96b2",
"efbdff285027610f03182009c89b953f19721cfcdb8accd74bab6ec4bdf3f555ab902cb0dd91284269d140638aaabd211748aa4da3b18cddc653b57e461b9ad8491807c535c08fe97d89eb587c6af19ca152e72479626ab764e8b62da89fefc8354c75a44851f985746d78715a5a92798dac1a4222be27897b3f0aa63d596aa7378545f49b259aa8518c3def8a2ec8f7aa956c43668c8717052035a7c36b47",
"0eea9bb83bdc324fd21b03669aa922fbebc448e7d25e210294c07862cfa6e061731dfb67b4810633f4dbe2130d90fa1c65843af436e74219d213c4458dcac1c48ec4541fc6e3b7918ab2bc621aedda53658050900c3865ca57cd5dfa1d28576827401956d2dd8b861fa90ab11bb0b544ded9bd3d62e3278ed484e17db8f2d5dc5ea4d19a0e15134ba6986714c2b22c59c2f0e517b74eb92ce40d2f5b89e6d79f",
"25da9f90d2d3f81b420ea5b03be69df8ccf05f91cc46d9ace62c7f56ead9de4af576fbeee747b906aad69e59104523fe03e1a0a4d5d902352df18d18dc8225855c46fefeec9bd09c508c916995ed4161ee633f6e6291cb16e8cac7edcce213417d34a2c1edea84a0e613278b1e853e25fb4d66ff4c7ee4584e7f9b681c319c874d43502534e8c16a57b1ae7cc0723783807738a55b661e617ee285bdb8b845607f",
"a76b6f81372df09322098868d469fb3fb9beafc5edb32c674974ca7032966aaca5b5c9bffef87bfe626bd8e33d1c5f054f7d5acd3b91ff95324d1ae39eb905b9f2694fe5cb03486cee86d2f661a751b0e6c716a61d1d405494c2d4e32bf803803dc02dba2c06eecf6f97fb1f6c5fd10cfc4215c06d627c46b6a16da0854e4c7c873d50aa1bd396b35961b5fa31ac962575230c07c369f8fbc1ff2256b47383a3df2a",
"f9db613812f2259972d91b1598ffb166031b339913925ee385f03b3b35dc4b2f1ae78a3c3d99c6ff6a07be129ce1f4b8d994d24988d7fbd31f20535d36ab6bd0592cfb4f8c1ed9244c7fa8a3c46e91272a1a40c6cfcf261c5658476c59793bf1a3775086e41a0492f88a31e2d9d1ce75cf1c6b4b928b3545d838d1de6b61b735d921bcf72e4e0615e9ff969ef76b4b947026cb016e2660ba39b0c4c953369a52c210de",
"e601c7e75f80b10a2d15b06c521618ddc1836fe9b024458385c53cbfcedd79f3b4239598cd7b9f72c42dec0b29dda9d4fa842173558ed16c2c0969f7117157317b57266990855b9acbf510e76310ebe4b96c0de47d7f6b00bb88d06fad2c2f01610b9a686079f3ed84613ba477922502bc2305681cd8dd465e70e357534503b7cbc68070ad16d9c51de96ccf0aae1599299331c5655b801fd1dd48dddf6902d0e9579f0c",
"ee5ff4ca16d1bde59ffaf2d064eac9141c1d8f120ea2bda942b7956ba3effc5f1e725a3b40b0b9223a14d7a50df1681d14ca0e0eda7bb09c428fa3b2701f83a7a3e139485a118f6287d266dbc7fe68c87b35becabc7782537c79cb8165bdc40cc103d7b6d4b627fafa0e4113f92341ab90ceab594bfae20dadbfafd401684584598941f1ffb8e23dc8a04ecd15376cda6d849fe0dfd177538c62413622d172d9d46e05c450",
"1daca80db6ed9cb162ae24aae07c02f4126f07cd09ecee8e798fa1bc25c26c644333b63731b4ebc3f287f2318a820c32a3a55fc976576bc936f7384e2553d2891e3771ff24dd4c7f0256906460a8f12d30ed2b23583a0259cb00a9065a757d654d6e4603e7c7eb4a8426b527ae8a849d9350e9094b890367df3e8b23ad2df4d7dcce416bd8ea3badd037f53f7b07c02e5926515f196d62aeb9b8b14c863f067fc12c5dfc90db",
"27ff4e58a34ff1fcd66855d014ea17889a3cf0021a9fea3fabfd5b270ae770f40b5439e00c0d26bd9766f6fb0b4f23c5fcc195edf6d04bf708e5b0bced4f5c256e5ae47cc5651e51cd9fe9dc5d101439b9bc5cc24f76a8e8847c72686e2af1ce7098ad7bc104dad00c096a6d48b6453322e9cd6773fb91fb1eabd05dc5185a9aea07a2f64c6fea9897681b4428aaffe1fe5fd3e8ceb890b12169ec9d51eaabf0ca3d5ba415770d",
"75e2fb56327983b04f640717be8cba6fef3655b4d8e5539587d6478356ec397efaed818b8425d052778eb30ef0dee656c52c2aeab079ed496ae4441a365f2130432c87ba757e25b4511656ad15e2eff84d342331fd2814d1f1d11af65d98a424c115ba183437c0d0aa55f5c44b8685028a47d89d0d36a0f20aed510c366ab338f074a941b404fb349caaec821e0850a627777cc8f5abce6b509290027a2a28ff1db62a5ed2f95fc6",
"c6ae8b6a060917cd498aa7874ad44baff73efc89a023d9f3e9d12c03d0b7f5bcb5e24e1bc2ab2f2c67b9a9d36ff8beb51b5affd4a3510361001c80642955b22ea4bf28b81a5affe5ecdbabd8d17960a6af3825a4522fe76b3d720b5d06e66bff5379d7a8de1f5cc3e7bb75163a854d77d9b3949bf904b6c4e568682f0dab7f217f80da7303cfdc9a53c17b6b51d8ddff0ce49541e0c7d7b2eed82a9d6be4aec73274c30895f5f0f5fa",
"606c9a15a89cd66a00f26122e33ab0a08c4f73f073d843e0f6a4c1618271cfd64e52a055327deaaea8841bdd5b778ebbbd46fbc5f43362326208fdb0d0f93153c57072e2e84cecfe3b45accae7cf9dd1b3eaf9d8250d8174b3dade2256ecc8c3acc77f79d1bf9795a53c46c0f04196d8b492608a9f2a0f0b80294e2abe012dc01e60af94323c467f44c536bf375cddbb068c78432843703dd00544f4fff3eaa1a5a1467afaae7815f80d",
"88b383cb266937c4259fc65b9005a8c190ee6cc4b7d3575900e6f3f091d0a2cefa26e601259ffb3fd03083270eb63db1ffb8b4515ec454d12f0944f8f9f6869eedc2c5f1689766a748d74e79ad83ff6a1639aefdec6109342dead31e9cead50bcc00c5b2206e8aaa47fdd01397b141880490174141a1e6e19268378c1b54a84aba60ca711fd72f7df88e120dfea2caa140085a0cf73342f3c588b7edfb5b5e5ccabd68a32364746d92d536",
"dc0b293f1ba02a326743509f41efdfeeac1efc45137ac03e397a3273a1f586a0190cfb4ea96d6c13ca692a4de6de905c8338c3e29a04cbae76272f568b9d795cea5d758106b9d9cff6f80ef650d6b7c428ea3946c3acc594907fe4227ed68faf31f2f6775f1be5139dc0b4d73ed6308fa226b9077561c9e4c7a4df68cc6b819b0f463a11b9a09682ba99752c4db7aea9beac1d9279f2c2675d42b551d27aa2c1c34125e32f2f6f45c35bca45",
"5d801a7413311e1d1b19b3c321542b22e2a4ccbe340545d272abede9223741d9835a0fc80cc9da97a13f8bb4110eb4ad71093efba165b1edad0da01da89d86726e0d8e42ae003b4b50297d233c87da08406f0e7fc58ba6da5ee5ba3d2d7142cbe6632734eb2e7b7863c15cc82198ee8f9a0ae0b7f93bdbda1ed269b3824d5d3c8e78513815b17a4c0cc8c9706b9c77423a309ae3fd98e1e05cdbe9e2577834fd71f964301b10b66c316a2d8f2c",
"2fd32a2bc15a9e96a100624404fd0a4e54ba9f8c0543d8ccf7c5c2e35f5e8c3c11dfd497320aa903900a4ca55a2b323b3ac4a7cfcd01bf0b448db8829072bee6b77c3d7bec2e1d8b414d907288d4a804d2379546ef2e2dc628269589164b13fceb32dba6fd5d48a956ce0b5c3eb28d894a95af58bf52f0d6d6cbe51317152744b4ccfc918ed17fa6856478d580b389016b772e1d02e57d2217a204e25361d91d4845a3fa20fefe2c5004f1f89ff7",
"f537b437662759bef8bd64368536b9c64fffbddc5e2cbdad465c3966b7f2c4bc5b96767ef40a1c144a4f1cd49edc4cc5b57e7eb30d9b90108f6fd3c0dc8a8808b9e0bd13aa3d661c4863637c5e4ba286553694a60bef18801299ae349df53a355051dcc46a7d003c4aa613808f430e9db8ca7dfe0b3f0a4c5ab6eb306aeb53e11a01f910064fbe6ca78b2a94fac34a2602f73de3f275953e13ff5c6bb5c39b82321ead17ec0f8ecc479e6afbc926e1",
"1dd9fb7d5b5d5074971e69300720014deba6fbdb942bd29704cdfcd40fa5281d2a1b9f5b776183e03ff99c29587f10e8d325cb49c5c93e94f5132741b92c4086eec1374dea5c1e772cbb230c7b31f3e962eb572be810076bdb926b63732522cdf815c3ab99bbc164a1036aab103cac7b823dd21a911aec9bc794028f07b7f839bae0e68211286441f1c8d3a35b281fd321312577bbda04f643ecb2a74ec4527bb5148dbccbeba749f5ea19b6072366ba",
"5bd63737449de2d20ca63943953338ecf4cdd6cd0a726241adb04376385a809cc6ba0f3482a310746fbc2cd5eb214f03a14cdc548777fb0d048d659cd75a962e490c4fe47affc2430a34b10275e4c76752a115aae3a24d4fb4fad89ce4d79d65de10292f3490bfdaeabfae08ed51bda6ec8230e66cb07ddbeec26e3ef68dd71c852900659fcf0c963f4574ffe4626a33db9abf0873dde68b21138498b81e8cc44d354be4073615889a7ddff633b5447d38",
"a683ec8250506571f9c640fb1837e1ebb06f123e745f95e521e4ea7a0b2b08a514bbe5bdfd316903d1d6a05f5a143d94dab61d8a3a146ab40b2d6b72df2f0e945875a8aa7051ed115975f6f1567cfcbf04c5e11e3a7027b8e179ba00739181ba10b028e3df7259d0712f4a6cef96469ff737865b85fee2c2db02a6423e32505381e18a1e0b4ce3c7998b8d6b1b5e09c3a280b85486d0984c9e193b0ad2043c2bc4ad04f5b00a73956715937eebf6b3e27afc",
"4df9d160b8e81c42930c48956fcb46b20b6656ee30e5a51dd6317876dc33e0160d31280fc185e58479f994991d575a917073b4439919c9ac49b6a7c3f985211d084c82c9d5c5b9a2d29c5699a22e79de3958d7b0e856b9aa97493cd4563aaa04fa3977a9bb89e0bc06a82296bdc76d20c8d393770176d648712454305fdfcf4e117d05acb5a5b006a9f8d0dc66dca708c4e4103ca825d2331750685c44ce3d9b3e753455580f4d6ac4533edeeb02cebec7cc84",
"67bb59c3ef5ee8bc79b89a673e331e581215076cc36b68f517ca0a74f74efafe9dcc240e6d8ca4b21019c27d6c9289f4419b4f218eeb39eb741c5ebebfe0ed2f6faeec5e8c477acf71907990e8e288f4d4049111779b0635c7bbec16b76493f1c22f645745fdac2b383679fee573e4f47af45ee08d84f63a5ace4ee1c06fa41e2e6e14b7bc392e38426813087a3a461efc62ed1941dc8f1728a2bdc04fde72a0b786558783c84abd4bd100e4926979a0a5e707b1",
"d341147169d2937ff2373bd0a9aefa77968ec8f0d993c6f9881eb174a1911e05cdc45993cb86d149a754bbe321ae38363f9518c50dd3faf087ffeeeb6a058b226ccab7858c00ba6de0e8f4d034b1d27508da5cc473f3a413189ee6fd912d7750486912944d4dc34405ce5ccc3885fb0aabcb922bcfa9081d0ab84c288022bd501235a835eb2e1124ed1d48fd4f8682da8e7919321031326502273375625c4e3a7282b9f53452195e53c6b4b57cd5c66f621bed1814",
"27e7872a54dfff359ea7f0fca256983f7600236e716e111be15a1fe72eb66923ea60038ca2953b0286447dfe4fe853ca13c4d1ddc7a578f1fc5fc8598b05809ad0c64a4363c0228f8d15e28280837a16a5c4dadab681e28968ae17934639fbc124bc59212138e494eecad48f6546c38366f1b7b2a0f56f579f41fb3aef75dc5a0958b25deaa50cb7fd1c69816aa9a51874a98e57911a33daf773c6e6166cecfeec7a0cf54df01ab4b931984f54424e92e08cd92d5e43",
"13dcc9c2783b3fbf6711d02505b924e72ec6736131159017b966dda90986b97522bf52fd15fc0560ecb91e2175322334aaaa0097e1f3777c0be6d5d3de18ed6fa3444133486068a777443a8d0fa212ca46994944555c87ad1fb3a367db711c7ebd8f7a7a6dbb3a0207de85851d1b0ad2f4149bdd5a5ba0e1a81ff742df95edee850c0de20e90dd01753137cb8f2c64e5e4638ceb893a3879ae2c049aa5bce44d56bf3f325b6c5029b2b8e1b2da8de7d4e48ca7d8f6fbdc",
"9ca875115b109eab538d4ec7023600ad953cacdb49b5abe263e68b48eafac89a15e803e838d048d9625972f271cc8f36344bed7bab69abf0bf05979a4cfff273b82f9961626509765fcb4b4e7fa48212bcb3ab2b1f2dd5e2af768cba6300a813514dd13e4d269e3d36548af0cacdb18bb2439ec9459f6d847d39f5598304ec46a26d75de1f9f0c2a88db915bd26e45e1f1e68c5b5b50d1890e97a3803c36755f026863d14176b8b57f42e91d3ff37787f9b38e333e9f0433",
"ec006ac11e6d62b6d9b32ebe2e18c002353a9ffd5dfbc5161ab887770ddd9b8c0e19e5321e5bc105add22e473050b71f0399327c7eba1ef809f8667c1f4e2c7172e10e753705e9a083f5bce88d77521225ecd9e89f1e1caed367fb0275dc28f620fbd67e6b176c9ae5d2659e6ec662116c9f2bbca3a93043233a4861e0688db6dc1800f752c5d58aa5033c250c891d9126e534ed921a9026eb333333fa8292059b8b446f336ca6a0cb4c7946b6aea3831653122f154a4ea1d7",
"23deadc94481ce28188f3a0ca3e85431964cb31b60fabf381e6bd45ef0332bd4dde774b0281d317dc2e7d0c298fcf8625fa734126968df8b68ef8a35c325d84ba4fc53936ff3ffdd8838d2a8cabf8a9cac54aa444ed9875944e55994a22f7fa8538b1e983b57d9215fac5c0052029644044e790ce2f5044655608c1d7ad3bb862203ba3aba3b526606f273d342ed5721648e3f600942d3f7546f679161436389d879dd8094e1bd1b1e12cde15cd3cda4c30a40835665e4e5cf94",
"94701e06340114f9cf715a1fb659988d33db59e87bc4844b1500448960af757b5282f6d52967a6ae11aa4ecfc6818c962b084c811a57724f5d401191567f24ce917e4f8c3963474fdc9d2c8613c16f62446448b6da6eeae54d672825ed7606a90e4611d0e318ff00566862c955b636b5e81fec3362e8672ad2a6d222a515cf410482836deba092a51a4d464dfbbab35c50a33437ac16a88256e9e23ddd3c827cc58d3e5000ee90b12e4c5175c5733662d4848ae0d406c2f0a4f498",
"735b0758d5a331b2304f01081172eb95ae4115de651b1a6693c5b9543de33df25d9f421dbaeca033fc8bff57313b482778005aa9fdcbca65c643da2f3320e34197868eec3848ff3c70d7ac7d910fc332e9a359f892ae01641be253013b554a0d3f249b3586b1857e5a0f9482ebd91432a852b221f4287a6e81ed24e8064645d5b28ab9a13b26cc1420ce73dbc47b31acf8a871601022ce23bc443b1222ce9a037a2fe5226295feb4efd4fd671338f459ae146032697cf82fc55c8fbf",
"c48d94f14549352790079fee69e3e72ebaa380510e3581a0824066413e7044a36ad08affbf9b52b21963d2f8e092ff0ac1c973c423ade3ece5d3bca852b894675e8173290529226939c24109f50b8b0d5c9f762ff10388833d99bea99c5ef3ebb2a9d19d2231e67ca6c9056d8834730605897426cd069cbeb6a46b9f5332be73ab45c03fcc35c2d91f22bf3861b2b2549f9ec8798aeff83ceaf707325c77e7389b388de8dab7c7c63a4110ec156c5145e42203c4a8e3d071a7cb83b4cd",
"553e9e0de274167ecdd7b5fc85f9c0e665be7c22c93ddc6ec840ce171cf5d1d1a476743eb7ea0c9492eac5a4c9837c62a91dd1a6ea9e6fff1f1470b22cc62359474a6ba0b0334b2739528454470f4e14b9c4eeb6fd2cdd7e7c6f97668eebd1000bef4388015630a8332de7b17c2004060ecb11e58029b3f9575040a5dd4e294e7c78e4fc99e4390c56534a4e933d9a45460f62ffaaba25da293f7765cd7a4ce78c28a85013b893a0099c1c128b01ee66a76f051dc1409bf4176e5afec90e",
"dea8f97c66a3e375d0a3412105ed4f0784f3973ec8c57b4f553d3da40fd4cfd39761de563ec96a9178804641f7ebbee48caf9dec17a14bc8246618b22e683c0090259e3db19dc5b6175710df80cdc735a92a990a3cfb166461ae713adda7d9fa3c4cf9f409b1467f3cf85d2141ef3f119d1c53f23c0380b1ebd728d7e932c535965bca41a414b6ea5bf0f9a381e098d282a554a25ce41980d7c7be75ff5ce4b1e54cc61e683f1dd817b8e2c1a430d7f895e5e7af13912cc110f0bbb95372fb",
"9dfda2e2f732867e60ed2b5fa99ab88eb82dc7a54334d02031258beef75fa4bd6962a1083b9c29e4eeb3e5ab8065f3e2fc732675b8d7705c16cfb4ef7305eb58120f1af5ddc55872a2cbde3a48661a0598f48f63e2e9aadc603545e2b6001748e3af9e86e1830af7b84ffd3e8f16679213d37cac91f07af0af02b37f5ed946ef5c955b60d488acc6ae736b10459ca7dabeacd7dabcfd656511ac913174f6d99327be59befe3e463a49afbb5235f0ce2840588c6edfbaaba00a4211c0764dd638",
"ddcd23e8b9dc8889b8599c721e7f8ecc2cbdca03e5a8fd5105f7f2941daec4e2906c654210bdd478374ddee43ee749a920ee91872e057a1157d384dcd111266221b3c79774476b4862fe450704ff2c5353e9a936cac87c96515c28ed4c830335a55d084cb5873c5fd2dd907f3266d8eb7bf13b6dd7cd4966982a0949efd8e428dae13daee549e01cc3c226211d6307823f742c5ef2155601a4644c46eddd603d4abd959c6d242e427768df3b1e22d87971df58a1564b38311a897c85b497a72556",
"39016647acfbc63fe55a74598bc1956eaf4e0cb49d532c5d8323fc6a3f15a0231597f06eafd74ad245e672bf6b21e4da503cb5bf9d15e9038ef354b38807564d91f38b4258378ccd9b9420a1562d7136196822a1291c913d83c4cd99fd8d420990c72cdc47607124de21da8d9c7f472fdcc780379f186a04da93cd87628abf323c8dadcd7fb8fbade37d7d2b5c9f9fc524ff77494c98f42f2158a6f68c906105ca9e8bb2df463863cfc1e9008d8344f55c4e3203dde6699b59812d49ce1279fa1c86",
"02cff7567067cbca5911664c6bd7daaf484181edd2a771d0b64566c3ab08d382e83932cdd7b4dbf86c9cdd1a4c353a511e68afb6746a507a9cd385c198246f4543d606c6149a5384e4ff54c1b90d663dc7a4b91aeac3cf716db7ca6f9a1914e3a33efe82e7ccc4215999c0b012782402db4726db1d7d1c73571d45739aa6fcb5a20eeb54a84d5f99902a8d356cbf95f34c9c28c8f2badfbc08c69233514493c0c04963268c88bc54039ab2999c7b06cba405936dfc43b48cb53f62e18e7ff8ff3f6eb9",
"5764812ae6ab9491d8d295a0299228ec7146148ff373241a510faee7db7080706a8dada87938bf726c754e416c8c63c0ac617266a0a4863c2582412bf0f53b827e9a3465949a03dc2db3cb10b8c75e45cb9bf65410a0f6e6410b7f71f3a7e229e647cbbd5a54904bb96f8358adea1aaa0e845ac2838f6dd16936baa15a7c755af8029ef50aed3066d375d3265eaaa38822d11b173f4a1de39461d17d1629c8df7334d8da1b6401daaf7f34b2b48d6556ae99cd29ed1073926bcda867421832a4c36c7095",
"4df3043cf0f90462b37d9106e67366d112e4938c4f06abae97869531af89e9feebce0812dffe71a226de5dc36be652e26ef6a4be47d9b2db5cdd43809a565e4fc0988bfe82037c505dd276b757b785203249fd083fb474a25acccc9f38dc5164ff9097e05989aa6e280739a755231f93670e7226e22046914c155bf33d135b3f736ccca84cc47ae643215a054b54b7e13ffcd7ad73cced9279dc3210b80700fcc757acfb64c68e0bc4da05aac2b6a99d5582e79b303c88a7ac4dd8ed4289516bba0e243527",
"bf041a11622715426c3a755c637d5f478dd7da949e50f05377bf333f1c62c671ebdbf9467d37b780c25f7af9d453fc67fafb2f065a3f9f15d4c3561eeaa73fa6c813bf96dcf02430a2e6b65da8d174d2558110dc1208bdcb7898e2670894c0b9e2c894da3b130f57a90ec8ea1bffd27a37b4da4645c546b2b141db4e2c919154dac00e78dd3eb6e4445974e3bb07905982da35e4069ee8f8c5acd0efcfa5c981b4fd5d42da83c633e3e35ebdc959bd14c8bacb52212b4334f94aa64d2ee183861db35d2d8a94",
"a170ceda0613adc9c3a1e427f07beacf3b16ed69fb42b6bc09a38d803f632ad2929dba215b85683b74e2feb1d18fe17d0ea0db84d1be4e2e73476917a2a4cff51d6eca7c5e82232afde00dd2286a4c20eb09800b4d5d80e7ea35b6965b9792d99e399abda8cf32174ae2b7414b9bdb9d63e148f7357635a7310b130c939593cd3479164724011966c4232142df9966f09422f34f20b30af4b640a2c6d3dd985fe0ba3dfa9083cbb9b8dfe540ff9f6c608d18481213040768ef33300d773f9890c724ead320a1e7",
"929477e9c2d0bbad3429a0e0de776695255013108261dc6404cb09828770e274d8bb650a50e490dfe917fc2047b0f8ee72e105927d9fa70523c727778cbf6ae876d641ad562938c870d12f2e047bb78920739dba0c3f8ce1fb77589623a5f1625f5d6ab81940c7dfc3dc3a641d82b2813629bab8282999317d6b93842334f123fb4693a9c2c9d8ba9bfc746642dfbd045cd2021b272eab7358aa954d453da53fc5392dfa7eb881f6f53809b692d27f3366595ff403289efcc691e118b4744a1147071d8909bef1e8",
"3e98bb14fff5bdf7db38a3960dc55ca7d02333daed8712cca13dd5bffd114636559279db72554cc0a0ee1f7e15557d77cab0f2f1131f94fe698db81be38300a856a5eca85e5cf915fb7b6f38ccd2f27350e62cc30ce10ffe835118be3d435d2342ed3d06199b7e20c8e34d68902f0ab8745bd8b7d5b863d525c1f5906d2dca598db8a0f1e67736182cac15677579c58b8c670cae1be3e3c882153b2aa2988933e579ec2d6dbb00c671da64443dfc027dee6dfc3233c99758304570a982bf9b2eb59ccd70d0b54c4b54",
"aa12c7fa50ffdc2811c1872e4bee15f43e6909212385c872eb489f7e06dc1787043f56126f8373bdfa4b3f61405c73dd4dfd3f40aa5cd207e8520849c26f67716a46c0989a99efff42f24e0736e327af8e607c401a1bac77341e9a78c91e35d55b2457bdd5317a405a1fcf7a2a23de68ef92b65819e8aa3807c545361dfc9fe89125123492da958dc313cb5d03cb4b192c54ac6b27fcbc498652f5ed36b587bb74942b3ad453a8d79e5ddc06ebf806dad5046b73251064582ef5777dc530f8701701761884783fdf197f",
"83e615cf6e17a29e63945710b548a6d9935850eec69830841e26cb6071e908bf72c87cf079ffb34c5eb1a390def72d004a9488224a18e189aa1092a0f1135712834d257a53dc1d0e2c6417d8f472ff13b181910f4c93a307420d44beec8875d5219a3160b8e921434ddf3f71d68db1c1d5c39d68edb7a604792f8b4e31ecda7895c99fc7031a5b98a22009c1da005ac8fd2da0b5d742743f5712d12fd76d11a18e487776ce21ca0d6e5ab9ca6d8c394c321b91c14e291399a642721361811a73b7392e8603a3004e7060bf",
"ae1a8f7bfe4b1a0fa94708921dadb2c20b938239d7b9a2c7c598528f20f49764d322ebe85a5b2ea15563cf2f2304baf55d6607c52e2e1160859dcb7af6d7856899eada0e9128a180d3de6fed9334ba52b80c5c362d5591a0ec30f86d37a399927eb1c53076a12d26775522c511c83eb5b7abc2a00bd2dfd5627a8febba53d85f9b74c4b7f0c862ddb0d9298899b646b774d6cc23e4e23ab47174fccd34499253996d5e0917210e2f6daa1685f89f2f1fdfd5509ebc38191d539ecfb54ff0f5bbe6ef36ea35d425af6462f518",
"1d033e06be253ab800c8176d3a9650ab2a5bcaa03e11ea95fb9ab3834b41eb0d1b2bcecfe219364c3104ef65a8d692bd77c798548b7d9a8faf7f5172db24ec7c93006d6e9839368291b8277a82c034a3731f1b2e298d6e0282ec8a7902e4f844d132f1d261d171375c646065e201849f2df73e3748d853a3122c2206aac92fea448500c5418ecfb3d80e0e6c0d51f85831ce74f6c659cc291f5348a1ef8b949f1b2a753633e382f40c1bd1b2f44748ea61127b6f568255ae25e1da9f52c8c53cd62cd482788ae430388a92694c",
"104bc838b16a641749dcf73c57b207ea3bcc84381170e4ca362065a3d492e892b426a1f4fd82f69461d1ce1f3aaf8fc291ea30d6667e7e1aea4c44f7d52a5fa6d34709e6658483260ff5da76bfb74e7d194ad40dcac00daf0e45e74db4bc2248100a8b256b257278c3c98f1f2e3a80cdb812352aaf4155b3a4033999fb9fe7f506994fcf3a8db31e9e5ca8ef8c2e9c6326ca5b0803724ba641950eca877fe6ed6afc2e014651c56d0e6a61eaff7c5ed0b861d4bebe42904c0a568c26aa8abb2e97da2bfb40f14eafb6bf16cd208f",
"5b92e4a175437d0a53eb10de2c56401720b11715a034459ebf506c3fd6534b5e817a0f09deac4bcfd353301d8d031b1331582ac09189b48e6ccea444655866c4bbd123d45ebabb774f877cf12d33b84cfca4a6a94f3f98869fcf2bbb6cc1b964c2438c2f348bcdf9001dce60a4706d20c169a040baa61cbeb0b8e58d505e6e3739ab03e110ae7efdf91347474033defbd1e86af322ec6456d3394699ca7ca6a29a70d9b10a38fe666eab2858bfe12dacb31568549c826c15af5b6fddf779954351be1872f04e53db7b3b5fbf61fd18",
"401cc7bd9f8227efaed70dad83fc8db3bd38efc166f0f11ab142c565c68ba9db680423a3d698b6f3476ef440051fd20b93f6a2ed045825567df5a65e3f62e4442ec396ad260a16a13a1dee46c7e8d88bdd7edf223ab76a9a787c1f4fe9925c051a4ca0e77a0e78baa29f36d193c862fd3a60653f544ea9e3f75f2f553891be8c1fb882f6a6aad118f576f3c2793efc67221b37a45ab6137434f6228cb002fc137b91fb8572c757f00736879453d64a8a868c131810ffdad9e9d028d132157ecb1da675d54047d19b27d3258c9b1bca0a",
"c20cf0354982ca6a19d9a4dbf78f810934db2373941a12c263adefa61a5f385c859bc47028829c531dc25ccc0004c7510e707175a102ec3c4b4c933e3f52033e67476ff5f864c446c042a21e6037f7798363d20267891b965879fde80af6b59d77862e3a229af01b7ac78b578e94bd9f9b073c38a627c1864df0083aabb17024bdab6c3c0f0f73d31d59480523a2f23b78baa0385c15f290114305d7f98786b7dbc17a8c2aad97448e8ea389e68ef71091a6a9735ac12ca5497b9171da11a93c28d3273f58b74e2e46279d3ce9d0b20d19",
"e2365c2754073b511f16a1881ff8a537541ca7362ae7b84223d3c7d1d49d03a37d6d05dd2b819af9705c015dacc9dda83474eb14b7d5fce6e8a8f8c58e870149338d320e5ae476da6749af45e65ffed550d225a39dc74ffd93ba7da476985d6f44e90fc8e82454496260458431804d802fe804d825f611772f9710667377adfb1a11e4275bcecb42175c515f6a9439a359824f82cc9d480954364e6693099a821ace362e6c7ecbe68be8823bb5b49b4f23ad81b64139e3b63d9d4d298a842f013ef0d91ce7915ee8f816c70ba2aa3994216f",
"9c43944676fe859327096f82049cf69e48b98715878400fdf2805e0d5ee642e6cc9c43739f418b701348a033c5cb96bf8702fcd2fac9be58262a843c1e4155ed8a1724b6ebf7cce659d88a95a0c54deb2d7d9574a45219b6419ee173d1d8fad3ace47c962b349abe1048565df85bbd0eb9b11698258c23598023a00fdd26573e41951452027125c6e894a97736ecd63fd15b29a55d8dd9dab7e2e18f541a2e341890a61b7c896e7dc67aa82f3479dacd4a8ec7558d40c34d9ae4060e13718d676c2450258d83de8a86e012813693098c165b4e",
"1c707c29582d98a0e99639211102f3f041660ca03ad0939fe3855b8c1b22d6a9b8673c93e3eabc0ab231509b2b0d73c76a290a363943d12d2ff0ea30c6dd54eda753767effe04cabb4c3966388fa4c83a1906a0f48519a5fba9aeb585e0f8c45d6123a75ebe98fd1d0272f733a3925119481a321fe7509346c05128302851ba17a137f956f184e057a305e79a148727a5926de6854eb0314d5492fd735fa773d99ea34c95ca7546bd3a3aa8e66bcc6d860cec3d35d0e2165d5fbe8be99b6e7967df6693e5a6243e94c9c4a2528ae6305cbeca209",
"8f1e88103ffa378f062cade0ec509bec99a5c73fb273e79dbef24abf718ac26ac23dfd2b8932038ed3cb9637b71643c161142019f45b25b4fa4c52356737a27027e805ec635154327a66bfe64efc6285cca98c34edc7fb6c0766970a545342cf840aec0a5ba1dd3c6949be4fe97b0f8c8186de07536fd9074db34d09b2f08af9dcf9424d6edbf9cd044102c0e5dc35aff78c36d079dbd2c500e19c8c985ae2abaf6b2a20716bb719754a8840ce97632116c4d0b0e3c83ccca27f11c4204b76b5d6cfe6348a9615d8e4af53500dc4c2cabf12ec8c76",
"b9a0c28f1a6156992c103a84655fc6e654fa6e45e45819513afa797024717c00cc195994512fd53ecd1e12dac4d2448e0c40308382312084d2111f7db147b2e6589ce6d977f6115f629508167df8f45bac98abd49f6b272bcc4fd874dd5e29fb6daceb2d727a2a892194cfb9269eda00626ac89b4e74bd29b21e9f6ef18cb69889a02d4f0a06a2e5718899c1dc3b051c2cfa29653e782f87fefa478e6465bf5ff27f8b6abdb500077aac97100bd955ec535a587d66f23354be51cd8170289344bac9451f74e8aee3639f7c09981f4885e018912324d7",
"456844a34ae1074246f8f71eeef2010ec8733265bed7c1cc60043d770edfa320cbd4284a94be2574337e16d27f125074ebd7e99031f7abb4547b9540a7b0b5148ef501b550dd929f3dfe39ac65519f563e9254424aaafa05b1d37c16c771882e9e25d4906ac58603da749adf686932cd73d81e2658134fe69294c7a521d257eaf2110c667fc9d6f09b52d24b93910e532184eeb96eae9d9c9750ac3c39e79367431ac1af7011172d0a8be46a31010219a0310a733068c589bfc4748f3626aa4ff8d355cc893d05111c287c9992e95ad47481a6c42d6eca",
"c5c4b9900b9727bdc24baa544cad5faf8340be6b3759361f53889f71f5f4b224aa0090d875a00ea7116772117dbefc3a81c6950ca7ceeae71e4ba975c50d61fec82e6d9448d3a0dfd10bb087bdf0673e3e19fa2aaa7e97eebf71f11b86034fcf5a61240c71444ac3da15ef09b27b3523d37d309e8722380f835c1aee4a767bb027ec0674040853e5b53d6a31657f51acff6d2487860becd5ce695696cfe5937f4a0217b69e01cc6facc24dfe5f5230b8692a0b718e3b3c789d682db36101795a9a5f8bbb838c3679be72f7941a1db180135347d0a884ab7c",
"1781df2fedd2c39137854737d054cd3ed16b0ade411e41d97888ac900fdb46d9ae26b3d2dd07e118fd57eabd0dfd03a55793c76420666444865371adffc9b2f35068a0d70f9cfda1ac27ccb4beff4ffa5b8bb8bddac843386675c38a181fd0d935d6d51b25d78e7ff4ecef27a9853c0f0d2879c395ed1c4883987d123890d04f851c3e042e1164c68c0d503de16816f4b0e554236e5f4c339ea11d01ce652f6208f78f457a2417a97c0a6a240f443262def4b6763abf53e597bf1a28f907dc7cbdc751a234ea7d75710ad5ab0c37e8e9805102a375abd44011",
"8963552ad1e729ead07750df599d734157aaa4bcdcac17e8eb19b4f99cdb162686ff433137aa4e8a0cc8df0053999196262115aec326cf37567d9ba4760e0ad21d5763977f1ab9b35c0fc667890fa87fc946ceb776a811b5adc69446bfb8f5d9908029dc5aa38db816e4a4e8f98e5a48cf0a01627031c5bd1ced8bc1940dcafe4ae2f1199b186468eafc07e96a89d95dc18ef0fed3eda5b58ce58f221a47ba5311313cc680367eeb058fafc7bcadce5f520b6371489d9e529278ae6ee2650a85aed82896879038bbd9aa8d685fc9528943ccf2235cdf69a86464",
"23ceae3008085134433f5de4b47bafe0f443d443491e6cd47b216dd2dcc3da65239515a6e6b9beb9a939ae9f1f1f5e11f88326475e0962f319d9bf75ddfb4a46e7cc3f799d7547f3c0b2e089018b75787b82ea1a7295e7411f4852f94c94170e98bb0647923b8eb7d184038e56560da46085540cbfef82b6b577c445d038f6c93fbfdfc96ab3a0191d20a57b8610efb4cc45cd95198198e6f80ac46b0601511885f650eb00992605be903bcb46cd53c360c6f86e476c4c9ca4ad052eb572bbf26eb81dd9c73bcbec137aea6ee27aa97dadf7bef733fa1555019dab",
"c0fd31e82c996d7edef095cccfcf669accb85a483ea9c59f368cc980f73da7202a95c5156c34192ae4ebf773c1a683c079b17ac9d08b4265b4054fcddaf6666ca50f38f1a2ef2497459a68c06837363a526e850ecfbd223f55dba67db017eadb7a9139abb5bf3854834478b838aafa16c5ee90ea52fb2f7b8db2bcefb85b06fc455c2b6c27d0af9a49dbf2f313bf2599370637393e7972b31d8bf6759f3e6115c618e672831f84d76ba1879c754144e1df4d56b1e264b1797dcb8ab165040c8d20b931071081d7f74fbff590bdc8e888e71acc6a720270da8db7c821",
"936fdab91fba396e4a8754a97a04ba333daadc29885c9d0c8fea3387165278f4974e468fea57f2bfd8428c4d0f010833283db73735d39de0c0cb5898d0c06c0ecd05f61098935cb6130a8da60d1a6c2ecfe420f972263fff5a631b09e81c837183c5528bb1c740b36fc39cb082f3383c2b4afb25d04ad1d1f4af63dcf26a0bf5a647cd2e35a51cc119c4dc5031f5715b3bfa1f2b92de06bdac0d670fdd30980f32c51f3936b51e5db6b95a8d36279da5faa4c4e454f2b7e54e9f488071011c7f6f9b63da260a2e46d796d36c9a9dcae88085806a10a77bbb670d475778",
"a55fe162b287bd6eebd6cf7e7aeea8672322d924ae42c7404ff89aedb98943f3755d2889bca488cc7000e6e9b8e7a0ef289273cd29c44cc600e330d1775e3cb767f12150e1615dca8c3f67466463a3ca993a1b788cf67a7a35b95dfff954206eb5ea1e1bf7fb06482a551625b5c9fd9a86e8414c8cf79d3a14104a153cbe04aac5172aa4c4a89349f5856c4262dd1d7317a7544c9afbbed449e7dcc2b58d9df6c9c9ed3883e42e80f5c2433550f30e73c7bce0fccdd880adc19282a392dae26a0108e7faf168cfc15937aeb046d60712603286b8ddfb27916b79242d56f1",
"2bd6976592408cdbc4e41dcd3ecfbb786775ddedef914d9058e6753f839fdfe15b17d549dbc084aa6cdf3befa0158aa84c5d58c5876144fd7e6c41ab7d42419d0dd353732e0e6d3fafc4f5626c07433390a4fd467197e85b5de7e2cf1c26cc575356adedcc0740008523b503df12ff571387726c5ccb280376d19cbacb1d7ce7aab8b13292c6a8b8881e949cbf6d4610d16ebba1d46cdb8d0459596e0aa683d0307bd926e14de19b9bfeaefa29d91b82248604673a455520cbb64eef3f38cfad8e126a3b1cfa1aaba53a784c8ae0c50279c0ecdab54095d36f67ace9b8ebbb",
"71913ae2b1c8729ed6da003c24a1d4f96e28d7faf55ca14ee0b2865282b9b61103ce6ee0b00b00aacf2081adedea5616f9dfd22c6d6d4f5907bcc02eb33edf92de0bd479794f51246d9b612b4543f6ff633c4fc83bfa6144c9d26721cdc690a3d5a8db54d8bc7873bfd32924eeb502810732b5ac2f1852bb021c401d26c39aa3b7eb09083093a9e89bf889b53383b5af61110aca1b9fdf38908c7d5a184fc5f46b3423a66a2749feb8de2c541c563987278dbd0513d99b732411012b5b75e385510de5f6839c3797dc094c9501d5f0504b06b43efb6e746f2129ca189c1da424",
"9d048a83294de08d3063d2ee4b4f3106641d9b340a3785c076233686dd3382d9064a349c9eaa78028d35652078b583e3f708e036eb2ced3f7f0e936c0fd98f5d0f8aa91b8d9badef298bd0c06843831279e7c0c67ca7e572f552cfdd984c12e924c08c13aeec6f7e13d161785546ebfd794b5d6a92a4744e52c4cab1d0df93b9468be6e264e8cfcc488f9c3c1817cbe501f4b9cc5999483b7433aea777226b25273a6ef2331b5f3b6db8091591e8e276015da3ef78bb2ee0526ffe23def2d8d193cbe594e8ced1f3d216fcedae2a1eb288da82e34cf98aebc28def658ee0849ae7",
"3251c96cbf82ee2e5264528c0b6cdfc23d20e1eb2d6441b5d62f0fd24c692a0d45a8bc8aac32884b7141ac0f4f113ec9fc7f6b4db3d696374177f9a42d602ca471275b928f639105a55b846da9ac7274cc37de8c38541f6895f94d72a81e117844b46601c201f7189b935a96e42505f2098ac985d92dfe86349a706ef6325b3c2e4060ced3c453e68ed09e043bcc75846b80118dc53530248da250fb57922d0afa53a7b2c89161aa4fa372a46b2a8e1307741cecedf585d2f998a9d496763800b6965c38a5d8aa566c709f13699c8185ab4fd8fdc8b824f4dd6d1c255b4788f50574",
"2de31dbc8a012254586f3229d3524fc529554e98850d30acdfc11406bba6a142029126ac165ee90b2de7509fc3571a8ee12e16b05054eb8baea879d135b39627f0d8331be3e66bc720c2096ce74e437daebf3bc53d8f2ccc228c3256d3edb6e9ae7c354a0c9350e6d663a9a30630bf9da3d96b96608a2a171ae28105714058b6c4b38a36c56561c4612c32aad25c65b7fb6faa4e4ecd44ebf9b2fad42ff9a807cda2581614fd30d41a7436069399b8d4f062a37a5bd4066a93d541fa5797a7d3e7dc9c4c40f0bbf5256f71613240f9ef128b3423eacaf428ada06b6a531f835281e4f3",
"07dadee629a08223dcd7ec441287b4c5e26347451d9c003e3a8496b4ea313b51126283a6720d7851e24423d9c9c818b4601247178f38a61f45fd4c8596d79529d416834226666a2c8552bbc901cc5cc3406a18fc88077fea52e1b620748553052ab7788c0d025b095b736fbe714cb3a968ec16b5917652eba2d7cf32ef3140d6c27b25d053e9786d24cd09a5306a0ef55e46201faa6196a91084267d7a7b5ca57c2efdeb2cb97d682d2a191b915553c8933f1d1b7faf0b4a1d83ef611f1e44438bc1c3d860fbfd12b5f26e5a6889a31ce26ae6a55c7a563b5816d113423ef3f25fa9befc",
"1d94166bb387526d519c4ce150221954da8930f66765fe6a5504e30a69962d595cfdd07a82c003843598864261f053bdb6f5086d516c261e089caa89990f0967605768ae9200bdfe4dcd7b77a93265cb33d9851a2a1036113c732bf3f37534530641300f0620de5c16101e16f4baf39d9fcbfcb01c52afce0992c329d8dbb438c314eee995c5020611d6f889e06b8a032785cba9a415580dbf752b5e510523c89f478cc6f047bd926f51e4a965c9749d1e76379c0e7e5b56803893bafaa4d2892b4c52f143b2fa777cd1035ea418684b8019df084f9a3f1f768753096621f342895c510d01",
"fc0073f199ed8a1d6edc8e7bdf182670003108d82b283aba82326e856f8de378987a03d0fe8d2041440fd29d51c63796aab44090d2b14ee00859b3a08cbe88f724badcd3c401226c5db8b307b8deea5be305412b080e9f99cf79d6d08d3646f347a7afebb62912e3e246e2e726f9aec5c101d916e47f984507b1d65d313697256c77da7eca3bc5811c87bee02a2826cefff0d92bae989609aaf95d70561b40d98474c37277c884aed887a1606d206b11e8a8a71d1f1d19319557b57351228ff0404be700a6cc56c0a30f3d4b7a0a046463fdaf19e7d5f59e155f378e35baa33db1e881f2207f",
"f42a6a91278d6a076feba985b1cf4ce0af1fa9d6d039c136e8971e665ff088a10b6b9a379a6f5526fc5957773a0ccb8972a4a19be0745ac13937030a54b18dee4f4c5df47a58a33a7516b90e646e5da999166ab0e52f457f7c9b7e391836a687eaae37b377e59a4c995ab0c57162c307ab951a9ba6590f429cd27250e7010eb794ec1b1ec35f8aad189b2fd3e8aff24d93601d91a4884e6f84b02757ce7620a02901519fccfda52f68ad6df709d112a9c25d66bcbb9622806427ca8b8d346b6db05874bde800cde9cf17df4b05baab0f133febd1ebbb053b49c109a7f5b1f864a304d10288e2f0",
"bbcefaf4a0739509f8a2f831c954071aac52e60cfa882a867b8b910dcf7edf92e1c0692bb027bc378c460a01cb6ecc8f2a012dd84ee5a678cd497b1457b6d393421fbee98ff544fc7eba24cbc3aae506254d9a2d74dde74437ce4c8a69010718506bf4c5943342a942e5e2d3406a3016280b6e37954c5d5e763346251afb0b746cad68cac757f9df765e092518729cfb9a5e76300c124e708ca33591a369767ffb63933cb72fba67beb2223d98984d0b75eb5d1a38615913747b520b3d613c715c0c77d2987bb88f3c419bcc5d38573cf4a8a4f550b2d876f05ca252d88c70a561d869a5018b32f7",
"dc2437010cb05d9cab2af5c275e1d2acd627ce19fb86355df91fb8d059e60d591663c8eb077d48388c9a321057a98136f49f0098348d9f29d808936f98bb1787c7ac75fb14f6076dfd2de5b59b1fa4848cabaa9a99a091dc24b561911c392ecdbe53f4adae82b852d830adea3a10490c908e337ce0a6d12354ce05a37ad3a06696b66820af8a1f67e6287533fd6f38a5f6ad1c6b078c08baf2c37d2683af01e6a5b33796c8ae48935a888f9bd265f4f11a4e27c433b8b1c9afd140bcd21a07e24378ad6badde8e47c57e3340f49e2406e8d49afadd65eaaa4c3d078c27d7e42118cb86cd248100a356",
"6c290db326dd3152e6fa9b9c0cd7d49e50a0221b96e32f5f34a8cb7d0c2edd3e937a7d025d6999b7b468add4d6894d8f7aceaabc18f4d9c171f1fe95ea1ae8570382a8450fbc595d95b1f51d24e1abc2970b0e1d20ca40aa21bdfb3656adf2f19882eda606f5ef1c03174e1d94c8d12f0fee8dce6852f42a364eeafa27a7971d4379405db8e46baac4d685b969238e5df06292a6c790bf1994a051b038e1d8db91e1bc4804f32443781c34a552ed2e8100cea374e77af56ba0e11c45990d3ba68df9087b1f4968cbcbb1c42f99b7267c76af926ff3134e093df28fab039cad420c6b70f2d9b5e678c155",
"ac724a22ebabaedbbb052953e3c264a4b6440f313bad501cdc1484b64f33402a2230898776db5c818c28035ffae6ea24abd04b7159e42159833903a0c23a7c564f7645e49ddedb748fd9e51bd6cbf2eced98caaa35226970f003ce1fd260ac5795e096f1c04aebf8fd36e5e2adeea929b5e963a3cb71d6b55c85bb7d3a2b03a7e74b4416de8fa68950168d7c3ae8ed2e29bad1e8a182a7c5418e5d564373163778cd3c34e9d320eb1a60480a8f98b12e0026cbd7752e6079812e3767d9f55f3f10b8c214a6eceb2a58954091a06b33862af171a9b60bf2c6a44e8766e6c56e98092c56f2a8510f6d05c103",
"8c70114f7cffb375c2b9a06e27297a5c32418b2daf68af5bbedcc7106edbc070e764bf40c1f8eb15079e2ab77f898afff3490108ed9afb7ea9cb05df41d263be0e42d2321d3d2656622d7bd232bf68d37375fe7314b09cba66f19c8b59424198ee69e7a9f3de0ecce0685127807ce336fa479ccaf7aa1ebc4e406271ce6c4923ec36093516498cc227f9218869346c80ba5ae83e023aca0ae2bc86b5bf5d115a4616b6587cb869d92f8c780ab70d5766de07a204af5e1c8dbba622516d2e911b36c82e4687e4d258ea616c07f76ff0baa376c8d5975cffac0b25817f779ae3ce88b72eb47e378484ce999bf0",
"0733d59f041036398233fd47a84b93f6778ae5259ef5d62aa3b9faedec34c7edb570c18b2a5d2c4c55cf656d98a1ae396d45a3b746b7ad6f07312c3d05d1a50ffa90bcdcdba105e25b7b0c52664223f8c2476925d46dc6ea2406ded7d0b0b292f6656cebcc7616cfa4b82aec68b35d1da67f6ed2bf0171849d6bb65128d8a140ea5cf97f1003f8d7093bee077be78def4f7bd2caccbf0644f26b26285225142c40038484c3bb9ba9597744f4389e76dca3eb695c33ccc621cab1fb603cb3535a0ad318d220385d5e94f8674f3d55e97e097f8d5c049e911946afbfce783819951d65d6bff4567dc951390d1aaa",
"398ddbba3dcb5642c102efa841c1fcdaf067062e7eef8e2ee0cd73d7f77e57372d6ee1a9b7b6f86ad12d575001ae71f593449cb5a476c6bfeddaa2af0f9239c1d7effdedf66ceaf413707b5ab9661a7cc0ef8cfe4d1651579c4f0f64e2d12a52653c54f2dd60864e769eab8a627c89c56ee93365d031f0d2523cb95664b1575d51b122f33c9e94de75432a690658c977b68aa5b721a393f9b9b3b612c10e920a7d510c6d8460b35f8614c42f5d2c241a01b28105aa7c1b521ac63ebbedafac6d5a38c898e8590f918a1927bc53aecc2b1c8b18d7df9107c6997d9b3fa4b0bdb1c603da619d9e75670b97a5b40f06",
"ef07bbc7c4150dd47f8c69a7989948fe831dc798b0424dcd6551bfa8e88216095a7e5d720909bf3d23526b9ba464b66ff6b63a7337c31451ab9a15f04ead809a62bb52206237de77597a730106d02d227dd6099ea9ee2a92cdc446ac3b9d024e32255adb3e9b56b561c431e0b5a721f0336f19568a5335d0ebc6c73ed8ff2c15e219477d9e4b67f2928e251f8a61a2848857e037d010806c718ab062967fd8e85f3722252957923f5f9005aae47b4b1b3fa464e3ba9df573a56055f17e903126fbbcb6cb96de92fe617c97f84ef3ba0d8f2651dc4aa80c157f372ae1bc02e5067ad076f3fe48bb72c0f3c99273f82b",
"c7076986d2333f3a6752adf11f1a9e5c6bc4755f341073cc86a9c7519c8db029d5ae833fdf3fee826ff4692c57880c5074620ea97c00f1dde1e8a0f18501627984ded4d1b5c4af35be5cc1bcc868060a49a968dc0547acde490b4c68d79924a93a986aa0ad060c7de706e8a99ce8f84a4f8707b52a8ee122b763ba580d6b1f35f6af25094c69f49247da96c836991851ad36f60bf577863d7471608a012afa7a56656abeee7cd9b4f1f4d9d13a8526c0f33cd251caf7486639e787250390e7e488e9ec311fc3d847a7266cc59bcc2bc34192554aa57cf25db10ce04bdabef3fde6db85f55195ecc2ff892b2e268ebea6",
"01789f40d42d8d3e4a416fd9ae7de78c3a30507809eda200e1afaaf8d7020cd1fad18eba62d821946f220506cf105ff0e2069a771a2c233714afa6b2f695497e4b95c9693dbb93ec4c9a14720676aa87ee31dd34e4e081756477032b4a57b328285f2cdec1b269754c474936927e93acc26012aff1bb36f30c2402aca0a9b9ce9568f5000e2c934263933b436c94f8d6589c89db7edabc5d03a8fe795fe50c5166beab64ed7c22662b984ae2c66dbe4c090b0df603b27c759278f8d66859afea3f6a8f02c2c2a2202b9fc29132256f164b5050a803b43688dc4c9ba86374a3522afba5d1a19bb3820b883aebc267627095",
"2c61944bd6a50da00ebb951d2b67d79fc6b6fb5aca83b1de3dbd7690ab756bb1e1a21051ccf1e24136ac8ccb42a2ee10be94d2cb9289d5f52b6f90e9d07a3478f36a1eb7d08c3dec52ca154fd1427ba92a4ecbe73a71bceafbd26e9a39d50821e2876d3a0c0e6e373b9795dbf72ea29cc439ff42706be798c90d4617b39c90ec84bf9fb699dc8a9a34e25d81759d6c57df45efb1d0d68aa51278564b99633ed5dc464bb7d53c5c21f798f33bcd868657ecfe75a1ed8149d394b398969ef624831b30f1458465bfd2fdf3f284f2ffc54bf2817b5fab2e02056e864f78bb6fd870c64f3609dab218f25da8060f756e45121e79",
"942fa0c68cc72f69518a3a7aac0cde45bab0e928b5cb2bd24d049fc313f74b6afa87c4e34150484f3b5200163f8a6472d04777928ecc49319539fc17d71a38090f55a74f757fe45781a3c09f08dcd3dd4c73c8533a5e00cf8a86ebe77fe45be2848574f7c5d25e9a0632a60d2dd41febdbf987d2a0487e4a4ce6ed5f49f2d741a88ecac232b1498253fa4ee8147bbd0f600abdf295e81f7570015aac5fe6ca7bb4a99bb3fc54287106d7fc1132a574af49db82a7b9a5f33e193cde527ca2176c52cdab672165e0fe5720f71ada57ee90060aa069ae2a0bfe67c1b71b17c601c3c2224bf9891bc11ba216e3ebcb51fd95b8d7cb",
"0d68cfe9c087ec116fe7572042385159cc705960f842aabad1ed1387ec1697f4413a23c6090041328fedd4b626c6eeaac5b5a71acc1fd1bb8fbd228857ac5bd045c364be7a5a26338ff04c99c4c473cf445a891db6422d1bdef4533442df171643fc36a092fabb464298e4194c9e2950884de13d113ee24160a416404c16ddc5d2476cb3fb80da543e6ed9105f6003977acb34e1fdd2cbdf7a00d5ff84350b74ac231418c0d88269d02d824802791ff42a51cc835deb9869a6023f867f82ef6dc0bfb03e6dfa835646bb18a4074773486e308aa39e532aaea4e6fb35dcada7e060f8282c371ed26d22302323d4fd142a85534671",
"45e24b167a0bbef1bd8f79dd047763d0754f36a7b623f298059d177e8ac994945c37d2c4af06f01318960301595941124592f2995af1459d854339998d3ae17534df2d9793d6e203857d02c98a0cd88991e641b3e640090ba303f87b907dca8ca462fac19ad079b2c82ea5b521ab891b10138b083b3d9fa214a8fe60d1cb3599c5d199c61a2cfb7ee2f39e5a5abad5ac4998b707545f73e92128d21803420526d2598a53bb314adf29a0ef56b94bd2221601eb53ecb8540e8fffd38fba7bd827ef255e4ef55491475c0f383a241f81c72af4e1dbf2a65cd4d18a497615aa0de2791a3511a7977a8d4d41492bfa4085f2fd4e8f751d",
"1c1bb695ae90e6e33fc1e8b2a62ab98bf835ac7193440f2351c8cdd830472b637d2fd9c9013cb83caef506abc1c4f7567706db6046b1d184579c7a9223ab1b35e32898c70a3c27628123ffcfa518612f080a2c4a9f8e0a927a47dc98307d2b48de9d5dddcb5c82f0b0e4e610d44f1baa9bbbf7f5a727134680bb7d1327b73b52d8e5e36dbb53971e99e699d79f75a3fc01316bd7012947d119d6aeb7f75b8fbf0479c03002148553fa0da450fd59d4f1bebc252caa11ed9bec5b6ef54279b5f8382b61cffc67ec03f4baa7ea476c31364b86aa8ccad9fd0818717f0ced2dd49477874b4341c602d7a1beab860eb476c7e3ce597e6926",
"7a3cd9bb2277e2c7f1134fe7233f0f7883c2db9fba80aa5742b03041de0fe589d9e5ea84470dabf41bb66816f3e33ebf19a0ca5aba1004cf971249b258ff26a98dbd0c37ec6cd574854109433357720040bafed4531e0079186b1e853e0ced35d08d27f6d732ed6e2c6651b51cc15c420a24f2dc36c16ef4b3896df1bb03b3963f9aaeb02a48eac5772abd5948c2fd0db2bb74e3351e5eabd681c4f413655bd94dec96b1544c1d5d2d1df4bdc26020d25fe81d5238de824687a5505e1fbe08d11b3924b3ccc070fd225bf01eb79e3d21f7b62a836cd3bcc11c931669c37613470e356143df87c48848a829f5e018973a5db88eb6c60203",
"3f158afd0733fcc5dfe1efc2dd4eada732f942af734ee664955bb1ba613eafd0f349e7554a14d68200c62d8f2dca2ec8b81c8350735eaf437041f78b452598825b6899560963ade66a0fc74ad01f8343d1d19c7bb327a8dc14ffdb1c42fa72b2970d9155e2da6a2e6419d4117842d826ff38ffab9617307a0283d3ea28c8104ad9a6e087bb750ed1d10fd8f7100b1663682e979d80e43968c33d9eff66f4d1344e583ee521e78d0a2193c0577516b978339c143bfc689bc744bbc4a9163063de82c9706384b6b385e54666c86b34f23c1e25be293af06092ca31d857e11e5b2caf0d19dd3afbe85380878eda76d718b4bb869c67e044e242",
"a177af4387b9bfa3d59e97ee7b0ff5f4ae4a326fd9204c8d28831a67fcc385ee6c4828247b16d11aea9bb8cd9e6c4d2876c6b2fa6d5041ad39e1b04039071e29c4d86417e7eac4fc7d3823958a021823e2c880a757dfbcd0c8196371db5bbfac15e4d1a0596508b6d26f8c4a664924c95082d173f817995b44c4285d625d9b2f56c86632fe1295c5a8a7a3760028072bcb07bc245a705e7174d06b9d5c0c8ca495b9ac218f1921fa63f2db3fd148f07545366d008fb5aead7497d902b91fbaa39669929d4ae9d07df8557f1f0aed7b51252f10c6606e5ff3ede1327530ca356b4896ecf14bf7322d77fddfbe28d52f6de7f66eeb81704c87e2",
"01a15b9018e35cc342c926b01d03ad9db4993a6bf92e0555969fee90033f28f3ec234c1268b11b040dfa0770d4ceb39edfeb8ee6a589f4eebcc08d2d1b0a1a52953aa26eb44fdf4a2743c3dacb212a0c0f325572f645f53027b6f3c0c55abaeb1b0918c89bedcb5028f094d743ea354f8ff553c45f111a8fd5a14a4e5c835164747d302472e19a67da04b4c8e39756a9d248ce14d1ed43de75aca86850f2455eccd4639b2af035bb3f504cc9065d091c1c47e036083cb3fc50bf39292b11737c7ce0b49673ba93981de304dc65a671775b6ff927e3ff93850b214fffb5792105a4bdc81354d5b09e84afbdd1792b8fb4e9d0ae3dad2492b03282",
"24f07ae31279ceed18ec6d35990f21200934ad6b132c6c62e82fe92a40a0e60a5bed10720eff5a1f728971888682772b2d9060d4fee88f37d0824e7384dddcc549475f0e1a44eda4804778b62febe46e04657a20577ee70acb3425e334881eebd8ddf714ae8c527ea747e3367de384e595a43b299b6bb3f6b0a4716cf90038e0f75a47d5057d7fcc3c8a8f9224992c67f8ae0d3251ea09a24aed9ce57ab637f6b3cbb7083df62b6287f64d0877984c4249d113bdb2b07865082aa24cd7ec07061b17de320f51f29f25b82d7073d369cf2dbf96310c0c311997911b2cc02f606f9cd99663c57e78499192a2a78f9c9fa67013e0f9817287faa69b22",
"4aeb32bf9d050f10bea18d9f71b4afea7bd08550e574e7d50df234c7413668b297b6721d7a0f0bdcdcceb2f55adddea28cd59bd44be0c5ec067039e428706caae11f565d961ad6e7f4c51b0aed6d05cc5b8d826c4b9c39daefb6c7da46dce619a359dc9ce215a215218fa8d54ee0b4f301b6c201c7c2c5f7cb1c6e0cb76ba6c6e8f63ef7a5213d550b0d0857fa0ff9e3e38e497161617413ac066e2fa539520233193a5cb7baa0c2cb20b45e56bfed2c40a9544d1f230dd0cd6d4976e7cf51da8a13200c3957c0154c8237b2931ce19b824963ac576ea49b548cc6aa85c47796b470fb2c6308d88f390bb13607e294c84a838b2713b14ca6a5e8bcee",
"77e607478be5502432230c913d9ec82f967d87c0ee169a74076f989648853eca693277287f8a5b306bc94dfdbf64ca5cb5dfc0bc498589d51a691b8d57d4b0a9ee247d038fe1b5571183be3e75c37045bf1235863ff1b84b208c10e7f1a5ba54ff36af5b2870129867164d013e0a6d2cc067a3509bba2f46390302c80b651cf590ef69aad8effd94cab28a9b44be6a38b58cfc47c9c725d6fa467894163383b6873d10d263b1cbbad932ded59ab503920267ac026726f794a335a88f6ef564f8968c6fa6f5d3ea161eb6062ca349b9a0e4038273399cfa297a6b07ceda1ebaa99c9de2d935ee230a08c5a488ad46f3393243371d40916b8063cac9da63",
"50957c407519951bd32e45d21129d6b83436e520b0801ec8292d79a828106a41583a0d607f853dc4410e0a1427f7e873455a75df065cfc6eef970f7e49d123b346976460aadd91cf513c140c356442a84656904a8b1d708dc6089db371c36f4fe059c62302eaab3c06c0cb3b429961f899dcf99798464b8571a440cac7a52b495f32417af6bc8f58adc63647531f804b4e96273b29b42434c1236bde80ba3744fef7b1d11c2f9db332b35bc25123338ac9a0796aac213c9709b3c514ea7ecd80e22d3d8a74f28c8194418a6e1ff30714d0f5a61c068b73b2ba6cad14e05569b4a5a100da3f91429d6e3ffee10ceea057845ec6fc47a6c5125b22e598b2dc",
"f2273ec31e03cf42d9ca953f8b87e78c291cb538098e0f2436194b308ce30583f553fccb21ae6c2d58f3a5a2ca6037c1b8b7afb291009e4310a0c518e75314c5bb1e813bf521f56d0a4891d0772ad84f09a00634815029a3f9ad4e41eafb4a745e409ef3d4f0b1cf6232b70a5ce262b9432f096e834201a0992db5d09ffa5cbc5471460519a4bc7cdc33ae6dfe6ffc1e80ea5d29813136406499c3514186ced71854a340701519ef33b6c82ca67049ab58578ff49c4c4fbf7d97bfec2ecd8fbefec1b6d6467503fea9d26e134e8c35739a422647aaf4db29c9a32e3df36e5845791fdd75a70903e0ce808313a3327431b7772567f779bbaee2e134c109a387",
"5784e614d538f7f26c803191deb464a884817002988c36448dcbecfad1997fe51ab0b3853c51ed49ce9f4e477522fb3f32cc50515b753c18fb89a8d965afcf1ed5e099b22c4225732baeb986f5c5bc88e4582d27915e2a19126d3d4555fab4f6516a6a156dbfeed9e982fc589e33ce2b9e1ba2b416e11852ddeab93025974267ac82c84f071c3d07f215f47e3565fd1d962c76e0d635892ea71488273765887d31f250a26c4ddc377ed89b17326e259f6cc1de0e63158e83aebb7f5a7c08c63c767876c8203639958a407acca096d1f606c04b4f4b3fd771781a5901b1c3cee7c04c3b6870226eee309b74f51edbf70a3817cc8da87875301e04d0416a65dc5d",
}<|fim▁end|>
|
"a4fe2bd0f96a215fa7164ae1a405f4030a586c12b0c29806a099d7d7fdd8dd72",
"7dce710a20f42ab687ec6ea83b53faaa418229ce0d5a2ff2a5e66defb0b65c03c9",
"0320c40b5eea641d0bc25420b7545ac1d796b61563728a4dc451207f1addeedcf860",
"460539415f2baeb626fad748dee0eb3e9f27221661160e13edf39d1b5d476ee0672400",
|
<|file_name|>NewPollScreen.js<|end_file_name|><|fim▁begin|>import React from 'react';
import { View, ScrollView } from 'react-native';
import ConcensusButton from '../components/ConcensusButton';
import axios from 'axios';
const t = require('tcomb-form-native');
const Form = t.form.Form;
const NewPollScreen = ({ navigation }) => {
function onProposePress() {
navigation.navigate('QRCodeShower');
axios.post('http://4d23f078.ngrok.io/createPoll');
}
return (
<View style={{ padding: 20 }}>
<ScrollView>
<Form type={Poll} />
</ScrollView>
<ConcensusButton label="Propose Motion" onPress={onProposePress} />
</View>
);
};<|fim▁hole|>
NewPollScreen.navigationOptions = ({ navigation }) => ({
title: 'Propose a Motion',
});
export default NewPollScreen;
const Poll = t.struct({
subject: t.String,
proposal: t.String,
endsInMinutes: t.Number,
consensusPercentage: t.Number,
});<|fim▁end|>
| |
<|file_name|>test_driver.py<|end_file_name|><|fim▁begin|># Copyright 2010 OpenStack Foundation
# Copyright 2012 University Of Minho
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from collections import deque
from collections import OrderedDict
import contextlib
import copy
import datetime
import errno
import glob
import os
import random
import re
import shutil
import signal
import threading
import time
import uuid
import eventlet
from eventlet import greenthread
import fixtures
from lxml import etree
import mock
from mox3 import mox
from os_brick.initiator import connector
import os_vif
from oslo_concurrency import lockutils
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_service import loopingcall
from oslo_utils import encodeutils
from oslo_utils import fileutils
from oslo_utils import fixture as utils_fixture
from oslo_utils import importutils
from oslo_utils import units
from oslo_utils import uuidutils
from oslo_utils import versionutils
import six
from six.moves import builtins
from six.moves import range
from nova.api.metadata import base as instance_metadata
from nova.compute import arch
from nova.compute import cpumodel
from nova.compute import manager
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import vm_mode
from nova.compute import vm_states
import nova.conf
from nova import context
from nova import db
from nova import exception
from nova.network import model as network_model
from nova import objects
from nova.objects import block_device as block_device_obj
from nova.objects import fields
from nova.objects import migrate_data as migrate_data_obj
from nova.objects import virtual_interface as obj_vif
from nova.pci import manager as pci_manager
from nova.pci import utils as pci_utils
from nova import test
from nova.tests.unit import fake_block_device
from nova.tests.unit import fake_instance
from nova.tests.unit import fake_network
import nova.tests.unit.image.fake
from nova.tests.unit import matchers
from nova.tests.unit.objects import test_pci_device
from nova.tests.unit.objects import test_vcpu_model
from nova.tests.unit.virt.libvirt import fake_imagebackend
from nova.tests.unit.virt.libvirt import fake_libvirt_utils
from nova.tests.unit.virt.libvirt import fakelibvirt
from nova.tests import uuidsentinel as uuids
from nova import utils
from nova import version
from nova.virt import block_device as driver_block_device
from nova.virt.disk import api as disk_api
from nova.virt import driver
from nova.virt import fake
from nova.virt import firewall as base_firewall
from nova.virt import hardware
from nova.virt.image import model as imgmodel
from nova.virt import images
from nova.virt.libvirt import blockinfo
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import driver as libvirt_driver
from nova.virt.libvirt import firewall
from nova.virt.libvirt import guest as libvirt_guest
from nova.virt.libvirt import host
from nova.virt.libvirt import imagebackend
from nova.virt.libvirt import imagecache
from nova.virt.libvirt import migration as libvirt_migrate
from nova.virt.libvirt.storage import dmcrypt
from nova.virt.libvirt.storage import lvm
from nova.virt.libvirt.storage import rbd_utils
from nova.virt.libvirt import utils as libvirt_utils
from nova.virt.libvirt.volume import volume as volume_drivers
libvirt_driver.libvirt = fakelibvirt
host.libvirt = fakelibvirt
libvirt_guest.libvirt = fakelibvirt
libvirt_migrate.libvirt = fakelibvirt
CONF = nova.conf.CONF
_fake_network_info = fake_network.fake_get_instance_nw_info
_fake_NodeDevXml = \
{"pci_0000_04_00_3": """
<device>
<name>pci_0000_04_00_3</name>
<parent>pci_0000_00_01_1</parent>
<driver>
<name>igb</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>4</bus>
<slot>0</slot>
<function>3</function>
<product id='0x1521'>I350 Gigabit Network Connection</product>
<vendor id='0x8086'>Intel Corporation</vendor>
<capability type='virt_functions'>
<address domain='0x0000' bus='0x04' slot='0x10' function='0x3'/>
<address domain='0x0000' bus='0x04' slot='0x10' function='0x7'/>
<address domain='0x0000' bus='0x04' slot='0x11' function='0x3'/>
<address domain='0x0000' bus='0x04' slot='0x11' function='0x7'/>
</capability>
</capability>
</device>""",
"pci_0000_04_10_7": """
<device>
<name>pci_0000_04_10_7</name>
<parent>pci_0000_00_01_1</parent>
<driver>
<name>igbvf</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>4</bus>
<slot>16</slot>
<function>7</function>
<product id='0x1520'>I350 Ethernet Controller Virtual Function
</product>
<vendor id='0x8086'>Intel Corporation</vendor>
<capability type='phys_function'>
<address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/>
</capability>
<capability type='virt_functions'>
</capability>
</capability>
</device>""",
"pci_0000_04_11_7": """
<device>
<name>pci_0000_04_11_7</name>
<parent>pci_0000_00_01_1</parent>
<driver>
<name>igbvf</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>4</bus>
<slot>17</slot>
<function>7</function>
<product id='0x1520'>I350 Ethernet Controller Virtual Function
</product>
<vendor id='0x8086'>Intel Corporation</vendor>
<numa node='0'/>
<capability type='phys_function'>
<address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/>
</capability>
<capability type='virt_functions'>
</capability>
</capability>
</device>""",
"pci_0000_04_00_1": """
<device>
<name>pci_0000_04_00_1</name>
<path>/sys/devices/pci0000:00/0000:00:02.0/0000:04:00.1</path>
<parent>pci_0000_00_02_0</parent>
<driver>
<name>mlx5_core</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>4</bus>
<slot>0</slot>
<function>1</function>
<product id='0x1013'>MT27700 Family [ConnectX-4]</product>
<vendor id='0x15b3'>Mellanox Technologies</vendor>
<iommuGroup number='15'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
</iommuGroup>
<numa node='0'/>
<pci-express>
<link validity='cap' port='0' speed='8' width='16'/>
<link validity='sta' speed='8' width='16'/>
</pci-express>
</capability>
</device>""",
# libvirt >= 1.3.0 nodedev-dumpxml
"pci_0000_03_00_0": """
<device>
<name>pci_0000_03_00_0</name>
<path>/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.0</path>
<parent>pci_0000_00_02_0</parent>
<driver>
<name>mlx5_core</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>3</bus>
<slot>0</slot>
<function>0</function>
<product id='0x1013'>MT27700 Family [ConnectX-4]</product>
<vendor id='0x15b3'>Mellanox Technologies</vendor>
<capability type='virt_functions' maxCount='16'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x2'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x3'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x4'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x5'/>
</capability>
<iommuGroup number='15'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
</iommuGroup>
<numa node='0'/>
<pci-express>
<link validity='cap' port='0' speed='8' width='16'/>
<link validity='sta' speed='8' width='16'/>
</pci-express>
</capability>
</device>""",
"pci_0000_03_00_1": """
<device>
<name>pci_0000_03_00_1</name>
<path>/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.1</path>
<parent>pci_0000_00_02_0</parent>
<driver>
<name>mlx5_core</name>
</driver>
<capability type='pci'>
<domain>0</domain>
<bus>3</bus>
<slot>0</slot>
<function>1</function>
<product id='0x1013'>MT27700 Family [ConnectX-4]</product>
<vendor id='0x15b3'>Mellanox Technologies</vendor>
<capability type='virt_functions' maxCount='16'/>
<iommuGroup number='15'>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x0'/>
<address domain='0x0000' bus='0x03' slot='0x00' function='0x1'/>
</iommuGroup>
<numa node='0'/>
<pci-express>
<link validity='cap' port='0' speed='8' width='16'/>
<link validity='sta' speed='8' width='16'/>
</pci-express>
</capability>
</device>""",
}
_fake_cpu_info = {
"arch": "test_arch",
"model": "test_model",
"vendor": "test_vendor",
"topology": {
"sockets": 1,
"cores": 8,
"threads": 16
},
"features": ["feature1", "feature2"]
}
eph_default_ext = utils.get_hash_str(disk_api._DEFAULT_FILE_SYSTEM)[:7]
def eph_name(size):
return ('ephemeral_%(size)s_%(ext)s' %
{'size': size, 'ext': eph_default_ext})
def fake_disk_info_byname(instance, type='qcow2'):
"""Return instance_disk_info corresponding accurately to the properties of
the given Instance object. The info is returned as an OrderedDict of
name->disk_info for each disk.
:param instance: The instance we're generating fake disk_info for.
:param type: libvirt's disk type.
:return: disk_info
:rtype: OrderedDict
"""
instance_dir = os.path.join(CONF.instances_path, instance.uuid)
def instance_path(name):
return os.path.join(instance_dir, name)
disk_info = OrderedDict()
# root disk
if instance.image_ref is not None:
cache_name = imagecache.get_cache_fname(instance.image_ref)
disk_info['disk'] = {
'type': type,
'path': instance_path('disk'),
'virt_disk_size': instance.flavor.root_gb * units.Gi,
'backing_file': cache_name,
'disk_size': instance.flavor.root_gb * units.Gi,
'over_committed_disk_size': 0}
swap_mb = instance.flavor.swap
if swap_mb > 0:
disk_info['disk.swap'] = {
'type': type,
'path': instance_path('disk.swap'),
'virt_disk_size': swap_mb * units.Mi,
'backing_file': 'swap_%s' % swap_mb,
'disk_size': swap_mb * units.Mi,
'over_committed_disk_size': 0}
eph_gb = instance.flavor.ephemeral_gb
if eph_gb > 0:
disk_info['disk.local'] = {
'type': type,
'path': instance_path('disk.local'),
'virt_disk_size': eph_gb * units.Gi,
'backing_file': eph_name(eph_gb),
'disk_size': eph_gb * units.Gi,
'over_committed_disk_size': 0}
if instance.config_drive:
disk_info['disk.config'] = {
'type': 'raw',
'path': instance_path('disk.config'),
'virt_disk_size': 1024,
'backing_file': '',
'disk_size': 1024,
'over_committed_disk_size': 0}
return disk_info
def fake_disk_info_json(instance, type='qcow2'):
"""Return fake instance_disk_info corresponding accurately to the
properties of the given Instance object.
:param instance: The instance we're generating fake disk_info for.
:param type: libvirt's disk type.
:return: JSON representation of instance_disk_info for all disks.
:rtype: str
"""
disk_info = fake_disk_info_byname(instance, type)
return jsonutils.dumps(disk_info.values())
def _concurrency(signal, wait, done, target, is_block_dev=False):
signal.send()
wait.wait()
done.send()
class FakeVirtDomain(object):
def __init__(self, fake_xml=None, uuidstr=None, id=None, name=None):
if uuidstr is None:
uuidstr = str(uuid.uuid4())
self.uuidstr = uuidstr
self.id = id
self.domname = name
self._info = [power_state.RUNNING, 2048 * units.Mi, 1234 * units.Mi,
None, None]
if fake_xml:
self._fake_dom_xml = fake_xml
else:
self._fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
</devices>
</domain>
"""
def name(self):
if self.domname is None:
return "fake-domain %s" % self
else:
return self.domname
def ID(self):
return self.id
def info(self):
return self._info
def create(self):
pass
def managedSave(self, *args):
pass
def createWithFlags(self, launch_flags):
pass
def XMLDesc(self, flags):
return self._fake_dom_xml
def UUIDString(self):
return self.uuidstr
def attachDeviceFlags(self, xml, flags):
pass
def attachDevice(self, xml):
pass
def detachDeviceFlags(self, xml, flags):
pass
def snapshotCreateXML(self, xml, flags):
pass
def blockCommit(self, disk, base, top, bandwidth=0, flags=0):
pass
def blockRebase(self, disk, base, bandwidth=0, flags=0):
pass
def blockJobInfo(self, path, flags):
pass
def resume(self):
pass
def destroy(self):
pass
def fsFreeze(self, disks=None, flags=0):
pass
def fsThaw(self, disks=None, flags=0):
pass
def isActive(self):
return True
class CacheConcurrencyTestCase(test.NoDBTestCase):
def setUp(self):
super(CacheConcurrencyTestCase, self).setUp()
self.flags(instances_path=self.useFixture(fixtures.TempDir()).path)
# utils.synchronized() will create the lock_path for us if it
# doesn't already exist. It will also delete it when it's done,
# which can cause race conditions with the multiple threads we
# use for tests. So, create the path here so utils.synchronized()
# won't delete it out from under one of the threads.
self.lock_path = os.path.join(CONF.instances_path, 'locks')
fileutils.ensure_tree(self.lock_path)
def fake_exists(fname):
basedir = os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name)
if fname == basedir or fname == self.lock_path:
return True
return False
def fake_execute(*args, **kwargs):
pass
def fake_extend(image, size, use_cow=False):
pass
self.stub_out('os.path.exists', fake_exists)
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(imagebackend.disk, 'extend', fake_extend)
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def _fake_instance(self, uuid):
return objects.Instance(id=1, uuid=uuid)
def test_same_fname_concurrency(self):
# Ensures that the same fname cache runs at a sequentially.
uuid = uuidutils.generate_uuid()
backend = imagebackend.Backend(False)
wait1 = eventlet.event.Event()
done1 = eventlet.event.Event()
sig1 = eventlet.event.Event()
thr1 = eventlet.spawn(backend.image(self._fake_instance(uuid),
'name').cache,
_concurrency, 'fname', None,
signal=sig1, wait=wait1, done=done1)
eventlet.sleep(0)
# Thread 1 should run before thread 2.
sig1.wait()
wait2 = eventlet.event.Event()
done2 = eventlet.event.Event()
sig2 = eventlet.event.Event()
thr2 = eventlet.spawn(backend.image(self._fake_instance(uuid),
'name').cache,
_concurrency, 'fname', None,
signal=sig2, wait=wait2, done=done2)
wait2.send()
eventlet.sleep(0)
try:
self.assertFalse(done2.ready())
finally:
wait1.send()
done1.wait()
eventlet.sleep(0)
self.assertTrue(done2.ready())
# Wait on greenthreads to assert they didn't raise exceptions
# during execution
thr1.wait()
thr2.wait()
def test_different_fname_concurrency(self):
# Ensures that two different fname caches are concurrent.
uuid = uuidutils.generate_uuid()
backend = imagebackend.Backend(False)
wait1 = eventlet.event.Event()
done1 = eventlet.event.Event()
sig1 = eventlet.event.Event()
thr1 = eventlet.spawn(backend.image(self._fake_instance(uuid),
'name').cache,
_concurrency, 'fname2', None,
signal=sig1, wait=wait1, done=done1)
eventlet.sleep(0)
# Thread 1 should run before thread 2.
sig1.wait()
wait2 = eventlet.event.Event()
done2 = eventlet.event.Event()
sig2 = eventlet.event.Event()
thr2 = eventlet.spawn(backend.image(self._fake_instance(uuid),
'name').cache,
_concurrency, 'fname1', None,
signal=sig2, wait=wait2, done=done2)
eventlet.sleep(0)
# Wait for thread 2 to start.
sig2.wait()
wait2.send()
tries = 0
while not done2.ready() and tries < 10:
eventlet.sleep(0)
tries += 1
try:
self.assertTrue(done2.ready())
finally:
wait1.send()
eventlet.sleep(0)
# Wait on greenthreads to assert they didn't raise exceptions
# during execution
thr1.wait()
thr2.wait()
class FakeVolumeDriver(object):
def __init__(self, *args, **kwargs):
pass
def attach_volume(self, *args):
pass
def detach_volume(self, *args):
pass
def get_xml(self, *args):
return ""
def get_config(self, *args):
"""Connect the volume to a fake device."""
conf = vconfig.LibvirtConfigGuestDisk()
conf.source_type = "network"
conf.source_protocol = "fake"
conf.source_name = "fake"
conf.target_dev = "fake"
conf.target_bus = "fake"
return conf
def connect_volume(self, *args):
"""Connect the volume to a fake device."""
pass
class FakeConfigGuestDisk(object):
def __init__(self, *args, **kwargs):
self.source_type = None
self.driver_cache = None
class FakeConfigGuest(object):
def __init__(self, *args, **kwargs):
self.driver_cache = None
class FakeNodeDevice(object):
def __init__(self, fakexml):
self.xml = fakexml
def XMLDesc(self, flags):
return self.xml
def _create_test_instance():
flavor = objects.Flavor(memory_mb=2048,
swap=0,
vcpu_weight=None,
root_gb=10,
id=2,
name=u'm1.small',
ephemeral_gb=20,
rxtx_factor=1.0,
flavorid=u'1',
vcpus=2,
extra_specs={})
return {
'id': 1,
'uuid': '32dfcb37-5af1-552b-357c-be8c3aa38310',
'memory_kb': '1024000',
'basepath': '/some/path',
'bridge_name': 'br100',
'display_name': "Acme webserver",
'vcpus': 2,
'project_id': 'fake',
'bridge': 'br101',
'image_ref': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
'root_gb': 10,
'ephemeral_gb': 20,
'instance_type_id': '5', # m1.small
'extra_specs': {},
'system_metadata': {
'image_disk_format': 'raw',
},
'flavor': flavor,
'new_flavor': None,
'old_flavor': None,
'pci_devices': objects.PciDeviceList(),
'numa_topology': None,
'config_drive': None,
'vm_mode': None,
'kernel_id': None,
'ramdisk_id': None,
'os_type': 'linux',
'user_id': '838a72b0-0d54-4827-8fd6-fb1227633ceb',
'ephemeral_key_uuid': None,
'vcpu_model': None,
'host': 'fake-host',
'task_state': None,
}
class LibvirtConnTestCase(test.NoDBTestCase):
REQUIRES_LOCKING = True
_EPHEMERAL_20_DEFAULT = eph_name(20)
def setUp(self):
super(LibvirtConnTestCase, self).setUp()
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.get_admin_context()
temp_dir = self.useFixture(fixtures.TempDir()).path
self.flags(instances_path=temp_dir)
self.flags(snapshots_directory=temp_dir, group='libvirt')
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.libvirt_utils',
fake_libvirt_utils))
self.flags(sysinfo_serial="hardware", group="libvirt")
# normally loaded during nova-compute startup
os_vif.initialize()
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
def fake_extend(image, size, use_cow=False):
pass
self.stubs.Set(libvirt_driver.disk_api, 'extend', fake_extend)
self.stubs.Set(imagebackend.Image, 'resolve_driver_format',
imagebackend.Image._get_driver_format)
self.useFixture(fakelibvirt.FakeLibvirtFixture())
self.test_instance = _create_test_instance()
self.test_image_meta = {
"disk_format": "raw",
}
self.image_service = nova.tests.unit.image.fake.stub_out_image_service(
self)
self.device_xml_tmpl = """
<domain type='kvm'>
<devices>
<disk type='block' device='disk'>
<driver name='qemu' type='raw' cache='none'/>
<source dev='{device_path}'/>
<target bus='virtio' dev='vdb'/>
<serial>58a84f6d-3f0c-4e19-a0af-eb657b790657</serial>
<address type='pci' domain='0x0' bus='0x0' slot='0x04' \
function='0x0'/>
</disk>
</devices>
</domain>
"""
def relpath(self, path):
return os.path.relpath(path, CONF.instances_path)
def tearDown(self):
nova.tests.unit.image.fake.FakeImageService_reset()
super(LibvirtConnTestCase, self).tearDown()
def test_driver_capabilities(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertTrue(drvr.capabilities['has_imagecache'],
'Driver capabilities for \'has_imagecache\' '
'is invalid')
self.assertTrue(drvr.capabilities['supports_recreate'],
'Driver capabilities for \'supports_recreate\' '
'is invalid')
self.assertFalse(drvr.capabilities['supports_migrate_to_same_host'],
'Driver capabilities for '
'\'supports_migrate_to_same_host\' is invalid')
self.assertTrue(drvr.capabilities['supports_attach_interface'],
'Driver capabilities for '
'\'supports_attach_interface\' '
'is invalid')
def create_fake_libvirt_mock(self, **kwargs):
"""Defining mocks for LibvirtDriver(libvirt is not used)."""
# A fake libvirt.virConnect
class FakeLibvirtDriver(object):
def defineXML(self, xml):
return FakeVirtDomain()
# Creating mocks
volume_driver = ['iscsi=nova.tests.unit.virt.libvirt.test_driver'
'.FakeVolumeDriver']
fake = FakeLibvirtDriver()
# Customizing above fake if necessary
for key, val in kwargs.items():
fake.__setattr__(key, val)
self.stubs.Set(libvirt_driver.LibvirtDriver, '_conn', fake)
self.stubs.Set(libvirt_driver.LibvirtDriver, '_get_volume_drivers',
lambda x: volume_driver)
self.stubs.Set(host.Host, 'get_connection', lambda x: fake)
def fake_lookup(self, instance_name):
return FakeVirtDomain()
def fake_execute(self, *args, **kwargs):
open(args[-1], "a").close()
def _create_service(self, **kwargs):
service_ref = {'host': kwargs.get('host', 'dummy'),
'disabled': kwargs.get('disabled', False),
'binary': 'nova-compute',
'topic': 'compute',
'report_count': 0}
return objects.Service(**service_ref)
def _get_pause_flag(self, drvr, network_info, power_on=True,
vifs_already_plugged=False):
timeout = CONF.vif_plugging_timeout
events = []
if (drvr._conn_supports_start_paused and
utils.is_neutron() and
not vifs_already_plugged and
power_on and timeout):
events = drvr._get_neutron_events(network_info)
return bool(events)
def test_public_api_signatures(self):
baseinst = driver.ComputeDriver(None)
inst = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertPublicAPISignatures(baseinst, inst)
def test_legacy_block_device_info(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertFalse(drvr.need_legacy_block_device_info)
@mock.patch.object(host.Host, "has_min_version")
def test_min_version_start_ok(self, mock_version):
mock_version.return_value = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
@mock.patch.object(host.Host, "has_min_version")
def test_min_version_start_abort(self, mock_version):
mock_version.return_value = False
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) - 1)
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_next_min_version_deprecation_warning(self, mock_warning,
mock_get_libversion):
# Skip test if there's no currently planned new min version
if (versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) ==
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_VERSION)):
self.skipTest("NEXT_MIN_LIBVIRT_VERSION == MIN_LIBVIRT_VERSION")
# Test that a warning is logged if the libvirt version is less than
# the next required minimum version.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
# assert that the next min version is in a warning message
expected_arg = {'version': versionutils.convert_version_to_str(
versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))}
version_arg_found = False
for call in mock_warning.call_args_list:
if call[0][1] == expected_arg:
version_arg_found = True
break
self.assertTrue(version_arg_found)
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION) - 1)
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_next_min_qemu_version_deprecation_warning(self, mock_warning,
mock_get_libversion):
# Skip test if there's no currently planned new min version
if (versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION) ==
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_VERSION)):
self.skipTest("NEXT_MIN_QEMU_VERSION == MIN_QEMU_VERSION")
# Test that a warning is logged if the libvirt version is less than
# the next required minimum version.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
# assert that the next min version is in a warning message
expected_arg = {'version': versionutils.convert_version_to_str(
versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION))}
version_arg_found = False
for call in mock_warning.call_args_list:
if call[0][1] == expected_arg:
version_arg_found = True
break
self.assertTrue(version_arg_found)
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_next_min_version_ok(self, mock_warning, mock_get_libversion):
# Skip test if there's no currently planned new min version
if (versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) ==
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_VERSION)):
self.skipTest("NEXT_MIN_LIBVIRT_VERSION == MIN_LIBVIRT_VERSION")
# Test that a warning is not logged if the libvirt version is greater
# than or equal to NEXT_MIN_LIBVIRT_VERSION.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
# assert that the next min version is in a warning message
expected_arg = {'version': versionutils.convert_version_to_str(
versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_LIBVIRT_VERSION))}
version_arg_found = False
for call in mock_warning.call_args_list:
if call[0][1] == expected_arg:
version_arg_found = True
break
self.assertFalse(version_arg_found)
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION))
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_next_min_qemu_version_ok(self, mock_warning, mock_get_libversion):
# Skip test if there's no currently planned new min version
if (versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION) ==
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_VERSION)):
self.skipTest("NEXT_MIN_QEMU_VERSION == MIN_QEMU_VERSION")
# Test that a warning is not logged if the libvirt version is greater
# than or equal to NEXT_MIN_QEMU_VERSION.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
# assert that the next min version is in a warning message
expected_arg = {'version': versionutils.convert_version_to_str(
versionutils.convert_version_to_int(
libvirt_driver.NEXT_MIN_QEMU_VERSION))}
version_arg_found = False
for call in mock_warning.call_args_list:
if call[0][1] == expected_arg:
version_arg_found = True
break
self.assertFalse(version_arg_found)
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.PPC64)) - 1)
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.PPC64)))
@mock.patch.object(arch, "from_host", return_value=arch.PPC64)
def test_min_version_ppc_old_libvirt(self, mock_libv, mock_qemu,
mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.PPC64)))
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.PPC64)) - 1)
@mock.patch.object(arch, "from_host", return_value=arch.PPC64)
def test_min_version_ppc_old_qemu(self, mock_libv, mock_qemu,
mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.PPC64)))
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.PPC64)))
@mock.patch.object(arch, "from_host", return_value=arch.PPC64)
def test_min_version_ppc_ok(self, mock_libv, mock_qemu, mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.S390X)) - 1)
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.S390X)))
@mock.patch.object(arch, "from_host", return_value=arch.S390X)
def test_min_version_s390_old_libvirt(self, mock_libv, mock_qemu,
mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.S390X)))
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.S390X)) - 1)
@mock.patch.object(arch, "from_host", return_value=arch.S390X)
def test_min_version_s390_old_qemu(self, mock_libv, mock_qemu,
mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.init_host,
"dummyhost")
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_OTHER_ARCH.get(
arch.S390X)))
@mock.patch.object(fakelibvirt.Connection, 'getVersion',
return_value=versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_OTHER_ARCH.get(
arch.S390X)))
@mock.patch.object(arch, "from_host", return_value=arch.S390X)
def test_min_version_s390_ok(self, mock_libv, mock_qemu, mock_arch):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("dummyhost")
def _do_test_parse_migration_flags(self, lm_expected=None,
bm_expected=None):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr._parse_migration_flags()
if lm_expected is not None:
self.assertEqual(lm_expected, drvr._live_migration_flags)
if bm_expected is not None:
self.assertEqual(bm_expected, drvr._block_migration_flags)
def test_parse_live_migration_flags_default(self):
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE))
def test_parse_live_migration_flags(self):
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE))
def test_parse_block_migration_flags_default(self):
self._do_test_parse_migration_flags(
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_parse_block_migration_flags(self):
self._do_test_parse_migration_flags(
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_parse_migration_flags_p2p_xen(self):
self.flags(virt_type='xen', group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_live_migration_tunnelled_none(self):
self.flags(live_migration_tunnelled=None, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED))
def test_live_migration_tunnelled_true(self):
self.flags(live_migration_tunnelled=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_TUNNELLED))
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_live_migration_permit_postcopy_true(self, host):
self.flags(live_migration_permit_post_copy=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY))
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_live_migration_permit_auto_converge_true(self, host):
self.flags(live_migration_permit_auto_converge=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE))
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_live_migration_permit_auto_converge_and_post_copy_true(self,
host):
self.flags(live_migration_permit_auto_converge=True, group='libvirt')
self.flags(live_migration_permit_post_copy=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_POSTCOPY))
@mock.patch.object(host.Host, 'has_min_version')
def test_live_migration_auto_converge_and_post_copy_true_old_libvirt(
self, mock_host):
self.flags(live_migration_permit_auto_converge=True, group='libvirt')
self.flags(live_migration_permit_post_copy=True, group='libvirt')
def fake_has_min_version(lv_ver=None, hv_ver=None, hv_type=None):
if (lv_ver == libvirt_driver.MIN_LIBVIRT_POSTCOPY_VERSION and
hv_ver == libvirt_driver.MIN_QEMU_POSTCOPY_VERSION):
return False
return True
mock_host.side_effect = fake_has_min_version
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC |
libvirt_driver.libvirt.VIR_MIGRATE_AUTO_CONVERGE))
@mock.patch.object(host.Host, 'has_min_version', return_value=False)
def test_live_migration_permit_postcopy_true_old_libvirt(self, host):
self.flags(live_migration_permit_post_copy=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
@mock.patch.object(host.Host, 'has_min_version', return_value=False)
def test_live_migration_permit_auto_converge_true_old_libvirt(self, host):
self.flags(live_migration_permit_auto_converge=True, group='libvirt')
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_live_migration_permit_postcopy_false(self):
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
def test_live_migration_permit_autoconverge_false(self):
self._do_test_parse_migration_flags(
lm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE),
bm_expected=(libvirt_driver.libvirt.VIR_MIGRATE_UNDEFINE_SOURCE |
libvirt_driver.libvirt.VIR_MIGRATE_PEER2PEER |
libvirt_driver.libvirt.VIR_MIGRATE_LIVE |
libvirt_driver.libvirt.VIR_MIGRATE_NON_SHARED_INC))
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password(self, mock_get_guest, ver, mock_image):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.set_admin_password(instance, "123")
mock_guest.set_user_password.assert_called_once_with("root", "123")
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password_parallels(self, mock_get_guest, ver):
self.flags(virt_type='parallels', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.set_admin_password(instance, "123")
mock_guest.set_user_password.assert_called_once_with("root", "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password_windows(self, mock_get_guest, ver, mock_image):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
instance.os_type = "windows"
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.set_admin_password(instance, "123")
mock_guest.set_user_password.assert_called_once_with(
"Administrator", "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password_image(self, mock_get_guest, ver, mock_image):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes",
"os_admin_user": "foo"
}}
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.set_admin_password(instance, "123")
mock_guest.set_user_password.assert_called_once_with("foo", "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=False)
def test_set_admin_password_bad_version(self, mock_svc, mock_image):
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
for hyp in ('kvm', 'parallels'):
self.flags(virt_type=hyp, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.SetAdminPasswdNotSupported,
drvr.set_admin_password, instance, "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_set_admin_password_bad_hyp(self, mock_svc, mock_image):
self.flags(virt_type='lxc', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.SetAdminPasswdNotSupported,
drvr.set_admin_password, instance, "123")
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_set_admin_password_guest_agent_not_running(self, mock_svc):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.QemuGuestAgentNotEnabled,
drvr.set_admin_password, instance, "123")
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def test_set_admin_password_error(self, mock_get_guest, ver, mock_image):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.test_instance)
mock_image.return_value = {"properties": {
"hw_qemu_guest_agent": "yes"}}
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_guest.set_user_password.side_effect = (
fakelibvirt.libvirtError("error"))
mock_get_guest.return_value = mock_guest
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.NovaException,
drvr.set_admin_password, instance, "123")
@mock.patch.object(objects.Service, 'save')
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_set_host_enabled_with_disable(self, mock_svc, mock_save):
# Tests disabling an enabled host.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
svc = self._create_service(host='fake-mini')
mock_svc.return_value = svc
drvr._set_host_enabled(False)
self.assertTrue(svc.disabled)
mock_save.assert_called_once_with()
@mock.patch.object(objects.Service, 'save')
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_set_host_enabled_with_enable(self, mock_svc, mock_save):
# Tests enabling a disabled host.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
svc = self._create_service(disabled=True, host='fake-mini')
mock_svc.return_value = svc
drvr._set_host_enabled(True)
# since disabled_reason is not set and not prefixed with "AUTO:",
# service should not be enabled.
mock_save.assert_not_called()
self.assertTrue(svc.disabled)
@mock.patch.object(objects.Service, 'save')
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_set_host_enabled_with_enable_state_enabled(self, mock_svc,
mock_save):
# Tests enabling an enabled host.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
svc = self._create_service(disabled=False, host='fake-mini')
mock_svc.return_value = svc
drvr._set_host_enabled(True)
self.assertFalse(svc.disabled)
mock_save.assert_not_called()
@mock.patch.object(objects.Service, 'save')
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_set_host_enabled_with_disable_state_disabled(self, mock_svc,
mock_save):
# Tests disabling a disabled host.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
svc = self._create_service(disabled=True, host='fake-mini')
mock_svc.return_value = svc
drvr._set_host_enabled(False)
mock_save.assert_not_called()
self.assertTrue(svc.disabled)
def test_set_host_enabled_swallows_exceptions(self):
# Tests that set_host_enabled will swallow exceptions coming from the
# db_api code so they don't break anything calling it, e.g. the
# _get_new_connection method.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
with mock.patch.object(db, 'service_get_by_compute_host') as db_mock:
# Make db.service_get_by_compute_host raise NovaException; this
# is more robust than just raising ComputeHostNotFound.
db_mock.side_effect = exception.NovaException
drvr._set_host_enabled(False)
@mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName")
def test_prepare_pci_device(self, mock_lookup):
pci_devices = [dict(hypervisor_name='xxx')]
self.flags(virt_type='xen', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conn = drvr._host.get_connection()
mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn)
drvr._prepare_pci_devices_for_use(pci_devices)
@mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName")
@mock.patch.object(fakelibvirt.virNodeDevice, "dettach")
def test_prepare_pci_device_exception(self, mock_detach, mock_lookup):
pci_devices = [dict(hypervisor_name='xxx',
id='id1',
instance_uuid='uuid')]
self.flags(virt_type='xen', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conn = drvr._host.get_connection()
mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn)
mock_detach.side_effect = fakelibvirt.libvirtError("xxxx")
self.assertRaises(exception.PciDevicePrepareFailed,
drvr._prepare_pci_devices_for_use, pci_devices)
@mock.patch.object(host.Host, "has_min_version", return_value=False)
def test_device_metadata(self, mock_version):
xml = """
<domain>
<name>dummy</name>
<uuid>32dfcb37-5af1-552b-357c-be8c3aa38310</uuid>
<memory>1048576</memory>
<vcpu>1</vcpu>
<os>
<type arch='x86_64' machine='pc-i440fx-2.4'>hvm</type>
</os>
<devices>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/dev/mapper/generic'/>
<target dev='sda' bus='scsi'/>
<address type='drive' controller='0' bus='0' target='0' unit='0'/>
</disk>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/dev/mapper/generic-1'/>
<target dev='hda' bus='ide'/>
<address type='drive' controller='0' bus='1' target='0' unit='0'/>
</disk>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/dev/mapper/generic-2'/>
<target dev='hdb' bus='ide'/>
<address type='drive' controller='0' bus='1' target='1' unit='1'/>
</disk>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/dev/mapper/aa1'/>
<target dev='sdb' bus='usb'/>
</disk>
<disk type='block' device='disk'>
<driver name='qemu' type='qcow2'/>
<source dev='/var/lib/libvirt/images/centos'/>
<backingStore/>
<target dev='vda' bus='virtio'/>
<boot order='1'/>
<alias name='virtio-disk0'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x09'
function='0x0'/>
</disk>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='none'/>
<source file='/var/lib/libvirt/images/generic.qcow2'/>
<target dev='vdb' bus='virtio'/>
<address type='virtio-mmio'/>
</disk>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2'/>
<source file='/var/lib/libvirt/images/test.qcow2'/>
<backingStore/>
<target dev='vdc' bus='virtio'/>
<alias name='virtio-disk1'/>
<address type='ccw' cssid='0xfe' ssid='0x0' devno='0x0000'/>
</disk>
<interface type='network'>
<mac address='52:54:00:f6:35:8f'/>
<source network='default'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x03'
function='0x0'/>
</interface>
<interface type='network'>
<mac address='51:5a:2c:a4:5e:1b'/>
<source network='default'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x04'
function='0x1'/>
</interface>
<interface type='network'>
<mac address='fa:16:3e:d1:28:e4'/>
<source network='default'/>
<model type='virtio'/>
<address type='virtio-mmio'/>
</interface>
<interface type='network'>
<mac address='52:54:00:14:6f:50'/>
<source network='default' bridge='virbr0'/>
<target dev='vnet0'/>
<model type='virtio'/>
<alias name='net0'/>
<address type='ccw' cssid='0xfe' ssid='0x0' devno='0x0001'/>
</interface>
</devices>
</domain>"""
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
guest = libvirt_guest.Guest(dom)
instance_ref = objects.Instance(**self.test_instance)
bdms = block_device_obj.block_device_make_list_from_dicts(
self.context, [
fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sda', 'tag': "db"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/hda', 'tag': "nfvfunc1"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 3,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sdb', 'tag': "nfvfunc2"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 4,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/hdb'}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 5,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vda', 'tag': "nfvfunc3"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 6,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vdb', 'tag': "nfvfunc4"}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 7,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vdc', 'tag': "nfvfunc5"}),
]
)
vif = obj_vif.VirtualInterface(context=self.context)
vif.address = '52:54:00:f6:35:8f'
vif.network_id = 123
vif.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
vif.uuid = '12ec4b21-ef22-6c21-534b-ba3e3ab3a311'
vif.tag = 'mytag1'
vif1 = obj_vif.VirtualInterface(context=self.context)
vif1.address = '51:5a:2c:a4:5e:1b'
vif1.network_id = 123
vif1.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
vif1.uuid = 'abec4b21-ef22-6c21-534b-ba3e3ab3a312'
vif1.tag = None
vif2 = obj_vif.VirtualInterface(context=self.context)
vif2.address = 'fa:16:3e:d1:28:e4'
vif2.network_id = 123
vif2.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
vif2.uuid = '645686e4-7086-4eab-8c2f-c41f017a1b16'
vif2.tag = 'mytag2'
vif3 = obj_vif.VirtualInterface(context=self.context)
vif3.address = '52:54:00:14:6f:50'
vif3.network_id = 123
vif3.instance_uuid = '32dfcb37-5af1-552b-357c-be8c3aa38310'
vif3.uuid = '99cc3604-782d-4a32-a27c-bc33ac56ce86'
vif3.tag = 'mytag3'
vifs = [vif, vif1, vif2, vif3]
with test.nested(
mock.patch('nova.objects.VirtualInterfaceList'
'.get_by_instance_uuid', return_value=vifs),
mock.patch('nova.objects.BlockDeviceMappingList'
'.get_by_instance_uuid', return_value=bdms),
mock.patch('nova.virt.libvirt.host.Host.get_guest',
return_value=guest),
mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc',
return_value=xml)):
metadata_obj = drvr._build_device_metadata(self.context,
instance_ref)
metadata = metadata_obj.devices
self.assertEqual(9, len(metadata))
self.assertIsInstance(metadata[0],
objects.DiskMetadata)
self.assertIsInstance(metadata[0].bus,
objects.SCSIDeviceBus)
self.assertEqual(['db'], metadata[0].tags)
self.assertFalse(metadata[0].bus.obj_attr_is_set('address'))
self.assertEqual(['nfvfunc1'], metadata[1].tags)
self.assertIsInstance(metadata[1],
objects.DiskMetadata)
self.assertIsInstance(metadata[1].bus,
objects.IDEDeviceBus)
self.assertEqual(['nfvfunc1'], metadata[1].tags)
self.assertFalse(metadata[1].bus.obj_attr_is_set('address'))
self.assertIsInstance(metadata[2],
objects.DiskMetadata)
self.assertIsInstance(metadata[2].bus,
objects.USBDeviceBus)
self.assertEqual(['nfvfunc2'], metadata[2].tags)
self.assertFalse(metadata[2].bus.obj_attr_is_set('address'))
self.assertIsInstance(metadata[3],
objects.DiskMetadata)
self.assertIsInstance(metadata[3].bus,
objects.PCIDeviceBus)
self.assertEqual(['nfvfunc3'], metadata[3].tags)
self.assertEqual('0000:00:09.0', metadata[3].bus.address)
self.assertIsInstance(metadata[4],
objects.DiskMetadata)
self.assertEqual(['nfvfunc4'], metadata[4].tags)
self.assertIsInstance(metadata[5],
objects.DiskMetadata)
self.assertEqual(['nfvfunc5'], metadata[5].tags)
self.assertIsInstance(metadata[6],
objects.NetworkInterfaceMetadata)
self.assertIsInstance(metadata[6].bus,
objects.PCIDeviceBus)
self.assertEqual(['mytag1'], metadata[6].tags)
self.assertEqual('0000:00:03.0', metadata[6].bus.address)
self.assertIsInstance(metadata[7],
objects.NetworkInterfaceMetadata)
self.assertEqual(['mytag2'], metadata[7].tags)
self.assertIsInstance(metadata[8],
objects.NetworkInterfaceMetadata)
self.assertEqual(['mytag3'], metadata[8].tags)
@mock.patch.object(host.Host, 'get_connection')
@mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc')
def test_detach_pci_devices(self, mocked_get_xml_desc, mock_conn):
fake_domXML1_with_pci = (
"""<domain> <devices>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='none'/>
<source file='xxx'/>
<target dev='vda' bus='virtio'/>
<alias name='virtio-disk0'/>
<address type='pci' domain='0x0000' bus='0x00'
slot='0x04' function='0x0'/>
</disk>
<hostdev mode="subsystem" type="pci" managed="yes">
<source>
<address function="0x1" slot="0x10" domain="0x0001"
bus="0x04"/>
</source>
</hostdev></devices></domain>""")
fake_domXML1_without_pci = (
"""<domain> <devices>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='none'/>
<source file='xxx'/>
<target dev='vda' bus='virtio'/>
<alias name='virtio-disk0'/>
<address type='pci' domain='0x0001' bus='0x00'
slot='0x04' function='0x0'/>
</disk></devices></domain>""")
pci_device_info = {'compute_node_id': 1,
'instance_uuid': 'uuid',
'address': '0001:04:10.1'}
pci_device = objects.PciDevice(**pci_device_info)
pci_devices = [pci_device]
mocked_get_xml_desc.return_value = fake_domXML1_without_pci
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
dom = fakelibvirt.Domain(
drvr._get_connection(), fake_domXML1_with_pci, False)
guest = libvirt_guest.Guest(dom)
drvr._detach_pci_devices(guest, pci_devices)
@mock.patch.object(host.Host, 'get_connection')
@mock.patch.object(nova.virt.libvirt.guest.Guest, 'get_xml_desc')
def test_detach_pci_devices_timeout(self, mocked_get_xml_desc, mock_conn):
fake_domXML1_with_pci = (
"""<domain> <devices>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='none'/>
<source file='xxx'/>
<target dev='vda' bus='virtio'/>
<alias name='virtio-disk0'/>
<address type='pci' domain='0x0000' bus='0x00'
slot='0x04' function='0x0'/>
</disk>
<hostdev mode="subsystem" type="pci" managed="yes">
<source>
<address function="0x1" slot="0x10" domain="0x0001"
bus="0x04"/>
</source>
</hostdev></devices></domain>""")
pci_device_info = {'compute_node_id': 1,
'instance_uuid': 'uuid',
'address': '0001:04:10.1'}
pci_device = objects.PciDevice(**pci_device_info)
pci_devices = [pci_device]
mocked_get_xml_desc.return_value = fake_domXML1_with_pci
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
dom = fakelibvirt.Domain(
drvr._get_connection(), fake_domXML1_with_pci, False)
guest = libvirt_guest.Guest(dom)
self.assertRaises(exception.PciDeviceDetachFailed,
drvr._detach_pci_devices, guest, pci_devices)
@mock.patch.object(connector, 'get_connector_properties')
def test_get_connector(self, fake_get_connector):
initiator = 'fake.initiator.iqn'
ip = 'fakeip'
host = 'fakehost'
wwpns = ['100010604b019419']
wwnns = ['200010604b019419']
self.flags(my_ip=ip)
self.flags(host=host)
expected = {
'ip': ip,
'initiator': initiator,
'host': host,
'wwpns': wwpns,
'wwnns': wwnns
}
volume = {
'id': 'fake'
}
# TODO(walter-boring) add the fake in os-brick
fake_get_connector.return_value = expected
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
result = drvr.get_volume_connector(volume)
self.assertThat(expected, matchers.DictMatches(result))
@mock.patch.object(connector, 'get_connector_properties')
def test_get_connector_storage_ip(self, fake_get_connector):
ip = '100.100.100.100'
storage_ip = '101.101.101.101'
self.flags(my_block_storage_ip=storage_ip, my_ip=ip)
volume = {
'id': 'fake'
}
expected = {
'ip': storage_ip
}
# TODO(walter-boring) add the fake in os-brick
fake_get_connector.return_value = expected
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
result = drvr.get_volume_connector(volume)
self.assertEqual(storage_ip, result['ip'])
def test_lifecycle_event_registration(self):
calls = []
def fake_registerErrorHandler(*args, **kwargs):
calls.append('fake_registerErrorHandler')
def fake_get_host_capabilities(**args):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.arch = arch.ARMV7
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
calls.append('fake_get_host_capabilities')
return caps
@mock.patch.object(fakelibvirt, 'registerErrorHandler',
side_effect=fake_registerErrorHandler)
@mock.patch.object(host.Host, "get_capabilities",
side_effect=fake_get_host_capabilities)
def test_init_host(get_host_capabilities, register_error_handler):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host("test_host")
test_init_host()
# NOTE(dkliban): Will fail if get_host_capabilities is called before
# registerErrorHandler
self.assertEqual(['fake_registerErrorHandler',
'fake_get_host_capabilities'], calls)
def test_sanitize_log_to_xml(self):
# setup fake data
data = {'auth_password': 'scrubme'}
bdm = [{'connection_info': {'data': data}}]
bdi = {'block_device_mapping': bdm}
# Tests that the parameters to the _get_guest_xml method
# are sanitized for passwords when logged.
def fake_debug(*args, **kwargs):
if 'auth_password' in args[0]:
self.assertNotIn('scrubme', args[0])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conf = mock.Mock()
with test.nested(
mock.patch.object(libvirt_driver.LOG, 'debug',
side_effect=fake_debug),
mock.patch.object(drvr, '_get_guest_config', return_value=conf)
) as (
debug_mock, conf_mock
):
drvr._get_guest_xml(self.context, self.test_instance,
network_info={}, disk_info={},
image_meta={}, block_device_info=bdi)
# we don't care what the log message is, we just want to make sure
# our stub method is called which asserts the password is scrubbed
self.assertTrue(debug_mock.called)
@mock.patch.object(time, "time")
def test_get_guest_config(self, time_mock):
time_mock.return_value = 1234567.89
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
test_instance = copy.deepcopy(self.test_instance)
test_instance["display_name"] = "purple tomatoes"
ctxt = context.RequestContext(project_id=123,
project_name="aubergine",
user_id=456,
user_name="pie")
flavor = objects.Flavor(name='m1.small',
memory_mb=6,
vcpus=28,
root_gb=496,
ephemeral_gb=8128,
swap=33550336,
extra_specs={})
instance_ref = objects.Instance(**test_instance)
instance_ref.flavor = flavor
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info,
context=ctxt)
self.assertEqual(cfg.uuid, instance_ref["uuid"])
self.assertEqual(2, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureAPIC)
self.assertEqual(cfg.memory, 6 * units.Ki)
self.assertEqual(cfg.vcpus, 28)
self.assertEqual(cfg.os_type, vm_mode.HVM)
self.assertEqual(cfg.os_boot_dev, ["hd"])
self.assertIsNone(cfg.os_root)
self.assertEqual(len(cfg.devices), 10)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(len(cfg.metadata), 1)
self.assertIsInstance(cfg.metadata[0],
vconfig.LibvirtConfigGuestMetaNovaInstance)
self.assertEqual(version.version_string_with_package(),
cfg.metadata[0].package)
self.assertEqual("purple tomatoes",
cfg.metadata[0].name)
self.assertEqual(1234567.89,
cfg.metadata[0].creationTime)
self.assertEqual("image",
cfg.metadata[0].roottype)
self.assertEqual(str(instance_ref["image_ref"]),
cfg.metadata[0].rootid)
self.assertIsInstance(cfg.metadata[0].owner,
vconfig.LibvirtConfigGuestMetaNovaOwner)
self.assertEqual(456,
cfg.metadata[0].owner.userid)
self.assertEqual("pie",
cfg.metadata[0].owner.username)
self.assertEqual(123,
cfg.metadata[0].owner.projectid)
self.assertEqual("aubergine",
cfg.metadata[0].owner.projectname)
self.assertIsInstance(cfg.metadata[0].flavor,
vconfig.LibvirtConfigGuestMetaNovaFlavor)
self.assertEqual("m1.small",
cfg.metadata[0].flavor.name)
self.assertEqual(6,
cfg.metadata[0].flavor.memory)
self.assertEqual(28,
cfg.metadata[0].flavor.vcpus)
self.assertEqual(496,
cfg.metadata[0].flavor.disk)
self.assertEqual(8128,
cfg.metadata[0].flavor.ephemeral)
self.assertEqual(33550336,
cfg.metadata[0].flavor.swap)
def test_get_guest_config_lxc(self):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, {'mapping': {}})
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
self.assertEqual(vm_mode.EXE, cfg.os_type)
self.assertEqual("/sbin/init", cfg.os_init_path)
self.assertEqual("console=tty0 console=ttyS0", cfg.os_cmdline)
self.assertIsNone(cfg.os_root)
self.assertEqual(3, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestFilesys)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestConsole)
def test_get_guest_config_lxc_with_id_maps(self):
self.flags(virt_type='lxc', group='libvirt')
self.flags(uid_maps=['0:1000:100'], group='libvirt')
self.flags(gid_maps=['0:1000:100'], group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, {'mapping': {}})
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.vcpus, cfg.vcpus)
self.assertEqual(vm_mode.EXE, cfg.os_type)
self.assertEqual("/sbin/init", cfg.os_init_path)
self.assertEqual("console=tty0 console=ttyS0", cfg.os_cmdline)
self.assertIsNone(cfg.os_root)
self.assertEqual(3, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestFilesys)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestConsole)
self.assertEqual(len(cfg.idmaps), 2)
self.assertIsInstance(cfg.idmaps[0],
vconfig.LibvirtConfigGuestUIDMap)
self.assertIsInstance(cfg.idmaps[1],
vconfig.LibvirtConfigGuestGIDMap)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_fits(self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps)):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_no_fit(self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=4096, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set', return_value=set([3])),
mock.patch.object(random, 'choice')
) as (get_host_cap_mock,
get_vcpu_pin_set_mock, choice_mock):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertFalse(choice_mock.called)
self.assertEqual(set([3]), cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
def _test_get_guest_memory_backing_config(
self, host_topology, inst_topology, numatune):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
with mock.patch.object(
drvr, "_get_host_numa_topology",
return_value=host_topology):
return drvr._get_guest_memory_backing_config(
inst_topology, numatune, {})
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_get_guest_memory_backing_config_large_success(self, mock_version):
host_topology = objects.NUMATopology(
cells=[
objects.NUMACell(
id=3, cpuset=set([1]), memory=1024, mempages=[
objects.NUMAPagesTopology(size_kb=4, total=2000,
used=0),
objects.NUMAPagesTopology(size_kb=2048, total=512,
used=0),
objects.NUMAPagesTopology(size_kb=1048576, total=0,
used=0),
])])
inst_topology = objects.InstanceNUMATopology(cells=[
objects.InstanceNUMACell(
id=3, cpuset=set([0, 1]), memory=1024, pagesize=2048)])
numa_tune = vconfig.LibvirtConfigGuestNUMATune()
numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()]
numa_tune.memnodes[0].cellid = 0
numa_tune.memnodes[0].nodeset = [3]
result = self._test_get_guest_memory_backing_config(
host_topology, inst_topology, numa_tune)
self.assertEqual(1, len(result.hugepages))
self.assertEqual(2048, result.hugepages[0].size_kb)
self.assertEqual([0], result.hugepages[0].nodeset)
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_get_guest_memory_backing_config_smallest(self, mock_version):
host_topology = objects.NUMATopology(
cells=[
objects.NUMACell(
id=3, cpuset=set([1]), memory=1024, mempages=[
objects.NUMAPagesTopology(size_kb=4, total=2000,
used=0),
objects.NUMAPagesTopology(size_kb=2048, total=512,
used=0),
objects.NUMAPagesTopology(size_kb=1048576, total=0,
used=0),
])])
inst_topology = objects.InstanceNUMATopology(cells=[
objects.InstanceNUMACell(
id=3, cpuset=set([0, 1]), memory=1024, pagesize=4)])
numa_tune = vconfig.LibvirtConfigGuestNUMATune()
numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()]
numa_tune.memnodes[0].cellid = 0
numa_tune.memnodes[0].nodeset = [3]
result = self._test_get_guest_memory_backing_config(
host_topology, inst_topology, numa_tune)
self.assertIsNone(result)
def test_get_guest_memory_backing_config_realtime(self):
flavor = {"extra_specs": {
"hw:cpu_realtime": "yes",
"hw:cpu_policy": "dedicated"
}}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
membacking = drvr._get_guest_memory_backing_config(
None, None, flavor)
self.assertTrue(membacking.locked)
self.assertFalse(membacking.sharedpages)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_pci_no_numa_info(
self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
pci_device_info = dict(test_pci_device.fake_db_dev)
pci_device_info.update(compute_node_id=1,
label='fake',
status=fields.PciDeviceStatus.AVAILABLE,
address='0000:00:00.1',
instance_uuid=None,
request_id=None,
extra_info={},
numa_node=None)
pci_device = objects.PciDevice(**pci_device_info)
with test.nested(
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(
host.Host, "get_capabilities", return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set', return_value=set([3])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
mock.patch.object(pci_manager, "get_instance_pci_devs",
return_value=[pci_device])):
cfg = conn._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(set([3]), cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_2pci_no_fit(self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=4096, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
pci_device_info = dict(test_pci_device.fake_db_dev)
pci_device_info.update(compute_node_id=1,
label='fake',
status=fields.PciDeviceStatus.AVAILABLE,
address='0000:00:00.1',
instance_uuid=None,
request_id=None,
extra_info={},
numa_node=1)
pci_device = objects.PciDevice(**pci_device_info)
pci_device_info.update(numa_node=0, address='0000:00:00.2')
pci_device2 = objects.PciDevice(**pci_device_info)
with test.nested(
mock.patch.object(
host.Host, "get_capabilities", return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set', return_value=set([3])),
mock.patch.object(random, 'choice'),
mock.patch.object(pci_manager, "get_instance_pci_devs",
return_value=[pci_device, pci_device2])
) as (get_host_cap_mock,
get_vcpu_pin_set_mock, choice_mock, pci_mock):
cfg = conn._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertFalse(choice_mock.called)
self.assertEqual(set([3]), cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
@mock.patch.object(fakelibvirt.Connection, 'getType')
@mock.patch.object(fakelibvirt.Connection, 'getVersion')
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
@mock.patch.object(host.Host, 'get_capabilities')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_set_host_enabled')
def _test_get_guest_config_numa_unsupported(self, fake_lib_version,
fake_version, fake_type,
fake_arch, exception_class,
pagesize, mock_host,
mock_caps, mock_lib_version,
mock_version, mock_type):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=0, cpuset=set([0]),
memory=1024, pagesize=pagesize)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = fake_arch
caps.host.topology = self._fake_caps_numa_topology()
mock_type.return_value = fake_type
mock_version.return_value = fake_version
mock_lib_version.return_value = fake_lib_version
mock_caps.return_value = caps
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.assertRaises(exception_class,
drvr._get_guest_config,
instance_ref, [],
image_meta, disk_info)
def test_get_guest_config_numa_old_version_libvirt(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) - 1,
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_old_version_libvirt_ppc(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION_PPC) - 1,
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.PPC64LE,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_bad_version_libvirt(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.BAD_LIBVIRT_NUMA_VERSIONS[0]),
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.NUMATopologyUnsupported,
None)
@mock.patch.object(libvirt_driver.LOG, 'warning')
def test_has_numa_support_bad_version_libvirt_log(self, mock_warn):
# Tests that a warning is logged once and only once when there is a bad
# BAD_LIBVIRT_NUMA_VERSIONS detected.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertFalse(hasattr(drvr, '_bad_libvirt_numa_version_warn'))
with mock.patch.object(drvr._host, 'has_version', return_value=True):
for i in range(2):
self.assertFalse(drvr._has_numa_support())
self.assertTrue(drvr._bad_libvirt_numa_version_warn)
self.assertEqual(1, mock_warn.call_count)
# assert the version is logged properly
self.assertEqual('1.2.9.2', mock_warn.call_args[0][1])
def test_get_guest_config_numa_old_version_qemu(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION),
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) - 1,
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_other_arch_qemu(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION),
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.S390,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_xen(self):
self.flags(virt_type='xen', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION),
versionutils.convert_version_to_int((4, 5, 0)),
'XEN',
arch.X86_64,
exception.NUMATopologyUnsupported,
None)
def test_get_guest_config_numa_old_pages_libvirt(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION) - 1,
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION),
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.MemoryPagesUnsupported,
2048)
def test_get_guest_config_numa_old_pages_qemu(self):
self.flags(virt_type='kvm', group='libvirt')
self._test_get_guest_config_numa_unsupported(
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION),
versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) - 1,
host.HV_DRIVER_QEMU,
arch.X86_64,
exception.NUMATopologyUnsupported,
2048)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_fit_w_cpu_pinset(
self, is_able):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=1024, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology(kb_mem=4194304)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set', return_value=set([2, 3])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8)))
) as (has_min_version_mock, get_host_cap_mock,
get_vcpu_pin_set_mock, get_online_cpus_mock):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
# NOTE(ndipanov): we make sure that pin_set was taken into account
# when choosing viable cells
self.assertEqual(set([2, 3]), cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.cpu.numa)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_non_numa_host_instance_topo(self, is_able):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=0, cpuset=set([0]), memory=1024),
objects.InstanceNUMACell(
id=1, cpuset=set([2]), memory=1024)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps)):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
self.assertEqual(0, len(cfg.cputune.vcpupin))
self.assertIsNone(cfg.numatune)
self.assertIsNotNone(cfg.cpu.numa)
for instance_cell, numa_cfg_cell in zip(
instance_topology.cells, cfg.cpu.numa.cells):
self.assertEqual(instance_cell.id, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_numa_host_instance_topo(self, is_able):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]), memory=1024, pagesize=None),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]), memory=1024,
pagesize=None)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set',
return_value=set([2, 3, 4, 5])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
# Test that the pinning is correct and limited to allowed only
self.assertEqual(0, cfg.cputune.vcpupin[0].id)
self.assertEqual(set([2, 3]), cfg.cputune.vcpupin[0].cpuset)
self.assertEqual(1, cfg.cputune.vcpupin[1].id)
self.assertEqual(set([2, 3]), cfg.cputune.vcpupin[1].cpuset)
self.assertEqual(2, cfg.cputune.vcpupin[2].id)
self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[2].cpuset)
self.assertEqual(3, cfg.cputune.vcpupin[3].id)
self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[3].cpuset)
self.assertIsNotNone(cfg.cpu.numa)
self.assertIsInstance(cfg.cputune.emulatorpin,
vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
self.assertEqual(set([2, 3, 4, 5]), cfg.cputune.emulatorpin.cpuset)
for instance_cell, numa_cfg_cell, index in zip(
instance_topology.cells,
cfg.cpu.numa.cells,
range(len(instance_topology.cells))):
self.assertEqual(index, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
allnodes = [cell.id for cell in instance_topology.cells]
self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
self.assertEqual("strict", cfg.numatune.memory.mode)
for instance_cell, memnode, index in zip(
instance_topology.cells,
cfg.numatune.memnodes,
range(len(instance_topology.cells))):
self.assertEqual(index, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
def test_get_guest_config_numa_host_instance_topo_reordered(self):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=3, cpuset=set([0, 1]), memory=1024),
objects.InstanceNUMACell(
id=0, cpuset=set([2, 3]), memory=1024)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
# Test that the pinning is correct and limited to allowed only
self.assertEqual(0, cfg.cputune.vcpupin[0].id)
self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[0].cpuset)
self.assertEqual(1, cfg.cputune.vcpupin[1].id)
self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[1].cpuset)
self.assertEqual(2, cfg.cputune.vcpupin[2].id)
self.assertEqual(set([0, 1]), cfg.cputune.vcpupin[2].cpuset)
self.assertEqual(3, cfg.cputune.vcpupin[3].id)
self.assertEqual(set([0, 1]), cfg.cputune.vcpupin[3].cpuset)
self.assertIsNotNone(cfg.cpu.numa)
self.assertIsInstance(cfg.cputune.emulatorpin,
vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
self.assertEqual(set([0, 1, 6, 7]), cfg.cputune.emulatorpin.cpuset)
for index, (instance_cell, numa_cfg_cell) in enumerate(zip(
instance_topology.cells,
cfg.cpu.numa.cells)):
self.assertEqual(index, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
self.assertIsNone(numa_cfg_cell.memAccess)
allnodes = set([cell.id for cell in instance_topology.cells])
self.assertEqual(allnodes, set(cfg.numatune.memory.nodeset))
self.assertEqual("strict", cfg.numatune.memory.mode)
for index, (instance_cell, memnode) in enumerate(zip(
instance_topology.cells,
cfg.numatune.memnodes)):
self.assertEqual(index, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
def test_get_guest_config_numa_host_instance_topo_cpu_pinning(self):
instance_topology = objects.InstanceNUMATopology(
cells=[objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]), memory=1024,
cpu_pinning={0: 24, 1: 25}),
objects.InstanceNUMACell(
id=0, cpuset=set([2, 3]), memory=1024,
cpu_pinning={2: 0, 3: 1})])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology(
sockets_per_cell=4, cores_per_socket=3, threads_per_core=2)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = conn._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertIsNone(cfg.cpuset)
# Test that the pinning is correct and limited to allowed only
self.assertEqual(0, cfg.cputune.vcpupin[0].id)
self.assertEqual(set([24]), cfg.cputune.vcpupin[0].cpuset)
self.assertEqual(1, cfg.cputune.vcpupin[1].id)
self.assertEqual(set([25]), cfg.cputune.vcpupin[1].cpuset)
self.assertEqual(2, cfg.cputune.vcpupin[2].id)
self.assertEqual(set([0]), cfg.cputune.vcpupin[2].cpuset)
self.assertEqual(3, cfg.cputune.vcpupin[3].id)
self.assertEqual(set([1]), cfg.cputune.vcpupin[3].cpuset)
self.assertIsNotNone(cfg.cpu.numa)
# Emulator must be pinned to union of cfg.cputune.vcpupin[*].cpuset
self.assertIsInstance(cfg.cputune.emulatorpin,
vconfig.LibvirtConfigGuestCPUTuneEmulatorPin)
self.assertEqual(set([0, 1, 24, 25]),
cfg.cputune.emulatorpin.cpuset)
for i, (instance_cell, numa_cfg_cell) in enumerate(zip(
instance_topology.cells, cfg.cpu.numa.cells)):
self.assertEqual(i, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
self.assertIsNone(numa_cfg_cell.memAccess)
allnodes = set([cell.id for cell in instance_topology.cells])
self.assertEqual(allnodes, set(cfg.numatune.memory.nodeset))
self.assertEqual("strict", cfg.numatune.memory.mode)
for i, (instance_cell, memnode) in enumerate(zip(
instance_topology.cells, cfg.numatune.memnodes)):
self.assertEqual(i, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
def test_get_guest_config_numa_host_mempages_shared(self):
instance_topology = objects.InstanceNUMATopology(
cells=[
objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]),
memory=1024, pagesize=2048),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]),
memory=1024, pagesize=2048)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set',
return_value=set([2, 3, 4, 5])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for instance_cell, numa_cfg_cell, index in zip(
instance_topology.cells,
cfg.cpu.numa.cells,
range(len(instance_topology.cells))):
self.assertEqual(index, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
self.assertEqual("shared", numa_cfg_cell.memAccess)
allnodes = [cell.id for cell in instance_topology.cells]
self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
self.assertEqual("strict", cfg.numatune.memory.mode)
for instance_cell, memnode, index in zip(
instance_topology.cells,
cfg.numatune.memnodes,
range(len(instance_topology.cells))):
self.assertEqual(index, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
self.assertEqual(0, len(cfg.cputune.vcpusched))
self.assertEqual(set([2, 3, 4, 5]), cfg.cputune.emulatorpin.cpuset)
def test_get_guest_config_numa_host_instance_cpu_pinning_realtime(self):
instance_topology = objects.InstanceNUMATopology(
cells=[
objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]),
memory=1024, pagesize=2048),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]),
memory=1024, pagesize=2048)])
instance_ref = objects.Instance(**self.test_instance)
instance_ref.numa_topology = instance_topology
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496,
ephemeral_gb=8128, swap=33550336, name='fake',
extra_specs={
"hw:cpu_realtime": "yes",
"hw:cpu_policy": "dedicated",
"hw:cpu_realtime_mask": "^0-1"
})
instance_ref.flavor = flavor
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with test.nested(
mock.patch.object(
objects.InstanceNUMATopology, "get_by_instance_uuid",
return_value=instance_topology),
mock.patch.object(host.Host, 'has_min_version',
return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set',
return_value=set([2, 3, 4, 5])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set(range(8))),
):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for instance_cell, numa_cfg_cell, index in zip(
instance_topology.cells,
cfg.cpu.numa.cells,
range(len(instance_topology.cells))):
self.assertEqual(index, numa_cfg_cell.id)
self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus)
self.assertEqual(instance_cell.memory * units.Ki,
numa_cfg_cell.memory)
self.assertEqual("shared", numa_cfg_cell.memAccess)
allnodes = [cell.id for cell in instance_topology.cells]
self.assertEqual(allnodes, cfg.numatune.memory.nodeset)
self.assertEqual("strict", cfg.numatune.memory.mode)
for instance_cell, memnode, index in zip(
instance_topology.cells,
cfg.numatune.memnodes,
range(len(instance_topology.cells))):
self.assertEqual(index, memnode.cellid)
self.assertEqual([instance_cell.id], memnode.nodeset)
self.assertEqual("strict", memnode.mode)
self.assertEqual(1, len(cfg.cputune.vcpusched))
self.assertEqual("fifo", cfg.cputune.vcpusched[0].scheduler)
self.assertEqual(set([2, 3]), cfg.cputune.vcpusched[0].vcpus)
self.assertEqual(set([0, 1]), cfg.cputune.emulatorpin.cpuset)
def test_get_cpu_numa_config_from_instance(self):
topology = objects.InstanceNUMATopology(cells=[
objects.InstanceNUMACell(id=0, cpuset=set([1, 2]), memory=128),
objects.InstanceNUMACell(id=1, cpuset=set([3, 4]), memory=128),
])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conf = drvr._get_cpu_numa_config_from_instance(topology, True)
self.assertIsInstance(conf, vconfig.LibvirtConfigGuestCPUNUMA)
self.assertEqual(0, conf.cells[0].id)
self.assertEqual(set([1, 2]), conf.cells[0].cpus)
self.assertEqual(131072, conf.cells[0].memory)
self.assertEqual("shared", conf.cells[0].memAccess)
self.assertEqual(1, conf.cells[1].id)
self.assertEqual(set([3, 4]), conf.cells[1].cpus)
self.assertEqual(131072, conf.cells[1].memory)
self.assertEqual("shared", conf.cells[1].memAccess)
def test_get_cpu_numa_config_from_instance_none(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conf = drvr._get_cpu_numa_config_from_instance(None, False)
self.assertIsNone(conf)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
return_value=True)
def test_get_memnode_numa_config_from_instance(self, mock_numa):
instance_topology = objects.InstanceNUMATopology(cells=[
objects.InstanceNUMACell(id=0, cpuset=set([1, 2]), memory=128),
objects.InstanceNUMACell(id=1, cpuset=set([3, 4]), memory=128),
objects.InstanceNUMACell(id=16, cpuset=set([5, 6]), memory=128)
])
host_topology = objects.NUMATopology(
cells=[
objects.NUMACell(
id=0, cpuset=set([1, 2]), memory=1024, mempages=[]),
objects.NUMACell(
id=1, cpuset=set([3, 4]), memory=1024, mempages=[]),
objects.NUMACell(
id=16, cpuset=set([5, 6]), memory=1024, mempages=[])])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
with test.nested(
mock.patch.object(drvr, "_get_host_numa_topology",
return_value=host_topology)):
guest_numa_config = drvr._get_guest_numa_config(instance_topology,
flavor={}, allowed_cpus=[1, 2, 3, 4, 5, 6], image_meta={})
self.assertEqual(2, guest_numa_config.numatune.memnodes[2].cellid)
self.assertEqual([16],
guest_numa_config.numatune.memnodes[2].nodeset)
self.assertEqual(set([5, 6]),
guest_numa_config.numaconfig.cells[2].cpus)
@mock.patch.object(host.Host, 'has_version', return_value=True)
def test_has_cpu_policy_support(self, mock_has_version):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(exception.CPUPinningNotSupported,
drvr._has_cpu_policy_support)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
return_value=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_hugepage_support",
return_value=True)
@mock.patch.object(host.Host, "get_capabilities")
def test_does_not_want_hugepages(self, mock_caps, mock_hp, mock_numa):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_topology = objects.InstanceNUMATopology(
cells=[
objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]),
memory=1024, pagesize=4),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]),
memory=1024, pagesize=4)])
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
mock_caps.return_value = caps
host_topology = drvr._get_host_numa_topology()
self.assertFalse(drvr._wants_hugepages(None, None))
self.assertFalse(drvr._wants_hugepages(host_topology, None))
self.assertFalse(drvr._wants_hugepages(None, instance_topology))
self.assertFalse(drvr._wants_hugepages(host_topology,
instance_topology))
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support",
return_value=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_hugepage_support",
return_value=True)
@mock.patch.object(host.Host, "get_capabilities")
def test_does_want_hugepages(self, mock_caps, mock_hp, mock_numa):
for each_arch in [arch.I686, arch.X86_64, arch.PPC64LE, arch.PPC64]:
self._test_does_want_hugepages(
mock_caps, mock_hp, mock_numa, each_arch)
def _test_does_want_hugepages(self, mock_caps, mock_hp, mock_numa,
architecture):
self.flags(reserved_huge_pages=[
{'node': 0, 'size': 2048, 'count': 128},
{'node': 1, 'size': 2048, 'count': 1},
{'node': 3, 'size': 2048, 'count': 64}])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_topology = objects.InstanceNUMATopology(
cells=[
objects.InstanceNUMACell(
id=1, cpuset=set([0, 1]),
memory=1024, pagesize=2048),
objects.InstanceNUMACell(
id=2, cpuset=set([2, 3]),
memory=1024, pagesize=2048)])
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = architecture
caps.host.topology = self._fake_caps_numa_topology()
mock_caps.return_value = caps
host_topology = drvr._get_host_numa_topology()
self.assertEqual(128, host_topology.cells[0].mempages[1].reserved)
self.assertEqual(1, host_topology.cells[1].mempages[1].reserved)
self.assertEqual(0, host_topology.cells[2].mempages[1].reserved)
self.assertEqual(64, host_topology.cells[3].mempages[1].reserved)
self.assertTrue(drvr._wants_hugepages(host_topology,
instance_topology))
def test_get_guest_config_clock(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
hpet_map = {
arch.X86_64: True,
arch.I686: True,
arch.PPC: False,
arch.PPC64: False,
arch.ARMV7: False,
arch.AARCH64: False,
}
for guestarch, expect_hpet in hpet_map.items():
with mock.patch.object(libvirt_driver.libvirt_utils,
'get_arch',
return_value=guestarch):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta,
disk_info)
self.assertIsInstance(cfg.clock,
vconfig.LibvirtConfigGuestClock)
self.assertEqual(cfg.clock.offset, "utc")
self.assertIsInstance(cfg.clock.timers[0],
vconfig.LibvirtConfigGuestTimer)
self.assertIsInstance(cfg.clock.timers[1],
vconfig.LibvirtConfigGuestTimer)
self.assertEqual(cfg.clock.timers[0].name, "pit")
self.assertEqual(cfg.clock.timers[0].tickpolicy,
"delay")
self.assertEqual(cfg.clock.timers[1].name, "rtc")
self.assertEqual(cfg.clock.timers[1].tickpolicy,
"catchup")
if expect_hpet:
self.assertEqual(3, len(cfg.clock.timers))
self.assertIsInstance(cfg.clock.timers[2],
vconfig.LibvirtConfigGuestTimer)
self.assertEqual('hpet', cfg.clock.timers[2].name)
self.assertFalse(cfg.clock.timers[2].present)
else:
self.assertEqual(2, len(cfg.clock.timers))
@mock.patch.object(libvirt_utils, 'get_arch')
@mock.patch.object(host.Host, 'has_min_version')
def test_get_guest_config_windows(self, mock_version, mock_get_arch):
mock_version.return_value = False
mock_get_arch.return_value = arch.I686
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref['os_type'] = 'windows'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(cfg.clock,
vconfig.LibvirtConfigGuestClock)
self.assertEqual(cfg.clock.offset, "localtime")
self.assertEqual(3, len(cfg.clock.timers), cfg.clock.timers)
self.assertEqual("pit", cfg.clock.timers[0].name)
self.assertEqual("rtc", cfg.clock.timers[1].name)
self.assertEqual("hpet", cfg.clock.timers[2].name)
self.assertFalse(cfg.clock.timers[2].present)
@mock.patch.object(libvirt_utils, 'get_arch')
@mock.patch.object(host.Host, 'has_min_version')
def test_get_guest_config_windows_timer(self, mock_version, mock_get_arch):
mock_version.return_value = True
mock_get_arch.return_value = arch.I686
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref['os_type'] = 'windows'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(cfg.clock,
vconfig.LibvirtConfigGuestClock)
self.assertEqual(cfg.clock.offset, "localtime")
self.assertEqual(4, len(cfg.clock.timers), cfg.clock.timers)
self.assertEqual("pit", cfg.clock.timers[0].name)
self.assertEqual("rtc", cfg.clock.timers[1].name)
self.assertEqual("hpet", cfg.clock.timers[2].name)
self.assertFalse(cfg.clock.timers[2].present)
self.assertEqual("hypervclock", cfg.clock.timers[3].name)
self.assertTrue(cfg.clock.timers[3].present)
self.assertEqual(3, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureAPIC)
self.assertIsInstance(cfg.features[2],
vconfig.LibvirtConfigGuestFeatureHyperV)
@mock.patch.object(host.Host, 'has_min_version')
def test_get_guest_config_windows_hyperv_feature2(self, mock_version):
mock_version.return_value = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref['os_type'] = 'windows'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(cfg.clock,
vconfig.LibvirtConfigGuestClock)
self.assertEqual(cfg.clock.offset, "localtime")
self.assertEqual(3, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureAPIC)
self.assertIsInstance(cfg.features[2],
vconfig.LibvirtConfigGuestFeatureHyperV)
self.assertTrue(cfg.features[2].relaxed)
self.assertTrue(cfg.features[2].spinlocks)
self.assertEqual(8191, cfg.features[2].spinlock_retries)
self.assertTrue(cfg.features[2].vapic)
def test_get_guest_config_with_two_nics(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 2),
image_meta, disk_info)
self.assertEqual(2, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureAPIC)
self.assertEqual(cfg.memory, instance_ref.flavor.memory_mb * units.Ki)
self.assertEqual(cfg.vcpus, instance_ref.flavor.vcpus)
self.assertEqual(cfg.os_type, vm_mode.HVM)
self.assertEqual(cfg.os_boot_dev, ["hd"])
self.assertIsNone(cfg.os_root)
self.assertEqual(len(cfg.devices), 10)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
def test_get_guest_config_bug_1118829(self):
self.flags(virt_type='uml', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
disk_info = {'disk_bus': 'virtio',
'cdrom_bus': 'ide',
'mapping': {u'vda': {'bus': 'virtio',
'type': 'disk',
'dev': u'vda'},
'root': {'bus': 'virtio',
'type': 'disk',
'dev': 'vda'}}}
# NOTE(jdg): For this specific test leave this blank
# This will exercise the failed code path still,
# and won't require fakes and stubs of the iscsi discovery
block_device_info = {}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
drvr._get_guest_config(instance_ref, [], image_meta, disk_info,
None, block_device_info)
self.assertEqual(instance_ref['root_device_name'], '/dev/vda')
def test_get_guest_config_with_root_device_name(self):
self.flags(virt_type='uml', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
block_device_info = {'root_device_name': '/dev/vdb'}
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
block_device_info)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info,
None, block_device_info)
self.assertEqual(0, len(cfg.features))
self.assertEqual(cfg.memory, instance_ref.flavor.memory_mb * units.Ki)
self.assertEqual(cfg.vcpus, instance_ref.flavor.vcpus)
self.assertEqual(cfg.os_type, "uml")
self.assertEqual(cfg.os_boot_dev, [])
self.assertEqual(cfg.os_root, '/dev/vdb')
self.assertEqual(len(cfg.devices), 3)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestConsole)
def test_has_uefi_support_with_invalid_version(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
with mock.patch.object(drvr._host,
'has_min_version', return_value=False):
self.assertFalse(drvr._has_uefi_support())
def test_has_uefi_support_not_supported_arch(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "alpha"
self.assertFalse(drvr._has_uefi_support())
@mock.patch('os.path.exists', return_value=False)
def test_has_uefi_support_with_no_loader_existed(self, mock_exist):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertFalse(drvr._has_uefi_support())
@mock.patch('os.path.exists', return_value=True)
def test_has_uefi_support(self, mock_has_version):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
with mock.patch.object(drvr._host,
'has_min_version', return_value=True):
self.assertTrue(drvr._has_uefi_support())
def test_get_guest_config_with_uefi(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_firmware_type": "uefi"}})
instance_ref = objects.Instance(**self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with mock.patch.object(drvr, "_has_uefi_support",
return_value=True) as mock_support:
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
mock_support.assert_called_once_with()
self.assertEqual(cfg.os_loader_type, "pflash")
def test_get_guest_config_with_block_device(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
conn_info = {'driver_volume_type': 'fake'}
bdms = block_device_obj.block_device_make_list_from_dicts(
self.context, [
fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vdc'}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/vdd'}),
]
)
info = {'block_device_mapping': driver_block_device.convert_volumes(
bdms
)}
info['block_device_mapping'][0]['connection_info'] = conn_info
info['block_device_mapping'][1]['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
info)
with mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'
) as mock_save:
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info,
None, info)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[2].target_dev, 'vdc')
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[3].target_dev, 'vdd')
mock_save.assert_called_with()
def test_get_guest_config_lxc_with_attached_volume(self):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
conn_info = {'driver_volume_type': 'fake'}
bdms = block_device_obj.block_device_make_list_from_dicts(
self.context, [
fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'source_type': 'volume', 'destination_type': 'volume',
'boot_index': 0}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'source_type': 'volume', 'destination_type': 'volume',
}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 3,
'source_type': 'volume', 'destination_type': 'volume',
}),
]
)
info = {'block_device_mapping': driver_block_device.convert_volumes(
bdms
)}
info['block_device_mapping'][0]['connection_info'] = conn_info
info['block_device_mapping'][1]['connection_info'] = conn_info
info['block_device_mapping'][2]['connection_info'] = conn_info
info['block_device_mapping'][0]['mount_device'] = '/dev/vda'
info['block_device_mapping'][1]['mount_device'] = '/dev/vdc'
info['block_device_mapping'][2]['mount_device'] = '/dev/vdd'
with mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'
) as mock_save:
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
info)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info,
None, info)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[1].target_dev, 'vdc')
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[2].target_dev, 'vdd')
mock_save.assert_called_with()
def test_get_guest_config_with_configdrive(self):
# It's necessary to check if the architecture is power, because
# power doesn't have support to ide, and so libvirt translate
# all ide calls to scsi
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
# make configdrive.required_by() return True
instance_ref['config_drive'] = True
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
# The last device is selected for this. on x86 is the last ide
# device (hdd). Since power only support scsi, the last device
# is sdz
expect = {"ppc": "sdz", "ppc64": "sdz",
"ppc64le": "sdz", "aarch64": "sdz"}
disk = expect.get(blockinfo.libvirt_utils.get_arch({}), "hdd")
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[2].target_dev, disk)
def test_get_guest_config_with_virtio_scsi_bus(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_scsi_model": "virtio-scsi"}})
instance_ref = objects.Instance(**self.test_instance)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
[])
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestController)
self.assertEqual(cfg.devices[2].model, 'virtio-scsi')
def test_get_guest_config_with_virtio_scsi_bus_bdm(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_scsi_model": "virtio-scsi"}})
instance_ref = objects.Instance(**self.test_instance)
conn_info = {'driver_volume_type': 'fake'}
bdms = block_device_obj.block_device_make_list_from_dicts(
self.context, [
fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sdc', 'disk_bus': 'scsi'}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sdd', 'disk_bus': 'scsi'}),
]
)
bd_info = {
'block_device_mapping': driver_block_device.convert_volumes(bdms)}
bd_info['block_device_mapping'][0]['connection_info'] = conn_info
bd_info['block_device_mapping'][1]['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
bd_info)
with mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'
) as mock_save:
cfg = drvr._get_guest_config(instance_ref, [], image_meta,
disk_info, [], bd_info)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[2].target_dev, 'sdc')
self.assertEqual(cfg.devices[2].target_bus, 'scsi')
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[3].target_dev, 'sdd')
self.assertEqual(cfg.devices[3].target_bus, 'scsi')
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestController)
self.assertEqual(cfg.devices[4].model, 'virtio-scsi')
mock_save.assert_called_with()
def test_get_guest_config_with_vnc(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='kvm', group='libvirt')
self.flags(pointer_model='ps2mouse')
self.flags(enabled=False, group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 7)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "vnc")
def test_get_guest_config_with_vnc_and_tablet(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=True,
group='libvirt')
self.flags(enabled=False, group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].type, "vnc")
def test_get_guest_config_with_spice_and_tablet(self):
self.flags(enabled=False, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=True,
group='libvirt')
self.flags(enabled=True,
agent_enabled=False,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].type, "spice")
def test_get_guest_config_with_spice_and_agent(self):
self.flags(enabled=False, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=True,
group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestChannel)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].target_name, "com.redhat.spice.0")
self.assertEqual(cfg.devices[5].type, "spice")
self.assertEqual(cfg.devices[6].type, "qxl")
@mock.patch('nova.console.serial.acquire_port')
@mock.patch('nova.virt.hardware.get_number_of_serial_ports',
return_value=1)
@mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',)
def test_create_serial_console_devices_based_on_arch(self, mock_get_arch,
mock_get_port_number,
mock_acquire_port):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
expected = {arch.X86_64: vconfig.LibvirtConfigGuestSerial,
arch.S390: vconfig.LibvirtConfigGuestConsole,
arch.S390X: vconfig.LibvirtConfigGuestConsole}
for guest_arch, device_type in expected.items():
mock_get_arch.return_value = guest_arch
guest = vconfig.LibvirtConfigGuest()
drvr._create_serial_console_devices(guest, instance=None,
flavor={}, image_meta={})
self.assertEqual(1, len(guest.devices))
console_device = guest.devices[0]
self.assertIsInstance(console_device, device_type)
self.assertEqual("tcp", console_device.type)
@mock.patch('nova.virt.hardware.get_number_of_serial_ports',
return_value=4)
@mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',
side_effect=[arch.X86_64, arch.S390, arch.S390X])
def test_create_serial_console_devices_with_limit_exceeded_based_on_arch(
self, mock_get_arch, mock_get_port_number):
self.flags(enabled=True, group='serial_console')
self.flags(virt_type="qemu", group='libvirt')
flavor = 'fake_flavor'
image_meta = objects.ImageMeta()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
guest = vconfig.LibvirtConfigGuest()
self.assertRaises(exception.SerialPortNumberLimitExceeded,
drvr._create_serial_console_devices,
guest, None, flavor, image_meta)
mock_get_arch.assert_called_with(image_meta)
mock_get_port_number.assert_called_with(flavor,
image_meta)
drvr._create_serial_console_devices(guest, None, flavor, image_meta)
mock_get_arch.assert_called_with(image_meta)
mock_get_port_number.assert_called_with(flavor,
image_meta)
drvr._create_serial_console_devices(guest, None, flavor, image_meta)
mock_get_arch.assert_called_with(image_meta)
mock_get_port_number.assert_called_with(flavor,
image_meta)
@mock.patch('nova.console.serial.acquire_port')
def test_get_guest_config_serial_console(self, acquire_port):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
acquire_port.return_value = 11111
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(8, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("tcp", cfg.devices[2].type)
self.assertEqual(11111, cfg.devices[2].listen_port)
def test_get_guest_config_serial_console_through_flavor(self):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw:serial_port_count': 3}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(10, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("tcp", cfg.devices[2].type)
self.assertEqual("tcp", cfg.devices[3].type)
self.assertEqual("tcp", cfg.devices[4].type)
def test_get_guest_config_serial_console_invalid_flavor(self):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw:serial_port_count': "a"}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.assertRaises(
exception.ImageSerialPortNumberInvalid,
drvr._get_guest_config, instance_ref, [],
image_meta, disk_info)
def test_get_guest_config_serial_console_image_and_flavor(self):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_serial_port_count": "3"}})
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw:serial_port_count': 4}
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta,
disk_info)
self.assertEqual(10, len(cfg.devices), cfg.devices)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("tcp", cfg.devices[2].type)
self.assertEqual("tcp", cfg.devices[3].type)
self.assertEqual("tcp", cfg.devices[4].type)
@mock.patch('nova.console.serial.acquire_port')
def test_get_guest_config_serial_console_through_port_rng_exhausted(
self, acquire_port):
self.flags(enabled=True, group='serial_console')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
acquire_port.side_effect = exception.SocketPortRangeExhaustedException(
'127.0.0.1')
self.assertRaises(
exception.SocketPortRangeExhaustedException,
drvr._get_guest_config, instance_ref, [],
image_meta, disk_info)
@mock.patch('nova.console.serial.release_port')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info')
@mock.patch.object(host.Host, 'get_guest')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_get_serial_ports_from_guest')
def test_serial_console_release_port(
self, mock_get_serial_ports_from_guest, mock_get_guest,
mock_get_info, mock_release_port):
self.flags(enabled="True", group='serial_console')
guest = libvirt_guest.Guest(FakeVirtDomain())
guest.power_off = mock.Mock()
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.SHUTDOWN)
mock_get_guest.return_value = guest
mock_get_serial_ports_from_guest.return_value = iter([
('127.0.0.1', 10000), ('127.0.0.1', 10001)])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._destroy(objects.Instance(**self.test_instance))
mock_release_port.assert_has_calls(
[mock.call(host='127.0.0.1', port=10000),
mock.call(host='127.0.0.1', port=10001)])
@mock.patch('os.path.getsize', return_value=0) # size doesn't matter
@mock.patch('nova.virt.libvirt.storage.lvm.get_volume_size',
return_value='fake-size')
def test_detach_encrypted_volumes(self, mock_getsize,
mock_get_volume_size):
"""Test that unencrypted volumes are not disconnected with dmcrypt."""
instance = objects.Instance(**self.test_instance)
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<driver name='fake-driver' type='fake-type' />
<source file='filename'/>
<target dev='vdc' bus='virtio'/>
</disk>
<disk type='block' device='disk'>
<driver name='fake-driver' type='fake-type' />
<source dev='/dev/mapper/disk'/>
<target dev='vda'/>
</disk>
<disk type='block' device='disk'>
<driver name='fake-driver' type='fake-type' />
<source dev='/dev/mapper/swap'/>
<target dev='vdb'/>
</disk>
</devices>
</domain>
"""
dom = FakeVirtDomain(fake_xml=xml)
instance.ephemeral_key_uuid = uuids.ephemeral_key_uuid # encrypted
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
@mock.patch.object(dmcrypt, 'delete_volume')
@mock.patch.object(conn._host, 'get_domain', return_value=dom)
def detach_encrypted_volumes(block_device_info, mock_get_domain,
mock_delete_volume):
conn._detach_encrypted_volumes(instance, block_device_info)
mock_get_domain.assert_called_once_with(instance)
self.assertFalse(mock_delete_volume.called)
block_device_info = {'root_device_name': '/dev/vda',
'ephemerals': [],
'block_device_mapping': []}
detach_encrypted_volumes(block_device_info)
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_serial_ports_from_guest(self, mock_get_xml_desc):
i = self._test_get_serial_ports_from_guest(None,
mock_get_xml_desc)
self.assertEqual([
('127.0.0.1', 100),
('127.0.0.1', 101),
('127.0.0.2', 100),
('127.0.0.2', 101)], list(i))
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_serial_ports_from_guest_bind_only(self, mock_get_xml_desc):
i = self._test_get_serial_ports_from_guest('bind',
mock_get_xml_desc)
self.assertEqual([
('127.0.0.1', 101),
('127.0.0.2', 100)], list(i))
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_serial_ports_from_guest_connect_only(self,
mock_get_xml_desc):
i = self._test_get_serial_ports_from_guest('connect',
mock_get_xml_desc)
self.assertEqual([
('127.0.0.1', 100),
('127.0.0.2', 101)], list(i))
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_serial_ports_from_guest_on_s390(self, mock_get_xml_desc):
i = self._test_get_serial_ports_from_guest(None,
mock_get_xml_desc,
'console')
self.assertEqual([
('127.0.0.1', 100),
('127.0.0.1', 101),
('127.0.0.2', 100),
('127.0.0.2', 101)], list(i))
def _test_get_serial_ports_from_guest(self, mode, mock_get_xml_desc,
dev_name='serial'):
xml = """
<domain type='kvm'>
<devices>
<%(dev_name)s type="tcp">
<source host="127.0.0.1" service="100" mode="connect"/>
</%(dev_name)s>
<%(dev_name)s type="tcp">
<source host="127.0.0.1" service="101" mode="bind"/>
</%(dev_name)s>
<%(dev_name)s type="tcp">
<source host="127.0.0.2" service="100" mode="bind"/>
</%(dev_name)s>
<%(dev_name)s type="tcp">
<source host="127.0.0.2" service="101" mode="connect"/>
</%(dev_name)s>
</devices>
</domain>""" % {'dev_name': dev_name}
mock_get_xml_desc.return_value = xml
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
guest = libvirt_guest.Guest(FakeVirtDomain())
return drvr._get_serial_ports_from_guest(guest, mode=mode)
def test_get_guest_config_with_type_xen(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='xen',
use_usb_tablet=False,
group='libvirt')
self.flags(enabled=False,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 6)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestConsole)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[3].type, "vnc")
self.assertEqual(cfg.devices[4].type, "xen")
@mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',
return_value=arch.S390X)
def test_get_guest_config_with_type_kvm_on_s390(self, mock_get_arch):
self.flags(enabled=False, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=False,
group='libvirt')
self._stub_host_capabilities_cpu_arch(arch.S390X)
instance_ref = objects.Instance(**self.test_instance)
cfg = self._get_guest_config_via_fake_api(instance_ref)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
log_file_device = cfg.devices[2]
self.assertIsInstance(log_file_device,
vconfig.LibvirtConfigGuestConsole)
self.assertEqual("sclplm", log_file_device.target_type)
self.assertEqual("file", log_file_device.type)
terminal_device = cfg.devices[3]
self.assertIsInstance(terminal_device,
vconfig.LibvirtConfigGuestConsole)
self.assertEqual("sclp", terminal_device.target_type)
self.assertEqual("pty", terminal_device.type)
self.assertEqual("s390-ccw-virtio", cfg.os_mach_type)
def _stub_host_capabilities_cpu_arch(self, cpu_arch):
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.arch = cpu_arch
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
return caps
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
def _get_guest_config_via_fake_api(self, instance):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
return drvr._get_guest_config(instance, [],
image_meta, disk_info)
def test_get_guest_config_with_type_xen_pae_hvm(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='xen',
use_usb_tablet=False,
group='libvirt')
self.flags(enabled=False,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref['vm_mode'] = vm_mode.HVM
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(cfg.os_type, vm_mode.HVM)
self.assertEqual(cfg.os_loader, CONF.libvirt.xen_hvmloader_path)
self.assertEqual(3, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeaturePAE)
self.assertIsInstance(cfg.features[1],
vconfig.LibvirtConfigGuestFeatureACPI)
self.assertIsInstance(cfg.features[2],
vconfig.LibvirtConfigGuestFeatureAPIC)
def test_get_guest_config_with_type_xen_pae_pvm(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='xen',
use_usb_tablet=False,
group='libvirt')
self.flags(enabled=False,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(cfg.os_type, vm_mode.XEN)
self.assertEqual(1, len(cfg.features))
self.assertIsInstance(cfg.features[0],
vconfig.LibvirtConfigGuestFeaturePAE)
def test_get_guest_config_with_vnc_and_spice(self):
self.flags(enabled=True, group='vnc')
self.flags(virt_type='kvm',
use_usb_tablet=True,
group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 10)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestChannel)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[9],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].target_name, "com.redhat.spice.0")
self.assertEqual(cfg.devices[6].type, "vnc")
self.assertEqual(cfg.devices[7].type, "spice")
def test_get_guest_config_with_watchdog_action_image_meta(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_watchdog_action": "none"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertEqual(len(cfg.devices), 9)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestWatchdog)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("none", cfg.devices[7].action)
def _test_get_guest_usb_tablet(self, vnc_enabled, spice_enabled, os_type,
agent_enabled=False, image_meta=None):
self.flags(enabled=vnc_enabled, group='vnc')
self.flags(enabled=spice_enabled,
agent_enabled=agent_enabled, group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict(image_meta)
return drvr._get_guest_pointer_model(os_type, image_meta)
def test_use_ps2_mouse(self):
self.flags(pointer_model='ps2mouse')
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNone(tablet)
def test_get_guest_usb_tablet_wipe(self):
self.flags(use_usb_tablet=True, group='libvirt')
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(True, False, vm_mode.HVM)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(False, True, vm_mode.HVM)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(False, False, vm_mode.HVM)
self.assertIsNone(tablet)
tablet = self._test_get_guest_usb_tablet(True, True, "foo")
self.assertIsNone(tablet)
tablet = self._test_get_guest_usb_tablet(
False, True, vm_mode.HVM, True)
self.assertIsNone(tablet)
def test_get_guest_usb_tablet_image_meta(self):
self.flags(use_usb_tablet=True, group='libvirt')
image_meta = {"properties": {"hw_pointer_model": "usbtablet"}}
tablet = self._test_get_guest_usb_tablet(
True, True, vm_mode.HVM, image_meta=image_meta)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(
True, False, vm_mode.HVM, image_meta=image_meta)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(
False, True, vm_mode.HVM, image_meta=image_meta)
self.assertIsNotNone(tablet)
tablet = self._test_get_guest_usb_tablet(
False, False, vm_mode.HVM, image_meta=image_meta)
self.assertIsNone(tablet)
tablet = self._test_get_guest_usb_tablet(
True, True, "foo", image_meta=image_meta)
self.assertIsNone(tablet)
tablet = self._test_get_guest_usb_tablet(
False, True, vm_mode.HVM, True, image_meta=image_meta)
self.assertIsNone(tablet)
def test_get_guest_usb_tablet_image_meta_no_vnc(self):
self.flags(use_usb_tablet=False, group='libvirt')
self.flags(pointer_model=None)
image_meta = {"properties": {"hw_pointer_model": "usbtablet"}}
self.assertRaises(
exception.UnsupportedPointerModelRequested,
self._test_get_guest_usb_tablet,
False, False, vm_mode.HVM, True, image_meta=image_meta)
def test_get_guest_no_pointer_model_usb_tablet_set(self):
self.flags(use_usb_tablet=True, group='libvirt')
self.flags(pointer_model=None)
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNotNone(tablet)
def test_get_guest_no_pointer_model_usb_tablet_not_set(self):
self.flags(use_usb_tablet=False, group='libvirt')
self.flags(pointer_model=None)
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNone(tablet)
def test_get_guest_pointer_model_usb_tablet(self):
self.flags(use_usb_tablet=False, group='libvirt')
self.flags(pointer_model='usbtablet')
tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM)
self.assertIsNotNone(tablet)
def test_get_guest_pointer_model_usb_tablet_image(self):
image_meta = {"properties": {"hw_pointer_model": "usbtablet"}}
tablet = self._test_get_guest_usb_tablet(
True, True, vm_mode.HVM, image_meta=image_meta)
self.assertIsNotNone(tablet)
def test_get_guest_pointer_model_usb_tablet_image_no_HVM(self):
self.flags(pointer_model=None)
self.flags(use_usb_tablet=False, group='libvirt')
image_meta = {"properties": {"hw_pointer_model": "usbtablet"}}
self.assertRaises(
exception.UnsupportedPointerModelRequested,
self._test_get_guest_usb_tablet,
True, True, vm_mode.XEN, image_meta=image_meta)
def _test_get_guest_config_with_watchdog_action_flavor(self,
hw_watchdog_action="hw:watchdog_action"):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {hw_watchdog_action: 'none'}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(9, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestWatchdog)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("none", cfg.devices[7].action)
def test_get_guest_config_with_watchdog_action_through_flavor(self):
self._test_get_guest_config_with_watchdog_action_flavor()
# TODO(pkholkin): the test accepting old property name 'hw_watchdog_action'
# should be removed in the next release
def test_get_guest_config_with_watchdog_action_through_flavor_no_scope(
self):
self._test_get_guest_config_with_watchdog_action_flavor(
hw_watchdog_action="hw_watchdog_action")
def test_get_guest_config_with_watchdog_overrides_flavor(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_watchdog_action': 'none'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_watchdog_action": "pause"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(9, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestWatchdog)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual("pause", cfg.devices[7].action)
def test_get_guest_config_with_video_driver_image_meta(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_video_model": "vmvga"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[5].type, "vnc")
self.assertEqual(cfg.devices[6].type, "vmvga")
def test_get_guest_config_with_qga_through_image_meta(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_qemu_guest_agent": "yes"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertEqual(len(cfg.devices), 9)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigGuestChannel)
self.assertIsInstance(cfg.devices[8],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].type, "vnc")
self.assertEqual(cfg.devices[7].type, "unix")
self.assertEqual(cfg.devices[7].target_name, "org.qemu.guest_agent.0")
def test_get_guest_config_with_video_driver_vram(self):
self.flags(enabled=False, group='vnc')
self.flags(virt_type='kvm', group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_video:ram_max_mb': "100"}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_video_model": "qxl",
"hw_video_ram": "64"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestChannel)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[5].type, "spice")
self.assertEqual(cfg.devices[6].type, "qxl")
self.assertEqual(cfg.devices[6].vram, 64 * units.Mi / units.Ki)
@mock.patch('nova.virt.disk.api.teardown_container')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info')
@mock.patch('nova.virt.disk.api.setup_container')
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch.object(fake_libvirt_utils, 'get_instance_path')
def test_unmount_fs_if_error_during_lxc_create_domain(self,
mock_get_inst_path, mock_ensure_tree, mock_setup_container,
mock_get_info, mock_teardown):
"""If we hit an error during a `_create_domain` call to `libvirt+lxc`
we need to ensure the guest FS is unmounted from the host so that any
future `lvremove` calls will work.
"""
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_instance = mock.MagicMock()
mock_get_inst_path.return_value = '/tmp/'
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_image = mock.MagicMock()
mock_image.path = '/tmp/test.img'
drvr.image_backend.image.return_value = mock_image
mock_setup_container.return_value = '/dev/nbd0'
mock_get_info.side_effect = exception.InstanceNotFound(
instance_id='foo')
drvr._conn.defineXML = mock.Mock()
drvr._conn.defineXML.side_effect = ValueError('somethingbad')
with test.nested(
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr, 'firewall_driver'),
mock.patch.object(drvr, 'cleanup')):
self.assertRaises(ValueError,
drvr._create_domain_and_network,
self.context,
'xml',
mock_instance, None, None)
mock_teardown.assert_called_with(container_dir='/tmp/rootfs')
def test_video_driver_flavor_limit_not_set(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_video_model": "qxl",
"hw_video_ram": "64"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with mock.patch.object(objects.Instance, 'save'):
self.assertRaises(exception.RequestedVRamTooHigh,
drvr._get_guest_config,
instance_ref,
[],
image_meta,
disk_info)
def test_video_driver_ram_above_flavor_limit(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(enabled=True,
agent_enabled=True,
group='spice')
instance_ref = objects.Instance(**self.test_instance)
instance_type = instance_ref.get_flavor()
instance_type.extra_specs = {'hw_video:ram_max_mb': "50"}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_video_model": "qxl",
"hw_video_ram": "64"}})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
with mock.patch.object(objects.Instance, 'save'):
self.assertRaises(exception.RequestedVRamTooHigh,
drvr._get_guest_config,
instance_ref,
[],
image_meta,
disk_info)
def test_get_guest_config_without_qga_through_image_meta(self):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_qemu_guest_agent": "no"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[4].type, "tablet")
self.assertEqual(cfg.devices[5].type, "vnc")
def test_get_guest_config_with_rng_device(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(pointer_model='ps2mouse')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestRng)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[6].model, 'random')
self.assertIsNone(cfg.devices[6].backend)
self.assertIsNone(cfg.devices[6].rate_bytes)
self.assertIsNone(cfg.devices[6].rate_period)
def test_get_guest_config_with_rng_not_allowed(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(pointer_model='ps2mouse')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 7)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigMemoryBalloon)
def test_get_guest_config_with_rng_limits(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(pointer_model='ps2mouse')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True',
'hw_rng:rate_bytes': '1024',
'hw_rng:rate_period': '2'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestRng)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[6].model, 'random')
self.assertIsNone(cfg.devices[6].backend)
self.assertEqual(cfg.devices[6].rate_bytes, 1024)
self.assertEqual(cfg.devices[6].rate_period, 2)
@mock.patch('nova.virt.libvirt.driver.os.path.exists')
def test_get_guest_config_with_rng_backend(self, mock_path):
self.flags(virt_type='kvm',
rng_dev_path='/dev/hw_rng',
group='libvirt')
self.flags(pointer_model='ps2mouse')
mock_path.return_value = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(len(cfg.devices), 8)
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestSerial)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
self.assertIsInstance(cfg.devices[6],
vconfig.LibvirtConfigGuestRng)
self.assertIsInstance(cfg.devices[7],
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual(cfg.devices[6].model, 'random')
self.assertEqual(cfg.devices[6].backend, '/dev/hw_rng')
self.assertIsNone(cfg.devices[6].rate_bytes)
self.assertIsNone(cfg.devices[6].rate_period)
@mock.patch('nova.virt.libvirt.driver.os.path.exists')
def test_get_guest_config_with_rng_dev_not_present(self, mock_path):
self.flags(virt_type='kvm',
use_usb_tablet=False,
rng_dev_path='/dev/hw_rng',
group='libvirt')
mock_path.return_value = False
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'}
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_rng_model": "virtio"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.assertRaises(exception.RngDeviceNotExist,
drvr._get_guest_config,
instance_ref,
[],
image_meta, disk_info)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_guest_cpu_shares_with_multi_vcpu(self, is_able):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.vcpus = 4
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(4096, cfg.cputune.shares)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_with_cpu_quota(self, is_able):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'quota:cpu_shares': '10000',
'quota:cpu_period': '20000'}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(10000, cfg.cputune.shares)
self.assertEqual(20000, cfg.cputune.period)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=True)
def test_get_guest_config_with_bogus_cpu_quota(self, is_able):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'quota:cpu_shares': 'fishfood',
'quota:cpu_period': '20000'}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.assertRaises(ValueError,
drvr._get_guest_config,
instance_ref, [], image_meta, disk_info)
@mock.patch.object(
host.Host, "is_cpu_control_policy_capable", return_value=False)
def test_get_update_guest_cputune(self, is_able):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = {'quota:cpu_shares': '10000',
'quota:cpu_period': '20000'}
self.assertRaises(
exception.UnsupportedHostCPUControlPolicy,
drvr._update_guest_cputune, {}, instance_ref.flavor, "kvm")
def _test_get_guest_config_sysinfo_serial(self, expected_serial):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
cfg = drvr._get_guest_config_sysinfo(instance_ref)
self.assertIsInstance(cfg, vconfig.LibvirtConfigGuestSysinfo)
self.assertEqual(version.vendor_string(),
cfg.system_manufacturer)
self.assertEqual(version.product_string(),
cfg.system_product)
self.assertEqual(version.version_string_with_package(),
cfg.system_version)
self.assertEqual(expected_serial,
cfg.system_serial)
self.assertEqual(instance_ref['uuid'],
cfg.system_uuid)
self.assertEqual("Virtual Machine",
cfg.system_family)
def test_get_guest_config_sysinfo_serial_none(self):
self.flags(sysinfo_serial="none", group="libvirt")
self._test_get_guest_config_sysinfo_serial(None)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_host_sysinfo_serial_hardware")
def test_get_guest_config_sysinfo_serial_hardware(self, mock_uuid):
self.flags(sysinfo_serial="hardware", group="libvirt")
theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc"
mock_uuid.return_value = theuuid
self._test_get_guest_config_sysinfo_serial(theuuid)
@contextlib.contextmanager
def patch_exists(self, result):
real_exists = os.path.exists
def fake_exists(filename):
if filename == "/etc/machine-id":
return result
return real_exists(filename)
with mock.patch.object(os.path, "exists") as mock_exists:
mock_exists.side_effect = fake_exists
yield mock_exists
def test_get_guest_config_sysinfo_serial_os(self):
self.flags(sysinfo_serial="os", group="libvirt")
theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc"
with test.nested(
mock.patch.object(six.moves.builtins, "open",
mock.mock_open(read_data=theuuid)),
self.patch_exists(True)):
self._test_get_guest_config_sysinfo_serial(theuuid)
def test_get_guest_config_sysinfo_serial_os_empty_machine_id(self):
self.flags(sysinfo_serial="os", group="libvirt")
with test.nested(
mock.patch.object(six.moves.builtins, "open",
mock.mock_open(read_data="")),
self.patch_exists(True)):
self.assertRaises(exception.NovaException,
self._test_get_guest_config_sysinfo_serial,
None)
def test_get_guest_config_sysinfo_serial_os_no_machine_id_file(self):
self.flags(sysinfo_serial="os", group="libvirt")
with self.patch_exists(False):
self.assertRaises(exception.NovaException,
self._test_get_guest_config_sysinfo_serial,
None)
def test_get_guest_config_sysinfo_serial_auto_hardware(self):
self.flags(sysinfo_serial="auto", group="libvirt")
real_exists = os.path.exists
with test.nested(
mock.patch.object(os.path, "exists"),
mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_host_sysinfo_serial_hardware")
) as (mock_exists, mock_uuid):
def fake_exists(filename):
if filename == "/etc/machine-id":
return False
return real_exists(filename)
mock_exists.side_effect = fake_exists
theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc"
mock_uuid.return_value = theuuid
self._test_get_guest_config_sysinfo_serial(theuuid)
def test_get_guest_config_sysinfo_serial_auto_os(self):
self.flags(sysinfo_serial="auto", group="libvirt")
real_exists = os.path.exists
real_open = builtins.open
with test.nested(
mock.patch.object(os.path, "exists"),
mock.patch.object(builtins, "open"),
) as (mock_exists, mock_open):
def fake_exists(filename):
if filename == "/etc/machine-id":
return True
return real_exists(filename)
mock_exists.side_effect = fake_exists
theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc"
def fake_open(filename, *args, **kwargs):
if filename == "/etc/machine-id":
h = mock.MagicMock()
h.read.return_value = theuuid
h.__enter__.return_value = h
return h
return real_open(filename, *args, **kwargs)
mock_open.side_effect = fake_open
self._test_get_guest_config_sysinfo_serial(theuuid)
def _create_fake_service_compute(self):
service_info = {
'id': 1729,
'host': 'fake',
'report_count': 0
}
service_ref = objects.Service(**service_info)
compute_info = {
'id': 1729,
'vcpus': 2,
'memory_mb': 1024,
'local_gb': 2048,
'vcpus_used': 0,
'memory_mb_used': 0,
'local_gb_used': 0,
'free_ram_mb': 1024,
'free_disk_gb': 2048,
'hypervisor_type': 'xen',
'hypervisor_version': 1,
'running_vms': 0,
'cpu_info': '',
'current_workload': 0,
'service_id': service_ref['id'],
'host': service_ref['host']
}
compute_ref = objects.ComputeNode(**compute_info)
return (service_ref, compute_ref)
def test_get_guest_config_with_pci_passthrough_kvm(self):
self.flags(virt_type='kvm', group='libvirt')
service_ref, compute_ref = self._create_fake_service_compute()
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
pci_device_info = dict(test_pci_device.fake_db_dev)
pci_device_info.update(compute_node_id=1,
label='fake',
status=fields.PciDeviceStatus.ALLOCATED,
address='0000:00:00.1',
compute_id=compute_ref.id,
instance_uuid=instance.uuid,
request_id=None,
extra_info={})
pci_device = objects.PciDevice(**pci_device_info)
pci_list = objects.PciDeviceList()
pci_list.objects.append(pci_device)
instance.pci_devices = pci_list
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
cfg = drvr._get_guest_config(instance, [],
image_meta, disk_info)
had_pci = 0
# care only about the PCI devices
for dev in cfg.devices:
if type(dev) == vconfig.LibvirtConfigGuestHostdevPCI:
had_pci += 1
self.assertEqual(dev.type, 'pci')
self.assertEqual(dev.managed, 'yes')
self.assertEqual(dev.mode, 'subsystem')
self.assertEqual(dev.domain, "0000")
self.assertEqual(dev.bus, "00")
self.assertEqual(dev.slot, "00")
self.assertEqual(dev.function, "1")
self.assertEqual(had_pci, 1)
def test_get_guest_config_with_pci_passthrough_xen(self):
self.flags(virt_type='xen', group='libvirt')
service_ref, compute_ref = self._create_fake_service_compute()
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
pci_device_info = dict(test_pci_device.fake_db_dev)
pci_device_info.update(compute_node_id=1,
label='fake',
status=fields.PciDeviceStatus.ALLOCATED,
address='0000:00:00.2',
compute_id=compute_ref.id,
instance_uuid=instance.uuid,
request_id=None,
extra_info={})
pci_device = objects.PciDevice(**pci_device_info)
pci_list = objects.PciDeviceList()
pci_list.objects.append(pci_device)
instance.pci_devices = pci_list
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
cfg = drvr._get_guest_config(instance, [],
image_meta, disk_info)
had_pci = 0
# care only about the PCI devices
for dev in cfg.devices:
if type(dev) == vconfig.LibvirtConfigGuestHostdevPCI:
had_pci += 1
self.assertEqual(dev.type, 'pci')
self.assertEqual(dev.managed, 'no')
self.assertEqual(dev.mode, 'subsystem')
self.assertEqual(dev.domain, "0000")
self.assertEqual(dev.bus, "00")
self.assertEqual(dev.slot, "00")
self.assertEqual(dev.function, "2")
self.assertEqual(had_pci, 1)
def test_get_guest_config_os_command_line_through_image_meta(self):
self.flags(virt_type="kvm",
cpu_mode='none',
group='libvirt')
self.test_instance['kernel_id'] = "fake_kernel_id"
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"os_command_line":
"fake_os_command_line"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_cmdline, "fake_os_command_line")
def test_get_guest_config_os_command_line_without_kernel_id(self):
self.flags(virt_type="kvm",
cpu_mode='none',
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"os_command_line":
"fake_os_command_line"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsNone(cfg.os_cmdline)
def test_get_guest_config_os_command_empty(self):
self.flags(virt_type="kvm",
cpu_mode='none',
group='libvirt')
self.test_instance['kernel_id'] = "fake_kernel_id"
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"os_command_line": ""}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
# the instance has 'root=/dev/vda console=tty0 console=ttyS0' set by
# default, so testing an empty string and None value in the
# os_command_line image property must pass
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertNotEqual(cfg.os_cmdline, "")
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_guest_storage_config")
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support")
def test_get_guest_config_armv7(self, mock_numa, mock_storage):
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.arch = arch.ARMV7
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
return caps
self.flags(virt_type="kvm",
group="libvirt")
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_mach_type, "vexpress-a15")
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_guest_storage_config")
@mock.patch.object(libvirt_driver.LibvirtDriver, "_has_numa_support")
def test_get_guest_config_aarch64(self, mock_numa, mock_storage):
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigGuestCPU()
cpu.arch = arch.AARCH64
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
return caps
self.flags(virt_type="kvm",
group="libvirt")
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_mach_type, "virt")
def test_get_guest_config_machine_type_s390(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigGuestCPU()
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
host_cpu_archs = (arch.S390, arch.S390X)
for host_cpu_arch in host_cpu_archs:
caps.host.cpu.arch = host_cpu_arch
os_mach_type = drvr._get_machine_type(image_meta, caps)
self.assertEqual('s390-ccw-virtio', os_mach_type)
def test_get_guest_config_machine_type_through_image_meta(self):
self.flags(virt_type="kvm",
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict({
"disk_format": "raw",
"properties": {"hw_machine_type":
"fake_machine_type"}})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_mach_type, "fake_machine_type")
def test_get_guest_config_machine_type_from_config(self):
self.flags(virt_type='kvm', group='libvirt')
self.flags(hw_machine_type=['x86_64=fake_machine_type'],
group='libvirt')
def fake_getCapabilities():
return """
<capabilities>
<host>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<cpu>
<arch>x86_64</arch>
<model>Penryn</model>
<vendor>Intel</vendor>
<topology sockets='1' cores='2' threads='1'/>
<feature name='xtpr'/>
</cpu>
</host>
</capabilities>
"""
def fake_baselineCPU(cpu, flag):
return """<cpu mode='custom' match='exact'>
<model fallback='allow'>Penryn</model>
<vendor>Intel</vendor>
<feature policy='require' name='xtpr'/>
</cpu>
"""
# Make sure the host arch is mocked as x86_64
self.create_fake_libvirt_mock(getCapabilities=fake_getCapabilities,
baselineCPU=fake_baselineCPU,
getVersion=lambda: 1005001)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual(cfg.os_mach_type, "fake_machine_type")
def _test_get_guest_config_ppc64(self, device_index):
"""Test for nova.virt.libvirt.driver.LibvirtDriver._get_guest_config.
"""
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
expected = (arch.PPC64, arch.PPC)
for guestarch in expected:
with mock.patch.object(libvirt_driver.libvirt_utils,
'get_arch',
return_value=guestarch):
cfg = drvr._get_guest_config(instance_ref, [],
image_meta,
disk_info)
self.assertIsInstance(cfg.devices[device_index],
vconfig.LibvirtConfigGuestVideo)
self.assertEqual(cfg.devices[device_index].type, 'vga')
def test_get_guest_config_ppc64_through_image_meta_vnc_enabled(self):
self.flags(enabled=True, group='vnc')
self._test_get_guest_config_ppc64(6)
def test_get_guest_config_ppc64_through_image_meta_spice_enabled(self):
self.flags(enabled=True,
agent_enabled=True,
group='spice')
self._test_get_guest_config_ppc64(8)
def _test_get_guest_config_bootmenu(self, image_meta, extra_specs):
self.flags(virt_type='kvm', group='libvirt')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.extra_specs = extra_specs
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref, image_meta)
conf = conn._get_guest_config(instance_ref, [], image_meta, disk_info)
self.assertTrue(conf.os_bootmenu)
def test_get_guest_config_bootmenu_via_image_meta(self):
image_meta = objects.ImageMeta.from_dict(
{"disk_format": "raw",
"properties": {"hw_boot_menu": "True"}})
self._test_get_guest_config_bootmenu(image_meta, {})
def test_get_guest_config_bootmenu_via_extra_specs(self):
image_meta = objects.ImageMeta.from_dict(
self.test_image_meta)
self._test_get_guest_config_bootmenu(image_meta,
{'hw:boot_menu': 'True'})
def test_get_guest_cpu_config_none(self):
self.flags(cpu_mode="none", group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertIsNone(conf.cpu.mode)
self.assertIsNone(conf.cpu.model)
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_config_default_kvm(self):
self.flags(virt_type="kvm",
cpu_mode='none',
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertIsNone(conf.cpu.mode)
self.assertIsNone(conf.cpu.model)
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_config_default_uml(self):
self.flags(virt_type="uml",
cpu_mode='none',
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsNone(conf.cpu)
def test_get_guest_cpu_config_default_lxc(self):
self.flags(virt_type="lxc",
cpu_mode='none',
group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsNone(conf.cpu)
def test_get_guest_cpu_config_host_passthrough(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.flags(cpu_mode="host-passthrough", group='libvirt')
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertEqual(conf.cpu.mode, "host-passthrough")
self.assertIsNone(conf.cpu.model)
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_config_host_model(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.flags(cpu_mode="host-model", group='libvirt')
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertEqual(conf.cpu.mode, "host-model")
self.assertIsNone(conf.cpu.model)
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_config_custom(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.flags(cpu_mode="custom",
cpu_model="Penryn",
group='libvirt')
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertEqual(conf.cpu.mode, "custom")
self.assertEqual(conf.cpu.model, "Penryn")
self.assertEqual(conf.cpu.sockets, instance_ref.flavor.vcpus)
self.assertEqual(conf.cpu.cores, 1)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_cpu_topology(self):
instance_ref = objects.Instance(**self.test_instance)
instance_ref.flavor.vcpus = 8
instance_ref.flavor.extra_specs = {'hw:cpu_max_sockets': '4'}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
conf = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertIsInstance(conf.cpu,
vconfig.LibvirtConfigGuestCPU)
self.assertEqual(conf.cpu.mode, "host-model")
self.assertEqual(conf.cpu.sockets, 4)
self.assertEqual(conf.cpu.cores, 2)
self.assertEqual(conf.cpu.threads, 1)
def test_get_guest_memory_balloon_config_by_default(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for device in cfg.devices:
if device.root_name == 'memballoon':
self.assertIsInstance(device,
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual('virtio', device.model)
self.assertEqual(10, device.period)
def test_get_guest_memory_balloon_config_disable(self):
self.flags(mem_stats_period_seconds=0, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
no_exist = True
for device in cfg.devices:
if device.root_name == 'memballoon':
no_exist = False
break
self.assertTrue(no_exist)
def test_get_guest_memory_balloon_config_period_value(self):
self.flags(mem_stats_period_seconds=21, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for device in cfg.devices:
if device.root_name == 'memballoon':
self.assertIsInstance(device,
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual('virtio', device.model)
self.assertEqual(21, device.period)
def test_get_guest_memory_balloon_config_qemu(self):
self.flags(virt_type='qemu', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for device in cfg.devices:
if device.root_name == 'memballoon':
self.assertIsInstance(device,
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual('virtio', device.model)
self.assertEqual(10, device.period)
def test_get_guest_memory_balloon_config_xen(self):
self.flags(virt_type='xen', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
for device in cfg.devices:
if device.root_name == 'memballoon':
self.assertIsInstance(device,
vconfig.LibvirtConfigMemoryBalloon)
self.assertEqual('xen', device.model)
self.assertEqual(10, device.period)
def test_get_guest_memory_balloon_config_lxc(self):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
no_exist = True
for device in cfg.devices:
if device.root_name == 'memballoon':
no_exist = False
break
self.assertTrue(no_exist)
@mock.patch('nova.virt.libvirt.driver.LOG.warning')
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(host.Host, "get_capabilities")
def test_get_supported_perf_events_foo(self, mock_get_caps,
mock_min_version,
mock_warn):
self.flags(enabled_perf_events=['foo'], group='libvirt')
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
mock_get_caps.return_value = caps
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
events = drvr._get_supported_perf_events()
self.assertTrue(mock_warn.called)
self.assertEqual([], events)
@mock.patch.object(host.Host, "get_capabilities")
def _test_get_guest_with_perf(self, caps, events, mock_get_caps):
mock_get_caps.return_value = caps
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.init_host('test_perf')
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref, [],
image_meta, disk_info)
self.assertEqual(events, cfg.perf_events)
@mock.patch.object(fakelibvirt, 'VIR_PERF_PARAM_CMT', True,
create=True)
@mock.patch.object(fakelibvirt, 'VIR_PERF_PARAM_MBMT', True,
create=True)
@mock.patch.object(fakelibvirt, 'VIR_PERF_PARAM_MBML', True,
create=True)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_get_guest_with_perf_supported(self,
mock_min_version):
self.flags(enabled_perf_events=['cmt', 'mbml', 'mbmt'],
group='libvirt')
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
features = []
for f in ('cmt', 'mbm_local', 'mbm_total'):
feature = vconfig.LibvirtConfigGuestCPUFeature()
feature.name = f
feature.policy = cpumodel.POLICY_REQUIRE
features.append(feature)
caps.host.cpu.features = set(features)
self._test_get_guest_with_perf(caps, ['cmt', 'mbml', 'mbmt'])
@mock.patch.object(host.Host, 'has_min_version')
def test_get_guest_with_perf_libvirt_unsupported(self, mock_min_version):
def fake_has_min_version(lv_ver=None, hv_ver=None, hv_type=None):
if lv_ver == libvirt_driver.MIN_LIBVIRT_PERF_VERSION:
return False
return True
mock_min_version.side_effect = fake_has_min_version
self.flags(enabled_perf_events=['cmt'], group='libvirt')
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
self._test_get_guest_with_perf(caps, [])
@mock.patch.object(fakelibvirt, 'VIR_PERF_PARAM_CMT', True,
create=True)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_get_guest_with_perf_host_unsupported(self,
mock_min_version):
self.flags(enabled_perf_events=['cmt'], group='libvirt')
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = "x86_64"
caps.host.topology = self._fake_caps_numa_topology()
self._test_get_guest_with_perf(caps, [])
def test_xml_and_uri_no_ramdisk_no_kernel(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data,
expect_kernel=False, expect_ramdisk=False)
def test_xml_and_uri_no_ramdisk_no_kernel_xen_hvm(self):
instance_data = dict(self.test_instance)
instance_data.update({'vm_mode': vm_mode.HVM})
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, expect_xen_hvm=True)
def test_xml_and_uri_no_ramdisk_no_kernel_xen_pv(self):
instance_data = dict(self.test_instance)
instance_data.update({'vm_mode': vm_mode.XEN})
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, expect_xen_hvm=False,
xen_only=True)
def test_xml_and_uri_no_ramdisk(self):
instance_data = dict(self.test_instance)
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=True, expect_ramdisk=False)
def test_xml_and_uri_no_kernel(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=False, expect_ramdisk=False)
def test_xml_and_uri(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data,
expect_kernel=True, expect_ramdisk=True)
def test_xml_and_uri_rescue(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'ari-deadbeef'
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=True,
expect_ramdisk=True, rescue=instance_data)
def test_xml_and_uri_rescue_no_kernel_no_ramdisk(self):
instance_data = dict(self.test_instance)
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=False, rescue=instance_data)
def test_xml_and_uri_rescue_no_kernel(self):
instance_data = dict(self.test_instance)
instance_data['ramdisk_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=False,
expect_ramdisk=True, rescue=instance_data)
def test_xml_and_uri_rescue_no_ramdisk(self):
instance_data = dict(self.test_instance)
instance_data['kernel_id'] = 'aki-deadbeef'
self._check_xml_and_uri(instance_data, expect_kernel=True,
expect_ramdisk=False, rescue=instance_data)
def test_xml_uuid(self):
self._check_xml_and_uuid(self.test_image_meta)
def test_lxc_container_and_uri(self):
instance_data = dict(self.test_instance)
self._check_xml_and_container(instance_data)
def test_xml_disk_prefix(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_prefix(instance_data, None)
def test_xml_user_specified_disk_prefix(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_prefix(instance_data, 'sd')
def test_xml_disk_driver(self):
instance_data = dict(self.test_instance)
self._check_xml_and_disk_driver(instance_data)
def test_xml_disk_bus_virtio(self):
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self._check_xml_and_disk_bus(image_meta,
None,
(("disk", "virtio", "vda"),))
def test_xml_disk_bus_ide(self):
# It's necessary to check if the architecture is power, because
# power doesn't have support to ide, and so libvirt translate
# all ide calls to scsi
expected = {arch.PPC: ("cdrom", "scsi", "sda"),
arch.PPC64: ("cdrom", "scsi", "sda"),
arch.PPC64LE: ("cdrom", "scsi", "sda"),
arch.AARCH64: ("cdrom", "scsi", "sda")}
expec_val = expected.get(blockinfo.libvirt_utils.get_arch({}),
("cdrom", "ide", "hda"))
image_meta = objects.ImageMeta.from_dict({
"disk_format": "iso"})
self._check_xml_and_disk_bus(image_meta,
None,
(expec_val,))
def test_xml_disk_bus_ide_and_virtio(self):
# It's necessary to check if the architecture is power, because
# power doesn't have support to ide, and so libvirt translate
# all ide calls to scsi
expected = {arch.PPC: ("cdrom", "scsi", "sda"),
arch.PPC64: ("cdrom", "scsi", "sda"),
arch.PPC64LE: ("cdrom", "scsi", "sda"),
arch.AARCH64: ("cdrom", "scsi", "sda")}
swap = {'device_name': '/dev/vdc',
'swap_size': 1}
ephemerals = [{'device_type': 'disk',
'disk_bus': 'virtio',
'device_name': '/dev/vdb',
'size': 1}]
block_device_info = {
'swap': swap,
'ephemerals': ephemerals}
expec_val = expected.get(blockinfo.libvirt_utils.get_arch({}),
("cdrom", "ide", "hda"))
image_meta = objects.ImageMeta.from_dict({
"disk_format": "iso"})
self._check_xml_and_disk_bus(image_meta,
block_device_info,
(expec_val,
("disk", "virtio", "vdb"),
("disk", "virtio", "vdc")))
@mock.patch.object(host.Host, "list_instance_domains")
def test_list_instances(self, mock_list):
vm1 = FakeVirtDomain(id=3, name="instance00000001")
vm2 = FakeVirtDomain(id=17, name="instance00000002")
vm3 = FakeVirtDomain(name="instance00000003")
vm4 = FakeVirtDomain(name="instance00000004")
mock_list.return_value = [vm1, vm2, vm3, vm4]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
names = drvr.list_instances()
self.assertEqual(names[0], vm1.name())
self.assertEqual(names[1], vm2.name())
self.assertEqual(names[2], vm3.name())
self.assertEqual(names[3], vm4.name())
mock_list.assert_called_with(only_guests=True, only_running=False)
@mock.patch.object(host.Host, "list_instance_domains")
def test_list_instance_uuids(self, mock_list):
vm1 = FakeVirtDomain(id=3, name="instance00000001")
vm2 = FakeVirtDomain(id=17, name="instance00000002")
vm3 = FakeVirtDomain(name="instance00000003")
vm4 = FakeVirtDomain(name="instance00000004")
mock_list.return_value = [vm1, vm2, vm3, vm4]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
uuids = drvr.list_instance_uuids()
self.assertEqual(len(uuids), 4)
self.assertEqual(uuids[0], vm1.UUIDString())
self.assertEqual(uuids[1], vm2.UUIDString())
self.assertEqual(uuids[2], vm3.UUIDString())
self.assertEqual(uuids[3], vm4.UUIDString())
mock_list.assert_called_with(only_guests=True, only_running=False)
@mock.patch('nova.virt.libvirt.host.Host.get_online_cpus')
def test_get_host_vcpus(self, get_online_cpus):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.flags(vcpu_pin_set="4-5")
get_online_cpus.return_value = set([4, 5, 6])
expected_vcpus = 2
vcpus = drvr._get_vcpu_total()
self.assertEqual(expected_vcpus, vcpus)
@mock.patch('nova.virt.libvirt.host.Host.get_online_cpus')
def test_get_host_vcpus_out_of_range(self, get_online_cpus):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.flags(vcpu_pin_set="4-6")
get_online_cpus.return_value = set([4, 5])
self.assertRaises(exception.Invalid, drvr._get_vcpu_total)
@mock.patch('nova.virt.libvirt.host.Host.get_online_cpus')
def test_get_host_vcpus_libvirt_error(self, get_online_cpus):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
not_supported_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'this function is not supported by the connection driver:'
' virNodeNumOfDevices',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
self.flags(vcpu_pin_set="4-6")
get_online_cpus.side_effect = not_supported_exc
self.assertRaises(exception.Invalid, drvr._get_vcpu_total)
@mock.patch('nova.virt.libvirt.host.Host.get_online_cpus')
def test_get_host_vcpus_libvirt_error_success(self, get_online_cpus):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
not_supported_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'this function is not supported by the connection driver:'
' virNodeNumOfDevices',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
self.flags(vcpu_pin_set="1")
get_online_cpus.side_effect = not_supported_exc
expected_vcpus = 1
vcpus = drvr._get_vcpu_total()
self.assertEqual(expected_vcpus, vcpus)
@mock.patch('nova.virt.libvirt.host.Host.get_cpu_count')
def test_get_host_vcpus_after_hotplug(self, get_cpu_count):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
get_cpu_count.return_value = 2
expected_vcpus = 2
vcpus = drvr._get_vcpu_total()
self.assertEqual(expected_vcpus, vcpus)
get_cpu_count.return_value = 3
expected_vcpus = 3
vcpus = drvr._get_vcpu_total()
self.assertEqual(expected_vcpus, vcpus)
@mock.patch.object(host.Host, "has_min_version", return_value=True)
def test_quiesce(self, mock_has_min_version):
self.create_fake_libvirt_mock(lookupByName=self.fake_lookup)
with mock.patch.object(FakeVirtDomain, "fsFreeze") as mock_fsfreeze:
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(
{"properties": {"hw_qemu_guest_agent": "yes"}})
self.assertIsNone(drvr.quiesce(self.context, instance, image_meta))
mock_fsfreeze.assert_called_once_with()
def test_quiesce_not_supported(self):
self.create_fake_libvirt_mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
instance = objects.Instance(**self.test_instance)
self.assertRaises(exception.InstanceQuiesceNotSupported,
drvr.quiesce, self.context, instance, None)
@mock.patch.object(host.Host, "has_min_version", return_value=True)
def test_unquiesce(self, mock_has_min_version):
self.create_fake_libvirt_mock(getLibVersion=lambda: 1002005,
lookupByName=self.fake_lookup)
with mock.patch.object(FakeVirtDomain, "fsThaw") as mock_fsthaw:
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(
{"properties": {"hw_qemu_guest_agent": "yes"}})
self.assertIsNone(drvr.unquiesce(self.context, instance,
image_meta))
mock_fsthaw.assert_called_once_with()
def test_create_snapshot_metadata(self):
base = objects.ImageMeta.from_dict(
{'disk_format': 'raw'})
instance_data = {'kernel_id': 'kernel',
'project_id': 'prj_id',
'ramdisk_id': 'ram_id',
'os_type': None}
instance = objects.Instance(**instance_data)
img_fmt = 'raw'
snp_name = 'snapshot_name'
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = drvr._create_snapshot_metadata(base, instance, img_fmt, snp_name)
expected = {'is_public': False,
'status': 'active',
'name': snp_name,
'properties': {
'kernel_id': instance['kernel_id'],
'image_location': 'snapshot',
'image_state': 'available',
'owner_id': instance['project_id'],
'ramdisk_id': instance['ramdisk_id'],
},
'disk_format': img_fmt,
'container_format': 'bare',
}
self.assertEqual(ret, expected)
# simulate an instance with os_type field defined
# disk format equals to ami
# container format not equals to bare
instance['os_type'] = 'linux'
base = objects.ImageMeta.from_dict(
{'disk_format': 'ami',
'container_format': 'test_container'})
expected['properties']['os_type'] = instance['os_type']
expected['disk_format'] = base.disk_format
expected['container_format'] = base.container_format
ret = drvr._create_snapshot_metadata(base, instance, img_fmt, snp_name)
self.assertEqual(ret, expected)
def test_get_volume_driver(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
connection_info = {'driver_volume_type': 'fake',
'data': {'device_path': '/fake',
'access_mode': 'rw'}}
driver = conn._get_volume_driver(connection_info)
result = isinstance(driver, volume_drivers.LibvirtFakeVolumeDriver)
self.assertTrue(result)
def test_get_volume_driver_unknown(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
connection_info = {'driver_volume_type': 'unknown',
'data': {'device_path': '/fake',
'access_mode': 'rw'}}
self.assertRaises(
exception.VolumeDriverNotFound,
conn._get_volume_driver,
connection_info
)
@mock.patch.object(volume_drivers.LibvirtFakeVolumeDriver,
'connect_volume')
@mock.patch.object(volume_drivers.LibvirtFakeVolumeDriver, 'get_config')
def test_get_volume_config(self, get_config, connect_volume):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
connection_info = {'driver_volume_type': 'fake',
'data': {'device_path': '/fake',
'access_mode': 'rw'}}
bdm = {'device_name': 'vdb',
'disk_bus': 'fake-bus',
'device_type': 'fake-type'}
disk_info = {'bus': bdm['disk_bus'], 'type': bdm['device_type'],
'dev': 'vdb'}
mock_config = mock.MagicMock()
get_config.return_value = mock_config
config = drvr._get_volume_config(connection_info, disk_info)
get_config.assert_called_once_with(connection_info, disk_info)
self.assertEqual(mock_config, config)
def test_attach_invalid_volume_type(self):
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
instance = objects.Instance(**self.test_instance)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.VolumeDriverNotFound,
drvr.attach_volume, None,
{"driver_volume_type": "badtype"},
instance,
"/dev/sda")
def test_attach_blockio_invalid_hypervisor(self):
self.flags(virt_type='lxc', group='libvirt')
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
instance = objects.Instance(**self.test_instance)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.InvalidHypervisorType,
drvr.attach_volume, None,
{"driver_volume_type": "fake",
"data": {"logical_block_size": "4096",
"physical_block_size": "4096"}
},
instance,
"/dev/sda")
def _test_check_discard(self, mock_log, driver_discard=None,
bus=None, should_log=False):
mock_config = mock.Mock()
mock_config.driver_discard = driver_discard
mock_config.target_bus = bus
mock_instance = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._check_discard_for_attach_volume(mock_config, mock_instance)
self.assertEqual(should_log, mock_log.called)
@mock.patch('nova.virt.libvirt.driver.LOG.debug')
def test_check_discard_for_attach_volume_no_unmap(self, mock_log):
self._test_check_discard(mock_log, driver_discard=None,
bus='scsi', should_log=False)
@mock.patch('nova.virt.libvirt.driver.LOG.debug')
def test_check_discard_for_attach_volume_blk_controller(self, mock_log):
self._test_check_discard(mock_log, driver_discard='unmap',
bus='virtio', should_log=True)
@mock.patch('nova.virt.libvirt.driver.LOG.debug')
def test_check_discard_for_attach_volume_valid_controller(self, mock_log):
self._test_check_discard(mock_log, driver_discard='unmap',
bus='scsi', should_log=False)
@mock.patch('nova.virt.libvirt.driver.LOG.debug')
def test_check_discard_for_attach_volume_blk_controller_no_unmap(self,
mock_log):
self._test_check_discard(mock_log, driver_discard=None,
bus='virtio', should_log=False)
@mock.patch('nova.utils.get_image_from_system_metadata')
@mock.patch('nova.virt.libvirt.blockinfo.get_info_from_bdm')
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
def test_attach_volume_with_vir_domain_affect_live_flag(self,
mock_get_domain, mock_get_info, get_image):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
image_meta = {}
get_image.return_value = image_meta
mock_dom = mock.MagicMock()
mock_get_domain.return_value = mock_dom
connection_info = {"driver_volume_type": "fake",
"data": {"device_path": "/fake",
"access_mode": "rw"}}
bdm = {'device_name': 'vdb',
'disk_bus': 'fake-bus',
'device_type': 'fake-type'}
disk_info = {'bus': bdm['disk_bus'], 'type': bdm['device_type'],
'dev': 'vdb'}
mock_get_info.return_value = disk_info
mock_conf = mock.MagicMock()
flags = (fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE)
with test.nested(
mock.patch.object(drvr, '_connect_volume'),
mock.patch.object(drvr, '_get_volume_config',
return_value=mock_conf),
mock.patch.object(drvr, '_set_cache_mode'),
mock.patch.object(drvr, '_check_discard_for_attach_volume')
) as (mock_connect_volume, mock_get_volume_config,
mock_set_cache_mode, mock_check_discard):
for state in (power_state.RUNNING, power_state.PAUSED):
mock_dom.info.return_value = [state, 512, 512, 2, 1234, 5678]
drvr.attach_volume(self.context, connection_info, instance,
"/dev/vdb", disk_bus=bdm['disk_bus'],
device_type=bdm['device_type'])
mock_get_domain.assert_called_with(instance)
mock_get_info.assert_called_with(
instance,
CONF.libvirt.virt_type,
test.MatchType(objects.ImageMeta),
bdm)
mock_connect_volume.assert_called_with(
connection_info, disk_info)
mock_get_volume_config.assert_called_with(
connection_info, disk_info)
mock_set_cache_mode.assert_called_with(mock_conf)
mock_dom.attachDeviceFlags.assert_called_with(
mock_conf.to_xml(), flags=flags)
mock_check_discard.assert_called_with(mock_conf, instance)
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
def test_detach_volume_with_vir_domain_affect_live_flag(self,
mock_get_domain):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_xml_with_disk = """<domain>
<devices>
<disk type='file'>
<source file='/path/to/fake-volume'/>
<target dev='vdc' bus='virtio'/>
</disk>
</devices>
</domain>"""
mock_xml_without_disk = """<domain>
<devices>
</devices>
</domain>"""
mock_dom = mock.MagicMock()
# Second time don't return anything about disk vdc so it looks removed
return_list = [mock_xml_with_disk, mock_xml_without_disk]
# Doubling the size of return list because we test with two guest power
# states
mock_dom.XMLDesc.side_effect = return_list + return_list
connection_info = {"driver_volume_type": "fake",
"data": {"device_path": "/fake",
"access_mode": "rw"}}
flags = (fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE)
with mock.patch.object(drvr, '_disconnect_volume') as \
mock_disconnect_volume:
for state in (power_state.RUNNING, power_state.PAUSED):
mock_dom.info.return_value = [state, 512, 512, 2, 1234, 5678]
mock_get_domain.return_value = mock_dom
drvr.detach_volume(connection_info, instance, '/dev/vdc')
mock_get_domain.assert_called_with(instance)
mock_dom.detachDeviceFlags.assert_called_with("""<disk type="file" device="disk">
<source file="/path/to/fake-volume"/>
<target bus="virtio" dev="vdc"/>
</disk>
""", flags=flags)
mock_disconnect_volume.assert_called_with(
connection_info, 'vdc')
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
def test_detach_volume_disk_not_found(self, mock_get_domain):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_xml_without_disk = """<domain>
<devices>
</devices>
</domain>"""
mock_dom = mock.MagicMock(return_value=mock_xml_without_disk)
connection_info = {"driver_volume_type": "fake",
"data": {"device_path": "/fake",
"access_mode": "rw"}}
mock_dom.info.return_value = [power_state.RUNNING, 512, 512, 2, 1234,
5678]
mock_get_domain.return_value = mock_dom
self.assertRaises(exception.DiskNotFound, drvr.detach_volume,
connection_info, instance, '/dev/vdc')
mock_get_domain.assert_called_once_with(instance)
def test_multi_nic(self):
network_info = _fake_network_info(self, 2)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drvr._get_guest_xml(self.context, instance_ref,
network_info, disk_info,
image_meta)
tree = etree.fromstring(xml)
interfaces = tree.findall("./devices/interface")
self.assertEqual(len(interfaces), 2)
self.assertEqual(interfaces[0].get('type'), 'bridge')
def _behave_supports_direct_io(self, raise_open=False, raise_write=False,
exc=ValueError()):
open_behavior = os.open(os.path.join('.', '.directio.test'),
os.O_CREAT | os.O_WRONLY | os.O_DIRECT)
if raise_open:
open_behavior.AndRaise(exc)
else:
open_behavior.AndReturn(3)
write_bahavior = os.write(3, mox.IgnoreArg())
if raise_write:
write_bahavior.AndRaise(exc)
# ensure unlink(filepath) will actually remove the file by deleting
# the remaining link to it in close(fd)
os.close(3)
os.unlink(3)
def test_supports_direct_io(self):
# O_DIRECT is not supported on all Python runtimes, so on platforms
# where it's not supported (e.g. Mac), we can still test the code-path
# by stubbing out the value.
if not hasattr(os, 'O_DIRECT'):
# `mock` seems to have trouble stubbing an attr that doesn't
# originally exist, so falling back to stubbing out the attribute
# directly.
os.O_DIRECT = 16384
self.addCleanup(delattr, os, 'O_DIRECT')
einval = OSError()
einval.errno = errno.EINVAL
self.mox.StubOutWithMock(os, 'open')
self.mox.StubOutWithMock(os, 'write')
self.mox.StubOutWithMock(os, 'close')
self.mox.StubOutWithMock(os, 'unlink')
_supports_direct_io = libvirt_driver.LibvirtDriver._supports_direct_io
self._behave_supports_direct_io()
self._behave_supports_direct_io(raise_write=True)
self._behave_supports_direct_io(raise_open=True)
self._behave_supports_direct_io(raise_write=True, exc=einval)
self._behave_supports_direct_io(raise_open=True, exc=einval)
self.mox.ReplayAll()
self.assertTrue(_supports_direct_io('.'))
self.assertRaises(ValueError, _supports_direct_io, '.')
self.assertRaises(ValueError, _supports_direct_io, '.')
self.assertFalse(_supports_direct_io('.'))
self.assertFalse(_supports_direct_io('.'))
self.mox.VerifyAll()
def _check_xml_and_container(self, instance):
instance_ref = objects.Instance(**instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEqual(drvr._uri(), 'lxc:///')
network_info = _fake_network_info(self, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drvr._get_guest_xml(self.context, instance_ref,
network_info, disk_info,
image_meta)
tree = etree.fromstring(xml)
check = [
(lambda t: t.find('.').get('type'), 'lxc'),
(lambda t: t.find('./os/type').text, 'exe'),
(lambda t: t.find('./devices/filesystem/target').get('dir'), '/')]
for i, (check, expected_result) in enumerate(check):
self.assertEqual(check(tree),
expected_result,
'%s failed common check %d' % (xml, i))
target = tree.find('./devices/filesystem/source').get('dir')
self.assertGreater(len(target), 0)
def _check_xml_and_disk_prefix(self, instance, prefix):
instance_ref = objects.Instance(**instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
def _get_prefix(p, default):
if p:
return p + 'a'
return default
type_disk_map = {
'qemu': [
(lambda t: t.find('.').get('type'), 'qemu'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'vda'))],
'xen': [
(lambda t: t.find('.').get('type'), 'xen'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'xvda'))],
'kvm': [
(lambda t: t.find('.').get('type'), 'kvm'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'vda'))],
'uml': [
(lambda t: t.find('.').get('type'), 'uml'),
(lambda t: t.find('./devices/disk/target').get('dev'),
_get_prefix(prefix, 'ubda'))]
}
for (virt_type, checks) in six.iteritems(type_disk_map):
self.flags(virt_type=virt_type, group='libvirt')
if prefix:
self.flags(disk_prefix=prefix, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
network_info = _fake_network_info(self, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drvr._get_guest_xml(self.context, instance_ref,
network_info, disk_info,
image_meta)
tree = etree.fromstring(xml)
for i, (check, expected_result) in enumerate(checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed check %d' %
(check(tree), expected_result, i))
def _check_xml_and_disk_driver(self, image_meta):
os_open = os.open
directio_supported = True
def os_open_stub(path, flags, *args, **kwargs):
if flags & os.O_DIRECT:
if not directio_supported:
raise OSError(errno.EINVAL,
'%s: %s' % (os.strerror(errno.EINVAL), path))
flags &= ~os.O_DIRECT
return os_open(path, flags, *args, **kwargs)
self.stub_out('os.open', os_open_stub)
@staticmethod
def connection_supports_direct_io_stub(dirpath):
return directio_supported
self.stubs.Set(libvirt_driver.LibvirtDriver,
'_supports_direct_io', connection_supports_direct_io_stub)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
network_info = _fake_network_info(self, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drv._get_guest_xml(self.context, instance_ref,
network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
disks = tree.findall('./devices/disk/driver')
for guest_disk in disks:
self.assertEqual(guest_disk.get("cache"), "none")
directio_supported = False
# The O_DIRECT availability is cached on first use in
# LibvirtDriver, hence we re-create it here
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drv._get_guest_xml(self.context, instance_ref,
network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
disks = tree.findall('./devices/disk/driver')
for guest_disk in disks:
self.assertEqual(guest_disk.get("cache"), "writethrough")
def _check_xml_and_disk_bus(self, image_meta,
block_device_info, wantConfig):
instance_ref = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
block_device_info)
xml = drv._get_guest_xml(self.context, instance_ref,
network_info, disk_info, image_meta,
block_device_info=block_device_info)
tree = etree.fromstring(xml)
got_disks = tree.findall('./devices/disk')
got_disk_targets = tree.findall('./devices/disk/target')
for i in range(len(wantConfig)):
want_device_type = wantConfig[i][0]
want_device_bus = wantConfig[i][1]
want_device_dev = wantConfig[i][2]
got_device_type = got_disks[i].get('device')
got_device_bus = got_disk_targets[i].get('bus')
got_device_dev = got_disk_targets[i].get('dev')
self.assertEqual(got_device_type, want_device_type)
self.assertEqual(got_device_bus, want_device_bus)
self.assertEqual(got_device_dev, want_device_dev)
def _check_xml_and_uuid(self, image_meta):
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
network_info = _fake_network_info(self, 1)
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
xml = drv._get_guest_xml(self.context, instance_ref,
network_info, disk_info, image_meta)
tree = etree.fromstring(xml)
self.assertEqual(tree.find('./uuid').text,
instance_ref['uuid'])
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_get_host_sysinfo_serial_hardware",)
def _check_xml_and_uri(self, instance, mock_serial,
expect_ramdisk=False, expect_kernel=False,
rescue=None, expect_xen_hvm=False, xen_only=False):
mock_serial.return_value = "cef19ce0-0ca2-11df-855d-b19fbce37686"
instance_ref = objects.Instance(**instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
xen_vm_mode = vm_mode.XEN
if expect_xen_hvm:
xen_vm_mode = vm_mode.HVM
type_uri_map = {'qemu': ('qemu:///system',
[(lambda t: t.find('.').get('type'), 'qemu'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM),
(lambda t: t.find('./devices/emulator'), None)]),
'kvm': ('qemu:///system',
[(lambda t: t.find('.').get('type'), 'kvm'),
(lambda t: t.find('./os/type').text,
vm_mode.HVM),
(lambda t: t.find('./devices/emulator'), None)]),
'uml': ('uml:///system',
[(lambda t: t.find('.').get('type'), 'uml'),
(lambda t: t.find('./os/type').text,
vm_mode.UML)]),
'xen': ('xen:///',
[(lambda t: t.find('.').get('type'), 'xen'),
(lambda t: t.find('./os/type').text,
xen_vm_mode)])}
if expect_xen_hvm or xen_only:
hypervisors_to_check = ['xen']
else:
hypervisors_to_check = ['qemu', 'kvm', 'xen']
for hypervisor_type in hypervisors_to_check:
check_list = type_uri_map[hypervisor_type][1]
if rescue:
suffix = '.rescue'
else:
suffix = ''
if expect_kernel:
check = (lambda t: self.relpath(t.find('./os/kernel').text).
split('/')[1], 'kernel' + suffix)
else:
check = (lambda t: t.find('./os/kernel'), None)
check_list.append(check)
if expect_kernel:
check = (lambda t: "no_timer_check" in t.find('./os/cmdline').
text, hypervisor_type == "qemu")
check_list.append(check)
# Hypervisors that only support vm_mode.HVM and Xen
# should not produce configuration that results in kernel
# arguments
if not expect_kernel and (hypervisor_type in
['qemu', 'kvm', 'xen']):
check = (lambda t: t.find('./os/root'), None)
check_list.append(check)
check = (lambda t: t.find('./os/cmdline'), None)
check_list.append(check)
if expect_ramdisk:
check = (lambda t: self.relpath(t.find('./os/initrd').text).
split('/')[1], 'ramdisk' + suffix)
else:
check = (lambda t: t.find('./os/initrd'), None)
check_list.append(check)
if hypervisor_type in ['qemu', 'kvm']:
xpath = "./sysinfo/system/entry"
check = (lambda t: t.findall(xpath)[0].get("name"),
"manufacturer")
check_list.append(check)
check = (lambda t: t.findall(xpath)[0].text,
version.vendor_string())
check_list.append(check)
check = (lambda t: t.findall(xpath)[1].get("name"),
"product")
check_list.append(check)
check = (lambda t: t.findall(xpath)[1].text,
version.product_string())
check_list.append(check)
check = (lambda t: t.findall(xpath)[2].get("name"),
"version")
check_list.append(check)
# NOTE(sirp): empty strings don't roundtrip in lxml (they are
# converted to None), so we need an `or ''` to correct for that
check = (lambda t: t.findall(xpath)[2].text or '',
version.version_string_with_package())
check_list.append(check)
check = (lambda t: t.findall(xpath)[3].get("name"),
"serial")
check_list.append(check)
check = (lambda t: t.findall(xpath)[3].text,
"cef19ce0-0ca2-11df-855d-b19fbce37686")
check_list.append(check)
check = (lambda t: t.findall(xpath)[4].get("name"),
"uuid")
check_list.append(check)
check = (lambda t: t.findall(xpath)[4].text,
instance['uuid'])
check_list.append(check)
if hypervisor_type in ['qemu', 'kvm']:
check = (lambda t: t.findall('./devices/serial')[0].get(
'type'), 'file')
check_list.append(check)
check = (lambda t: t.findall('./devices/serial')[1].get(
'type'), 'pty')
check_list.append(check)
check = (lambda t: self.relpath(t.findall(
'./devices/serial/source')[0].get('path')).
split('/')[1], 'console.log')
check_list.append(check)
else:
check = (lambda t: t.find('./devices/console').get(
'type'), 'pty')
check_list.append(check)
common_checks = [
(lambda t: t.find('.').tag, 'domain'),
(lambda t: t.find('./memory').text, '2097152')]
if rescue:
common_checks += [
(lambda t: self.relpath(t.findall('./devices/disk/source')[0].
get('file')).split('/')[1], 'disk.rescue'),
(lambda t: self.relpath(t.findall('./devices/disk/source')[1].
get('file')).split('/')[1], 'disk')]
else:
common_checks += [(lambda t: self.relpath(t.findall(
'./devices/disk/source')[0].get('file')).split('/')[1],
'disk')]
common_checks += [(lambda t: self.relpath(t.findall(
'./devices/disk/source')[1].get('file')).split('/')[1],
'disk.local')]
for virt_type in hypervisors_to_check:
expected_uri = type_uri_map[virt_type][0]
checks = type_uri_map[virt_type][1]
self.flags(virt_type=virt_type, group='libvirt')
with mock.patch('nova.virt.libvirt.driver.libvirt') as old_virt:
del old_virt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEqual(drvr._uri(), expected_uri)
network_info = _fake_network_info(self, 1)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
rescue=rescue)
xml = drvr._get_guest_xml(self.context, instance_ref,
network_info, disk_info,
image_meta,
rescue=rescue)
tree = etree.fromstring(xml)
for i, (check, expected_result) in enumerate(checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed check %d' %
(check(tree), expected_result, i))
for i, (check, expected_result) in enumerate(common_checks):
self.assertEqual(check(tree),
expected_result,
'%s != %s failed common check %d' %
(check(tree), expected_result, i))
filterref = './devices/interface/filterref'
vif = network_info[0]
nic_id = vif['address'].lower().replace(':', '')
fw = firewall.NWFilterFirewall(drvr)
instance_filter_name = fw._instance_filter_name(instance_ref,
nic_id)
self.assertEqual(tree.find(filterref).get('filter'),
instance_filter_name)
# This test is supposed to make sure we don't
# override a specifically set uri
#
# Deliberately not just assigning this string to CONF.connection_uri
# and checking against that later on. This way we make sure the
# implementation doesn't fiddle around with the CONF.
testuri = 'something completely different'
self.flags(connection_uri=testuri, group='libvirt')
for (virt_type, (expected_uri, checks)) in six.iteritems(type_uri_map):
self.flags(virt_type=virt_type, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertEqual(drvr._uri(), testuri)
def test_ensure_filtering_rules_for_instance_timeout(self):
# ensure_filtering_fules_for_instance() finishes with timeout.
# Preparing mocks
def fake_none(self, *args):
return
class FakeTime(object):
def __init__(self):
self.counter = 0
def sleep(self, t):
self.counter += t
fake_timer = FakeTime()
def fake_sleep(t):
fake_timer.sleep(t)
# _fake_network_info must be called before create_fake_libvirt_mock(),
# as _fake_network_info calls importutils.import_class() and
# create_fake_libvirt_mock() mocks importutils.import_class().
network_info = _fake_network_info(self, 1)
self.create_fake_libvirt_mock()
instance_ref = objects.Instance(**self.test_instance)
# Start test
self.mox.ReplayAll()
try:
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr.firewall_driver,
'setup_basic_filtering',
fake_none)
self.stubs.Set(drvr.firewall_driver,
'prepare_instance_filter',
fake_none)
self.stubs.Set(drvr.firewall_driver,
'instance_filter_exists',
fake_none)
self.stubs.Set(greenthread,
'sleep',
fake_sleep)
drvr.ensure_filtering_rules_for_instance(instance_ref,
network_info)
except exception.NovaException as e:
msg = ('The firewall filter for %s does not exist' %
instance_ref['name'])
c1 = (0 <= six.text_type(e).find(msg))
self.assertTrue(c1)
self.assertEqual(29, fake_timer.counter, "Didn't wait the expected "
"amount of time")
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_shared_storage_test_file')
@mock.patch.object(fakelibvirt.Connection, 'compareCPU')
def test_check_can_live_migrate_dest_all_pass_with_block_migration(
self, mock_cpu, mock_test_file, mock_svc):
instance_ref = objects.Instance(**self.test_instance)
instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'disk_available_least': 400,
'cpu_info': 'asdf',
}
filename = "file"
# _check_cpu_match
mock_cpu.return_value = 1
# mounted_on_same_shared_storage
mock_test_file.return_value = filename
# No need for the src_compute_info
return_value = drvr.check_can_live_migrate_destination(self.context,
instance_ref, None, compute_info, True)
return_value.is_volume_backed = False
self.assertThat({"filename": "file",
'image_type': 'default',
'disk_available_mb': 409600,
"disk_over_commit": False,
"block_migration": True,
"is_volume_backed": False},
matchers.DictMatches(return_value.to_legacy_dict()))
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_shared_storage_test_file')
@mock.patch.object(fakelibvirt.Connection, 'compareCPU')
def test_check_can_live_migrate_dest_all_pass_no_block_migration(
self, mock_cpu, mock_test_file, mock_svc):
instance_ref = objects.Instance(**self.test_instance)
instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'disk_available_least': 400,
'cpu_info': 'asdf',
}
filename = "file"
# _check_cpu_match
mock_cpu.return_value = 1
# mounted_on_same_shared_storage
mock_test_file.return_value = filename
# No need for the src_compute_info
return_value = drvr.check_can_live_migrate_destination(self.context,
instance_ref, None, compute_info, False)
return_value.is_volume_backed = False
self.assertThat({"filename": "file",
"image_type": 'default',
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 409600,
"is_volume_backed": False},
matchers.DictMatches(return_value.to_legacy_dict()))
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_shared_storage_test_file',
return_value='fake')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_compare_cpu')
def test_check_can_live_migrate_guest_cpu_none_model(
self, mock_cpu, mock_test_file):
# Tests that when instance.vcpu_model.model is None, the host cpu
# model is used for live migration.
instance_ref = objects.Instance(**self.test_instance)
instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel
instance_ref.vcpu_model.model = None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': 'asdf', 'disk_available_least': 1}
result = drvr.check_can_live_migrate_destination(
self.context, instance_ref, compute_info, compute_info)
result.is_volume_backed = False
mock_cpu.assert_called_once_with(None, 'asdf', instance_ref)
expected_result = {"filename": 'fake',
"image_type": CONF.libvirt.images_type,
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 1024,
"is_volume_backed": False}
self.assertEqual(expected_result, result.to_legacy_dict())
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_shared_storage_test_file')
@mock.patch.object(fakelibvirt.Connection, 'compareCPU')
def test_check_can_live_migrate_dest_no_instance_cpu_info(
self, mock_cpu, mock_test_file, mock_svc):
instance_ref = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': jsonutils.dumps({
"vendor": "AMD",
"arch": arch.I686,
"features": ["sse3"],
"model": "Opteron_G3",
"topology": {"cores": 2, "threads": 1, "sockets": 4}
}), 'disk_available_least': 1}
filename = "file"
# _check_cpu_match
mock_cpu.return_value = 1
# mounted_on_same_shared_storage
mock_test_file.return_value = filename
return_value = drvr.check_can_live_migrate_destination(self.context,
instance_ref, compute_info, compute_info, False)
# NOTE(danms): Compute manager would have set this, so set it here
return_value.is_volume_backed = False
self.assertThat({"filename": "file",
"image_type": 'default',
"block_migration": False,
"disk_over_commit": False,
"disk_available_mb": 1024,
"is_volume_backed": False},
matchers.DictMatches(return_value.to_legacy_dict()))
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(fakelibvirt.Connection, 'compareCPU')
def test_check_can_live_migrate_dest_incompatible_cpu_raises(
self, mock_cpu, mock_svc):
instance_ref = objects.Instance(**self.test_instance)
instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
compute_info = {'cpu_info': 'asdf', 'disk_available_least': 1}
mock_cpu.side_effect = exception.InvalidCPUInfo(reason='foo')
self.assertRaises(exception.InvalidCPUInfo,
drvr.check_can_live_migrate_destination,
self.context, instance_ref,
compute_info, compute_info, False)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt, 'config')
def test_compare_cpu_compatible_host_cpu(self, mock_vconfig, mock_compare):
instance = objects.Instance(**self.test_instance)
mock_compare.return_value = 5
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(None, jsonutils.dumps(_fake_cpu_info),
instance)
self.assertIsNone(ret)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt, 'config')
def test_compare_cpu_handles_not_supported_error_gracefully(self,
mock_vconfig,
mock_compare):
instance = objects.Instance(**self.test_instance)
not_supported_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'this function is not supported by the connection driver:'
' virCompareCPU',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
mock_compare.side_effect = not_supported_exc
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(None, jsonutils.dumps(_fake_cpu_info),
instance)
self.assertIsNone(ret)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt.LibvirtDriver,
'_vcpu_model_to_cpu_config')
def test_compare_cpu_compatible_guest_cpu(self, mock_vcpu_to_cpu,
mock_compare):
instance = objects.Instance(**self.test_instance)
mock_compare.return_value = 6
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(jsonutils.dumps(_fake_cpu_info), None,
instance)
self.assertIsNone(ret)
def test_compare_cpu_virt_type_xen(self):
instance = objects.Instance(**self.test_instance)
self.flags(virt_type='xen', group='libvirt')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(None, None, instance)
self.assertIsNone(ret)
def test_compare_cpu_virt_type_qemu(self):
instance = objects.Instance(**self.test_instance)
self.flags(virt_type='qemu', group='libvirt')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ret = conn._compare_cpu(None, None, instance)
self.assertIsNone(ret)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt, 'config')
def test_compare_cpu_invalid_cpuinfo_raises(self, mock_vconfig,
mock_compare):
instance = objects.Instance(**self.test_instance)
mock_compare.return_value = 0
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.InvalidCPUInfo,
conn._compare_cpu, None,
jsonutils.dumps(_fake_cpu_info),
instance)
@mock.patch.object(host.Host, 'compare_cpu')
@mock.patch.object(nova.virt.libvirt, 'config')
def test_compare_cpu_incompatible_cpu_raises(self, mock_vconfig,
mock_compare):
instance = objects.Instance(**self.test_instance)
mock_compare.side_effect = fakelibvirt.libvirtError('cpu')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.MigrationPreCheckError,
conn._compare_cpu, None,
jsonutils.dumps(_fake_cpu_info),
instance)
def test_check_can_live_migrate_dest_cleanup_works_correctly(self):
objects.Instance(**self.test_instance)
dest_check_data = objects.LibvirtLiveMigrateData(
filename="file",
block_migration=True,
disk_over_commit=False,
disk_available_mb=1024)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(drvr, '_cleanup_shared_storage_test_file')
drvr._cleanup_shared_storage_test_file("file")
self.mox.ReplayAll()
drvr.cleanup_live_migration_destination_check(self.context,
dest_check_data)
@mock.patch('os.path.exists', return_value=True)
@mock.patch('os.utime')
def test_check_shared_storage_test_file_exists(self, mock_utime,
mock_path_exists):
tmpfile_path = os.path.join(CONF.instances_path, 'tmp123')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertTrue(drvr._check_shared_storage_test_file(
'tmp123', mock.sentinel.instance))
mock_utime.assert_called_once_with(CONF.instances_path, None)
mock_path_exists.assert_called_once_with(tmpfile_path)
@mock.patch('os.path.exists', return_value=False)
@mock.patch('os.utime')
def test_check_shared_storage_test_file_does_not_exist(self, mock_utime,
mock_path_exists):
tmpfile_path = os.path.join(CONF.instances_path, 'tmp123')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._check_shared_storage_test_file(
'tmp123', mock.sentinel.instance))
mock_utime.assert_called_once_with(CONF.instances_path, None)
mock_path_exists.assert_called_once_with(tmpfile_path)
def _mock_can_live_migrate_source(self, block_migration=False,
is_shared_block_storage=False,
is_shared_instance_path=False,
is_booted_from_volume=False,
disk_available_mb=1024,
block_device_info=None,
block_device_text=None):
instance = objects.Instance(**self.test_instance)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
block_migration=block_migration,
disk_over_commit=False,
disk_available_mb=disk_available_mb)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(drvr, '_is_shared_block_storage')
drvr._is_shared_block_storage(instance, dest_check_data,
block_device_info).AndReturn(is_shared_block_storage)
self.mox.StubOutWithMock(drvr, '_check_shared_storage_test_file')
drvr._check_shared_storage_test_file('file', instance).AndReturn(
is_shared_instance_path)
self.mox.StubOutWithMock(drvr, "get_instance_disk_info")
drvr.get_instance_disk_info(instance,
block_device_info=block_device_info).\
AndReturn(block_device_text)
self.mox.StubOutWithMock(drvr, '_is_booted_from_volume')
drvr._is_booted_from_volume(instance, block_device_text).AndReturn(
is_booted_from_volume)
return (instance, dest_check_data, drvr)
def test_check_can_live_migrate_source_block_migration(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
block_migration=True)
self.mox.StubOutWithMock(drvr, "_assert_dest_node_has_enough_disk")
drvr._assert_dest_node_has_enough_disk(
self.context, instance, dest_check_data.disk_available_mb,
False, None)
self.mox.ReplayAll()
ret = drvr.check_can_live_migrate_source(self.context, instance,
dest_check_data)
self.assertIsInstance(ret, objects.LibvirtLiveMigrateData)
self.assertIn('is_shared_block_storage', ret)
self.assertIn('is_shared_instance_path', ret)
def test_check_can_live_migrate_source_shared_block_storage(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
is_shared_block_storage=True)
self.mox.ReplayAll()
drvr.check_can_live_migrate_source(self.context, instance,
dest_check_data)
def test_check_can_live_migrate_source_shared_instance_path(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
is_shared_instance_path=True)
self.mox.ReplayAll()
drvr.check_can_live_migrate_source(self.context, instance,
dest_check_data)
def test_check_can_live_migrate_source_non_shared_fails(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source()
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
drvr.check_can_live_migrate_source, self.context,
instance, dest_check_data)
def test_check_can_live_migrate_source_shared_block_migration_fails(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
block_migration=True,
is_shared_block_storage=True)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidLocalStorage,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data)
def test_check_can_live_migrate_shared_path_block_migration_fails(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
block_migration=True,
is_shared_instance_path=True)
self.mox.ReplayAll()
self.assertRaises(exception.InvalidLocalStorage,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data, None)
def test_check_can_live_migrate_non_shared_non_block_migration_fails(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source()
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data)
def test_check_can_live_migrate_source_with_dest_not_enough_disk(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
block_migration=True,
disk_available_mb=0)
drvr.get_instance_disk_info(instance,
block_device_info=None).AndReturn(
'[{"virt_disk_size":2}]')
self.mox.ReplayAll()
self.assertRaises(exception.MigrationError,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data)
def test_check_can_live_migrate_source_booted_from_volume(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
is_booted_from_volume=True,
block_device_text='[]')
self.mox.ReplayAll()
drvr.check_can_live_migrate_source(self.context, instance,
dest_check_data)
def test_check_can_live_migrate_source_booted_from_volume_with_swap(self):
instance, dest_check_data, drvr = self._mock_can_live_migrate_source(
is_booted_from_volume=True,
block_device_text='[{"path":"disk.swap"}]')
self.mox.ReplayAll()
self.assertRaises(exception.InvalidSharedStorage,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data)
@mock.patch.object(host.Host, 'has_min_version', return_value=False)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_has_local_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_booted_from_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_shared_block_storage', return_value=False)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_check_shared_storage_test_file', return_value=False)
def test_check_can_live_migrate_source_block_migration_with_bdm_error(
self, mock_check, mock_shared_block, mock_get_bdi,
mock_booted_from_volume, mock_has_local, mock_enough,
mock_min_version):
bdi = {'block_device_mapping': ['bdm']}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
block_migration=True,
disk_over_commit=False,
disk_available_mb=100)
self.assertRaises(exception.MigrationPreCheckError,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data,
block_device_info=bdi)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_has_local_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_booted_from_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_shared_block_storage', return_value=False)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_check_shared_storage_test_file', return_value=False)
def test_check_can_live_migrate_source_bm_with_bdm_tunnelled_error(
self, mock_check, mock_shared_block, mock_get_bdi,
mock_booted_from_volume, mock_has_local, mock_enough,
mock_min_version):
self.flags(live_migration_tunnelled=True,
group='libvirt')
bdi = {'block_device_mapping': ['bdm']}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
block_migration=True,
disk_over_commit=False,
disk_available_mb=100)
drvr._parse_migration_flags()
self.assertRaises(exception.MigrationPreCheckError,
drvr.check_can_live_migrate_source,
self.context, instance, dest_check_data,
block_device_info=bdi)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_has_local_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_booted_from_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_shared_block_storage')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_check_shared_storage_test_file')
def _test_check_can_live_migrate_source_block_migration_none(
self, block_migrate, is_shared_instance_path, is_share_block,
mock_check, mock_shared_block, mock_get_bdi,
mock_booted_from_volume, mock_has_local, mock_enough, mock_verson):
mock_check.return_value = is_shared_instance_path
mock_shared_block.return_value = is_share_block
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
disk_over_commit=False,
disk_available_mb=100)
dest_check_data_ret = drvr.check_can_live_migrate_source(
self.context, instance, dest_check_data)
self.assertEqual(block_migrate, dest_check_data_ret.block_migration)
def test_check_can_live_migrate_source_block_migration_none_shared1(self):
self._test_check_can_live_migrate_source_block_migration_none(
False,
True,
False)
def test_check_can_live_migrate_source_block_migration_none_shared2(self):
self._test_check_can_live_migrate_source_block_migration_none(
False,
False,
True)
def test_check_can_live_migrate_source_block_migration_none_no_share(self):
self._test_check_can_live_migrate_source_block_migration_none(
True,
False,
False)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_assert_dest_node_has_enough_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_has_local_disk')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_booted_from_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_is_shared_block_storage')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_check_shared_storage_test_file')
def test_check_can_live_migration_source_disk_over_commit_none(self,
mock_check, mock_shared_block, mock_get_bdi,
mock_booted_from_volume, mock_has_local,
mock_enough, mock_disk_check):
mock_check.return_value = False
mock_shared_block.return_value = False
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dest_check_data = objects.LibvirtLiveMigrateData(
filename='file',
image_type='default',
disk_available_mb=100)
drvr.check_can_live_migrate_source(
self.context, instance, dest_check_data)
self.assertFalse(mock_disk_check.called)
def _is_shared_block_storage_test_create_mocks(self, disks):
# Test data
instance_xml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>{}</devices></domain>")
disks_xml = ''
for dsk in disks:
if dsk['type'] is not 'network':
disks_xml = ''.join([disks_xml,
"<disk type='{type}'>"
"<driver name='qemu' type='{driver}'/>"
"<source {source}='{source_path}'/>"
"<target dev='{target_dev}' bus='virtio'/>"
"</disk>".format(**dsk)])
else:
disks_xml = ''.join([disks_xml,
"<disk type='{type}'>"
"<driver name='qemu' type='{driver}'/>"
"<source protocol='{source_proto}'"
"name='{source_image}' >"
"<host name='hostname' port='7000'/>"
"<config file='/path/to/file'/>"
"</source>"
"<target dev='{target_dev}'"
"bus='ide'/>".format(**dsk)])
# Preparing mocks
mock_virDomain = mock.Mock(fakelibvirt.virDomain)
mock_virDomain.XMLDesc = mock.Mock()
mock_virDomain.XMLDesc.return_value = (instance_xml.format(disks_xml))
mock_lookup = mock.Mock()
def mock_lookup_side_effect(name):
return mock_virDomain
mock_lookup.side_effect = mock_lookup_side_effect
mock_getsize = mock.Mock()
mock_getsize.return_value = "10737418240"
return (mock_getsize, mock_lookup)
def test_is_shared_block_storage_rbd(self):
self.flags(images_type='rbd', group='libvirt')
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_instance_disk_info = mock.Mock()
data = objects.LibvirtLiveMigrateData(image_type='rbd')
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertTrue(drvr._is_shared_block_storage(instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
self.assertTrue(drvr._is_storage_shared_with('foo', 'bar'))
def test_is_shared_block_storage_lvm(self):
self.flags(images_type='lvm', group='libvirt')
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
mock_get_instance_disk_info = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
data = objects.LibvirtLiveMigrateData(image_type='lvm',
is_volume_backed=False,
is_shared_instance_path=False)
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_is_shared_block_storage_qcow2(self):
self.flags(images_type='qcow2', group='libvirt')
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
mock_get_instance_disk_info = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
data = objects.LibvirtLiveMigrateData(image_type='qcow2',
is_volume_backed=False,
is_shared_instance_path=False)
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_is_shared_block_storage_rbd_only_source(self):
self.flags(images_type='rbd', group='libvirt')
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
mock_get_instance_disk_info = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
data = objects.LibvirtLiveMigrateData(is_shared_instance_path=False,
is_volume_backed=False)
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_is_shared_block_storage_rbd_only_dest(self):
bdi = {'block_device_mapping': []}
instance = objects.Instance(**self.test_instance)
mock_get_instance_disk_info = mock.Mock()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
data = objects.LibvirtLiveMigrateData(image_type='rbd',
is_volume_backed=False,
is_shared_instance_path=False)
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_is_shared_block_storage_volume_backed(self):
disks = [{'type': 'block',
'driver': 'raw',
'source': 'dev',
'source_path': '/dev/disk',
'target_dev': 'vda'}]
bdi = {'block_device_mapping': [
{'connection_info': 'info', 'mount_device': '/dev/vda'}]}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
(mock_getsize, mock_lookup) =\
self._is_shared_block_storage_test_create_mocks(disks)
data = objects.LibvirtLiveMigrateData(is_volume_backed=True,
is_shared_instance_path=False)
with mock.patch.object(host.Host, 'get_domain', mock_lookup):
self.assertTrue(drvr._is_shared_block_storage(instance, data,
block_device_info = bdi))
mock_lookup.assert_called_once_with(instance)
def test_is_shared_block_storage_volume_backed_with_disk(self):
disks = [{'type': 'block',
'driver': 'raw',
'source': 'dev',
'source_path': '/dev/disk',
'target_dev': 'vda'},
{'type': 'file',
'driver': 'raw',
'source': 'file',
'source_path': '/instance/disk.local',
'target_dev': 'vdb'}]
bdi = {'block_device_mapping': [
{'connection_info': 'info', 'mount_device': '/dev/vda'}]}
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
(mock_getsize, mock_lookup) =\
self._is_shared_block_storage_test_create_mocks(disks)
data = objects.LibvirtLiveMigrateData(is_volume_backed=True,
is_shared_instance_path=False)
with test.nested(
mock.patch.object(os.path, 'getsize', mock_getsize),
mock.patch.object(host.Host, 'get_domain', mock_lookup)):
self.assertFalse(drvr._is_shared_block_storage(
instance, data,
block_device_info = bdi))
mock_getsize.assert_called_once_with('/instance/disk.local')
mock_lookup.assert_called_once_with(instance)
def test_is_shared_block_storage_nfs(self):
bdi = {'block_device_mapping': []}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_backend = mock.MagicMock()
mock_image_backend.backend.return_value = mock_backend
mock_backend.is_file_in_instance_path.return_value = True
mock_get_instance_disk_info = mock.Mock()
data = objects.LibvirtLiveMigrateData(
is_shared_instance_path=True,
image_type='foo')
with mock.patch.object(drvr, 'get_instance_disk_info',
mock_get_instance_disk_info):
self.assertTrue(drvr._is_shared_block_storage(
'instance', data, block_device_info=bdi))
self.assertEqual(0, mock_get_instance_disk_info.call_count)
def test_live_migration_update_graphics_xml(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
xml_tmpl = ("<domain type='kvm'>"
"<devices>"
"<graphics type='vnc' listen='{vnc}'>"
"<listen address='{vnc}'/>"
"</graphics>"
"<graphics type='spice' listen='{spice}'>"
"<listen address='{spice}'/>"
"</graphics>"
"</devices>"
"</domain>")
initial_xml = xml_tmpl.format(vnc='1.2.3.4',
spice='5.6.7.8')
target_xml = xml_tmpl.format(vnc='10.0.0.1',
spice='10.0.0.2')
target_xml = etree.tostring(etree.fromstring(target_xml))
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
guest = libvirt_guest.Guest(vdmock)
self.mox.StubOutWithMock(vdmock, "migrateToURI2")
_bandwidth = CONF.libvirt.live_migration_bandwidth
vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE).AndReturn(
initial_xml)
vdmock.migrateToURI2(drvr._live_migration_uri('dest'),
dxml=target_xml,
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError("ERR"))
# start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='10.0.0.1',
graphics_listen_addr_spice='10.0.0.2',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=False)
self.mox.ReplayAll()
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
def test_live_migration_update_volume_xml(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
target_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'cde.67890.opst-lun-Z')
# start test
connection_info = {
u'driver_volume_type': u'iscsi',
u'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'data': {
u'access_mode': u'rw', u'target_discovered': False,
u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
},
}
bdm = objects.LibvirtLiveMigrateBDMInfo(
serial='58a84f6d-3f0c-4e19-a0af-eb657b790657',
bus='virtio', type='disk', dev='vdb',
connection_info=connection_info)
migrate_data = objects.LibvirtLiveMigrateData(
serial_listen_addr='',
target_connect_addr=None,
bdms=[bdm],
block_migration=False)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
test_mock = mock.MagicMock()
guest = libvirt_guest.Guest(test_mock)
with mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info') as \
mget_info,\
mock.patch.object(drvr._host, 'get_domain') as mget_domain,\
mock.patch.object(fakelibvirt.virDomain, 'migrateToURI2'),\
mock.patch.object(
libvirt_migrate, 'get_updated_guest_xml') as mupdate:
mget_info.side_effect = exception.InstanceNotFound(
instance_id='foo')
mget_domain.return_value = test_mock
test_mock.XMLDesc.return_value = target_xml
self.assertFalse(drvr._live_migration_operation(
self.context, instance_ref, 'dest', False,
migrate_data, guest, []))
mupdate.assert_called_once_with(
guest, migrate_data, mock.ANY)
def test_live_migration_with_valid_target_connect_addr(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
target_xml = self.device_xml_tmpl.format(<|fim▁hole|> 'cde.67890.opst-lun-Z')
# start test
connection_info = {
u'driver_volume_type': u'iscsi',
u'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'data': {
u'access_mode': u'rw', u'target_discovered': False,
u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
},
}
bdm = objects.LibvirtLiveMigrateBDMInfo(
serial='58a84f6d-3f0c-4e19-a0af-eb657b790657',
bus='virtio', type='disk', dev='vdb',
connection_info=connection_info)
migrate_data = objects.LibvirtLiveMigrateData(
serial_listen_addr='',
target_connect_addr='127.0.0.2',
bdms=[bdm],
block_migration=False)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
test_mock = mock.MagicMock()
guest = libvirt_guest.Guest(test_mock)
with mock.patch.object(libvirt_migrate,
'get_updated_guest_xml') as mupdate:
test_mock.XMLDesc.return_value = target_xml
drvr._live_migration_operation(self.context, instance_ref,
'dest', False, migrate_data,
guest, [])
test_mock.migrateToURI2.assert_called_once_with(
'qemu+tcp://127.0.0.2/system',
dxml=mupdate(), flags=0, bandwidth=0)
def test_update_volume_xml(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
initial_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'cde.67890.opst-lun-Z')
target_xml = etree.tostring(etree.fromstring(target_xml))
serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657"
bdmi = objects.LibvirtLiveMigrateBDMInfo(serial=serial,
bus='virtio',
type='disk',
dev='vdb')
bdmi.connection_info = {u'driver_volume_type': u'iscsi',
'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'data': {u'access_mode': u'rw', u'target_discovered': False,
u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}}
conf = vconfig.LibvirtConfigGuestDisk()
conf.source_device = bdmi.type
conf.driver_name = "qemu"
conf.driver_format = "raw"
conf.driver_cache = "none"
conf.target_dev = bdmi.dev
conf.target_bus = bdmi.bus
conf.serial = bdmi.connection_info.get('serial')
conf.source_type = "block"
conf.source_path = bdmi.connection_info['data'].get('device_path')
guest = libvirt_guest.Guest(mock.MagicMock())
with test.nested(
mock.patch.object(drvr, '_get_volume_config',
return_value=conf),
mock.patch.object(guest, 'get_xml_desc',
return_value=initial_xml)):
config = libvirt_migrate.get_updated_guest_xml(guest,
objects.LibvirtLiveMigrateData(bdms=[bdmi]),
drvr._get_volume_config)
parser = etree.XMLParser(remove_blank_text=True)
config = etree.fromstring(config, parser)
target_xml = etree.fromstring(target_xml, parser)
self.assertEqual(etree.tostring(target_xml),
etree.tostring(config))
def test_live_migration_uri(self):
hypervisor_uri_map = (
('xen', 'xenmigr://%s/system'),
('kvm', 'qemu+tcp://%s/system'),
('qemu', 'qemu+tcp://%s/system'),
# anything else will return None
('lxc', None),
('parallels', None),
)
dest = 'destination'
for hyperv, uri in hypervisor_uri_map:
self.flags(virt_type=hyperv, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
if uri is not None:
uri = uri % dest
self.assertEqual(uri, drvr._live_migration_uri(dest))
else:
self.assertRaises(exception.LiveMigrationURINotAvailable,
drvr._live_migration_uri,
dest)
def test_live_migration_uri_forced(self):
dest = 'destination'
for hyperv in ('kvm', 'xen'):
self.flags(virt_type=hyperv, group='libvirt')
forced_uri = 'foo://%s/bar'
self.flags(live_migration_uri=forced_uri, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(forced_uri % dest, drvr._live_migration_uri(dest))
def test_update_volume_xml_no_serial(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
xml_tmpl = """
<domain type='kvm'>
<devices>
<disk type='block' device='disk'>
<driver name='qemu' type='raw' cache='none'/>
<source dev='{device_path}'/>
<target bus='virtio' dev='vdb'/>
<serial></serial>
<address type='pci' domain='0x0' bus='0x0' slot='0x04' \
function='0x0'/>
</disk>
</devices>
</domain>
"""
initial_xml = xml_tmpl.format(device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = xml_tmpl.format(device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = etree.tostring(etree.fromstring(target_xml))
serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657"
connection_info = {
u'driver_volume_type': u'iscsi',
'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'data': {
u'access_mode': u'rw', u'target_discovered': False,
u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657',
u'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z',
},
}
bdmi = objects.LibvirtLiveMigrateBDMInfo(serial=serial,
bus='virtio',
dev='vdb',
type='disk')
bdmi.connection_info = connection_info
conf = vconfig.LibvirtConfigGuestDisk()
conf.source_device = bdmi.type
conf.driver_name = "qemu"
conf.driver_format = "raw"
conf.driver_cache = "none"
conf.target_dev = bdmi.dev
conf.target_bus = bdmi.bus
conf.serial = bdmi.connection_info.get('serial')
conf.source_type = "block"
conf.source_path = bdmi.connection_info['data'].get('device_path')
guest = libvirt_guest.Guest(mock.MagicMock())
with test.nested(
mock.patch.object(drvr, '_get_volume_config',
return_value=conf),
mock.patch.object(guest, 'get_xml_desc',
return_value=initial_xml)):
config = libvirt_migrate.get_updated_guest_xml(guest,
objects.LibvirtLiveMigrateData(bdms=[bdmi]),
drvr._get_volume_config)
self.assertEqual(target_xml, config)
def test_update_volume_xml_no_connection_info(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
initial_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = self.device_xml_tmpl.format(
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
'abc.12345.opst-lun-X')
target_xml = etree.tostring(etree.fromstring(target_xml))
serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657"
bdmi = objects.LibvirtLiveMigrateBDMInfo(serial=serial,
dev='vdb',
type='disk',
bus='scsi',
format='qcow')
bdmi.connection_info = {}
conf = vconfig.LibvirtConfigGuestDisk()
guest = libvirt_guest.Guest(mock.MagicMock())
with test.nested(
mock.patch.object(drvr, '_get_volume_config',
return_value=conf),
mock.patch.object(guest, 'get_xml_desc',
return_value=initial_xml)):
config = libvirt_migrate.get_updated_guest_xml(
guest,
objects.LibvirtLiveMigrateData(bdms=[bdmi]),
drvr._get_volume_config)
self.assertEqual(target_xml, config)
@mock.patch.object(fakelibvirt.virDomain, "migrateToURI2")
@mock.patch.object(fakelibvirt.virDomain, "XMLDesc")
def test_live_migration_update_serial_console_xml(self, mock_xml,
mock_migrate):
self.compute = importutils.import_object(CONF.compute_manager)
instance_ref = self.test_instance
xml_tmpl = ("<domain type='kvm'>"
"<devices>"
"<console type='tcp'>"
"<source mode='bind' host='{addr}' service='10000'/>"
"</console>"
"</devices>"
"</domain>")
initial_xml = xml_tmpl.format(addr='9.0.0.1')
target_xml = xml_tmpl.format(addr='9.0.0.12')
target_xml = etree.tostring(etree.fromstring(target_xml))
# Preparing mocks
mock_xml.return_value = initial_xml
mock_migrate.side_effect = fakelibvirt.libvirtError("ERR")
# start test
bandwidth = CONF.libvirt.live_migration_bandwidth
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='10.0.0.1',
graphics_listen_addr_spice='10.0.0.2',
serial_listen_addr='9.0.0.12',
target_connect_addr=None,
bdms=[],
block_migration=False)
dom = fakelibvirt.virDomain
guest = libvirt_guest.Guest(dom)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
mock_xml.assert_called_once_with(
flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE)
mock_migrate.assert_called_once_with(
drvr._live_migration_uri('dest'),
dxml=target_xml, flags=mock.ANY, bandwidth=bandwidth)
@mock.patch.object(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None,
create=True)
def test_live_migration_fails_with_serial_console_without_migratable(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_ref = self.test_instance
CONF.set_override("enabled", True, "serial_console")
dom = fakelibvirt.virDomain
migrate_data = objects.LibvirtLiveMigrateData(
serial_listen_addr='', target_connect_addr=None,
block_migration=False)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.MigrationError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, dom, [])
@mock.patch.object(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None,
create=True)
def test_live_migration_uses_migrateToURI_without_migratable_flag(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
guest = libvirt_guest.Guest(vdmock)
self.mox.StubOutWithMock(vdmock, "migrateToURI")
_bandwidth = CONF.libvirt.live_migration_bandwidth
vdmock.migrateToURI(drvr._live_migration_uri('dest'),
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError("ERR"))
# start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='0.0.0.0',
graphics_listen_addr_spice='0.0.0.0',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=False)
self.mox.ReplayAll()
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
def test_live_migration_uses_migrateToURI_without_dest_listen_addrs(self):
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
guest = libvirt_guest.Guest(vdmock)
self.mox.StubOutWithMock(vdmock, "migrateToURI")
_bandwidth = CONF.libvirt.live_migration_bandwidth
vdmock.migrateToURI(drvr._live_migration_uri('dest'),
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError("ERR"))
# start test
migrate_data = objects.LibvirtLiveMigrateData(
serial_listen_addr='',
target_connect_addr=None,
bdms=[],
block_migration=False)
self.mox.ReplayAll()
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(fakelibvirt.virDomain, "migrateToURI3")
@mock.patch('nova.virt.libvirt.migration.get_updated_guest_xml',
return_value='')
@mock.patch('nova.virt.libvirt.guest.Guest.get_xml_desc',
return_value='<xml></xml>')
def test_live_migration_uses_migrateToURI3(
self, mock_old_xml, mock_new_xml, mock_migrateToURI3,
mock_min_version):
# Preparing mocks
disk_paths = ['vda', 'vdb']
params = {
'migrate_disks': ['vda', 'vdb'],
'bandwidth': CONF.libvirt.live_migration_bandwidth,
'destination_xml': '',
}
mock_migrateToURI3.side_effect = fakelibvirt.libvirtError("ERR")
# Start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='0.0.0.0',
graphics_listen_addr_spice='0.0.0.0',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=False)
dom = fakelibvirt.virDomain
guest = libvirt_guest.Guest(dom)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance, 'dest',
False, migrate_data, guest, disk_paths)
mock_migrateToURI3.assert_called_once_with(
drvr._live_migration_uri('dest'),
params=params, flags=0)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(fakelibvirt.virDomain, "migrateToURI3")
@mock.patch('nova.virt.libvirt.migration.get_updated_guest_xml',
return_value='')
@mock.patch('nova.virt.libvirt.guest.Guest.get_xml_desc', return_value='')
def test_block_live_migration_tunnelled_migrateToURI3(
self, mock_old_xml, mock_new_xml,
mock_migrateToURI3, mock_min_version):
self.flags(live_migration_tunnelled=True, group='libvirt')
# Preparing mocks
disk_paths = []
params = {
'bandwidth': CONF.libvirt.live_migration_bandwidth,
'destination_xml': '',
}
# Start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='0.0.0.0',
graphics_listen_addr_spice='0.0.0.0',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=True)
dom = fakelibvirt.virDomain
guest = libvirt_guest.Guest(dom)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._parse_migration_flags()
instance = objects.Instance(**self.test_instance)
drvr._live_migration_operation(self.context, instance, 'dest',
True, migrate_data, guest, disk_paths)
mock_migrateToURI3.assert_called_once_with(
drvr._live_migration_uri('dest'),
params=params, flags=151)
@mock.patch.object(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None,
create=True)
def test_live_migration_fails_without_migratable_flag_or_0_addr(self):
self.flags(enabled=True, vncserver_listen='1.2.3.4', group='vnc')
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "migrateToURI")
# start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='1.2.3.4',
graphics_listen_addr_spice='1.2.3.4',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
block_migration=False)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.MigrationError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, vdmock, [])
def test_live_migration_raises_exception(self):
# Confirms recover method is called when exceptions are raised.
# Preparing data
self.compute = importutils.import_object(CONF.compute_manager)
instance_dict = dict(self.test_instance)
instance_dict.update({'host': 'fake',
'power_state': power_state.RUNNING,
'vm_state': vm_states.ACTIVE})
instance_ref = objects.Instance(**instance_dict)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
guest = libvirt_guest.Guest(vdmock)
self.mox.StubOutWithMock(vdmock, "migrateToURI2")
_bandwidth = CONF.libvirt.live_migration_bandwidth
if getattr(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None) is None:
vdmock.migrateToURI(drvr._live_migration_uri('dest'),
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError('ERR'))
else:
vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE
).AndReturn(FakeVirtDomain().XMLDesc(flags=0))
vdmock.migrateToURI2(drvr._live_migration_uri('dest'),
dxml=mox.IgnoreArg(),
flags=mox.IgnoreArg(),
bandwidth=_bandwidth).AndRaise(
fakelibvirt.libvirtError('ERR'))
# start test
migrate_data = objects.LibvirtLiveMigrateData(
graphics_listen_addr_vnc='127.0.0.1',
graphics_listen_addr_spice='127.0.0.1',
serial_listen_addr='127.0.0.1',
target_connect_addr=None,
bdms=[],
block_migration=False)
self.mox.ReplayAll()
self.assertRaises(fakelibvirt.libvirtError,
drvr._live_migration_operation,
self.context, instance_ref, 'dest',
False, migrate_data, guest, [])
self.assertEqual(vm_states.ACTIVE, instance_ref.vm_state)
self.assertEqual(power_state.RUNNING, instance_ref.power_state)
@mock.patch('shutil.rmtree')
@mock.patch('os.path.exists', return_value=True)
@mock.patch('nova.virt.libvirt.utils.get_instance_path_at_destination')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.destroy')
def test_rollback_live_migration_at_dest_not_shared(self, mock_destroy,
mock_get_instance_path,
mock_exist,
mock_shutil
):
# destroy method may raise InstanceTerminationFailure or
# InstancePowerOffFailure, here use their base class Invalid.
mock_destroy.side_effect = exception.Invalid(reason='just test')
fake_instance_path = os.path.join(cfg.CONF.instances_path,
'/fake_instance_uuid')
mock_get_instance_path.return_value = fake_instance_path
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
migrate_data = objects.LibvirtLiveMigrateData(
is_shared_instance_path=False,
instance_relative_path=False)
self.assertRaises(exception.Invalid,
drvr.rollback_live_migration_at_destination,
"context", "instance", [], None, True, migrate_data)
mock_exist.assert_called_once_with(fake_instance_path)
mock_shutil.assert_called_once_with(fake_instance_path)
@mock.patch('shutil.rmtree')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path_at_destination')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.destroy')
def test_rollback_live_migration_at_dest_shared(self, mock_destroy,
mock_get_instance_path,
mock_exist,
mock_shutil
):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
migrate_data = objects.LibvirtLiveMigrateData(
is_shared_instance_path=True,
instance_relative_path=False)
drvr.rollback_live_migration_at_destination("context", "instance", [],
None, True, migrate_data)
mock_destroy.assert_called_once_with("context", "instance", [],
None, True, migrate_data)
self.assertFalse(mock_get_instance_path.called)
self.assertFalse(mock_exist.called)
self.assertFalse(mock_shutil.called)
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(host.Host, "has_min_version", return_value=False)
@mock.patch.object(fakelibvirt.Domain, "XMLDesc")
def test_live_migration_copy_disk_paths(self, mock_xml, mock_version,
mock_conn):
xml = """
<domain>
<name>dummy</name>
<uuid>d4e13113-918e-42fe-9fc9-861693ffd432</uuid>
<devices>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.root"/>
<target dev="vda"/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.shared"/>
<target dev="vdb"/>
<shareable/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.config"/>
<target dev="vdc"/>
<readonly/>
</disk>
<disk type="block">
<source dev="/dev/mapper/somevol"/>
<target dev="vdd"/>
</disk>
<disk type="network">
<source protocol="https" name="url_path">
<host name="hostname" port="443"/>
</source>
</disk>
</devices>
</domain>"""
mock_xml.return_value = xml
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
guest = libvirt_guest.Guest(dom)
paths = drvr._live_migration_copy_disk_paths(None, None, guest)
self.assertEqual((["/var/lib/nova/instance/123/disk.root",
"/dev/mapper/somevol"], ['vda', 'vdd']), paths)
@mock.patch.object(fakelibvirt.Domain, "XMLDesc")
def test_live_migration_copy_disk_paths_tunnelled(self, mock_xml):
self.flags(live_migration_tunnelled=True, group='libvirt')
xml = """
<domain>
<name>dummy</name>
<uuid>d4e13113-918e-42fe-9fc9-861693ffd432</uuid>
<devices>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.root"/>
<target dev="vda"/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.shared"/>
<target dev="vdb"/>
<shareable/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.config"/>
<target dev="vdc"/>
<readonly/>
</disk>
<disk type="block">
<source dev="/dev/mapper/somevol"/>
<target dev="vdd"/>
</disk>
<disk type="network">
<source protocol="https" name="url_path">
<host name="hostname" port="443"/>
</source>
</disk>
</devices>
</domain>"""
mock_xml.return_value = xml
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._parse_migration_flags()
dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
guest = libvirt_guest.Guest(dom)
paths = drvr._live_migration_copy_disk_paths(None, None, guest)
self.assertEqual((["/var/lib/nova/instance/123/disk.root",
"/dev/mapper/somevol"], ['vda', 'vdd']), paths)
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(host.Host, "has_min_version", return_value=True)
@mock.patch('nova.virt.driver.get_block_device_info')
@mock.patch('nova.objects.BlockDeviceMappingList.get_by_instance_uuid')
@mock.patch.object(fakelibvirt.Domain, "XMLDesc")
def test_live_migration_copy_disk_paths_selective_block_migration(
self, mock_xml, mock_get_instance,
mock_block_device_info, mock_version, mock_conn):
xml = """
<domain>
<name>dummy</name>
<uuid>d4e13113-918e-42fe-9fc9-861693ffd432</uuid>
<devices>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.root"/>
<target dev="vda"/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.shared"/>
<target dev="vdb"/>
</disk>
<disk type="file">
<source file="/var/lib/nova/instance/123/disk.config"/>
<target dev="vdc"/>
</disk>
<disk type="block">
<source dev="/dev/mapper/somevol"/>
<target dev="vdd"/>
</disk>
<disk type="network">
<source protocol="https" name="url_path">
<host name="hostname" port="443"/>
</source>
</disk>
</devices>
</domain>"""
mock_xml.return_value = xml
instance = objects.Instance(**self.test_instance)
instance.root_device_name = '/dev/vda'
block_device_info = {
'swap': {
'disk_bus': u'virtio',
'swap_size': 10,
'device_name': u'/dev/vdc'
},
'root_device_name': u'/dev/vda',
'ephemerals': [{
'guest_format': u'ext3',
'device_name': u'/dev/vdb',
'disk_bus': u'virtio',
'device_type': u'disk',
'size': 1
}],
'block_device_mapping': [{
'guest_format': None,
'boot_index': None,
'mount_device': u'/dev/vdd',
'connection_info': {
u'driver_volume_type': u'iscsi',
'serial': u'147df29f-aec2-4851-b3fe-f68dad151834',
u'data': {
u'access_mode': u'rw',
u'target_discovered': False,
u'encrypted': False,
u'qos_specs': None,
u'target_iqn': u'iqn.2010-10.org.openstack:'
u'volume-147df29f-aec2-4851-b3fe-'
u'f68dad151834',
u'target_portal': u'10.102.44.141:3260', u'volume_id':
u'147df29f-aec2-4851-b3fe-f68dad151834',
u'target_lun': 1,
u'auth_password': u'cXELT66FngwzTwpf',
u'auth_username': u'QbQQjj445uWgeQkFKcVw',
u'auth_method': u'CHAP'
}
},
'disk_bus': None,
'device_type': None,
'delete_on_termination': False
}]
}
mock_block_device_info.return_value = block_device_info
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dom = fakelibvirt.Domain(drvr._get_connection(), xml, False)
guest = libvirt_guest.Guest(dom)
return_value = drvr._live_migration_copy_disk_paths(self.context,
instance,
guest)
expected = (['/var/lib/nova/instance/123/disk.root',
'/var/lib/nova/instance/123/disk.shared',
'/var/lib/nova/instance/123/disk.config'],
['vda', 'vdb', 'vdc'])
self.assertEqual(expected, return_value)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_live_migration_copy_disk_paths")
def test_live_migration_data_gb_plain(self, mock_paths):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
data_gb = drvr._live_migration_data_gb(instance, [])
self.assertEqual(2, data_gb)
self.assertEqual(0, mock_paths.call_count)
def test_live_migration_data_gb_block(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
def fake_stat(path):
class StatResult(object):
def __init__(self, size):
self._size = size
@property
def st_size(self):
return self._size
if path == "/var/lib/nova/instance/123/disk.root":
return StatResult(10 * units.Gi)
elif path == "/dev/mapper/somevol":
return StatResult(1.5 * units.Gi)
else:
raise Exception("Should not be reached")
disk_paths = ["/var/lib/nova/instance/123/disk.root",
"/dev/mapper/somevol"]
with mock.patch.object(os, "stat") as mock_stat:
mock_stat.side_effect = fake_stat
data_gb = drvr._live_migration_data_gb(instance, disk_paths)
# Expecting 2 GB for RAM, plus 10 GB for disk.root
# and 1.5 GB rounded to 2 GB for somevol, so 14 GB
self.assertEqual(14, data_gb)
EXPECT_SUCCESS = 1
EXPECT_FAILURE = 2
EXPECT_ABORT = 3
@mock.patch.object(libvirt_guest.Guest, "migrate_start_postcopy")
@mock.patch.object(time, "time")
@mock.patch.object(time, "sleep",
side_effect=lambda x: eventlet.sleep(0))
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(libvirt_guest.Guest, "get_job_info")
@mock.patch.object(objects.Instance, "save")
@mock.patch.object(objects.Migration, "save")
@mock.patch.object(fakelibvirt.Connection, "_mark_running")
@mock.patch.object(fakelibvirt.virDomain, "abortJob")
@mock.patch.object(libvirt_guest.Guest, "pause")
def _test_live_migration_monitoring(self,
job_info_records,
time_records,
expect_result,
mock_pause,
mock_abort,
mock_running,
mock_save,
mock_mig_save,
mock_job_info,
mock_conn,
mock_sleep,
mock_time,
mock_postcopy_switch,
current_mig_status=None,
expected_mig_status=None,
scheduled_action=None,
scheduled_action_executed=False,
block_migration=False,
expected_switch=False):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
drvr.active_migrations[instance.uuid] = deque()
dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", True)
guest = libvirt_guest.Guest(dom)
finish_event = eventlet.event.Event()
def fake_job_info():
while True:
self.assertGreater(len(job_info_records), 0)
rec = job_info_records.pop(0)
if type(rec) == str:
if rec == "thread-finish":
finish_event.send()
elif rec == "domain-stop":
dom.destroy()
elif rec == "force_complete":
drvr.active_migrations[instance.uuid].append(
"force-complete")
else:
if len(time_records) > 0:
time_records.pop(0)
return rec
return rec
def fake_time():
if len(time_records) > 0:
return time_records[0]
else:
return int(
datetime.datetime(2001, 1, 20, 20, 1, 0)
.strftime('%s'))
mock_job_info.side_effect = fake_job_info
mock_time.side_effect = fake_time
dest = mock.sentinel.migrate_dest
migration = objects.Migration(context=self.context, id=1)
migrate_data = objects.LibvirtLiveMigrateData(
migration=migration, block_migration=block_migration)
if current_mig_status:
migrate_data.migration.status = current_mig_status
else:
migrate_data.migration.status = "unset"
migrate_data.migration.save()
fake_post_method = mock.MagicMock()
fake_recover_method = mock.MagicMock()
drvr._live_migration_monitor(self.context, instance,
guest, dest,
fake_post_method,
fake_recover_method,
False,
migrate_data,
finish_event,
[])
if scheduled_action_executed:
if scheduled_action == 'pause':
self.assertTrue(mock_pause.called)
if scheduled_action == 'postcopy_switch':
self.assertTrue(mock_postcopy_switch.called)
else:
if scheduled_action == 'pause':
self.assertFalse(mock_pause.called)
if scheduled_action == 'postcopy_switch':
self.assertFalse(mock_postcopy_switch.called)
mock_mig_save.assert_called_with()
if expect_result == self.EXPECT_SUCCESS:
self.assertFalse(fake_recover_method.called,
'Recover method called when success expected')
self.assertFalse(mock_abort.called,
'abortJob not called when success expected')
if expected_switch:
self.assertTrue(mock_postcopy_switch.called)
fake_post_method.assert_called_once_with(
self.context, instance, dest, False, migrate_data)
else:
if expect_result == self.EXPECT_ABORT:
self.assertTrue(mock_abort.called,
'abortJob called when abort expected')
else:
self.assertFalse(mock_abort.called,
'abortJob not called when failure expected')
self.assertFalse(fake_post_method.called,
'Post method called when success not expected')
if expected_mig_status:
fake_recover_method.assert_called_once_with(
self.context, instance, dest, False, migrate_data,
migration_status=expected_mig_status)
else:
fake_recover_method.assert_called_once_with(
self.context, instance, dest, False, migrate_data)
self.assertNotIn(instance.uuid, drvr.active_migrations)
def test_live_migration_monitor_success(self):
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS)
def test_live_migration_handle_pause_normal(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in between VIR_DOMAIN_JOB_UNBOUNDED
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="running",
scheduled_action="pause",
scheduled_action_executed=True)
def test_live_migration_handle_pause_on_start(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in case of job type VIR_DOMAIN_JOB_NONE and finish_event is
# not ready yet
domain_info_records = [
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="preparing",
scheduled_action="pause",
scheduled_action_executed=True)
def test_live_migration_handle_pause_on_finish(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in case of job type VIR_DOMAIN_JOB_NONE and finish_event is
# ready
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="completed",
scheduled_action="pause",
scheduled_action_executed=False)
def test_live_migration_handle_pause_on_cancel(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in case of job type VIR_DOMAIN_JOB_CANCELLED
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
current_mig_status="cancelled",
expected_mig_status='cancelled',
scheduled_action="pause",
scheduled_action_executed=False)
def test_live_migration_handle_pause_on_failure(self):
# A normal sequence where see all the normal job states, and pause
# scheduled in case of job type VIR_DOMAIN_JOB_FAILED
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_FAILED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
scheduled_action="pause",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_normal(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# switch scheduled in between VIR_DOMAIN_JOB_UNBOUNDED
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="running",
scheduled_action="postcopy_switch",
scheduled_action_executed=True)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_start(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# switch scheduled in case of job type VIR_DOMAIN_JOB_NONE and
# finish_event is not ready yet
mock_postcopy_enabled.return_value = True
domain_info_records = [
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="preparing",
scheduled_action="postcopy_switch",
scheduled_action_executed=True)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_finish(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# switch scheduled in case of job type VIR_DOMAIN_JOB_NONE and
# finish_event is ready
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="completed",
scheduled_action="postcopy_switch",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_cancel(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# scheduled in case of job type VIR_DOMAIN_JOB_CANCELLED
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
current_mig_status="cancelled",
expected_mig_status='cancelled',
scheduled_action="postcopy_switch",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_pause_on_postcopy(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and pause
# scheduled after migration switched to postcopy
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="running (post-copy)",
scheduled_action="pause",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_postcopy(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and pause
# scheduled after migration switched to postcopy
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
current_mig_status="running (post-copy)",
scheduled_action="postcopy_switch",
scheduled_action_executed=False)
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_handle_postcopy_on_failure(self,
mock_postcopy_enabled):
# A normal sequence where see all the normal job states, and postcopy
# scheduled in case of job type VIR_DOMAIN_JOB_FAILED
mock_postcopy_enabled.return_value = True
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
"force_complete",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_FAILED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
scheduled_action="postcopy_switch",
scheduled_action_executed=False)
def test_live_migration_monitor_success_race(self):
# A normalish sequence but we're too slow to see the
# completed job state
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS)
def test_live_migration_monitor_failed(self):
# A failed sequence where we see all the expected events
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_FAILED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE)
def test_live_migration_monitor_failed_race(self):
# A failed sequence where we are too slow to see the
# failed event
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE)
def test_live_migration_monitor_cancelled(self):
# A cancelled sequence where we see all the events
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_FAILURE,
expected_mig_status='cancelled')
@mock.patch.object(fakelibvirt.virDomain, "migrateSetMaxDowntime")
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_migration_downtime_steps")
def test_live_migration_monitor_downtime(self, mock_downtime_steps,
mock_set_downtime):
self.flags(live_migration_completion_timeout=1000000,
live_migration_progress_timeout=1000000,
group='libvirt')
# We've setup 4 fake downtime steps - first value is the
# time delay, second is the downtime value
downtime_steps = [
(90, 10),
(180, 50),
(270, 200),
(500, 300),
]
mock_downtime_steps.return_value = downtime_steps
# Each one of these fake times is used for time.time()
# when a new domain_info_records entry is consumed.
# Times are chosen so that only the first 3 downtime
# steps are needed.
fake_times = [0, 1, 30, 95, 150, 200, 300]
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records,
fake_times, self.EXPECT_SUCCESS)
mock_set_downtime.assert_has_calls([mock.call(10),
mock.call(50),
mock.call(200)])
def test_live_migration_monitor_completion(self):
self.flags(live_migration_completion_timeout=100,
live_migration_progress_timeout=1000000,
group='libvirt')
# Each one of these fake times is used for time.time()
# when a new domain_info_records entry is consumed.
fake_times = [0, 40, 80, 120, 160, 200, 240, 280, 320]
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records,
fake_times, self.EXPECT_ABORT,
expected_mig_status='cancelled')
def test_live_migration_monitor_progress(self):
self.flags(live_migration_completion_timeout=1000000,
live_migration_progress_timeout=150,
group='libvirt')
# Each one of these fake times is used for time.time()
# when a new domain_info_records entry is consumed.
fake_times = [0, 40, 80, 120, 160, 200, 240, 280, 320]
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED),
]
self._test_live_migration_monitoring(domain_info_records,
fake_times, self.EXPECT_ABORT,
expected_mig_status='cancelled')
def test_live_migration_monitor_progress_zero_data_remaining(self):
self.flags(live_migration_completion_timeout=1000000,
live_migration_progress_timeout=150,
group='libvirt')
# Each one of these fake times is used for time.time()
# when a new domain_info_records entry is consumed.
fake_times = [0, 40, 80, 120, 160, 200, 240, 280, 320]
# A normal sequence where see all the normal job states
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=0),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=90),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=70),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=50),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=30),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=10),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED, data_remaining=0),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_FAILED),
]
self._test_live_migration_monitoring(domain_info_records,
fake_times, self.EXPECT_FAILURE)
def test_live_migration_downtime_steps(self):
self.flags(live_migration_downtime=400, group='libvirt')
self.flags(live_migration_downtime_steps=10, group='libvirt')
self.flags(live_migration_downtime_delay=30, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
steps = drvr._migration_downtime_steps(3.0)
self.assertEqual([
(0, 37),
(90, 38),
(180, 39),
(270, 42),
(360, 46),
(450, 55),
(540, 70),
(630, 98),
(720, 148),
(810, 238),
(900, 400),
], list(steps))
@mock.patch('nova.virt.libvirt.migration.should_switch_to_postcopy')
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_is_post_copy_enabled")
def test_live_migration_monitor_postcopy_switch(self,
mock_postcopy_enabled, mock_should_switch):
# A normal sequence where migration is switched to postcopy mode
mock_postcopy_enabled.return_value = True
switch_values = [False, False, True]
mock_should_switch.return_value = switch_values
domain_info_records = [
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_NONE),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED),
"thread-finish",
"domain-stop",
libvirt_guest.JobInfo(
type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED),
]
self._test_live_migration_monitoring(domain_info_records, [],
self.EXPECT_SUCCESS,
expected_switch=True)
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(utils, "spawn")
@mock.patch.object(libvirt_driver.LibvirtDriver, "_live_migration_monitor")
@mock.patch.object(host.Host, "get_guest")
@mock.patch.object(fakelibvirt.Connection, "_mark_running")
@mock.patch.object(libvirt_driver.LibvirtDriver,
"_live_migration_copy_disk_paths")
def test_live_migration_main(self, mock_copy_disk_path, mock_running,
mock_guest, mock_monitor, mock_thread,
mock_conn):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
dom = fakelibvirt.Domain(drvr._get_connection(),
"<domain><name>demo</name></domain>", True)
guest = libvirt_guest.Guest(dom)
migrate_data = objects.LibvirtLiveMigrateData(block_migration=True)
disks_to_copy = (['/some/path/one', '/test/path/two'],
['vda', 'vdb'])
mock_copy_disk_path.return_value = disks_to_copy
mock_guest.return_value = guest
def fake_post():
pass
def fake_recover():
pass
drvr._live_migration(self.context, instance, "fakehost",
fake_post, fake_recover, True,
migrate_data)
mock_copy_disk_path.assert_called_once_with(self.context, instance,
guest)
class AnyEventletEvent(object):
def __eq__(self, other):
return type(other) == eventlet.event.Event
mock_thread.assert_called_once_with(
drvr._live_migration_operation,
self.context, instance, "fakehost", True,
migrate_data, guest, disks_to_copy[1])
mock_monitor.assert_called_once_with(
self.context, instance, guest, "fakehost",
fake_post, fake_recover, True,
migrate_data, AnyEventletEvent(), disks_to_copy[0])
def _do_test_create_images_and_backing(self, disk_type):
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(drvr, '_fetch_instance_kernel_ramdisk')
self.mox.StubOutWithMock(libvirt_driver.libvirt_utils, 'create_image')
disk_info = {'path': 'foo', 'type': disk_type,
'disk_size': 1 * 1024 ** 3,
'virt_disk_size': 20 * 1024 ** 3,
'backing_file': None}
libvirt_driver.libvirt_utils.create_image(
disk_info['type'], mox.IgnoreArg(), disk_info['virt_disk_size'])
drvr._fetch_instance_kernel_ramdisk(self.context, instance,
fallback_from_host=None)
self.mox.ReplayAll()
self.stub_out('os.path.exists', lambda *args: False)
drvr._create_images_and_backing(self.context, instance,
"/fake/instance/dir", [disk_info])
def test_create_images_and_backing_qcow2(self):
self._do_test_create_images_and_backing('qcow2')
def test_create_images_and_backing_raw(self):
self._do_test_create_images_and_backing('raw')
def test_create_images_and_backing_images_not_exist_no_fallback(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.test_instance.update({'user_id': 'fake-user',
'os_type': None,
'project_id': 'fake-project'})
instance = objects.Instance(**self.test_instance)
backing_file = imagecache.get_cache_fname(instance.image_ref)
disk_info = [
{u'backing_file': backing_file,
u'disk_size': 10747904,
u'path': u'disk_path',
u'type': u'qcow2',
u'virt_disk_size': 25165824}]
with mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image',
side_effect=exception.ImageNotFound(
image_id="fake_id")):
self.assertRaises(exception.ImageNotFound,
conn._create_images_and_backing,
self.context, instance,
"/fake/instance/dir", disk_info)
def test_create_images_and_backing_images_not_exist_fallback(self):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
base_dir = os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name)
self.test_instance.update({'user_id': 'fake-user',
'os_type': None,
'kernel_id': uuids.kernel_id,
'ramdisk_id': uuids.ramdisk_id,
'project_id': 'fake-project'})
instance = objects.Instance(**self.test_instance)
backing_file = imagecache.get_cache_fname(instance.image_ref)
disk_info = [
{u'backing_file': backing_file,
u'disk_size': 10747904,
u'path': u'disk_path',
u'type': u'qcow2',
u'virt_disk_size': 25165824}]
with test.nested(
mock.patch.object(libvirt_driver.libvirt_utils, 'copy_image'),
mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image',
side_effect=exception.ImageNotFound(
image_id=uuids.fake_id)),
) as (copy_image_mock, fetch_image_mock):
conn._create_images_and_backing(self.context, instance,
"/fake/instance/dir", disk_info,
fallback_from_host="fake_host")
backfile_path = os.path.join(base_dir, backing_file)
kernel_path = os.path.join(CONF.instances_path,
self.test_instance['uuid'],
'kernel')
ramdisk_path = os.path.join(CONF.instances_path,
self.test_instance['uuid'],
'ramdisk')
copy_image_mock.assert_has_calls([
mock.call(dest=backfile_path, src=backfile_path,
host='fake_host', receive=True),
mock.call(dest=kernel_path, src=kernel_path,
host='fake_host', receive=True),
mock.call(dest=ramdisk_path, src=ramdisk_path,
host='fake_host', receive=True)
])
fetch_image_mock.assert_has_calls([
mock.call(context=self.context,
target=backfile_path,
image_id=self.test_instance['image_ref']),
mock.call(self.context, kernel_path, instance.kernel_id),
mock.call(self.context, ramdisk_path, instance.ramdisk_id)
])
@mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image')
def test_create_images_and_backing_images_exist(self, mock_fetch_image):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.test_instance.update({'user_id': 'fake-user',
'os_type': None,
'kernel_id': 'fake_kernel_id',
'ramdisk_id': 'fake_ramdisk_id',
'project_id': 'fake-project'})
instance = objects.Instance(**self.test_instance)
disk_info = [
{u'backing_file': imagecache.get_cache_fname(instance.image_ref),
u'disk_size': 10747904,
u'path': u'disk_path',
u'type': u'qcow2',
u'virt_disk_size': 25165824}]
with test.nested(
mock.patch.object(imagebackend.Image, 'get_disk_size'),
mock.patch.object(os.path, 'exists', return_value=True)
):
conn._create_images_and_backing(self.context, instance,
'/fake/instance/dir', disk_info)
self.assertFalse(mock_fetch_image.called)
def test_create_images_and_backing_ephemeral_gets_created(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
base_dir = os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name)
instance = objects.Instance(**self.test_instance)
disk_info_byname = fake_disk_info_byname(instance)
disk_info_byname['disk.local']['backing_file'] = 'ephemeral_foo'
disk_info_byname['disk.local']['virt_disk_size'] = 1 * units.Gi
disk_info = disk_info_byname.values()
with test.nested(
mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image'),
mock.patch.object(drvr, '_create_ephemeral'),
mock.patch.object(imagebackend.Image, 'verify_base_size'),
mock.patch.object(imagebackend.Image, 'get_disk_size')
) as (fetch_image_mock, create_ephemeral_mock, verify_base_size_mock,
disk_size_mock):
drvr._create_images_and_backing(self.context, instance,
CONF.instances_path, disk_info)
self.assertEqual(len(create_ephemeral_mock.call_args_list), 1)
root_backing, ephemeral_backing = [
os.path.join(base_dir, name)
for name in (disk_info_byname['disk']['backing_file'],
'ephemeral_foo')
]
m_args, m_kwargs = create_ephemeral_mock.call_args_list[0]
self.assertEqual(ephemeral_backing, m_kwargs['target'])
self.assertEqual(len(fetch_image_mock.call_args_list), 1)
m_args, m_kwargs = fetch_image_mock.call_args_list[0]
self.assertEqual(root_backing, m_kwargs['target'])
verify_base_size_mock.assert_has_calls([
mock.call(root_backing, instance.flavor.root_gb * units.Gi),
mock.call(ephemeral_backing, 1 * units.Gi)
])
def test_create_images_and_backing_disk_info_none(self):
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_backend = self.useFixture(fake_imagebackend.ImageBackendFixture())
drvr._create_images_and_backing(self.context, instance,
"/fake/instance/dir", None)
# Assert that we did nothing
self.assertEqual({}, fake_backend.created_disks)
def _generate_target_ret(self, target_connect_addr=None):
target_ret = {
'graphics_listen_addrs': {'spice': '127.0.0.1', 'vnc': '127.0.0.1'},
'target_connect_addr': target_connect_addr,
'serial_listen_addr': '127.0.0.1',
'volume': {
'12345': {'connection_info': {u'data': {'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'},
'serial': '12345'},
'disk_info': {'bus': 'scsi',
'dev': 'sda',
'type': 'disk'}},
'67890': {'connection_info': {u'data': {'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'},
'serial': '67890'},
'disk_info': {'bus': 'scsi',
'dev': 'sdb',
'type': 'disk'}}}}
return target_ret
def test_pre_live_migration_works_correctly_mocked(self):
self._test_pre_live_migration_works_correctly_mocked()
def test_pre_live_migration_with_transport_ip(self):
self.flags(live_migration_inbound_addr='127.0.0.2',
group='libvirt')
target_ret = self._generate_target_ret('127.0.0.2')
self._test_pre_live_migration_works_correctly_mocked(target_ret)
def _test_pre_live_migration_works_correctly_mocked(self,
target_ret=None):
# Creating testdata
vol = {'block_device_mapping': [
{'connection_info': {'serial': '12345', u'data':
{'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'}},
'mount_device': '/dev/sda'},
{'connection_info': {'serial': '67890', u'data':
{'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}},
'mount_device': '/dev/sdb'}]}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
class FakeNetworkInfo(object):
def fixed_ips(self):
return ["test_ip_addr"]
def fake_none(*args, **kwargs):
return
self.stubs.Set(drvr, '_create_images_and_backing', fake_none)
instance = objects.Instance(**self.test_instance)
c = context.get_admin_context()
nw_info = FakeNetworkInfo()
# Creating mocks
self.mox.StubOutWithMock(driver, "block_device_info_get_mapping")
driver.block_device_info_get_mapping(vol
).AndReturn(vol['block_device_mapping'])
self.mox.StubOutWithMock(drvr, "_connect_volume")
for v in vol['block_device_mapping']:
disk_info = {
'bus': "scsi",
'dev': v['mount_device'].rpartition("/")[2],
'type': "disk"
}
drvr._connect_volume(v['connection_info'],
disk_info)
self.mox.StubOutWithMock(drvr, 'plug_vifs')
drvr.plug_vifs(mox.IsA(instance), nw_info)
self.mox.ReplayAll()
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
block_migration=False,
instance_relative_path='foo',
is_shared_block_storage=False,
is_shared_instance_path=False,
)
result = drvr.pre_live_migration(
c, instance, vol, nw_info, None,
migrate_data=migrate_data)
if not target_ret:
target_ret = self._generate_target_ret()
self.assertEqual(
result.to_legacy_dict(
pre_migration_result=True)['pre_live_migration_result'],
target_ret)
@mock.patch.object(os, 'mkdir')
@mock.patch('nova.virt.libvirt.utils.get_instance_path_at_destination')
@mock.patch('nova.virt.libvirt.driver.remotefs.'
'RemoteFilesystem.copy_file')
@mock.patch('nova.virt.driver.block_device_info_get_mapping')
@mock.patch('nova.virt.configdrive.required_by', return_value=True)
def test_pre_live_migration_block_with_config_drive_success(
self, mock_required_by, block_device_info_get_mapping,
mock_copy_file, mock_get_instance_path, mock_mkdir):
self.flags(config_drive_format='iso9660')
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
fake_instance_path = os.path.join(cfg.CONF.instances_path,
'/fake_instance_uuid')
mock_get_instance_path.return_value = fake_instance_path
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
migrate_data = objects.LibvirtLiveMigrateData()
migrate_data.is_shared_instance_path = False
migrate_data.is_shared_block_storage = False
migrate_data.block_migration = True
migrate_data.instance_relative_path = 'foo'
src = "%s:%s/disk.config" % (instance.host, fake_instance_path)
result = drvr.pre_live_migration(
self.context, instance, vol, [], None, migrate_data)
block_device_info_get_mapping.assert_called_once_with(
{'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}
]}
)
mock_copy_file.assert_called_once_with(src, fake_instance_path)
migrate_data.graphics_listen_addrs_vnc = '127.0.0.1'
migrate_data.graphics_listen_addrs_spice = '127.0.0.1'
migrate_data.serial_listen_addr = '127.0.0.1'
self.assertEqual(migrate_data, result)
@mock.patch('nova.virt.driver.block_device_info_get_mapping',
return_value=())
def test_pre_live_migration_block_with_config_drive_mocked_with_vfat(
self, block_device_info_get_mapping):
self.flags(config_drive_format='vfat')
# Creating testdata
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
instance.config_drive = 'True'
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_instance_path=False,
is_shared_block_storage=False,
block_migration=False,
instance_relative_path='foo',
)
res_data = drvr.pre_live_migration(
self.context, instance, vol, [], None, migrate_data)
res_data = res_data.to_legacy_dict(pre_migration_result=True)
block_device_info_get_mapping.assert_called_once_with(
{'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sda'},
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}
]}
)
self.assertEqual({'graphics_listen_addrs': {'spice': '127.0.0.1',
'vnc': '127.0.0.1'},
'target_connect_addr': None,
'serial_listen_addr': '127.0.0.1',
'volume': {}}, res_data['pre_live_migration_result'])
def test_pre_live_migration_vol_backed_works_correctly_mocked(self):
# Creating testdata, using temp dir.
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
vol = {'block_device_mapping': [
{'connection_info': {'serial': '12345', u'data':
{'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'}},
'mount_device': '/dev/sda'},
{'connection_info': {'serial': '67890', u'data':
{'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}},
'mount_device': '/dev/sdb'}]}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
def fake_none(*args, **kwargs):
return
self.stubs.Set(drvr, '_create_images_and_backing', fake_none)
class FakeNetworkInfo(object):
def fixed_ips(self):
return ["test_ip_addr"]
inst_ref = objects.Instance(**self.test_instance)
c = context.get_admin_context()
nw_info = FakeNetworkInfo()
# Creating mocks
self.mox.StubOutWithMock(drvr, "_connect_volume")
for v in vol['block_device_mapping']:
disk_info = {
'bus': "scsi",
'dev': v['mount_device'].rpartition("/")[2],
'type': "disk"
}
drvr._connect_volume(v['connection_info'],
disk_info)
self.mox.StubOutWithMock(drvr, 'plug_vifs')
drvr.plug_vifs(mox.IsA(inst_ref), nw_info)
self.mox.ReplayAll()
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_instance_path=False,
is_shared_block_storage=False,
is_volume_backed=True,
block_migration=False,
instance_relative_path=inst_ref['name'],
disk_over_commit=False,
disk_available_mb=123,
image_type='qcow2',
filename='foo',
)
ret = drvr.pre_live_migration(c, inst_ref, vol, nw_info, None,
migrate_data)
target_ret = {
'graphics_listen_addrs': {'spice': '127.0.0.1',
'vnc': '127.0.0.1'},
'target_connect_addr': None,
'serial_listen_addr': '127.0.0.1',
'volume': {
'12345': {'connection_info': {u'data': {'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'},
'serial': '12345'},
'disk_info': {'bus': 'scsi',
'dev': 'sda',
'type': 'disk'}},
'67890': {'connection_info': {u'data': {'device_path':
u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'},
'serial': '67890'},
'disk_info': {'bus': 'scsi',
'dev': 'sdb',
'type': 'disk'}}}}
self.assertEqual(
ret.to_legacy_dict(True)['pre_live_migration_result'],
target_ret)
self.assertTrue(os.path.exists('%s/%s/' % (tmpdir,
inst_ref['name'])))
def test_pre_live_migration_plug_vifs_retry_fails(self):
self.flags(live_migration_retry_count=3)
instance = objects.Instance(**self.test_instance)
def fake_plug_vifs(instance, network_info):
raise processutils.ProcessExecutionError()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(eventlet.greenthread, 'sleep',
lambda x: eventlet.sleep(0))
disk_info_json = jsonutils.dumps({})
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=True,
is_shared_instance_path=True,
block_migration=False,
)
self.assertRaises(processutils.ProcessExecutionError,
drvr.pre_live_migration,
self.context, instance, block_device_info=None,
network_info=[], disk_info=disk_info_json,
migrate_data=migrate_data)
def test_pre_live_migration_plug_vifs_retry_works(self):
self.flags(live_migration_retry_count=3)
called = {'count': 0}
instance = objects.Instance(**self.test_instance)
def fake_plug_vifs(instance, network_info):
called['count'] += 1
if called['count'] < CONF.live_migration_retry_count:
raise processutils.ProcessExecutionError()
else:
return
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(eventlet.greenthread, 'sleep',
lambda x: eventlet.sleep(0))
disk_info_json = jsonutils.dumps({})
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=True,
is_shared_instance_path=True,
block_migration=False,
)
drvr.pre_live_migration(self.context, instance, block_device_info=None,
network_info=[], disk_info=disk_info_json,
migrate_data=migrate_data)
def test_pre_live_migration_image_not_created_with_shared_storage(self):
migrate_data_set = [{'is_shared_block_storage': False,
'is_shared_instance_path': True,
'is_volume_backed': False,
'filename': 'foo',
'instance_relative_path': 'bar',
'disk_over_commit': False,
'disk_available_mb': 123,
'image_type': 'qcow2',
'block_migration': False},
{'is_shared_block_storage': True,
'is_shared_instance_path': True,
'is_volume_backed': False,
'filename': 'foo',
'instance_relative_path': 'bar',
'disk_over_commit': False,
'disk_available_mb': 123,
'image_type': 'qcow2',
'block_migration': False},
{'is_shared_block_storage': False,
'is_shared_instance_path': True,
'is_volume_backed': False,
'filename': 'foo',
'instance_relative_path': 'bar',
'disk_over_commit': False,
'disk_available_mb': 123,
'image_type': 'qcow2',
'block_migration': True}]
def _to_obj(d):
return migrate_data_obj.LibvirtLiveMigrateData(**d)
migrate_data_set = map(_to_obj, migrate_data_set)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
# creating mocks
with test.nested(
mock.patch.object(drvr,
'_create_images_and_backing'),
mock.patch.object(drvr,
'ensure_filtering_rules_for_instance'),
mock.patch.object(drvr, 'plug_vifs'),
) as (
create_image_mock,
rules_mock,
plug_mock,
):
disk_info_json = jsonutils.dumps({})
for migrate_data in migrate_data_set:
res = drvr.pre_live_migration(self.context, instance,
block_device_info=None,
network_info=[],
disk_info=disk_info_json,
migrate_data=migrate_data)
self.assertFalse(create_image_mock.called)
self.assertIsInstance(res,
objects.LibvirtLiveMigrateData)
def test_pre_live_migration_with_not_shared_instance_path(self):
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=False,
is_shared_instance_path=False,
block_migration=False,
instance_relative_path='foo',
)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
def check_instance_dir(context, instance,
instance_dir, disk_info,
fallback_from_host=False):
self.assertTrue(instance_dir)
# creating mocks
with test.nested(
mock.patch.object(drvr,
'_create_images_and_backing',
side_effect=check_instance_dir),
mock.patch.object(drvr,
'ensure_filtering_rules_for_instance'),
mock.patch.object(drvr, 'plug_vifs'),
) as (
create_image_mock,
rules_mock,
plug_mock,
):
disk_info_json = jsonutils.dumps({})
res = drvr.pre_live_migration(self.context, instance,
block_device_info=None,
network_info=[],
disk_info=disk_info_json,
migrate_data=migrate_data)
create_image_mock.assert_has_calls(
[mock.call(self.context, instance, mock.ANY, {},
fallback_from_host=instance.host)])
self.assertIsInstance(res, objects.LibvirtLiveMigrateData)
def test_pre_live_migration_recreate_disk_info(self):
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=False,
is_shared_instance_path=False,
block_migration=True,
instance_relative_path='/some/path/',
)
disk_info = [{'disk_size': 5368709120, 'type': 'raw',
'virt_disk_size': 5368709120,
'path': '/some/path/disk',
'backing_file': '', 'over_committed_disk_size': 0},
{'disk_size': 1073741824, 'type': 'raw',
'virt_disk_size': 1073741824,
'path': '/some/path/disk.eph0',
'backing_file': '', 'over_committed_disk_size': 0}]
image_disk_info = {'/some/path/disk': 'raw',
'/some/path/disk.eph0': 'raw'}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
instance_path = os.path.dirname(disk_info[0]['path'])
disk_info_path = os.path.join(instance_path, 'disk.info')
with test.nested(
mock.patch.object(os, 'mkdir'),
mock.patch.object(fake_libvirt_utils, 'write_to_file'),
mock.patch.object(drvr, '_create_images_and_backing')
) as (
mkdir, write_to_file, create_images_and_backing
):
drvr.pre_live_migration(self.context, instance,
block_device_info=None,
network_info=[],
disk_info=jsonutils.dumps(disk_info),
migrate_data=migrate_data)
write_to_file.assert_called_with(disk_info_path,
jsonutils.dumps(image_disk_info))
def test_pre_live_migration_with_perf_events(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._supported_perf_events = ['cmt']
migrate_data = migrate_data_obj.LibvirtLiveMigrateData(
is_shared_block_storage=False,
is_shared_instance_path=False,
block_migration=False,
instance_relative_path='foo',
)
instance = objects.Instance(**self.test_instance)
res = drvr.pre_live_migration(self.context, instance,
block_device_info=None,
network_info=[],
disk_info=None,
migrate_data=migrate_data)
self.assertEqual(['cmt'], res.supported_perf_events)
def test_get_instance_disk_info_works_correctly(self):
# Test data
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance.name:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi
fake_libvirt_utils.disk_sizes['/test/disk.local'] = 20 * units.Gi
fake_libvirt_utils.disk_backing_files['/test/disk.local'] = 'file'
self.mox.StubOutWithMock(os.path, "getsize")
os.path.getsize('/test/disk').AndReturn((10737418240))
os.path.getsize('/test/disk.local').AndReturn((3328599655))
ret = ("image: /test/disk\n"
"file format: raw\n"
"virtual size: 20G (21474836480 bytes)\n"
"disk size: 3.1G\n"
"cluster_size: 2097152\n"
"backing file: /test/dummy (actual path: /backing/file)\n")
self.mox.StubOutWithMock(os.path, "exists")
os.path.exists('/test/disk.local').AndReturn(True)
self.mox.StubOutWithMock(utils, "execute")
utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
'/test/disk.local', prlimit = images.QEMU_IMG_LIMITS,
).AndReturn((ret, ''))
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = drvr.get_instance_disk_info(instance)
info = jsonutils.loads(info)
self.assertEqual(info[0]['type'], 'raw')
self.assertEqual(info[0]['path'], '/test/disk')
self.assertEqual(info[0]['disk_size'], 10737418240)
self.assertEqual(info[0]['backing_file'], "")
self.assertEqual(info[0]['over_committed_disk_size'], 0)
self.assertEqual(info[1]['type'], 'qcow2')
self.assertEqual(info[1]['path'], '/test/disk.local')
self.assertEqual(info[1]['virt_disk_size'], 21474836480)
self.assertEqual(info[1]['backing_file'], "file")
self.assertEqual(info[1]['over_committed_disk_size'], 18146236825)
def test_post_live_migration(self):
vol = {'block_device_mapping': [
{'connection_info': {
'data': {'multipath_id': 'dummy1'},
'serial': 'fake_serial1'},
'mount_device': '/dev/sda',
},
{'connection_info': {
'data': {},
'serial': 'fake_serial2'},
'mount_device': '/dev/sdb', }]}
def fake_initialize_connection(context, volume_id, connector):
return {'data': {}}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_connector = {'host': 'fake'}
inst_ref = {'id': 'foo'}
cntx = context.get_admin_context()
# Set up the mock expectations
with test.nested(
mock.patch.object(driver, 'block_device_info_get_mapping',
return_value=vol['block_device_mapping']),
mock.patch.object(drvr, "get_volume_connector",
return_value=fake_connector),
mock.patch.object(drvr._volume_api, "initialize_connection",
side_effect=fake_initialize_connection),
mock.patch.object(drvr, '_disconnect_volume')
) as (block_device_info_get_mapping, get_volume_connector,
initialize_connection, _disconnect_volume):
drvr.post_live_migration(cntx, inst_ref, vol)
block_device_info_get_mapping.assert_has_calls([
mock.call(vol)])
get_volume_connector.assert_has_calls([
mock.call(inst_ref)])
_disconnect_volume.assert_has_calls([
mock.call({'data': {'multipath_id': 'dummy1'}}, 'sda'),
mock.call({'data': {}}, 'sdb')])
def test_get_instance_disk_info_excludes_volumes(self):
# Test data
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/fake/path/to/volume1'/>"
"<target dev='vdc' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/fake/path/to/volume2'/>"
"<target dev='vdd' bus='virtio'/></disk>"
"</devices></domain>")
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance.name:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi
fake_libvirt_utils.disk_sizes['/test/disk.local'] = 20 * units.Gi
fake_libvirt_utils.disk_backing_files['/test/disk.local'] = 'file'
self.mox.StubOutWithMock(os.path, "getsize")
os.path.getsize('/test/disk').AndReturn((10737418240))
os.path.getsize('/test/disk.local').AndReturn((3328599655))
ret = ("image: /test/disk\n"
"file format: raw\n"
"virtual size: 20G (21474836480 bytes)\n"
"disk size: 3.1G\n"
"cluster_size: 2097152\n"
"backing file: /test/dummy (actual path: /backing/file)\n")
self.mox.StubOutWithMock(os.path, "exists")
os.path.exists('/test/disk.local').AndReturn(True)
self.mox.StubOutWithMock(utils, "execute")
utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info',
'/test/disk.local', prlimit = images.QEMU_IMG_LIMITS,
).AndReturn((ret, ''))
self.mox.ReplayAll()
conn_info = {'driver_volume_type': 'fake'}
info = {'block_device_mapping': [
{'connection_info': conn_info, 'mount_device': '/dev/vdc'},
{'connection_info': conn_info, 'mount_device': '/dev/vdd'}]}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = drvr.get_instance_disk_info(instance,
block_device_info=info)
info = jsonutils.loads(info)
self.assertEqual(info[0]['type'], 'raw')
self.assertEqual(info[0]['path'], '/test/disk')
self.assertEqual(info[0]['disk_size'], 10737418240)
self.assertEqual(info[0]['backing_file'], "")
self.assertEqual(info[0]['over_committed_disk_size'], 0)
self.assertEqual(info[1]['type'], 'qcow2')
self.assertEqual(info[1]['path'], '/test/disk.local')
self.assertEqual(info[1]['virt_disk_size'], 21474836480)
self.assertEqual(info[1]['backing_file'], "file")
self.assertEqual(info[1]['over_committed_disk_size'], 18146236825)
def test_get_instance_disk_info_no_bdinfo_passed(self):
# NOTE(ndipanov): _get_disk_overcomitted_size_total calls this method
# without access to Nova's block device information. We want to make
# sure that we guess volumes mostly correctly in that case as well
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='block'><driver name='qemu' type='raw'/>"
"<source file='/fake/path/to/volume1'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
# Preparing mocks
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance.name:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi
self.mox.StubOutWithMock(os.path, "getsize")
os.path.getsize('/test/disk').AndReturn((10737418240))
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = drvr.get_instance_disk_info(instance)
info = jsonutils.loads(info)
self.assertEqual(1, len(info))
self.assertEqual(info[0]['type'], 'raw')
self.assertEqual(info[0]['path'], '/test/disk')
self.assertEqual(info[0]['disk_size'], 10737418240)
self.assertEqual(info[0]['backing_file'], "")
self.assertEqual(info[0]['over_committed_disk_size'], 0)
def test_spawn_with_network_info(self):
# Preparing mocks
def fake_none(*args, **kwargs):
return
def fake_getLibVersion():
return fakelibvirt.FAKE_LIBVIRT_VERSION
def fake_getCapabilities():
return """
<capabilities>
<host>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<cpu>
<arch>x86_64</arch>
<model>Penryn</model>
<vendor>Intel</vendor>
<topology sockets='1' cores='2' threads='1'/>
<feature name='xtpr'/>
</cpu>
</host>
</capabilities>
"""
def fake_baselineCPU(cpu, flag):
return """<cpu mode='custom' match='exact'>
<model fallback='allow'>Penryn</model>
<vendor>Intel</vendor>
<feature policy='require' name='xtpr'/>
</cpu>
"""
# _fake_network_info must be called before create_fake_libvirt_mock(),
# as _fake_network_info calls importutils.import_class() and
# create_fake_libvirt_mock() mocks importutils.import_class().
network_info = _fake_network_info(self, 1)
self.create_fake_libvirt_mock(getLibVersion=fake_getLibVersion,
getCapabilities=fake_getCapabilities,
getVersion=lambda: 1005001,
baselineCPU=fake_baselineCPU)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456 # we send an int to test sha1 call
instance = objects.Instance(**instance_ref)
instance.config_drive = ''
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver,
'_build_device_metadata')
libvirt_driver.LibvirtDriver._build_device_metadata(self.context,
instance)
# Mock out the get_info method of the LibvirtDriver so that the polling
# in the spawn method of the LibvirtDriver returns immediately
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'get_info')
libvirt_driver.LibvirtDriver.get_info(instance
).AndReturn(hardware.InstanceInfo(state=power_state.RUNNING))
# Start test
self.mox.ReplayAll()
with mock.patch('nova.virt.libvirt.driver.libvirt') as old_virt:
del old_virt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr.firewall_driver,
'setup_basic_filtering',
fake_none)
self.stubs.Set(drvr.firewall_driver,
'prepare_instance_filter',
fake_none)
self.stubs.Set(imagebackend.Image,
'cache',
fake_none)
drvr.spawn(self.context, instance, image_meta, [], 'herp',
network_info=network_info)
path = os.path.join(CONF.instances_path, instance['name'])
if os.path.isdir(path):
shutil.rmtree(path)
path = os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name)
if os.path.isdir(path):
shutil.rmtree(os.path.join(CONF.instances_path,
CONF.image_cache_subdirectory_name))
# Methods called directly by spawn()
@mock.patch.object(libvirt_driver.LibvirtDriver, '_get_guest_xml')
@mock.patch.object(libvirt_driver.LibvirtDriver,
'_create_domain_and_network')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info')
# Methods called by _create_configdrive via post_xml_callback
@mock.patch('nova.virt.configdrive.ConfigDriveBuilder._make_iso9660')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_build_device_metadata')
@mock.patch.object(instance_metadata, 'InstanceMetadata')
def test_spawn_with_config_drive(self, mock_instance_metadata,
mock_build_device_metadata,
mock_mkisofs, mock_get_info,
mock_create_domain_and_network,
mock_get_guest_xml):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
instance.config_drive = 'True'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
instance_info = hardware.InstanceInfo(state=power_state.RUNNING)
mock_build_device_metadata.return_value = None
def fake_create_domain_and_network(
context, xml, instance, network_info, disk_info,
block_device_info=None, power_on=True, reboot=False,
vifs_already_plugged=False, post_xml_callback=None):
# The config disk should be created by this callback, so we need
# to execute it.
post_xml_callback()
fake_backend = self.useFixture(
fake_imagebackend.ImageBackendFixture(exists=lambda _: False))
mock_get_info.return_value = instance_info
mock_create_domain_and_network.side_effect = \
fake_create_domain_and_network
drvr.spawn(self.context, instance,
image_meta, [], None)
# We should have imported 'disk.config'
config_disk = fake_backend.disks['disk.config']
config_disk.import_file.assert_called_once_with(instance, mock.ANY,
'disk.config')
def test_spawn_without_image_meta(self):
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = objects.Instance(**instance_ref)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
fake_backend = self.useFixture(fake_imagebackend.ImageBackendFixture())
drvr.spawn(self.context, instance, image_meta, [], None)
# We should have created a root disk and an ephemeral disk
self.assertEqual(['disk', 'disk.local'],
sorted(fake_backend.created_disks.keys()))
def test_spawn_from_volume_calls_cache(self):
self.cache_called_for_disk = False
def fake_none(*args, **kwargs):
return
def fake_cache(*args, **kwargs):
if kwargs.get('image_id') == 'my_fake_image':
self.cache_called_for_disk = True
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(imagebackend.Image, 'cache', fake_cache)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
block_device_info = {'root_device_name': '/dev/vda',
'block_device_mapping': [
{'mount_device': 'vda',
'boot_index': 0}
]
}
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
# Volume-backed instance created without image
instance_ref = self.test_instance
instance_ref['image_ref'] = ''
instance_ref['root_device_name'] = '/dev/vda'
instance_ref['uuid'] = uuidutils.generate_uuid()
instance = objects.Instance(**instance_ref)
drvr.spawn(self.context, instance,
image_meta, [], None,
block_device_info=block_device_info)
self.assertFalse(self.cache_called_for_disk)
# Booted from volume but with placeholder image
instance_ref = self.test_instance
instance_ref['image_ref'] = 'my_fake_image'
instance_ref['root_device_name'] = '/dev/vda'
instance_ref['uuid'] = uuidutils.generate_uuid()
instance = objects.Instance(**instance_ref)
drvr.spawn(self.context, instance,
image_meta, [], None,
block_device_info=block_device_info)
self.assertFalse(self.cache_called_for_disk)
# Booted from an image
instance_ref['image_ref'] = 'my_fake_image'
instance_ref['uuid'] = uuidutils.generate_uuid()
instance = objects.Instance(**instance_ref)
drvr.spawn(self.context, instance,
image_meta, [], None)
self.assertTrue(self.cache_called_for_disk)
def test_start_lxc_from_volume(self):
self.flags(virt_type="lxc",
group='libvirt')
def check_setup_container(image, container_dir=None):
self.assertIsInstance(image, imgmodel.LocalBlockImage)
self.assertEqual(image.path, '/dev/path/to/dev')
return '/dev/nbd1'
bdm = {
'guest_format': None,
'boot_index': 0,
'mount_device': '/dev/sda',
'connection_info': {
'driver_volume_type': 'iscsi',
'serial': 'afc1',
'data': {
'access_mode': 'rw',
'target_discovered': False,
'encrypted': False,
'qos_specs': None,
'target_iqn': 'iqn: volume-afc1',
'target_portal': 'ip: 3260',
'volume_id': 'afc1',
'target_lun': 1,
'auth_password': 'uj',
'auth_username': '47',
'auth_method': 'CHAP'
}
},
'disk_bus': 'scsi',
'device_type': 'disk',
'delete_on_termination': False
}
def _connect_volume_side_effect(connection_info, disk_info):
bdm['connection_info']['data']['device_path'] = '/dev/path/to/dev'
def _get(key, opt=None):
return bdm.get(key, opt)
def getitem(key):
return bdm[key]
def setitem(key, val):
bdm[key] = val
bdm_mock = mock.MagicMock()
bdm_mock.__getitem__.side_effect = getitem
bdm_mock.__setitem__.side_effect = setitem
bdm_mock.get = _get
disk_mock = mock.MagicMock()
disk_mock.source_path = '/dev/path/to/dev'
block_device_info = {'block_device_mapping': [bdm_mock],
'root_device_name': '/dev/sda'}
# Volume-backed instance created without image
instance_ref = self.test_instance
instance_ref['image_ref'] = ''
instance_ref['root_device_name'] = '/dev/sda'
instance_ref['ephemeral_gb'] = 0
instance_ref['uuid'] = uuidutils.generate_uuid()
inst_obj = objects.Instance(**instance_ref)
image_meta = objects.ImageMeta.from_dict({})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter'),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, '_connect_volume',
side_effect=_connect_volume_side_effect),
mock.patch.object(drvr, '_get_volume_config',
return_value=disk_mock),
mock.patch.object(drvr, 'get_info',
return_value=hardware.InstanceInfo(
state=power_state.RUNNING)),
mock.patch('nova.virt.disk.api.setup_container',
side_effect=check_setup_container),
mock.patch('nova.virt.disk.api.teardown_container'),
mock.patch.object(objects.Instance, 'save')):
drvr.spawn(self.context, inst_obj, image_meta, [], None,
network_info=[],
block_device_info=block_device_info)
self.assertEqual('/dev/nbd1',
inst_obj.system_metadata.get(
'rootfs_device_name'))
def test_spawn_with_pci_devices(self):
def fake_none(*args, **kwargs):
return None
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
class FakeLibvirtPciDevice(object):
def dettach(self):
return None
def reset(self):
return None
def fake_node_device_lookup_by_name(address):
pattern = ("pci_%(hex)s{4}_%(hex)s{2}_%(hex)s{2}_%(oct)s{1}"
% dict(hex='[\da-f]', oct='[0-8]'))
pattern = re.compile(pattern)
if pattern.match(address) is None:
raise fakelibvirt.libvirtError()
return FakeLibvirtPciDevice()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
mock_connection = mock.MagicMock(
nodeDeviceLookupByName=fake_node_device_lookup_by_name)
instance_ref = self.test_instance
instance_ref['image_ref'] = 'my_fake_image'
instance = objects.Instance(**instance_ref)
instance['pci_devices'] = objects.PciDeviceList(
objects=[objects.PciDevice(address='0000:00:00.0')])
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
self.useFixture(fake_imagebackend.ImageBackendFixture())
with mock.patch.object(drvr, '_get_connection',
return_value=mock_connection):
drvr.spawn(self.context, instance, image_meta, [], None)
def _test_create_image_plain(self, os_type='', filename='', mkfs=False):
gotFiles = []
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = objects.Instance(**instance_ref)
instance['os_type'] = os_type
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
if mkfs:
self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND',
{os_type: 'mkfs.ext4 --label %(fs_label)s %(target)s'})
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
self.useFixture(
fake_imagebackend.ImageBackendFixture(got_files=gotFiles))
drvr._create_image(self.context, instance, disk_info['mapping'])
drvr._get_guest_xml(self.context, instance, None,
disk_info, image_meta)
wantFiles = [
{'filename': '356a192b7913b04c54574d18c28d46e6395428ab',
'size': 10 * units.Gi},
{'filename': filename,
'size': 20 * units.Gi},
]
self.assertEqual(gotFiles, wantFiles)
def test_create_image_plain_os_type_blank(self):
self._test_create_image_plain(os_type='',
filename=self._EPHEMERAL_20_DEFAULT,
mkfs=False)
def test_create_image_plain_os_type_none(self):
self._test_create_image_plain(os_type=None,
filename=self._EPHEMERAL_20_DEFAULT,
mkfs=False)
def test_create_image_plain_os_type_set_no_fs(self):
self._test_create_image_plain(os_type='test',
filename=self._EPHEMERAL_20_DEFAULT,
mkfs=False)
def test_create_image_plain_os_type_set_with_fs(self):
ephemeral_file_name = ('ephemeral_20_%s' % utils.get_hash_str(
'mkfs.ext4 --label %(fs_label)s %(target)s')[:7])
self._test_create_image_plain(os_type='test',
filename=ephemeral_file_name,
mkfs=True)
def test_create_image_initrd(self):
kernel_id = uuids.kernel_id
ramdisk_id = uuids.ramdisk_id
kernel_fname = imagecache.get_cache_fname(kernel_id)
ramdisk_fname = imagecache.get_cache_fname(ramdisk_id)
filename = self._EPHEMERAL_20_DEFAULT
gotFiles = []
instance_ref = self.test_instance
instance_ref['image_ref'] = uuids.instance_id
instance_ref['kernel_id'] = uuids.kernel_id
instance_ref['ramdisk_id'] = uuids.ramdisk_id
instance_ref['os_type'] = 'test'
instance = objects.Instance(**instance_ref)
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_backend = self.useFixture(
fake_imagebackend.ImageBackendFixture(got_files=gotFiles))
with test.nested(
mock.patch.object(driver, '_get_guest_xml'),
mock.patch.object(driver, '_create_domain_and_network'),
mock.patch.object(driver, 'get_info',
return_value=[hardware.InstanceInfo(state=power_state.RUNNING)])
):
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
driver._create_image(self.context, instance, disk_info['mapping'])
# Assert that kernel and ramdisk were fetched with fetch_raw_image
# and no size
for name, disk in six.iteritems(fake_backend.disks):
cache = disk.cache
if name in ('kernel', 'ramdisk'):
cache.assert_called_once_with(
context=self.context, filename=mock.ANY, image_id=mock.ANY,
fetch_func=fake_libvirt_utils.fetch_raw_image)
wantFiles = [
{'filename': kernel_fname,
'size': None},
{'filename': ramdisk_fname,
'size': None},
{'filename': imagecache.get_cache_fname(uuids.instance_id),
'size': 10 * units.Gi},
{'filename': filename,
'size': 20 * units.Gi},
]
self.assertEqual(wantFiles, gotFiles)
def _create_image_helper(self, callback, exists=None, suffix='',
test_create_configdrive=False):
def fake_none(*args, **kwargs):
return
def fake_get_info(instance):
return hardware.InstanceInfo(state=power_state.RUNNING)
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
# NOTE(mikal): use this callback to tweak the instance to match
# what you're trying to test
callback(instance_ref)
instance = objects.Instance(**instance_ref)
# Turn on some swap to exercise that codepath in _create_image
instance.flavor.swap = 500
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr, '_get_guest_xml', fake_none)
self.stubs.Set(drvr, '_create_domain_and_network', fake_none)
self.stubs.Set(drvr, 'get_info', fake_get_info)
self.stubs.Set(instance_metadata, 'InstanceMetadata', fake_none)
self.stubs.Set(nova.virt.configdrive.ConfigDriveBuilder,
'make_drive', fake_none)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
gotFiles = []
imported_files = []
self.useFixture(fake_imagebackend.ImageBackendFixture(
got_files=gotFiles, imported_files=imported_files, exists=exists))
if test_create_configdrive:
drvr._create_configdrive(self.context, instance)
else:
drvr._create_image(self.context, instance, disk_info['mapping'],
suffix=suffix)
drvr._get_guest_xml(self.context, instance, None,
disk_info, image_meta)
return gotFiles, imported_files
def test_create_image_with_swap(self):
def enable_swap(instance_ref):
# Turn on some swap to exercise that codepath in _create_image
instance_ref['system_metadata']['instance_type_swap'] = 500
gotFiles, _ = self._create_image_helper(enable_swap)
wantFiles = [
{'filename': '356a192b7913b04c54574d18c28d46e6395428ab',
'size': 10 * units.Gi},
{'filename': self._EPHEMERAL_20_DEFAULT,
'size': 20 * units.Gi},
{'filename': 'swap_500',
'size': 500 * units.Mi},
]
self.assertEqual(gotFiles, wantFiles)
@mock.patch(
'nova.virt.libvirt.driver.LibvirtDriver._build_device_metadata',
return_value=None)
def test_create_configdrive(self, mock_save):
def enable_configdrive(instance_ref):
instance_ref['config_drive'] = 'true'
# Ensure that we create a config drive and then import it into the
# image backend store
_, imported_files = self._create_image_helper(
enable_configdrive, exists=lambda name: False,
test_create_configdrive=True)
self.assertTrue(imported_files[0][0].endswith('/disk.config'))
self.assertEqual('disk.config', imported_files[0][1])
@mock.patch.object(nova.virt.libvirt.imagebackend.Image, 'cache',
side_effect=exception.ImageNotFound(image_id='fake-id'))
def test_create_image_not_exist_no_fallback(self, mock_cache):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
self.assertRaises(exception.ImageNotFound,
drvr._create_image,
self.context, instance, disk_info['mapping'])
@mock.patch.object(nova.virt.libvirt.imagebackend.Image, 'cache')
def test_create_image_not_exist_fallback(self, mock_cache):
def side_effect(fetch_func, filename, size=None, *args, **kwargs):
def second_call(fetch_func, filename, size=None, *args, **kwargs):
# call copy_from_host ourselves because we mocked image.cache()
fetch_func('fake-target')
# further calls have no side effect
mock_cache.side_effect = None
mock_cache.side_effect = second_call
# raise an error only the first call
raise exception.ImageNotFound(image_id='fake-id')
mock_cache.side_effect = side_effect
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
with mock.patch.object(libvirt_driver.libvirt_utils,
'copy_image') as mock_copy:
drvr._create_image(self.context, instance, disk_info['mapping'],
fallback_from_host='fake-source-host')
mock_copy.assert_called_once_with(src='fake-target',
dest='fake-target',
host='fake-source-host',
receive=True)
@mock.patch.object(nova.virt.libvirt.imagebackend.Image, 'cache')
def test_create_image_resize_snap_backend(self, mock_cache):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
instance.task_state = task_states.RESIZE_FINISH
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
fake_backend = self.useFixture(fake_imagebackend.ImageBackendFixture())
drvr._create_image(self.context, instance, disk_info['mapping'])
# Assert we called create_snap on the root disk
fake_backend.disks['disk'].create_snap.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME)
@mock.patch.object(utils, 'execute')
def test_create_ephemeral_specified_fs(self, mock_exec):
self.flags(default_ephemeral_format='ext3')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True, specified_fs='ext4')
mock_exec.assert_called_once_with('mkfs', '-t', 'ext4', '-F', '-L',
'myVol', '/dev/something',
run_as_root=True)
def test_create_ephemeral_specified_fs_not_valid(self):
CONF.set_override('default_ephemeral_format', 'ext4')
ephemerals = [{'device_type': 'disk',
'disk_bus': 'virtio',
'device_name': '/dev/vdb',
'guest_format': 'dummy',
'size': 1}]
block_device_info = {
'ephemerals': ephemerals}
instance_ref = self.test_instance
instance_ref['image_ref'] = 1
instance = objects.Instance(**instance_ref)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
image_meta = objects.ImageMeta.from_dict({'disk_format': 'raw'})
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta)
disk_info['mapping'].pop('disk.local')
with test.nested(
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr, 'get_info'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(imagebackend.Image, 'verify_base_size'),
mock.patch.object(imagebackend.Image, 'get_disk_size')):
self.assertRaises(exception.InvalidBDMFormat, drvr._create_image,
context, instance, disk_info['mapping'],
block_device_info=block_device_info)
def test_create_ephemeral_default(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkfs', '-t', 'ext4', '-F', '-L', 'myVol',
'/dev/something', run_as_root=True)
self.mox.ReplayAll()
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True)
def test_create_ephemeral_with_conf(self):
CONF.set_override('default_ephemeral_format', 'ext4')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkfs', '-t', 'ext4', '-F', '-L', 'myVol',
'/dev/something', run_as_root=True)
self.mox.ReplayAll()
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True)
def test_create_ephemeral_with_arbitrary(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND',
{'linux': 'mkfs.ext4 --label %(fs_label)s %(target)s'})
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkfs.ext4', '--label', 'myVol', '/dev/something',
run_as_root=True)
self.mox.ReplayAll()
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True)
def test_create_ephemeral_with_ext3(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND',
{'linux': 'mkfs.ext3 --label %(fs_label)s %(target)s'})
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkfs.ext3', '--label', 'myVol', '/dev/something',
run_as_root=True)
self.mox.ReplayAll()
drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux',
is_block_dev=True)
def test_create_swap_default(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.mox.StubOutWithMock(utils, 'execute')
utils.execute('mkswap', '/dev/something', run_as_root=False)
self.mox.ReplayAll()
drvr._create_swap('/dev/something', 1)
def test_get_console_output_file(self):
fake_libvirt_utils.files['console.log'] = '01234567890'
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = objects.Instance(**instance_ref)
console_dir = (os.path.join(tmpdir, instance['name']))
console_log = '%s/console.log' % (console_dir)
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='file'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % console_log
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
try:
prev_max = libvirt_driver.MAX_CONSOLE_BYTES
libvirt_driver.MAX_CONSOLE_BYTES = 5
with mock.patch('os.path.exists', return_value=True):
output = drvr.get_console_output(self.context, instance)
finally:
libvirt_driver.MAX_CONSOLE_BYTES = prev_max
self.assertEqual('67890', output)
def test_get_console_output_file_missing(self):
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = objects.Instance(**instance_ref)
console_log = os.path.join(tmpdir, instance['name'],
'non-existent.log')
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='file'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % console_log
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch('os.path.exists', return_value=False):
output = drvr.get_console_output(self.context, instance)
self.assertEqual('', output)
def test_get_console_output_pty(self):
fake_libvirt_utils.files['pty'] = '01234567890'
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456
instance = objects.Instance(**instance_ref)
console_dir = (os.path.join(tmpdir, instance['name']))
pty_file = '%s/fake_pty' % (console_dir)
fake_dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='pty'>
<source path='%s'/>
<target port='0'/>
</console>
</devices>
</domain>
""" % pty_file
def fake_lookup(id):
return FakeVirtDomain(fake_dom_xml)
def _fake_flush(self, fake_pty):
return 'foo'
def _fake_append_to_file(self, data, fpath):
return 'pty'
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup
libvirt_driver.LibvirtDriver._flush_libvirt_console = _fake_flush
libvirt_driver.LibvirtDriver._append_to_file = _fake_append_to_file
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
try:
prev_max = libvirt_driver.MAX_CONSOLE_BYTES
libvirt_driver.MAX_CONSOLE_BYTES = 5
output = drvr.get_console_output(self.context, instance)
finally:
libvirt_driver.MAX_CONSOLE_BYTES = prev_max
self.assertEqual('67890', output)
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
@mock.patch.object(libvirt_guest.Guest, "get_xml_desc")
def test_get_console_output_not_available(self, mock_get_xml, get_domain):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
</disk>
<console type='foo'>
<source path='srcpath'/>
<target port='0'/>
</console>
</devices>
</domain>
"""
mock_get_xml.return_value = xml
get_domain.return_value = mock.MagicMock()
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.ConsoleNotAvailable,
drvr.get_console_output, self.context, instance)
def test_get_host_ip_addr(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
ip = drvr.get_host_ip_addr()
self.assertEqual(ip, CONF.my_ip)
@mock.patch.object(libvirt_driver.LOG, 'warning')
@mock.patch('nova.compute.utils.get_machine_ips')
def test_get_host_ip_addr_failure(self, mock_ips, mock_log):
mock_ips.return_value = ['8.8.8.8', '75.75.75.75']
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.get_host_ip_addr()
mock_log.assert_called_once_with(u'my_ip address (%(my_ip)s) was '
u'not found on any of the '
u'interfaces: %(ifaces)s',
{'ifaces': '8.8.8.8, 75.75.75.75',
'my_ip': mock.ANY})
def test_conn_event_handler(self):
self.mox.UnsetStubs()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
service_mock = mock.MagicMock()
service_mock.disabled.return_value = False
with test.nested(
mock.patch.object(drvr._host, "_connect",
side_effect=fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
"Failed to connect to host",
error_code=
fakelibvirt.VIR_ERR_INTERNAL_ERROR)),
mock.patch.object(drvr._host, "_init_events",
return_value=None),
mock.patch.object(objects.Service, "get_by_compute_host",
return_value=service_mock)):
# verify that the driver registers for the close callback
# and re-connects after receiving the callback
self.assertRaises(exception.HypervisorUnavailable,
drvr.init_host,
"wibble")
self.assertTrue(service_mock.disabled)
def test_command_with_broken_connection(self):
self.mox.UnsetStubs()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
service_mock = mock.MagicMock()
service_mock.disabled.return_value = False
with test.nested(
mock.patch.object(drvr._host, "_connect",
side_effect=fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
"Failed to connect to host",
error_code=
fakelibvirt.VIR_ERR_INTERNAL_ERROR)),
mock.patch.object(drvr._host, "_init_events",
return_value=None),
mock.patch.object(host.Host, "has_min_version",
return_value=True),
mock.patch.object(drvr, "_do_quality_warnings",
return_value=None),
mock.patch.object(objects.Service, "get_by_compute_host",
return_value=service_mock),
mock.patch.object(host.Host, "get_capabilities")):
drvr.init_host("wibble")
self.assertRaises(exception.HypervisorUnavailable,
drvr.get_num_instances)
self.assertTrue(service_mock.disabled)
def test_service_resume_after_broken_connection(self):
self.mox.UnsetStubs()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
service_mock = mock.MagicMock()
service_mock.disabled.return_value = True
with test.nested(
mock.patch.object(drvr._host, "_connect",
return_value=mock.MagicMock()),
mock.patch.object(drvr._host, "_init_events",
return_value=None),
mock.patch.object(host.Host, "has_min_version",
return_value=True),
mock.patch.object(drvr, "_do_quality_warnings",
return_value=None),
mock.patch.object(objects.Service, "get_by_compute_host",
return_value=service_mock),
mock.patch.object(host.Host, "get_capabilities")):
drvr.init_host("wibble")
drvr.get_num_instances()
self.assertTrue(not service_mock.disabled and
service_mock.disabled_reason is None)
@mock.patch.object(objects.Instance, 'save')
def test_immediate_delete(self, mock_save):
def fake_get_domain(instance):
raise exception.InstanceNotFound(instance_id=instance.uuid)
def fake_delete_instance_files(instance):
pass
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, 'delete_instance_files',
fake_delete_instance_files)
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, {})
mock_save.assert_called_once_with()
@mock.patch.object(objects.Instance, 'get_by_uuid')
@mock.patch.object(objects.Instance, 'obj_load_attr', autospec=True)
@mock.patch.object(objects.Instance, 'save', autospec=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, '_destroy')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'delete_instance_files')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_disconnect_volume')
@mock.patch.object(driver, 'block_device_info_get_mapping')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_undefine_domain')
def _test_destroy_removes_disk(self, mock_undefine_domain, mock_mapping,
mock_disconnect_volume,
mock_delete_instance_files, mock_destroy,
mock_inst_save, mock_inst_obj_load_attr,
mock_get_by_uuid, volume_fail=False):
instance = objects.Instance(self.context, **self.test_instance)
vol = {'block_device_mapping': [
{'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]}
mock_mapping.return_value = vol['block_device_mapping']
mock_delete_instance_files.return_value = True
mock_get_by_uuid.return_value = instance
if volume_fail:
mock_disconnect_volume.return_value = (
exception.VolumeNotFound('vol'))
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.destroy(self.context, instance, [], vol)
def test_destroy_removes_disk(self):
self._test_destroy_removes_disk(volume_fail=False)
def test_destroy_removes_disk_volume_fails(self):
self._test_destroy_removes_disk(volume_fail=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, 'unplug_vifs')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_destroy')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_undefine_domain')
def test_destroy_not_removes_disk(self, mock_undefine_domain, mock_destroy,
mock_unplug_vifs):
instance = fake_instance.fake_instance_obj(
None, name='instancename', id=1,
uuid='875a8070-d0b9-4949-8b31-104d125c9a64')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.destroy(self.context, instance, [], None, False)
@mock.patch.object(libvirt_driver.LibvirtDriver, 'cleanup')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_teardown_container')
@mock.patch.object(host.Host, 'get_domain')
def test_destroy_lxc_calls_teardown_container(self, mock_get_domain,
mock_teardown_container,
mock_cleanup):
self.flags(virt_type='lxc', group='libvirt')
fake_domain = FakeVirtDomain()
def destroy_side_effect(*args, **kwargs):
fake_domain._info[0] = power_state.SHUTDOWN
with mock.patch.object(fake_domain, 'destroy',
side_effect=destroy_side_effect) as mock_domain_destroy:
mock_get_domain.return_value = fake_domain
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
network_info = []
drvr.destroy(self.context, instance, network_info, None, False)
mock_get_domain.assert_has_calls([mock.call(instance),
mock.call(instance)])
mock_domain_destroy.assert_called_once_with()
mock_teardown_container.assert_called_once_with(instance)
mock_cleanup.assert_called_once_with(self.context, instance,
network_info, None, False,
None)
@mock.patch.object(libvirt_driver.LibvirtDriver, 'cleanup')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_teardown_container')
@mock.patch.object(host.Host, 'get_domain')
def test_destroy_lxc_calls_teardown_container_when_no_domain(self,
mock_get_domain, mock_teardown_container, mock_cleanup):
self.flags(virt_type='lxc', group='libvirt')
instance = objects.Instance(**self.test_instance)
inf_exception = exception.InstanceNotFound(instance_id=instance.uuid)
mock_get_domain.side_effect = inf_exception
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
network_info = []
drvr.destroy(self.context, instance, network_info, None, False)
mock_get_domain.assert_has_calls([mock.call(instance),
mock.call(instance)])
mock_teardown_container.assert_called_once_with(instance)
mock_cleanup.assert_called_once_with(self.context, instance,
network_info, None, False,
None)
def test_reboot_different_ids(self):
class FakeLoopingCall(object):
def start(self, *a, **k):
return self
def wait(self):
return None
self.flags(wait_soft_reboot_seconds=1, group='libvirt')
info_tuple = ('fake', 'fake', 'fake', 'also_fake')
self.reboot_create_called = False
# Mock domain
mock_domain = self.mox.CreateMock(fakelibvirt.virDomain)
mock_domain.info().AndReturn(
(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple)
mock_domain.ID().AndReturn('some_fake_id')
mock_domain.ID().AndReturn('some_fake_id')
mock_domain.shutdown()
mock_domain.info().AndReturn(
(libvirt_guest.VIR_DOMAIN_CRASHED,) + info_tuple)
mock_domain.ID().AndReturn('some_other_fake_id')
mock_domain.ID().AndReturn('some_other_fake_id')
self.mox.ReplayAll()
def fake_get_domain(instance):
return mock_domain
def fake_create_domain(**kwargs):
self.reboot_create_called = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, '_create_domain', fake_create_domain)
self.stubs.Set(loopingcall, 'FixedIntervalLoopingCall',
lambda *a, **k: FakeLoopingCall())
self.stubs.Set(pci_manager, 'get_instance_pci_devs', lambda *a: [])
drvr.reboot(None, instance, [], 'SOFT')
self.assertTrue(self.reboot_create_called)
@mock.patch.object(pci_manager, 'get_instance_pci_devs')
@mock.patch.object(loopingcall, 'FixedIntervalLoopingCall')
@mock.patch.object(greenthread, 'sleep')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot')
@mock.patch.object(host.Host, 'get_domain')
def test_reboot_same_ids(self, mock_get_domain, mock_hard_reboot,
mock_sleep, mock_loopingcall,
mock_get_instance_pci_devs):
class FakeLoopingCall(object):
def start(self, *a, **k):
return self
def wait(self):
return None
self.flags(wait_soft_reboot_seconds=1, group='libvirt')
info_tuple = ('fake', 'fake', 'fake', 'also_fake')
self.reboot_hard_reboot_called = False
# Mock domain
mock_domain = mock.Mock(fakelibvirt.virDomain)
return_values = [(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple,
(libvirt_guest.VIR_DOMAIN_CRASHED,) + info_tuple]
mock_domain.info.side_effect = return_values
mock_domain.ID.return_value = 'some_fake_id'
mock_domain.shutdown.side_effect = mock.Mock()
def fake_hard_reboot(*args, **kwargs):
self.reboot_hard_reboot_called = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_get_domain.return_value = mock_domain
mock_hard_reboot.side_effect = fake_hard_reboot
mock_loopingcall.return_value = FakeLoopingCall()
mock_get_instance_pci_devs.return_value = []
drvr.reboot(None, instance, [], 'SOFT')
self.assertTrue(self.reboot_hard_reboot_called)
@mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot')
@mock.patch.object(host.Host, 'get_domain')
def test_soft_reboot_libvirt_exception(self, mock_get_domain,
mock_hard_reboot):
# Tests that a hard reboot is performed when a soft reboot results
# in raising a libvirtError.
info_tuple = ('fake', 'fake', 'fake', 'also_fake')
# setup mocks
mock_virDomain = mock.Mock(fakelibvirt.virDomain)
mock_virDomain.info.return_value = (
(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple)
mock_virDomain.ID.return_value = 'some_fake_id'
mock_virDomain.shutdown.side_effect = fakelibvirt.libvirtError('Err')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
context = None
instance = objects.Instance(**self.test_instance)
network_info = []
mock_get_domain.return_value = mock_virDomain
drvr.reboot(context, instance, network_info, 'SOFT')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot')
@mock.patch.object(host.Host, 'get_domain')
def _test_resume_state_on_host_boot_with_state(self, state,
mock_get_domain,
mock_hard_reboot):
mock_virDomain = mock.Mock(fakelibvirt.virDomain)
mock_virDomain.info.return_value = ([state, None, None, None, None])
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_domain.return_value = mock_virDomain
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
drvr.resume_state_on_host_boot(self.context, instance, network_info,
block_device_info=None)
ignored_states = (power_state.RUNNING,
power_state.SUSPENDED,
power_state.NOSTATE,
power_state.PAUSED)
self.assertEqual(mock_hard_reboot.called, state not in ignored_states)
def test_resume_state_on_host_boot_with_running_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.RUNNING)
def test_resume_state_on_host_boot_with_suspended_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.SUSPENDED)
def test_resume_state_on_host_boot_with_paused_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.PAUSED)
def test_resume_state_on_host_boot_with_nostate(self):
self._test_resume_state_on_host_boot_with_state(power_state.NOSTATE)
def test_resume_state_on_host_boot_with_shutdown_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.RUNNING)
def test_resume_state_on_host_boot_with_crashed_state(self):
self._test_resume_state_on_host_boot_with_state(power_state.CRASHED)
@mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot')
@mock.patch.object(host.Host, 'get_domain')
def test_resume_state_on_host_boot_with_instance_not_found_on_driver(
self, mock_get_domain, mock_hard_reboot):
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_domain.side_effect = exception.InstanceNotFound(
instance_id='fake')
drvr.resume_state_on_host_boot(self.context, instance, network_info=[],
block_device_info=None)
mock_hard_reboot.assert_called_once_with(self.context,
instance, [], None)
@mock.patch('nova.virt.libvirt.LibvirtDriver._undefine_domain')
@mock.patch('nova.virt.libvirt.LibvirtDriver.get_info')
@mock.patch('nova.virt.libvirt.LibvirtDriver._create_domain_and_network')
@mock.patch('nova.virt.libvirt.LibvirtDriver._create_images_and_backing')
@mock.patch('nova.virt.libvirt.LibvirtDriver._get_guest_xml')
@mock.patch('nova.virt.libvirt.LibvirtDriver._get_instance_disk_info')
@mock.patch('nova.virt.libvirt.blockinfo.get_disk_info')
@mock.patch('nova.virt.libvirt.LibvirtDriver._destroy')
def test_hard_reboot(self, mock_destroy, mock_get_disk_info,
mock_get_instance_disk_info, mock_get_guest_xml,
mock_create_images_and_backing,
mock_create_domain_and_network, mock_get_info,
mock_undefine):
self.context.auth_token = True # any non-None value will suffice
instance = objects.Instance(**self.test_instance)
instance_path = libvirt_utils.get_instance_path(instance)
network_info = _fake_network_info(self, 1)
block_device_info = None
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
return_values = [hardware.InstanceInfo(state=power_state.SHUTDOWN),
hardware.InstanceInfo(state=power_state.RUNNING)]
mock_get_info.side_effect = return_values
backing_disk_info = [{"virt_disk_size": 2}]
mock_get_disk_info.return_value = mock.sentinel.disk_info
mock_get_guest_xml.return_value = dummyxml
mock_get_instance_disk_info.return_value = backing_disk_info
drvr._hard_reboot(self.context, instance, network_info,
block_device_info)
mock_destroy.assert_called_once_with(instance)
mock_undefine.assert_called_once_with(instance)
# make sure that _create_images_and_backing is passed the disk_info
# returned from _get_instance_disk_info and not the one that is in
# scope from blockinfo.get_disk_info
mock_create_images_and_backing.assert_called_once_with(self.context,
instance, instance_path, backing_disk_info)
# make sure that _create_domain_and_network is passed the disk_info
# returned from blockinfo.get_disk_info and not the one that's
# returned from _get_instance_disk_info
mock_create_domain_and_network.assert_called_once_with(self.context,
dummyxml, instance, network_info, mock.sentinel.disk_info,
block_device_info=block_device_info,
reboot=True, vifs_already_plugged=True)
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall')
@mock.patch('nova.pci.manager.get_instance_pci_devs')
@mock.patch('nova.virt.libvirt.LibvirtDriver._prepare_pci_devices_for_use')
@mock.patch('nova.virt.libvirt.LibvirtDriver._create_domain_and_network')
@mock.patch('nova.virt.libvirt.LibvirtDriver._create_images_and_backing')
@mock.patch('nova.virt.libvirt.LibvirtDriver._get_instance_disk_info')
@mock.patch('nova.virt.libvirt.utils.write_to_file')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
@mock.patch('nova.virt.libvirt.LibvirtDriver._get_guest_config')
@mock.patch('nova.virt.libvirt.blockinfo.get_disk_info')
@mock.patch('nova.virt.libvirt.LibvirtDriver._destroy')
def test_hard_reboot_does_not_call_glance_show(self,
mock_destroy, mock_get_disk_info, mock_get_guest_config,
mock_get_instance_path, mock_write_to_file,
mock_get_instance_disk_info, mock_create_images_and_backing,
mock_create_domand_and_network, mock_prepare_pci_devices_for_use,
mock_get_instance_pci_devs, mock_looping_call, mock_ensure_tree):
"""For a hard reboot, we shouldn't need an additional call to glance
to get the image metadata.
This is important for automatically spinning up instances on a
host-reboot, since we won't have a user request context that'll allow
the Glance request to go through. We have to rely on the cached image
metadata, instead.
https://bugs.launchpad.net/nova/+bug/1339386
"""
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
network_info = mock.MagicMock()
block_device_info = mock.MagicMock()
mock_get_disk_info.return_value = {}
mock_get_guest_config.return_value = mock.MagicMock()
mock_get_instance_path.return_value = '/foo'
mock_looping_call.return_value = mock.MagicMock()
drvr._image_api = mock.MagicMock()
drvr._hard_reboot(self.context, instance, network_info,
block_device_info)
self.assertFalse(drvr._image_api.get.called)
mock_ensure_tree.assert_called_once_with('/foo')
def test_suspend(self):
guest = libvirt_guest.Guest(FakeVirtDomain(id=1))
dom = guest._domain
instance = objects.Instance(**self.test_instance)
instance.ephemeral_key_uuid = None
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
@mock.patch.object(dmcrypt, 'delete_volume')
@mock.patch.object(conn, '_get_instance_disk_info', return_value=[])
@mock.patch.object(conn, '_detach_sriov_ports')
@mock.patch.object(conn, '_detach_pci_devices')
@mock.patch.object(pci_manager, 'get_instance_pci_devs',
return_value='pci devs')
@mock.patch.object(conn._host, 'get_guest', return_value=guest)
def suspend(mock_get_guest, mock_get_instance_pci_devs,
mock_detach_pci_devices, mock_detach_sriov_ports,
mock_get_instance_disk_info, mock_delete_volume):
mock_managedSave = mock.Mock()
dom.managedSave = mock_managedSave
conn.suspend(self.context, instance)
mock_managedSave.assert_called_once_with(0)
self.assertFalse(mock_get_instance_disk_info.called)
mock_delete_volume.assert_has_calls([mock.call(disk['path'])
for disk in mock_get_instance_disk_info.return_value], False)
suspend()
@mock.patch.object(time, 'sleep')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_create_domain')
@mock.patch.object(host.Host, 'get_domain')
def _test_clean_shutdown(self, mock_get_domain, mock_create_domain,
mock_sleep, seconds_to_shutdown,
timeout, retry_interval,
shutdown_attempts, succeeds):
info_tuple = ('fake', 'fake', 'fake', 'also_fake')
shutdown_count = []
# Mock domain
mock_domain = mock.Mock(fakelibvirt.virDomain)
return_infos = [(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple]
return_shutdowns = [shutdown_count.append("shutdown")]
retry_countdown = retry_interval
for x in range(min(seconds_to_shutdown, timeout)):
return_infos.append(
(libvirt_guest.VIR_DOMAIN_RUNNING,) + info_tuple)
if retry_countdown == 0:
return_shutdowns.append(shutdown_count.append("shutdown"))
retry_countdown = retry_interval
else:
retry_countdown -= 1
if seconds_to_shutdown < timeout:
return_infos.append(
(libvirt_guest.VIR_DOMAIN_SHUTDOWN,) + info_tuple)
mock_domain.info.side_effect = return_infos
mock_domain.shutdown.side_effect = return_shutdowns
def fake_create_domain(**kwargs):
self.reboot_create_called = True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_get_domain.return_value = mock_domain
mock_create_domain.side_effect = fake_create_domain
result = drvr._clean_shutdown(instance, timeout, retry_interval)
self.assertEqual(succeeds, result)
self.assertEqual(shutdown_attempts, len(shutdown_count))
def test_clean_shutdown_first_time(self):
self._test_clean_shutdown(seconds_to_shutdown=2,
timeout=5,
retry_interval=3,
shutdown_attempts=1,
succeeds=True)
def test_clean_shutdown_with_retry(self):
self._test_clean_shutdown(seconds_to_shutdown=4,
timeout=5,
retry_interval=3,
shutdown_attempts=2,
succeeds=True)
def test_clean_shutdown_failure(self):
self._test_clean_shutdown(seconds_to_shutdown=6,
timeout=5,
retry_interval=3,
shutdown_attempts=2,
succeeds=False)
def test_clean_shutdown_no_wait(self):
self._test_clean_shutdown(seconds_to_shutdown=6,
timeout=0,
retry_interval=3,
shutdown_attempts=1,
succeeds=False)
@mock.patch.object(FakeVirtDomain, 'attachDeviceFlags')
@mock.patch.object(FakeVirtDomain, 'ID', return_value=1)
@mock.patch.object(utils, 'get_image_from_system_metadata',
return_value=None)
def test_attach_sriov_ports(self,
mock_get_image_metadata,
mock_ID,
mock_attachDevice):
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT
guest = libvirt_guest.Guest(FakeVirtDomain())
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._attach_sriov_ports(self.context, instance, guest, network_info)
mock_get_image_metadata.assert_called_once_with(
instance.system_metadata)
self.assertTrue(mock_attachDevice.called)
@mock.patch.object(FakeVirtDomain, 'attachDeviceFlags')
@mock.patch.object(FakeVirtDomain, 'ID', return_value=1)
@mock.patch.object(utils, 'get_image_from_system_metadata',
return_value=None)
def test_attach_sriov_direct_physical_ports(self,
mock_get_image_metadata,
mock_ID,
mock_attachDevice):
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT_PHYSICAL
guest = libvirt_guest.Guest(FakeVirtDomain())
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._attach_sriov_ports(self.context, instance, guest, network_info)
mock_get_image_metadata.assert_called_once_with(
instance.system_metadata)
self.assertTrue(mock_attachDevice.called)
@mock.patch.object(FakeVirtDomain, 'attachDeviceFlags')
@mock.patch.object(FakeVirtDomain, 'ID', return_value=1)
@mock.patch.object(utils, 'get_image_from_system_metadata',
return_value=None)
def test_attach_sriov_ports_with_info_cache(self,
mock_get_image_metadata,
mock_ID,
mock_attachDevice):
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT
instance.info_cache = objects.InstanceInfoCache(
network_info=network_info)
guest = libvirt_guest.Guest(FakeVirtDomain())
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr._attach_sriov_ports(self.context, instance, guest, None)
mock_get_image_metadata.assert_called_once_with(
instance.system_metadata)
self.assertTrue(mock_attachDevice.called)
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def _test_detach_sriov_ports(self,
mock_has_min_version, vif_type):
instance = objects.Instance(**self.test_instance)
expeted_pci_slot = "0000:00:00.0"
network_info = _fake_network_info(self, 1)
network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT
# some more adjustments for the fake network_info so that
# the correct get_config function will be executed (vif's
# get_config_hw_veb - which is according to the real SRIOV vif)
# and most importantly the pci_slot which is translated to
# cfg.source_dev, then to PciDevice.address and sent to
# _detach_pci_devices
network_info[0]['profile'] = dict(pci_slot=expeted_pci_slot)
network_info[0]['type'] = vif_type
network_info[0]['details'] = dict(vlan="2145")
instance.info_cache = objects.InstanceInfoCache(
network_info=network_info)
# fill the pci_devices of the instance so that
# pci_manager.get_instance_pci_devs will not return an empty list
# which will eventually fail the assertion for detachDeviceFlags
expected_pci_device_obj = (
objects.PciDevice(address=expeted_pci_slot, request_id=None))
instance.pci_devices = objects.PciDeviceList()
instance.pci_devices.objects = [expected_pci_device_obj]
domain = FakeVirtDomain()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
guest = libvirt_guest.Guest(domain)
with mock.patch.object(drvr, '_detach_pci_devices') as mock_detach_pci:
drvr._detach_sriov_ports(self.context, instance, guest)
mock_detach_pci.assert_called_once_with(
guest, [expected_pci_device_obj])
def test_detach_sriov_ports_interface_interface_hostdev(self):
# Note: test detach_sriov_ports method for vif with config
# LibvirtConfigGuestInterface
self._test_detach_sriov_ports(vif_type="hw_veb")
def test_detach_sriov_ports_interface_pci_hostdev(self):
# Note: test detach_sriov_ports method for vif with config
# LibvirtConfigGuestHostdevPCI
self._test_detach_sriov_ports(vif_type="ib_hostdev")
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(FakeVirtDomain, 'detachDeviceFlags')
def test_detach_duplicate_mac_sriov_ports(self,
mock_detachDeviceFlags,
mock_has_min_version):
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 2)
for network_info_inst in network_info:
network_info_inst['vnic_type'] = network_model.VNIC_TYPE_DIRECT
network_info_inst['type'] = "hw_veb"
network_info_inst['details'] = dict(vlan="2145")
network_info_inst['address'] = "fa:16:3e:96:2a:48"
network_info[0]['profile'] = dict(pci_slot="0000:00:00.0")
network_info[1]['profile'] = dict(pci_slot="0000:00:00.1")
instance.info_cache = objects.InstanceInfoCache(
network_info=network_info)
# fill the pci_devices of the instance so that
# pci_manager.get_instance_pci_devs will not return an empty list
# which will eventually fail the assertion for detachDeviceFlags
instance.pci_devices = objects.PciDeviceList()
instance.pci_devices.objects = [
objects.PciDevice(address='0000:00:00.0', request_id=None),
objects.PciDevice(address='0000:00:00.1', request_id=None)
]
domain = FakeVirtDomain()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
guest = libvirt_guest.Guest(domain)
drvr._detach_sriov_ports(self.context, instance, guest)
expected_xml = [
('<hostdev mode="subsystem" type="pci" managed="yes">\n'
' <source>\n'
' <address bus="0x00" domain="0x0000" \
function="0x0" slot="0x00"/>\n'
' </source>\n'
'</hostdev>\n'),
('<hostdev mode="subsystem" type="pci" managed="yes">\n'
' <source>\n'
' <address bus="0x00" domain="0x0000" \
function="0x1" slot="0x00"/>\n'
' </source>\n'
'</hostdev>\n')
]
mock_detachDeviceFlags.has_calls([
mock.call(expected_xml[0], flags=1),
mock.call(expected_xml[1], flags=1)
])
def test_resume(self):
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='file'><driver name='qemu' type='raw'/>"
"<source file='/test/disk'/>"
"<target dev='vda' bus='virtio'/></disk>"
"<disk type='file'><driver name='qemu' type='qcow2'/>"
"<source file='/test/disk.local'/>"
"<target dev='vdb' bus='virtio'/></disk>"
"</devices></domain>")
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
block_device_info = None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
guest = libvirt_guest.Guest('fake_dom')
with test.nested(
mock.patch.object(drvr, '_get_existing_domain_xml',
return_value=dummyxml),
mock.patch.object(drvr, '_create_domain_and_network',
return_value=guest),
mock.patch.object(drvr, '_attach_pci_devices'),
mock.patch.object(pci_manager, 'get_instance_pci_devs',
return_value='fake_pci_devs'),
mock.patch.object(utils, 'get_image_from_system_metadata'),
mock.patch.object(blockinfo, 'get_disk_info'),
) as (_get_existing_domain_xml, _create_domain_and_network,
_attach_pci_devices, get_instance_pci_devs, get_image_metadata,
get_disk_info):
get_image_metadata.return_value = {'bar': 234}
disk_info = {'foo': 123}
get_disk_info.return_value = disk_info
drvr.resume(self.context, instance, network_info,
block_device_info)
_get_existing_domain_xml.assert_has_calls([mock.call(instance,
network_info, block_device_info)])
_create_domain_and_network.assert_has_calls([mock.call(
self.context, dummyxml,
instance, network_info, disk_info,
block_device_info=block_device_info,
vifs_already_plugged=True)])
_attach_pci_devices.assert_has_calls([mock.call(guest,
'fake_pci_devs')])
@mock.patch.object(host.Host, 'get_domain')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'delete_instance_files')
@mock.patch.object(objects.Instance, 'save')
def test_destroy_undefines(self, mock_save, mock_delete_instance_files,
mock_get_info, mock_get_domain):
dom_mock = mock.MagicMock()
dom_mock.undefineFlags.return_value = 1
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_domain.return_value = dom_mock
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.SHUTDOWN, id=-1)
mock_delete_instance_files.return_value = None
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, [])
mock_save.assert_called_once_with()
@mock.patch.object(rbd_utils, 'RBDDriver')
def test_cleanup_rbd(self, mock_driver):
driver = mock_driver.return_value
driver.cleanup_volumes = mock.Mock()
fake_instance = {'uuid': '875a8070-d0b9-4949-8b31-104d125c9a64'}
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr._cleanup_rbd(fake_instance)
driver.cleanup_volumes.assert_called_once_with(fake_instance)
@mock.patch.object(objects.Instance, 'save')
def test_destroy_undefines_no_undefine_flags(self, mock_save):
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(fakelibvirt.libvirtError('Err'))
mock.ID().AndReturn(123)
mock.undefine()
self.mox.ReplayAll()
def fake_get_domain(instance):
return mock
def fake_get_info(instance_name):
return hardware.InstanceInfo(state=power_state.SHUTDOWN, id=-1)
def fake_delete_instance_files(instance):
return None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, 'get_info', fake_get_info)
self.stubs.Set(drvr, 'delete_instance_files',
fake_delete_instance_files)
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, [])
mock_save.assert_called_once_with()
@mock.patch.object(objects.Instance, 'save')
def test_destroy_undefines_no_attribute_with_managed_save(self, mock_save):
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(AttributeError())
mock.hasManagedSaveImage(0).AndReturn(True)
mock.managedSaveRemove(0)
mock.undefine()
self.mox.ReplayAll()
def fake_get_domain(instance):
return mock
def fake_get_info(instance_name):
return hardware.InstanceInfo(state=power_state.SHUTDOWN, id=-1)
def fake_delete_instance_files(instance):
return None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, 'get_info', fake_get_info)
self.stubs.Set(drvr, 'delete_instance_files',
fake_delete_instance_files)
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, [])
mock_save.assert_called_once_with()
@mock.patch.object(objects.Instance, 'save')
def test_destroy_undefines_no_attribute_no_managed_save(self, mock_save):
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy()
mock.undefineFlags(1).AndRaise(AttributeError())
mock.hasManagedSaveImage(0).AndRaise(AttributeError())
mock.undefine()
self.mox.ReplayAll()
def fake_get_domain(self, instance):
return mock
def fake_get_info(instance_name):
return hardware.InstanceInfo(state=power_state.SHUTDOWN)
def fake_delete_instance_files(instance):
return None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(host.Host, 'get_domain', fake_get_domain)
self.stubs.Set(drvr, 'get_info', fake_get_info)
self.stubs.Set(drvr, 'delete_instance_files',
fake_delete_instance_files)
instance = objects.Instance(self.context, **self.test_instance)
drvr.destroy(self.context, instance, [])
mock_save.assert_called_once_with()
def test_destroy_timed_out(self):
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy().AndRaise(fakelibvirt.libvirtError("timed out"))
self.mox.ReplayAll()
def fake_get_domain(self, instance):
return mock
def fake_get_error_code(self):
return fakelibvirt.VIR_ERR_OPERATION_TIMEOUT
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(host.Host, 'get_domain', fake_get_domain)
self.stubs.Set(fakelibvirt.libvirtError, 'get_error_code',
fake_get_error_code)
instance = objects.Instance(**self.test_instance)
self.assertRaises(exception.InstancePowerOffFailure,
drvr.destroy, self.context, instance, [])
def test_private_destroy_not_found(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
"No such domain",
error_code=fakelibvirt.VIR_ERR_NO_DOMAIN)
mock = self.mox.CreateMock(fakelibvirt.virDomain)
mock.ID()
mock.destroy().AndRaise(ex)
mock.info().AndRaise(ex)
mock.UUIDString()
self.mox.ReplayAll()
def fake_get_domain(instance):
return mock
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr._host, 'get_domain', fake_get_domain)
instance = objects.Instance(**self.test_instance)
# NOTE(vish): verifies destroy doesn't raise if the instance disappears
drvr._destroy(instance)
def test_private_destroy_lxc_processes_refused_to_die(self):
self.flags(virt_type='lxc', group='libvirt')
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError, "",
error_message="internal error: Some processes refused to die",
error_code=fakelibvirt.VIR_ERR_INTERNAL_ERROR)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(conn._host, 'get_domain') as mock_get_domain, \
mock.patch.object(conn, 'get_info') as mock_get_info:
mock_domain = mock.MagicMock()
mock_domain.ID.return_value = 1
mock_get_domain.return_value = mock_domain
mock_domain.destroy.side_effect = ex
mock_info = mock.MagicMock()
mock_info.id = 1
mock_info.state = power_state.SHUTDOWN
mock_get_info.return_value = mock_info
instance = objects.Instance(**self.test_instance)
conn._destroy(instance)
def test_private_destroy_processes_refused_to_die_still_raises(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError, "",
error_message="internal error: Some processes refused to die",
error_code=fakelibvirt.VIR_ERR_INTERNAL_ERROR)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(conn._host, 'get_domain') as mock_get_domain:
mock_domain = mock.MagicMock()
mock_domain.ID.return_value = 1
mock_get_domain.return_value = mock_domain
mock_domain.destroy.side_effect = ex
instance = objects.Instance(**self.test_instance)
self.assertRaises(fakelibvirt.libvirtError, conn._destroy,
instance)
def test_private_destroy_ebusy_timeout(self):
# Tests that _destroy will retry 3 times to destroy the guest when an
# EBUSY is raised, but eventually times out and raises the libvirtError
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
("Failed to terminate process 26425 with SIGKILL: "
"Device or resource busy"),
error_code=fakelibvirt.VIR_ERR_SYSTEM_ERROR,
int1=errno.EBUSY)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.poweroff = mock.Mock(side_effect=ex)
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(drvr._host, 'get_guest',
return_value=mock_guest):
self.assertRaises(fakelibvirt.libvirtError, drvr._destroy,
instance)
self.assertEqual(3, mock_guest.poweroff.call_count)
def test_private_destroy_ebusy_multiple_attempt_ok(self):
# Tests that the _destroy attempt loop is broken when EBUSY is no
# longer raised.
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
("Failed to terminate process 26425 with SIGKILL: "
"Device or resource busy"),
error_code=fakelibvirt.VIR_ERR_SYSTEM_ERROR,
int1=errno.EBUSY)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.poweroff = mock.Mock(side_effect=[ex, None])
inst_info = hardware.InstanceInfo(power_state.SHUTDOWN, id=1)
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(drvr._host, 'get_guest',
return_value=mock_guest):
with mock.patch.object(drvr, 'get_info', return_value=inst_info):
drvr._destroy(instance)
self.assertEqual(2, mock_guest.poweroff.call_count)
def test_undefine_domain_with_not_found_instance(self):
def fake_get_domain(self, instance):
raise exception.InstanceNotFound(instance_id=instance.uuid)
self.stubs.Set(host.Host, 'get_domain', fake_get_domain)
self.mox.StubOutWithMock(fakelibvirt.libvirtError, "get_error_code")
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
# NOTE(wenjianhn): verifies undefine doesn't raise if the
# instance disappears
drvr._undefine_domain(instance)
@mock.patch.object(host.Host, "list_instance_domains")
@mock.patch.object(objects.BlockDeviceMappingList, "bdms_by_instance_uuid")
@mock.patch.object(objects.InstanceList, "get_by_filters")
def test_disk_over_committed_size_total(self, mock_get, mock_bdms,
mock_list):
# Ensure destroy calls managedSaveRemove for saved instance.
class DiagFakeDomain(object):
def __init__(self, name):
self._name = name
self._uuid = str(uuid.uuid4())
def ID(self):
return 1
def name(self):
return self._name
def UUIDString(self):
return self._uuid
def XMLDesc(self, flags):
return "<domain/>"
instance_domains = [
DiagFakeDomain("instance0000001"),
DiagFakeDomain("instance0000002")]
mock_list.return_value = instance_domains
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_disks = {'instance0000001':
[{'type': 'qcow2', 'path': '/somepath/disk1',
'virt_disk_size': '10737418240',
'backing_file': '/somepath/disk1',
'disk_size': '83886080',
'over_committed_disk_size': '10653532160'}],
'instance0000002':
[{'type': 'raw', 'path': '/somepath/disk2',
'virt_disk_size': '0',
'backing_file': '/somepath/disk2',
'disk_size': '10737418240',
'over_committed_disk_size': '0'}]}
def get_info(instance_name, xml, **kwargs):
return fake_disks.get(instance_name)
instance_uuids = [dom.UUIDString() for dom in instance_domains]
instances = [objects.Instance(
uuid=instance_uuids[0],
root_device_name='/dev/vda'),
objects.Instance(
uuid=instance_uuids[1],
root_device_name='/dev/vdb')
]
mock_get.return_value = instances
with mock.patch.object(drvr,
"_get_instance_disk_info") as mock_info:
mock_info.side_effect = get_info
result = drvr._get_disk_over_committed_size_total()
self.assertEqual(result, 10653532160)
mock_list.assert_called_once_with()
self.assertEqual(2, mock_info.call_count)
filters = {'uuid': instance_uuids}
mock_get.assert_called_once_with(mock.ANY, filters, use_slave=True)
mock_bdms.assert_called_with(mock.ANY, instance_uuids)
@mock.patch.object(host.Host, "list_instance_domains")
@mock.patch.object(objects.BlockDeviceMappingList, "bdms_by_instance_uuid")
@mock.patch.object(objects.InstanceList, "get_by_filters")
def test_disk_over_committed_size_total_eperm(self, mock_get, mock_bdms,
mock_list):
# Ensure destroy calls managedSaveRemove for saved instance.
class DiagFakeDomain(object):
def __init__(self, name):
self._name = name
self._uuid = str(uuid.uuid4())
def ID(self):
return 1
def name(self):
return self._name
def UUIDString(self):
return self._uuid
def XMLDesc(self, flags):
return "<domain/>"
instance_domains = [
DiagFakeDomain("instance0000001"),
DiagFakeDomain("instance0000002"),
DiagFakeDomain("instance0000003"),
DiagFakeDomain("instance0000004")]
mock_list.return_value = instance_domains
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
fake_disks = {'instance0000001':
[{'type': 'qcow2', 'path': '/somepath/disk1',
'virt_disk_size': '10737418240',
'backing_file': '/somepath/disk1',
'disk_size': '83886080',
'over_committed_disk_size': '10653532160'}],
'instance0000002':
[{'type': 'raw', 'path': '/somepath/disk2',
'virt_disk_size': '0',
'backing_file': '/somepath/disk2',
'disk_size': '10737418240',
'over_committed_disk_size': '21474836480'}],
'instance0000003':
[{'type': 'raw', 'path': '/somepath/disk3',
'virt_disk_size': '0',
'backing_file': '/somepath/disk3',
'disk_size': '21474836480',
'over_committed_disk_size': '32212254720'}],
'instance0000004':
[{'type': 'raw', 'path': '/somepath/disk4',
'virt_disk_size': '0',
'backing_file': '/somepath/disk4',
'disk_size': '32212254720',
'over_committed_disk_size': '42949672960'}]}
def side_effect(name, dom, block_device_info):
if name == 'instance0000001':
self.assertEqual('/dev/vda',
block_device_info['root_device_name'])
raise OSError(errno.ENOENT, 'No such file or directory')
if name == 'instance0000002':
self.assertEqual('/dev/vdb',
block_device_info['root_device_name'])
raise OSError(errno.ESTALE, 'Stale NFS file handle')
if name == 'instance0000003':
self.assertEqual('/dev/vdc',
block_device_info['root_device_name'])
raise OSError(errno.EACCES, 'Permission denied')
if name == 'instance0000004':
self.assertEqual('/dev/vdd',
block_device_info['root_device_name'])
return fake_disks.get(name)
get_disk_info = mock.Mock()
get_disk_info.side_effect = side_effect
drvr._get_instance_disk_info = get_disk_info
instance_uuids = [dom.UUIDString() for dom in instance_domains]
instances = [objects.Instance(
uuid=instance_uuids[0],
root_device_name='/dev/vda'),
objects.Instance(
uuid=instance_uuids[1],
root_device_name='/dev/vdb'),
objects.Instance(
uuid=instance_uuids[2],
root_device_name='/dev/vdc'),
objects.Instance(
uuid=instance_uuids[3],
root_device_name='/dev/vdd')
]
mock_get.return_value = instances
result = drvr._get_disk_over_committed_size_total()
self.assertEqual(42949672960, result)
mock_list.assert_called_once_with()
self.assertEqual(4, get_disk_info.call_count)
filters = {'uuid': instance_uuids}
mock_get.assert_called_once_with(mock.ANY, filters, use_slave=True)
mock_bdms.assert_called_with(mock.ANY, instance_uuids)
@mock.patch.object(host.Host, "list_instance_domains",
return_value=[mock.MagicMock(name='foo')])
@mock.patch.object(libvirt_driver.LibvirtDriver, "_get_instance_disk_info",
side_effect=exception.VolumeBDMPathNotFound(path='bar'))
@mock.patch.object(objects.BlockDeviceMappingList, "bdms_by_instance_uuid")
@mock.patch.object(objects.InstanceList, "get_by_filters")
def test_disk_over_committed_size_total_bdm_not_found(self,
mock_get,
mock_bdms,
mock_get_disk_info,
mock_list_domains):
# Tests that we handle VolumeBDMPathNotFound gracefully.
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(0, drvr._get_disk_over_committed_size_total())
def test_cpu_info(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
def get_host_capabilities_stub(self):
cpu = vconfig.LibvirtConfigCPU()
cpu.model = "Opteron_G4"
cpu.vendor = "AMD"
cpu.arch = arch.X86_64
cpu.cells = 1
cpu.cores = 2
cpu.threads = 1
cpu.sockets = 4
cpu.add_feature(vconfig.LibvirtConfigCPUFeature("extapic"))
cpu.add_feature(vconfig.LibvirtConfigCPUFeature("3dnow"))
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = cpu
guest = vconfig.LibvirtConfigGuest()
guest.ostype = vm_mode.HVM
guest.arch = arch.X86_64
guest.domtype = ["kvm"]
caps.guests.append(guest)
guest = vconfig.LibvirtConfigGuest()
guest.ostype = vm_mode.HVM
guest.arch = arch.I686
guest.domtype = ["kvm"]
caps.guests.append(guest)
return caps
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
want = {"vendor": "AMD",
"features": set(["extapic", "3dnow"]),
"model": "Opteron_G4",
"arch": arch.X86_64,
"topology": {"cells": 1, "cores": 2, "threads": 1,
"sockets": 4}}
got = drvr._get_cpu_info()
self.assertEqual(want, got)
def test_get_pcidev_info(self):
def fake_nodeDeviceLookupByName(self, name):
return FakeNodeDevice(_fake_NodeDevXml[name])
self.mox.StubOutWithMock(host.Host, 'device_lookup_by_name')
host.Host.device_lookup_by_name = fake_nodeDeviceLookupByName
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(
fakelibvirt.Connection, 'getLibVersion') as mock_lib_version:
mock_lib_version.return_value = (
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION) - 1)
actualvf = drvr._get_pcidev_info("pci_0000_04_00_3")
expect_vf = {
"dev_id": "pci_0000_04_00_3",
"address": "0000:04:00.3",
"product_id": '1521',
"numa_node": None,
"vendor_id": '8086',
"label": 'label_8086_1521',
"dev_type": fields.PciDeviceType.SRIOV_PF,
}
self.assertEqual(expect_vf, actualvf)
actualvf = drvr._get_pcidev_info("pci_0000_04_10_7")
expect_vf = {
"dev_id": "pci_0000_04_10_7",
"address": "0000:04:10.7",
"product_id": '1520',
"numa_node": None,
"vendor_id": '8086',
"label": 'label_8086_1520',
"dev_type": fields.PciDeviceType.SRIOV_VF,
"parent_addr": '0000:04:00.3',
}
self.assertEqual(expect_vf, actualvf)
actualvf = drvr._get_pcidev_info("pci_0000_04_11_7")
expect_vf = {
"dev_id": "pci_0000_04_11_7",
"address": "0000:04:11.7",
"product_id": '1520',
"vendor_id": '8086',
"numa_node": 0,
"label": 'label_8086_1520',
"dev_type": fields.PciDeviceType.SRIOV_VF,
"parent_addr": '0000:04:00.3',
}
self.assertEqual(expect_vf, actualvf)
with mock.patch.object(
pci_utils, 'is_physical_function', return_value=True):
actualvf = drvr._get_pcidev_info("pci_0000_04_00_1")
expect_vf = {
"dev_id": "pci_0000_04_00_1",
"address": "0000:04:00.1",
"product_id": '1013',
"numa_node": 0,
"vendor_id": '15b3',
"label": 'label_15b3_1013',
"dev_type": fields.PciDeviceType.SRIOV_PF,
}
self.assertEqual(expect_vf, actualvf)
with mock.patch.object(
pci_utils, 'is_physical_function', return_value=False):
actualvf = drvr._get_pcidev_info("pci_0000_04_00_1")
expect_vf = {
"dev_id": "pci_0000_04_00_1",
"address": "0000:04:00.1",
"product_id": '1013',
"numa_node": 0,
"vendor_id": '15b3',
"label": 'label_15b3_1013',
"dev_type": fields.PciDeviceType.STANDARD,
}
self.assertEqual(expect_vf, actualvf)
with mock.patch.object(
fakelibvirt.Connection, 'getLibVersion') as mock_lib_version:
mock_lib_version.return_value = (
versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_PF_WITH_NO_VFS_CAP_VERSION))
actualvf = drvr._get_pcidev_info("pci_0000_03_00_0")
expect_vf = {
"dev_id": "pci_0000_03_00_0",
"address": "0000:03:00.0",
"product_id": '1013',
"numa_node": 0,
"vendor_id": '15b3',
"label": 'label_15b3_1013',
"dev_type": fields.PciDeviceType.SRIOV_PF,
}
self.assertEqual(expect_vf, actualvf)
actualvf = drvr._get_pcidev_info("pci_0000_03_00_1")
expect_vf = {
"dev_id": "pci_0000_03_00_1",
"address": "0000:03:00.1",
"product_id": '1013',
"numa_node": 0,
"vendor_id": '15b3',
"label": 'label_15b3_1013',
"dev_type": fields.PciDeviceType.SRIOV_PF,
}
self.assertEqual(expect_vf, actualvf)
def test_list_devices_not_supported(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Handle just the NO_SUPPORT error
not_supported_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'this function is not supported by the connection driver:'
' virNodeNumOfDevices',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
with mock.patch.object(drvr._conn, 'listDevices',
side_effect=not_supported_exc):
self.assertEqual('[]', drvr._get_pci_passthrough_devices())
# We cache not supported status to avoid emitting too many logging
# messages. Clear this value to test the other exception case.
del drvr._list_devices_supported
# Other errors should not be caught
other_exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'other exc',
error_code=fakelibvirt.VIR_ERR_NO_DOMAIN)
with mock.patch.object(drvr._conn, 'listDevices',
side_effect=other_exc):
self.assertRaises(fakelibvirt.libvirtError,
drvr._get_pci_passthrough_devices)
def test_get_pci_passthrough_devices(self):
def fakelistDevices(caps, fakeargs=0):
return ['pci_0000_04_00_3', 'pci_0000_04_10_7',
'pci_0000_04_11_7']
self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn')
libvirt_driver.LibvirtDriver._conn.listDevices = fakelistDevices
def fake_nodeDeviceLookupByName(self, name):
return FakeNodeDevice(_fake_NodeDevXml[name])
self.mox.StubOutWithMock(host.Host, 'device_lookup_by_name')
host.Host.device_lookup_by_name = fake_nodeDeviceLookupByName
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
actjson = drvr._get_pci_passthrough_devices()
expectvfs = [
{
"dev_id": "pci_0000_04_00_3",
"address": "0000:04:00.3",
"product_id": '1521',
"vendor_id": '8086',
"dev_type": fields.PciDeviceType.SRIOV_PF,
"phys_function": None,
"numa_node": None},
{
"dev_id": "pci_0000_04_10_7",
"domain": 0,
"address": "0000:04:10.7",
"product_id": '1520',
"vendor_id": '8086',
"numa_node": None,
"dev_type": fields.PciDeviceType.SRIOV_VF,
"phys_function": [('0x0000', '0x04', '0x00', '0x3')]},
{
"dev_id": "pci_0000_04_11_7",
"domain": 0,
"address": "0000:04:11.7",
"product_id": '1520',
"vendor_id": '8086',
"numa_node": 0,
"dev_type": fields.PciDeviceType.SRIOV_VF,
"phys_function": [('0x0000', '0x04', '0x00', '0x3')],
}
]
actualvfs = jsonutils.loads(actjson)
for dev in range(len(actualvfs)):
for key in actualvfs[dev].keys():
if key not in ['phys_function', 'virt_functions', 'label']:
self.assertEqual(expectvfs[dev][key], actualvfs[dev][key])
def _fake_caps_numa_topology(self,
cells_per_host=4,
sockets_per_cell=1,
cores_per_socket=1,
threads_per_core=2,
kb_mem=1048576):
# Generate mempages list per cell
cell_mempages = list()
for cellid in range(cells_per_host):
mempages_0 = vconfig.LibvirtConfigCapsNUMAPages()
mempages_0.size = 4
mempages_0.total = 1024 * cellid
mempages_1 = vconfig.LibvirtConfigCapsNUMAPages()
mempages_1.size = 2048
mempages_1.total = 0 + cellid
cell_mempages.append([mempages_0, mempages_1])
topology = fakelibvirt.HostInfo._gen_numa_topology(cells_per_host,
sockets_per_cell,
cores_per_socket,
threads_per_core,
kb_mem=kb_mem,
numa_mempages_list=cell_mempages)
return topology
def _test_get_host_numa_topology(self, mempages):
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = arch.X86_64
caps.host.topology = self._fake_caps_numa_topology()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
expected_topo_dict = {'cells': [
{'cpus': '0,1', 'cpu_usage': 0,
'mem': {'total': 256, 'used': 0},
'id': 0},
{'cpus': '3', 'cpu_usage': 0,
'mem': {'total': 256, 'used': 0},
'id': 1},
{'cpus': '', 'cpu_usage': 0,
'mem': {'total': 256, 'used': 0},
'id': 2},
{'cpus': '', 'cpu_usage': 0,
'mem': {'total': 256, 'used': 0},
'id': 3}]}
with test.nested(
mock.patch.object(host.Host, "get_capabilities",
return_value=caps),
mock.patch.object(
hardware, 'get_vcpu_pin_set',
return_value=set([0, 1, 3, 4, 5])),
mock.patch.object(host.Host, 'get_online_cpus',
return_value=set([0, 1, 2, 3, 6])),
):
got_topo = drvr._get_host_numa_topology()
got_topo_dict = got_topo._to_dict()
self.assertThat(
expected_topo_dict, matchers.DictMatches(got_topo_dict))
if mempages:
# cells 0
self.assertEqual(4, got_topo.cells[0].mempages[0].size_kb)
self.assertEqual(0, got_topo.cells[0].mempages[0].total)
self.assertEqual(2048, got_topo.cells[0].mempages[1].size_kb)
self.assertEqual(0, got_topo.cells[0].mempages[1].total)
# cells 1
self.assertEqual(4, got_topo.cells[1].mempages[0].size_kb)
self.assertEqual(1024, got_topo.cells[1].mempages[0].total)
self.assertEqual(2048, got_topo.cells[1].mempages[1].size_kb)
self.assertEqual(1, got_topo.cells[1].mempages[1].total)
else:
self.assertEqual([], got_topo.cells[0].mempages)
self.assertEqual([], got_topo.cells[1].mempages)
self.assertEqual(expected_topo_dict, got_topo_dict)
self.assertEqual(set([]), got_topo.cells[0].pinned_cpus)
self.assertEqual(set([]), got_topo.cells[1].pinned_cpus)
self.assertEqual(set([]), got_topo.cells[2].pinned_cpus)
self.assertEqual(set([]), got_topo.cells[3].pinned_cpus)
self.assertEqual([set([0, 1])], got_topo.cells[0].siblings)
self.assertEqual([], got_topo.cells[1].siblings)
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
def test_get_host_numa_topology(self, mock_version):
self._test_get_host_numa_topology(mempages=True)
@mock.patch.object(fakelibvirt.Connection, 'getType')
@mock.patch.object(fakelibvirt.Connection, 'getVersion')
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
def test_get_host_numa_topology_no_mempages(self, mock_lib_version,
mock_version, mock_type):
self.flags(virt_type='kvm', group='libvirt')
mock_lib_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION) - 1
mock_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION)
mock_type.return_value = host.HV_DRIVER_QEMU
self._test_get_host_numa_topology(mempages=False)
def test_get_host_numa_topology_empty(self):
caps = vconfig.LibvirtConfigCaps()
caps.host = vconfig.LibvirtConfigCapsHost()
caps.host.cpu = vconfig.LibvirtConfigCPU()
caps.host.cpu.arch = arch.X86_64
caps.host.topology = None
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(host.Host, 'has_min_version', return_value=True),
mock.patch.object(host.Host, "get_capabilities",
return_value=caps)
) as (has_min_version, get_caps):
self.assertIsNone(drvr._get_host_numa_topology())
self.assertEqual(2, get_caps.call_count)
@mock.patch.object(fakelibvirt.Connection, 'getType')
@mock.patch.object(fakelibvirt.Connection, 'getVersion')
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
def test_get_host_numa_topology_old_version(self, mock_lib_version,
mock_version, mock_type):
self.flags(virt_type='kvm', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_lib_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) - 1
mock_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION)
mock_type.return_value = host.HV_DRIVER_QEMU
self.assertIsNone(drvr._get_host_numa_topology())
@mock.patch.object(fakelibvirt.Connection, 'getType')
@mock.patch.object(fakelibvirt.Connection, 'getVersion')
@mock.patch.object(fakelibvirt.Connection, 'getLibVersion')
def test_get_host_numa_topology_xen(self, mock_lib_version,
mock_version, mock_type):
self.flags(virt_type='xen', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_lib_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_LIBVIRT_NUMA_VERSION)
mock_version.return_value = versionutils.convert_version_to_int(
libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION)
mock_type.return_value = host.HV_DRIVER_XEN
self.assertIsNone(drvr._get_host_numa_topology())
def test_diagnostic_vcpus_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
raise fakelibvirt.libvirtError('vcpus missing')
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
def test_diagnostic_blockstats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
raise fakelibvirt.libvirtError('blockStats missing')
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
def test_diagnostic_interfacestats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
raise fakelibvirt.libvirtError('interfaceStat missing')
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
def test_diagnostic_memorystats_exception(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
raise fakelibvirt.libvirtError('memoryStats missing')
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
def test_diagnostic_full(self):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self, instance):
return DiagFakeDomain()
self.stubs.Set(host.Host, "get_domain", fake_get_domain)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
@mock.patch.object(host.Host, 'get_domain')
def test_diagnostic_full_with_multiple_interfaces(self, mock_get_domain):
xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='filename'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio'/>
</disk>
<interface type='network'>
<mac address='52:54:00:a4:38:38'/>
<source network='default'/>
<target dev='vnet0'/>
</interface>
<interface type="bridge">
<mac address="53:55:00:a5:39:39"/>
<model type="virtio"/>
<target dev="br0"/>
</interface>
</devices>
</domain>
"""
class DiagFakeDomain(FakeVirtDomain):
def __init__(self):
super(DiagFakeDomain, self).__init__(fake_xml=xml)
def vcpus(self):
return ([(0, 1, 15340000000, 0),
(1, 1, 1640000000, 0),
(2, 1, 3040000000, 0),
(3, 1, 1420000000, 0)],
[(True, False),
(True, False),
(True, False),
(True, False)])
def blockStats(self, path):
return (169, 688640, 0, 0, -1)
def interfaceStats(self, path):
return (4408, 82, 0, 0, 0, 0, 0, 0)
def memoryStats(self):
return {'actual': 220160, 'rss': 200164}
def maxMemory(self):
return 280160
def fake_get_domain(self):
return DiagFakeDomain()
mock_get_domain.side_effect = fake_get_domain
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
actual = drvr.get_diagnostics(instance)
expect = {'cpu0_time': 15340000000,
'cpu1_time': 1640000000,
'cpu2_time': 3040000000,
'cpu3_time': 1420000000,
'vda_read': 688640,
'vda_read_req': 169,
'vda_write': 0,
'vda_write_req': 0,
'vda_errors': -1,
'vdb_read': 688640,
'vdb_read_req': 169,
'vdb_write': 0,
'vdb_write_req': 0,
'vdb_errors': -1,
'memory': 280160,
'memory-actual': 220160,
'memory-rss': 200164,
'vnet0_rx': 4408,
'vnet0_rx_drop': 0,
'vnet0_rx_errors': 0,
'vnet0_rx_packets': 82,
'vnet0_tx': 0,
'vnet0_tx_drop': 0,
'vnet0_tx_errors': 0,
'vnet0_tx_packets': 0,
'br0_rx': 4408,
'br0_rx_drop': 0,
'br0_rx_errors': 0,
'br0_rx_packets': 82,
'br0_tx': 0,
'br0_tx_drop': 0,
'br0_tx_errors': 0,
'br0_tx_packets': 0,
}
self.assertEqual(actual, expect)
lt = datetime.datetime(2012, 11, 22, 12, 00, 00)
diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10)
self.useFixture(utils_fixture.TimeFixture(diags_time))
instance.launched_at = lt
actual = drvr.get_instance_diagnostics(instance)
expected = {'config_drive': False,
'cpu_details': [{'time': 15340000000},
{'time': 1640000000},
{'time': 3040000000},
{'time': 1420000000}],
'disk_details': [{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0},
{'errors_count': 0,
'id': '',
'read_bytes': 688640,
'read_requests': 169,
'write_bytes': 0,
'write_requests': 0}],
'driver': 'libvirt',
'hypervisor_os': 'linux',
'memory_details': {'maximum': 2048, 'used': 1234},
'nic_details': [{'mac_address': '52:54:00:a4:38:38',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0},
{'mac_address': '53:55:00:a5:39:39',
'rx_drop': 0,
'rx_errors': 0,
'rx_octets': 4408,
'rx_packets': 82,
'tx_drop': 0,
'tx_errors': 0,
'tx_octets': 0,
'tx_packets': 0}],
'state': 'running',
'uptime': 10.,
'version': '1.0'}
self.assertEqual(expected, actual.serialize())
@mock.patch.object(host.Host, "list_instance_domains")
def test_failing_vcpu_count(self, mock_list):
"""Domain can fail to return the vcpu description in case it's
just starting up or shutting down. Make sure None is handled
gracefully.
"""
class DiagFakeDomain(object):
def __init__(self, vcpus):
self._vcpus = vcpus
def vcpus(self):
if self._vcpus is None:
raise fakelibvirt.libvirtError("fake-error")
else:
return ([[1, 2, 3, 4]] * self._vcpus, [True] * self._vcpus)
def ID(self):
return 1
def name(self):
return "instance000001"
def UUIDString(self):
return "19479fee-07a5-49bb-9138-d3738280d63c"
mock_list.return_value = [
DiagFakeDomain(None), DiagFakeDomain(5)]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(5, drvr._get_vcpu_used())
mock_list.assert_called_with(only_guests=True, only_running=True)
@mock.patch.object(host.Host, "list_instance_domains")
def test_failing_vcpu_count_none(self, mock_list):
"""Domain will return zero if the current number of vcpus used
is None. This is in case of VM state starting up or shutting
down. None type returned is counted as zero.
"""
class DiagFakeDomain(object):
def __init__(self):
pass
def vcpus(self):
return None
def ID(self):
return 1
def name(self):
return "instance000001"
mock_list.return_value = [DiagFakeDomain()]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(0, drvr._get_vcpu_used())
mock_list.assert_called_with(only_guests=True, only_running=True)
def test_get_instance_capabilities(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
def get_host_capabilities_stub(self):
caps = vconfig.LibvirtConfigCaps()
guest = vconfig.LibvirtConfigGuest()
guest.ostype = 'hvm'
guest.arch = arch.X86_64
guest.domtype = ['kvm', 'qemu']
caps.guests.append(guest)
guest = vconfig.LibvirtConfigGuest()
guest.ostype = 'hvm'
guest.arch = arch.I686
guest.domtype = ['kvm']
caps.guests.append(guest)
return caps
self.stubs.Set(host.Host, "get_capabilities",
get_host_capabilities_stub)
want = [(arch.X86_64, 'kvm', 'hvm'),
(arch.X86_64, 'qemu', 'hvm'),
(arch.I686, 'kvm', 'hvm')]
got = drvr._get_instance_capabilities()
self.assertEqual(want, got)
def test_set_cache_mode(self):
self.flags(disk_cachemodes=['file=directsync'], group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuestDisk()
fake_conf.source_type = 'file'
drvr._set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, 'directsync')
def test_set_cache_mode_invalid_mode(self):
self.flags(disk_cachemodes=['file=FAKE'], group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuestDisk()
fake_conf.source_type = 'file'
drvr._set_cache_mode(fake_conf)
self.assertIsNone(fake_conf.driver_cache)
def test_set_cache_mode_invalid_object(self):
self.flags(disk_cachemodes=['file=directsync'], group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_conf = FakeConfigGuest()
fake_conf.driver_cache = 'fake'
drvr._set_cache_mode(fake_conf)
self.assertEqual(fake_conf.driver_cache, 'fake')
@mock.patch('os.unlink')
@mock.patch.object(os.path, 'exists')
def _test_shared_storage_detection(self, is_same,
mock_exists, mock_unlink):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
drvr.get_host_ip_addr = mock.MagicMock(return_value='bar')
mock_exists.return_value = is_same
with test.nested(
mock.patch.object(drvr._remotefs, 'create_file'),
mock.patch.object(drvr._remotefs, 'remove_file')
) as (mock_rem_fs_create, mock_rem_fs_remove):
result = drvr._is_storage_shared_with('host', '/path')
mock_rem_fs_create.assert_any_call('host', mock.ANY)
create_args, create_kwargs = mock_rem_fs_create.call_args
self.assertTrue(create_args[1].startswith('/path'))
if is_same:
mock_unlink.assert_called_once_with(mock.ANY)
else:
mock_rem_fs_remove.assert_called_with('host', mock.ANY)
remove_args, remove_kwargs = mock_rem_fs_remove.call_args
self.assertTrue(remove_args[1].startswith('/path'))
return result
def test_shared_storage_detection_same_host(self):
self.assertTrue(self._test_shared_storage_detection(True))
def test_shared_storage_detection_different_host(self):
self.assertFalse(self._test_shared_storage_detection(False))
def test_shared_storage_detection_easy(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.mox.StubOutWithMock(drvr, 'get_host_ip_addr')
self.mox.StubOutWithMock(utils, 'execute')
self.mox.StubOutWithMock(os.path, 'exists')
self.mox.StubOutWithMock(os, 'unlink')
drvr.get_host_ip_addr().AndReturn('foo')
self.mox.ReplayAll()
self.assertTrue(drvr._is_storage_shared_with('foo', '/path'))
def test_store_pid_remove_pid(self):
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
popen = mock.Mock(pid=3)
drvr.job_tracker.add_job(instance, popen.pid)
self.assertIn(3, drvr.job_tracker.jobs[instance.uuid])
drvr.job_tracker.remove_job(instance, popen.pid)
self.assertNotIn(instance.uuid, drvr.job_tracker.jobs)
@mock.patch('nova.virt.libvirt.host.Host.get_domain')
def test_get_domain_info_with_more_return(self, mock_get_domain):
instance = objects.Instance(**self.test_instance)
dom_mock = mock.MagicMock()
dom_mock.info.return_value = [
1, 2048, 737, 8, 12345, 888888
]
dom_mock.ID.return_value = mock.sentinel.instance_id
mock_get_domain.return_value = dom_mock
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
info = drvr.get_info(instance)
self.assertEqual(1, info.state)
self.assertEqual(2048, info.max_mem_kb)
self.assertEqual(737, info.mem_kb)
self.assertEqual(8, info.num_cpu)
self.assertEqual(12345, info.cpu_time_ns)
self.assertEqual(mock.sentinel.instance_id, info.id)
dom_mock.info.assert_called_once_with()
dom_mock.ID.assert_called_once_with()
mock_get_domain.assert_called_once_with(instance)
def test_create_domain(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_domain = mock.MagicMock()
guest = drvr._create_domain(domain=mock_domain)
self.assertEqual(mock_domain, guest._domain)
mock_domain.createWithFlags.assert_has_calls([mock.call(0)])
@mock.patch('nova.virt.disk.api.clean_lxc_namespace')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info')
@mock.patch('nova.virt.disk.api.setup_container')
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch.object(fake_libvirt_utils, 'get_instance_path')
def test_create_domain_lxc(self, mock_get_inst_path, mock_ensure_tree,
mock_setup_container, mock_get_info, mock_clean):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_instance = mock.MagicMock()
inst_sys_meta = dict()
mock_instance.system_metadata = inst_sys_meta
mock_get_inst_path.return_value = '/tmp/'
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_image = mock.MagicMock()
mock_image.path = '/tmp/test.img'
drvr.image_backend.image.return_value = mock_image
mock_setup_container.return_value = '/dev/nbd0'
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.RUNNING)
with test.nested(
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')):
drvr._create_domain_and_network(self.context, 'xml',
mock_instance, [], None)
self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name'])
self.assertFalse(mock_instance.called)
mock_get_inst_path.assert_has_calls([mock.call(mock_instance)])
mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')])
drvr.image_backend.image.assert_has_calls([mock.call(mock_instance,
'disk')])
setup_container_call = mock.call(
mock_image.get_model(),
container_dir='/tmp/rootfs')
mock_setup_container.assert_has_calls([setup_container_call])
mock_get_info.assert_has_calls([mock.call(mock_instance)])
mock_clean.assert_has_calls([mock.call(container_dir='/tmp/rootfs')])
@mock.patch('nova.virt.disk.api.clean_lxc_namespace')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info')
@mock.patch.object(fake_libvirt_utils, 'chown_for_id_maps')
@mock.patch('nova.virt.disk.api.setup_container')
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch.object(fake_libvirt_utils, 'get_instance_path')
def test_create_domain_lxc_id_maps(self, mock_get_inst_path,
mock_ensure_tree, mock_setup_container,
mock_chown, mock_get_info, mock_clean):
self.flags(virt_type='lxc', uid_maps=["0:1000:100"],
gid_maps=["0:1000:100"], group='libvirt')
def chown_side_effect(path, id_maps):
self.assertEqual('/tmp/rootfs', path)
self.assertIsInstance(id_maps[0], vconfig.LibvirtConfigGuestUIDMap)
self.assertEqual(0, id_maps[0].start)
self.assertEqual(1000, id_maps[0].target)
self.assertEqual(100, id_maps[0].count)
self.assertIsInstance(id_maps[1], vconfig.LibvirtConfigGuestGIDMap)
self.assertEqual(0, id_maps[1].start)
self.assertEqual(1000, id_maps[1].target)
self.assertEqual(100, id_maps[1].count)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_instance = mock.MagicMock()
inst_sys_meta = dict()
mock_instance.system_metadata = inst_sys_meta
mock_get_inst_path.return_value = '/tmp/'
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_image = mock.MagicMock()
mock_image.path = '/tmp/test.img'
drvr.image_backend.image.return_value = mock_image
mock_setup_container.return_value = '/dev/nbd0'
mock_chown.side_effect = chown_side_effect
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.RUNNING)
with test.nested(
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')
) as (
mock_is_booted_from_volume, mock_create_domain, mock_plug_vifs,
mock_setup_basic_filtering, mock_prepare_instance_filter,
mock_apply_instance_filter
):
drvr._create_domain_and_network(self.context, 'xml',
mock_instance, [], None)
self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name'])
self.assertFalse(mock_instance.called)
mock_get_inst_path.assert_has_calls([mock.call(mock_instance)])
mock_is_booted_from_volume.assert_called_once_with(mock_instance, {})
mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')])
drvr.image_backend.image.assert_has_calls([mock.call(mock_instance,
'disk')])
setup_container_call = mock.call(
mock_image.get_model(),
container_dir='/tmp/rootfs')
mock_setup_container.assert_has_calls([setup_container_call])
mock_get_info.assert_has_calls([mock.call(mock_instance)])
mock_clean.assert_has_calls([mock.call(container_dir='/tmp/rootfs')])
@mock.patch('nova.virt.disk.api.teardown_container')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info')
@mock.patch('nova.virt.disk.api.setup_container')
@mock.patch('oslo_utils.fileutils.ensure_tree')
@mock.patch.object(fake_libvirt_utils, 'get_instance_path')
def test_create_domain_lxc_not_running(self, mock_get_inst_path,
mock_ensure_tree,
mock_setup_container,
mock_get_info, mock_teardown):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
mock_instance = mock.MagicMock()
inst_sys_meta = dict()
mock_instance.system_metadata = inst_sys_meta
mock_get_inst_path.return_value = '/tmp/'
mock_image_backend = mock.MagicMock()
drvr.image_backend = mock_image_backend
mock_image = mock.MagicMock()
mock_image.path = '/tmp/test.img'
drvr.image_backend.image.return_value = mock_image
mock_setup_container.return_value = '/dev/nbd0'
mock_get_info.return_value = hardware.InstanceInfo(
state=power_state.SHUTDOWN)
with test.nested(
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')):
drvr._create_domain_and_network(self.context, 'xml',
mock_instance, [], None)
self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name'])
self.assertFalse(mock_instance.called)
mock_get_inst_path.assert_has_calls([mock.call(mock_instance)])
mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')])
drvr.image_backend.image.assert_has_calls([mock.call(mock_instance,
'disk')])
setup_container_call = mock.call(
mock_image.get_model(),
container_dir='/tmp/rootfs')
mock_setup_container.assert_has_calls([setup_container_call])
mock_get_info.assert_has_calls([mock.call(mock_instance)])
teardown_call = mock.call(container_dir='/tmp/rootfs')
mock_teardown.assert_has_calls([teardown_call])
def test_create_domain_define_xml_fails(self):
"""Tests that the xml is logged when defining the domain fails."""
fake_xml = "<test>this is a test</test>"
def fake_defineXML(xml):
self.assertEqual(fake_xml, xml)
raise fakelibvirt.libvirtError('virDomainDefineXML() failed')
def fake_safe_decode(text, *args, **kwargs):
return text + 'safe decoded'
self.log_error_called = False
def fake_error(msg, *args, **kwargs):
self.log_error_called = True
self.assertIn(fake_xml, msg % args)
self.assertIn('safe decoded', msg % args)
self.stubs.Set(encodeutils, 'safe_decode', fake_safe_decode)
self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error)
self.create_fake_libvirt_mock(defineXML=fake_defineXML)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(fakelibvirt.libvirtError, drvr._create_domain,
fake_xml)
self.assertTrue(self.log_error_called)
def test_create_domain_with_flags_fails(self):
"""Tests that the xml is logged when creating the domain with flags
fails
"""
fake_xml = "<test>this is a test</test>"
fake_domain = FakeVirtDomain(fake_xml)
def fake_createWithFlags(launch_flags):
raise fakelibvirt.libvirtError('virDomainCreateWithFlags() failed')
self.log_error_called = False
def fake_error(msg, *args, **kwargs):
self.log_error_called = True
self.assertIn(fake_xml, msg % args)
self.stubs.Set(fake_domain, 'createWithFlags', fake_createWithFlags)
self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error)
self.create_fake_libvirt_mock()
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.assertRaises(fakelibvirt.libvirtError, drvr._create_domain,
domain=fake_domain)
self.assertTrue(self.log_error_called)
def test_create_domain_enable_hairpin_fails(self):
"""Tests that the xml is logged when enabling hairpin mode for the
domain fails.
"""
fake_xml = "<test>this is a test</test>"
fake_domain = FakeVirtDomain(fake_xml)
def fake_execute(*args, **kwargs):
raise processutils.ProcessExecutionError('error')
def fake_get_interfaces(*args):
return ["dev"]
self.log_error_called = False
def fake_error(msg, *args, **kwargs):
self.log_error_called = True
self.assertIn(fake_xml, msg % args)
self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error)
self.create_fake_libvirt_mock()
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
self.stubs.Set(nova.utils, 'execute', fake_execute)
self.stubs.Set(
nova.virt.libvirt.guest.Guest, 'get_interfaces',
fake_get_interfaces)
self.assertRaises(processutils.ProcessExecutionError,
drvr._create_domain,
domain=fake_domain,
power_on=False)
self.assertTrue(self.log_error_called)
def test_get_vnc_console(self):
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<graphics type='vnc' port='5900'/>"
"</devices></domain>")
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
vnc_dict = drvr.get_vnc_console(self.context, instance)
self.assertEqual(vnc_dict.port, '5900')
def test_get_vnc_console_unavailable(self):
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices></devices></domain>")
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.ConsoleTypeUnavailable,
drvr.get_vnc_console, self.context, instance)
def test_get_spice_console(self):
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<graphics type='spice' port='5950'/>"
"</devices></domain>")
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
spice_dict = drvr.get_spice_console(self.context, instance)
self.assertEqual(spice_dict.port, '5950')
def test_get_spice_console_unavailable(self):
instance = objects.Instance(**self.test_instance)
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices></devices></domain>")
vdmock = self.mox.CreateMock(fakelibvirt.virDomain)
self.mox.StubOutWithMock(vdmock, "XMLDesc")
vdmock.XMLDesc(flags=0).AndReturn(dummyxml)
def fake_lookup(instance_name):
if instance_name == instance['name']:
return vdmock
self.create_fake_libvirt_mock(lookupByName=fake_lookup)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertRaises(exception.ConsoleTypeUnavailable,
drvr.get_spice_console, self.context, instance)
def test_detach_volume_with_instance_not_found(self):
# Test that detach_volume() method does not raise exception,
# if the instance does not exist.
instance = objects.Instance(**self.test_instance)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(host.Host, 'get_domain',
side_effect=exception.InstanceNotFound(
instance_id=instance.uuid)),
mock.patch.object(drvr, '_disconnect_volume')
) as (_get_domain, _disconnect_volume):
connection_info = {'driver_volume_type': 'fake'}
drvr.detach_volume(connection_info, instance, '/dev/sda')
_get_domain.assert_called_once_with(instance)
_disconnect_volume.assert_called_once_with(connection_info,
'sda')
def _test_attach_detach_interface_get_config(self, method_name):
"""Tests that the get_config() method is properly called in
attach_interface() and detach_interface().
method_name: either \"attach_interface\" or \"detach_interface\"
depending on the method to test.
"""
self.stubs.Set(host.Host, "get_domain", lambda a, b: FakeVirtDomain())
instance = objects.Instance(**self.test_instance)
network_info = _fake_network_info(self, 1)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
fake_image_meta = objects.ImageMeta.from_dict(
{'id': instance['image_ref']})
if method_name == "attach_interface":
self.mox.StubOutWithMock(drvr.firewall_driver,
'setup_basic_filtering')
drvr.firewall_driver.setup_basic_filtering(instance, network_info)
expected = drvr.vif_driver.get_config(instance, network_info[0],
fake_image_meta,
instance.get_flavor(),
CONF.libvirt.virt_type,
drvr._host)
self.mox.StubOutWithMock(drvr.vif_driver, 'get_config')
drvr.vif_driver.get_config(instance, network_info[0],
mox.IsA(objects.ImageMeta),
mox.IsA(objects.Flavor),
CONF.libvirt.virt_type,
drvr._host).\
AndReturn(expected)
self.mox.ReplayAll()
if method_name == "attach_interface":
drvr.attach_interface(instance, fake_image_meta,
network_info[0])
elif method_name == "detach_interface":
drvr.detach_interface(instance, network_info[0])
else:
raise ValueError("Unhandled method %s" % method_name)
@mock.patch.object(lockutils, "external_lock")
def test_attach_interface_get_config(self, mock_lock):
"""Tests that the get_config() method is properly called in
attach_interface().
"""
mock_lock.return_value = threading.Semaphore()
self._test_attach_detach_interface_get_config("attach_interface")
def test_detach_interface_get_config(self):
"""Tests that the get_config() method is properly called in
detach_interface().
"""
self._test_attach_detach_interface_get_config("detach_interface")
def test_default_root_device_name(self):
instance = {'uuid': 'fake_instance'}
image_meta = objects.ImageMeta.from_dict({'id': uuids.image_id})
root_bdm = {'source_type': 'image',
'destination_type': 'volume',
'image_id': 'fake_id'}
self.flags(virt_type='qemu', group='libvirt')
self.mox.StubOutWithMock(blockinfo, 'get_disk_bus_for_device_type')
self.mox.StubOutWithMock(blockinfo, 'get_root_info')
blockinfo.get_disk_bus_for_device_type(instance,
'qemu',
image_meta,
'disk').InAnyOrder().\
AndReturn('virtio')
blockinfo.get_disk_bus_for_device_type(instance,
'qemu',
image_meta,
'cdrom').InAnyOrder().\
AndReturn('ide')
blockinfo.get_root_info(instance, 'qemu',
image_meta, root_bdm,
'virtio', 'ide').AndReturn({'dev': 'vda'})
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.assertEqual(drvr.default_root_device_name(instance, image_meta,
root_bdm), '/dev/vda')
@mock.patch.object(objects.BlockDeviceMapping, "save")
def test_default_device_names_for_instance(self, save_mock):
instance = objects.Instance(**self.test_instance)
instance.root_device_name = '/dev/vda'
ephemerals = [objects.BlockDeviceMapping(
**fake_block_device.AnonFakeDbBlockDeviceDict(
{'device_name': 'vdb',
'source_type': 'blank',
'volume_size': 2,
'destination_type': 'local'}))]
swap = [objects.BlockDeviceMapping(
**fake_block_device.AnonFakeDbBlockDeviceDict(
{'device_name': 'vdg',
'source_type': 'blank',
'volume_size': 512,
'guest_format': 'swap',
'destination_type': 'local'}))]
block_device_mapping = [
objects.BlockDeviceMapping(
**fake_block_device.AnonFakeDbBlockDeviceDict(
{'source_type': 'volume',
'destination_type': 'volume',
'volume_id': 'fake-image-id',
'device_name': '/dev/vdxx',
'disk_bus': 'scsi'}))]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.default_device_names_for_instance(instance,
instance.root_device_name,
ephemerals, swap,
block_device_mapping)
# Ephemeral device name was correct so no changes
self.assertEqual('/dev/vdb', ephemerals[0].device_name)
# Swap device name was incorrect so it was changed
self.assertEqual('/dev/vdc', swap[0].device_name)
# Volume device name was changed too, taking the bus into account
self.assertEqual('/dev/sda', block_device_mapping[0].device_name)
self.assertEqual(3, save_mock.call_count)
def _test_get_device_name_for_instance(self, new_bdm, expected_dev):
instance = objects.Instance(**self.test_instance)
instance.root_device_name = '/dev/vda'
instance.ephemeral_gb = 0
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
got_dev = drvr.get_device_name_for_instance(
instance, [], new_bdm)
self.assertEqual(expected_dev, got_dev)
def test_get_device_name_for_instance_simple(self):
new_bdm = objects.BlockDeviceMapping(
context=context,
source_type='volume', destination_type='volume',
boot_index=-1, volume_id='fake-id',
device_name=None, guest_format=None,
disk_bus=None, device_type=None)
self._test_get_device_name_for_instance(new_bdm, '/dev/vdb')
def test_get_device_name_for_instance_suggested(self):
new_bdm = objects.BlockDeviceMapping(
context=context,
source_type='volume', destination_type='volume',
boot_index=-1, volume_id='fake-id',
device_name='/dev/vdg', guest_format=None,
disk_bus=None, device_type=None)
self._test_get_device_name_for_instance(new_bdm, '/dev/vdb')
def test_get_device_name_for_instance_bus(self):
new_bdm = objects.BlockDeviceMapping(
context=context,
source_type='volume', destination_type='volume',
boot_index=-1, volume_id='fake-id',
device_name=None, guest_format=None,
disk_bus='scsi', device_type=None)
self._test_get_device_name_for_instance(new_bdm, '/dev/sda')
def test_get_device_name_for_instance_device_type(self):
new_bdm = objects.BlockDeviceMapping(
context=context,
source_type='volume', destination_type='volume',
boot_index=-1, volume_id='fake-id',
device_name=None, guest_format=None,
disk_bus=None, device_type='floppy')
self._test_get_device_name_for_instance(new_bdm, '/dev/fda')
def test_is_supported_fs_format(self):
supported_fs = [disk_api.FS_FORMAT_EXT2, disk_api.FS_FORMAT_EXT3,
disk_api.FS_FORMAT_EXT4, disk_api.FS_FORMAT_XFS]
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
for fs in supported_fs:
self.assertTrue(drvr.is_supported_fs_format(fs))
supported_fs = ['', 'dummy']
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
for fs in supported_fs:
self.assertFalse(drvr.is_supported_fs_format(fs))
def test_post_live_migration_at_destination_with_block_device_info(self):
# Preparing mocks
mock_domain = self.mox.CreateMock(fakelibvirt.virDomain)
self.resultXML = None
def fake_getLibVersion():
return fakelibvirt.FAKE_LIBVIRT_VERSION
def fake_getCapabilities():
return """
<capabilities>
<host>
<uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
<cpu>
<arch>x86_64</arch>
<model>Penryn</model>
<vendor>Intel</vendor>
<topology sockets='1' cores='2' threads='1'/>
<feature name='xtpr'/>
</cpu>
</host>
</capabilities>
"""
def fake_to_xml(context, instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None, write_to_disk=False):
if image_meta is None:
image_meta = objects.ImageMeta.from_dict({})
conf = drvr._get_guest_config(instance, network_info, image_meta,
disk_info, rescue, block_device_info)
self.resultXML = conf.to_xml()
return self.resultXML
def fake_get_domain(instance):
return mock_domain
def fake_baselineCPU(cpu, flag):
return """<cpu mode='custom' match='exact'>
<model fallback='allow'>Westmere</model>
<vendor>Intel</vendor>
<feature policy='require' name='aes'/>
</cpu>
"""
network_info = _fake_network_info(self, 1)
self.create_fake_libvirt_mock(getLibVersion=fake_getLibVersion,
getCapabilities=fake_getCapabilities,
getVersion=lambda: 1005001,
listDefinedDomains=lambda: [],
numOfDomains=lambda: 0,
baselineCPU=fake_baselineCPU)
instance_ref = self.test_instance
instance_ref['image_ref'] = 123456 # we send an int to test sha1 call
instance = objects.Instance(**instance_ref)
self.mox.ReplayAll()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(drvr,
'_get_guest_xml',
fake_to_xml)
self.stubs.Set(host.Host,
'get_domain',
fake_get_domain)
bdm = objects.BlockDeviceMapping(
self.context,
**fake_block_device.FakeDbBlockDeviceDict(
{'id': 1, 'guest_format': None,
'boot_index': 0,
'source_type': 'volume',
'destination_type': 'volume',
'device_name': '/dev/vda',
'disk_bus': 'virtio',
'device_type': 'disk',
'delete_on_termination': False}))
block_device_info = {'block_device_mapping':
driver_block_device.convert_volumes([bdm])}
block_device_info['block_device_mapping'][0]['connection_info'] = (
{'driver_volume_type': 'iscsi'})
with test.nested(
mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'),
mock.patch.object(objects.Instance, 'save')
) as (mock_volume_save, mock_instance_save):
drvr.post_live_migration_at_destination(
self.context, instance, network_info, True,
block_device_info=block_device_info)
self.assertIn('fake', self.resultXML)
mock_volume_save.assert_called_once_with()
def test_create_propagates_exceptions(self):
self.flags(virt_type='lxc', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(id=1, uuid=uuids.instance,
image_ref='my_fake_image')
with test.nested(
mock.patch.object(drvr, '_create_domain_setup_lxc'),
mock.patch.object(drvr, '_create_domain_cleanup_lxc'),
mock.patch.object(drvr, '_is_booted_from_volume',
return_value=False),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr, 'firewall_driver'),
mock.patch.object(drvr, '_create_domain',
side_effect=exception.NovaException),
mock.patch.object(drvr, 'cleanup')):
self.assertRaises(exception.NovaException,
drvr._create_domain_and_network,
self.context,
'xml',
instance, None, None)
def test_create_without_pause(self):
self.flags(virt_type='lxc', group='libvirt')
@contextlib.contextmanager
def fake_lxc_disk_handler(*args, **kwargs):
yield
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
with test.nested(
mock.patch.object(drvr, '_lxc_disk_handler',
side_effect=fake_lxc_disk_handler),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr, 'firewall_driver'),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr, 'cleanup')) as (
_handler, cleanup, firewall_driver, create, plug_vifs):
domain = drvr._create_domain_and_network(self.context, 'xml',
instance, None, None)
self.assertEqual(0, create.call_args_list[0][1]['pause'])
self.assertEqual(0, domain.resume.call_count)
def _test_create_with_network_events(self, neutron_failure=None,
power_on=True):
generated_events = []
def wait_timeout():
event = mock.MagicMock()
if neutron_failure == 'timeout':
raise eventlet.timeout.Timeout()
elif neutron_failure == 'error':
event.status = 'failed'
else:
event.status = 'completed'
return event
def fake_prepare(instance, event_name):
m = mock.MagicMock()
m.instance = instance
m.event_name = event_name
m.wait.side_effect = wait_timeout
generated_events.append(m)
return m
virtapi = manager.ComputeVirtAPI(mock.MagicMock())
prepare = virtapi._compute.instance_events.prepare_for_instance_event
prepare.side_effect = fake_prepare
drvr = libvirt_driver.LibvirtDriver(virtapi, False)
instance = objects.Instance(**self.test_instance)
vifs = [{'id': 'vif1', 'active': False},
{'id': 'vif2', 'active': False}]
@mock.patch.object(drvr, 'plug_vifs')
@mock.patch.object(drvr, 'firewall_driver')
@mock.patch.object(drvr, '_create_domain')
@mock.patch.object(drvr, 'cleanup')
def test_create(cleanup, create, fw_driver, plug_vifs):
domain = drvr._create_domain_and_network(self.context, 'xml',
instance, vifs, None,
power_on=power_on)
plug_vifs.assert_called_with(instance, vifs)
pause = self._get_pause_flag(drvr, vifs, power_on=power_on)
self.assertEqual(pause,
create.call_args_list[0][1]['pause'])
if pause:
domain.resume.assert_called_once_with()
if neutron_failure and CONF.vif_plugging_is_fatal:
cleanup.assert_called_once_with(self.context,
instance, network_info=vifs,
block_device_info=None)
test_create()
if utils.is_neutron() and CONF.vif_plugging_timeout and power_on:
prepare.assert_has_calls([
mock.call(instance, 'network-vif-plugged-vif1'),
mock.call(instance, 'network-vif-plugged-vif2')])
for event in generated_events:
if neutron_failure and generated_events.index(event) != 0:
self.assertEqual(0, event.call_count)
elif (neutron_failure == 'error' and
not CONF.vif_plugging_is_fatal):
event.wait.assert_called_once_with()
else:
self.assertEqual(0, prepare.call_count)
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron(self, is_neutron):
self._test_create_with_network_events()
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_power_off(self,
is_neutron):
# Tests that we don't wait for events if we don't start the instance.
self._test_create_with_network_events(power_on=False)
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_nowait(self, is_neutron):
self.flags(vif_plugging_timeout=0)
self._test_create_with_network_events()
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_failed_nonfatal_timeout(
self, is_neutron):
self.flags(vif_plugging_is_fatal=False)
self._test_create_with_network_events(neutron_failure='timeout')
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_failed_fatal_timeout(
self, is_neutron):
self.assertRaises(exception.VirtualInterfaceCreateException,
self._test_create_with_network_events,
neutron_failure='timeout')
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_failed_nonfatal_error(
self, is_neutron):
self.flags(vif_plugging_is_fatal=False)
self._test_create_with_network_events(neutron_failure='error')
@mock.patch('nova.utils.is_neutron', return_value=True)
def test_create_with_network_events_neutron_failed_fatal_error(
self, is_neutron):
self.assertRaises(exception.VirtualInterfaceCreateException,
self._test_create_with_network_events,
neutron_failure='error')
@mock.patch('nova.utils.is_neutron', return_value=False)
def test_create_with_network_events_non_neutron(self, is_neutron):
self._test_create_with_network_events()
@mock.patch('nova.volume.encryptors.get_encryption_metadata')
@mock.patch('nova.virt.libvirt.blockinfo.get_info_from_bdm')
def test_create_with_bdm(self, get_info_from_bdm, get_encryption_metadata):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
mock_dom = mock.MagicMock()
mock_encryption_meta = mock.MagicMock()
get_encryption_metadata.return_value = mock_encryption_meta
fake_xml = """
<domain>
<name>instance-00000001</name>
<memory>1048576</memory>
<vcpu>1</vcpu>
<devices>
<disk type='file' device='disk'>
<driver name='qemu' type='raw' cache='none'/>
<source file='/path/fake-volume1'/>
<target dev='vda' bus='virtio'/>
</disk>
</devices>
</domain>
"""
fake_volume_id = "fake-volume-id"
connection_info = {"driver_volume_type": "fake",
"data": {"access_mode": "rw",
"volume_id": fake_volume_id}}
def fake_getitem(*args, **kwargs):
fake_bdm = {'connection_info': connection_info,
'mount_device': '/dev/vda'}
return fake_bdm.get(args[0])
mock_volume = mock.MagicMock()
mock_volume.__getitem__.side_effect = fake_getitem
block_device_info = {'block_device_mapping': [mock_volume]}
network_info = [network_model.VIF(id='1'),
network_model.VIF(id='2', active=True)]
with test.nested(
mock.patch.object(drvr, '_get_volume_encryptor'),
mock.patch.object(drvr, 'plug_vifs'),
mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'),
mock.patch.object(drvr.firewall_driver,
'prepare_instance_filter'),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(drvr.firewall_driver, 'apply_instance_filter'),
) as (get_volume_encryptor, plug_vifs, setup_basic_filtering,
prepare_instance_filter, create_domain, apply_instance_filter):
create_domain.return_value = libvirt_guest.Guest(mock_dom)
guest = drvr._create_domain_and_network(
self.context, fake_xml, instance, network_info, None,
block_device_info=block_device_info)
get_encryption_metadata.assert_called_once_with(self.context,
drvr._volume_api, fake_volume_id, connection_info)
get_volume_encryptor.assert_called_once_with(connection_info,
mock_encryption_meta)
plug_vifs.assert_called_once_with(instance, network_info)
setup_basic_filtering.assert_called_once_with(instance,
network_info)
prepare_instance_filter.assert_called_once_with(instance,
network_info)
pause = self._get_pause_flag(drvr, network_info)
create_domain.assert_called_once_with(
fake_xml, pause=pause, power_on=True, post_xml_callback=None)
self.assertEqual(mock_dom, guest._domain)
def test_get_guest_storage_config(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
test_instance = copy.deepcopy(self.test_instance)
test_instance["default_swap_device"] = None
instance = objects.Instance(**test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
flavor = instance.get_flavor()
conn_info = {'driver_volume_type': 'fake', 'data': {}}
bdm = objects.BlockDeviceMapping(
self.context,
**fake_block_device.FakeDbBlockDeviceDict({
'id': 1,
'source_type': 'volume',
'destination_type': 'volume',
'device_name': '/dev/vdc'}))
bdi = {'block_device_mapping':
driver_block_device.convert_volumes([bdm])}
bdm = bdi['block_device_mapping'][0]
bdm['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
image_meta,
bdi)
mock_conf = mock.MagicMock(source_path='fake')
with test.nested(
mock.patch.object(driver_block_device.DriverVolumeBlockDevice,
'save'),
mock.patch.object(drvr, '_connect_volume'),
mock.patch.object(drvr, '_get_volume_config',
return_value=mock_conf),
mock.patch.object(drvr, '_set_cache_mode')
) as (volume_save, connect_volume, get_volume_config, set_cache_mode):
devices = drvr._get_guest_storage_config(instance, image_meta,
disk_info, False, bdi, flavor, "hvm")
self.assertEqual(3, len(devices))
self.assertEqual('/dev/vdb', instance.default_ephemeral_device)
self.assertIsNone(instance.default_swap_device)
connect_volume.assert_called_with(bdm['connection_info'],
{'bus': 'virtio', 'type': 'disk', 'dev': 'vdc'})
get_volume_config.assert_called_with(bdm['connection_info'],
{'bus': 'virtio', 'type': 'disk', 'dev': 'vdc'})
volume_save.assert_called_once_with()
self.assertEqual(3, set_cache_mode.call_count)
def test_get_neutron_events(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
network_info = [network_model.VIF(id='1'),
network_model.VIF(id='2', active=True)]
events = drvr._get_neutron_events(network_info)
self.assertEqual([('network-vif-plugged', '1')], events)
def test_unplug_vifs_ignores_errors(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
with mock.patch.object(drvr, 'vif_driver') as vif_driver:
vif_driver.unplug.side_effect = exception.AgentError(
method='unplug')
drvr._unplug_vifs('inst', [1], ignore_errors=True)
vif_driver.unplug.assert_called_once_with('inst', 1)
def test_unplug_vifs_reports_errors(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
with mock.patch.object(drvr, 'vif_driver') as vif_driver:
vif_driver.unplug.side_effect = exception.AgentError(
method='unplug')
self.assertRaises(exception.AgentError,
drvr.unplug_vifs, 'inst', [1])
vif_driver.unplug.assert_called_once_with('inst', 1)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._unplug_vifs')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain')
def test_cleanup_pass_with_no_mount_device(self, undefine, unplug):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
drvr.firewall_driver = mock.Mock()
drvr._disconnect_volume = mock.Mock()
fake_inst = {'name': 'foo'}
fake_bdms = [{'connection_info': 'foo',
'mount_device': None}]
with mock.patch('nova.virt.driver'
'.block_device_info_get_mapping',
return_value=fake_bdms):
drvr.cleanup('ctxt', fake_inst, 'netinfo', destroy_disks=False)
self.assertTrue(drvr._disconnect_volume.called)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._unplug_vifs')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain')
def test_cleanup_wants_vif_errors_ignored(self, undefine, unplug):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
fake_inst = {'name': 'foo'}
with mock.patch.object(drvr._conn, 'lookupByName') as lookup:
lookup.return_value = fake_inst
# NOTE(danms): Make unplug cause us to bail early, since
# we only care about how it was called
unplug.side_effect = test.TestingException
self.assertRaises(test.TestingException,
drvr.cleanup, 'ctxt', fake_inst, 'netinfo')
unplug.assert_called_once_with(fake_inst, 'netinfo', True)
@mock.patch.object(libvirt_driver.LibvirtDriver, 'unfilter_instance')
@mock.patch.object(libvirt_driver.LibvirtDriver, 'delete_instance_files',
return_value=True)
@mock.patch.object(objects.Instance, 'save')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_undefine_domain')
def test_cleanup_migrate_data_shared_block_storage(self,
_undefine_domain,
save,
delete_instance_files,
unfilter_instance):
# Tests the cleanup method when migrate_data has
# is_shared_block_storage=True and destroy_disks=False.
instance = objects.Instance(self.context, **self.test_instance)
migrate_data = objects.LibvirtLiveMigrateData(
is_shared_block_storage=True)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
drvr.cleanup(
self.context, instance, network_info={}, destroy_disks=False,
migrate_data=migrate_data, destroy_vifs=False)
delete_instance_files.assert_called_once_with(instance)
self.assertEqual(1, int(instance.system_metadata['clean_attempts']))
self.assertTrue(instance.cleaned)
save.assert_called_once_with()
def test_swap_volume(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
mock_dom = mock.MagicMock()
guest = libvirt_guest.Guest(mock_dom)
with mock.patch.object(drvr._conn, 'defineXML',
create=True) as mock_define:
xmldoc = "<domain/>"
srcfile = "/first/path"
dstfile = "/second/path"
mock_dom.XMLDesc.return_value = xmldoc
mock_dom.isPersistent.return_value = True
mock_dom.blockJobInfo.return_value = {
'type': 0,
'bandwidth': 0,
'cur': 100,
'end': 100
}
drvr._swap_volume(guest, srcfile, dstfile, 1)
mock_dom.XMLDesc.assert_called_once_with(
flags=(fakelibvirt.VIR_DOMAIN_XML_INACTIVE |
fakelibvirt.VIR_DOMAIN_XML_SECURE))
mock_dom.blockRebase.assert_called_once_with(
srcfile, dstfile, 0, flags=(
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_COPY |
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT))
mock_dom.blockResize.assert_called_once_with(
srcfile, 1 * units.Gi / units.Ki)
mock_define.assert_called_once_with(xmldoc)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._disconnect_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._swap_volume')
@mock.patch('nova.objects.block_device.BlockDeviceMapping.'
'get_by_volume_and_instance')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._get_volume_config')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._connect_volume')
@mock.patch('nova.virt.libvirt.host.Host.get_guest')
def _test_swap_volume_driver_bdm_save(self, get_guest,
connect_volume, get_volume_config,
get_by_volume_and_instance,
swap_volume,
disconnect_volume,
volume_save,
source_type):
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
instance = objects.Instance(**self.test_instance)
old_connection_info = {'driver_volume_type': 'fake',
'serial': 'old-volume-id',
'data': {'device_path': '/fake-old-volume',
'access_mode': 'rw'}}
new_connection_info = {'driver_volume_type': 'fake',
'serial': 'new-volume-id',
'data': {'device_path': '/fake-new-volume',
'access_mode': 'rw'}}
mock_dom = mock.MagicMock()
guest = libvirt_guest.Guest(mock_dom)
mock_dom.XMLDesc.return_value = """<domain>
<devices>
<disk type='file'>
<source file='/fake-old-volume'/>
<target dev='vdb' bus='virtio'/>
</disk>
</devices>
</domain>
"""
mock_dom.name.return_value = 'inst'
mock_dom.UUIDString.return_value = 'uuid'
get_guest.return_value = guest
disk_info = {'bus': 'virtio', 'type': 'disk', 'dev': 'vdb'}
get_volume_config.return_value = mock.MagicMock(
source_path='/fake-new-volume')
bdm = objects.BlockDeviceMapping(self.context,
**fake_block_device.FakeDbBlockDeviceDict(
{'id': 2, 'instance_uuid': uuids.instance,
'device_name': '/dev/vdb',
'source_type': source_type,
'destination_type': 'volume',
'volume_id': 'fake-volume-id-2',
'boot_index': 0}))
get_by_volume_and_instance.return_value = bdm
conn.swap_volume(old_connection_info, new_connection_info, instance,
'/dev/vdb', 1)
get_guest.assert_called_once_with(instance)
connect_volume.assert_called_once_with(new_connection_info, disk_info)
swap_volume.assert_called_once_with(guest, 'vdb',
'/fake-new-volume', 1)
disconnect_volume.assert_called_once_with(old_connection_info, 'vdb')
volume_save.assert_called_once_with()
@mock.patch('nova.virt.block_device.DriverVolumeBlockDevice.save')
def test_swap_volume_driver_bdm_save_source_is_volume(self, volume_save):
self._test_swap_volume_driver_bdm_save(volume_save=volume_save,
source_type='volume')
@mock.patch('nova.virt.block_device.DriverImageBlockDevice.save')
def test_swap_volume_driver_bdm_save_source_is_image(self, volume_save):
self._test_swap_volume_driver_bdm_save(volume_save=volume_save,
source_type='image')
@mock.patch('nova.virt.block_device.DriverSnapshotBlockDevice.save')
def test_swap_volume_driver_bdm_save_source_is_snapshot(self, volume_save):
self._test_swap_volume_driver_bdm_save(volume_save=volume_save,
source_type='snapshot')
def _test_live_snapshot(self, can_quiesce=False, require_quiesce=False):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
mock_dom = mock.MagicMock()
test_image_meta = self.test_image_meta.copy()
if require_quiesce:
test_image_meta = {'properties': {'os_require_quiesce': 'yes'}}
with test.nested(
mock.patch.object(drvr._conn, 'defineXML', create=True),
mock.patch.object(fake_libvirt_utils, 'get_disk_size'),
mock.patch.object(fake_libvirt_utils, 'get_disk_backing_file'),
mock.patch.object(fake_libvirt_utils, 'create_cow_image'),
mock.patch.object(fake_libvirt_utils, 'chown'),
mock.patch.object(fake_libvirt_utils, 'extract_snapshot'),
mock.patch.object(drvr, '_set_quiesced')
) as (mock_define, mock_size, mock_backing, mock_create_cow,
mock_chown, mock_snapshot, mock_quiesce):
xmldoc = "<domain/>"
srcfile = "/first/path"
dstfile = "/second/path"
bckfile = "/other/path"
dltfile = dstfile + ".delta"
mock_dom.XMLDesc.return_value = xmldoc
mock_dom.isPersistent.return_value = True
mock_size.return_value = 1004009
mock_backing.return_value = bckfile
guest = libvirt_guest.Guest(mock_dom)
if not can_quiesce:
mock_quiesce.side_effect = (
exception.InstanceQuiesceNotSupported(
instance_id=self.test_instance['id'], reason='test'))
image_meta = objects.ImageMeta.from_dict(test_image_meta)
drvr._live_snapshot(self.context, self.test_instance, guest,
srcfile, dstfile, "qcow2", "qcow2", image_meta)
mock_dom.XMLDesc.assert_called_once_with(flags=(
fakelibvirt.VIR_DOMAIN_XML_INACTIVE |
fakelibvirt.VIR_DOMAIN_XML_SECURE))
mock_dom.blockRebase.assert_called_once_with(
srcfile, dltfile, 0, flags=(
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_COPY |
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT |
fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_SHALLOW))
mock_size.assert_called_once_with(srcfile, format="qcow2")
mock_backing.assert_called_once_with(srcfile, basename=False,
format="qcow2")
mock_create_cow.assert_called_once_with(bckfile, dltfile, 1004009)
mock_chown.assert_called_once_with(dltfile, os.getuid())
mock_snapshot.assert_called_once_with(dltfile, "qcow2",
dstfile, "qcow2")
mock_define.assert_called_once_with(xmldoc)
mock_quiesce.assert_any_call(mock.ANY, self.test_instance,
mock.ANY, True)
if can_quiesce:
mock_quiesce.assert_any_call(mock.ANY, self.test_instance,
mock.ANY, False)
def test_live_snapshot(self):
self._test_live_snapshot()
def test_live_snapshot_with_quiesce(self):
self._test_live_snapshot(can_quiesce=True)
def test_live_snapshot_with_require_quiesce(self):
self._test_live_snapshot(can_quiesce=True, require_quiesce=True)
def test_live_snapshot_with_require_quiesce_fails(self):
self.assertRaises(exception.InstanceQuiesceNotSupported,
self._test_live_snapshot,
can_quiesce=False, require_quiesce=True)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_live_migration")
def test_live_migration_hostname_valid(self, mock_lm):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.live_migration(self.context, self.test_instance,
"host1.example.com",
lambda x: x,
lambda x: x)
self.assertEqual(1, mock_lm.call_count)
@mock.patch.object(libvirt_driver.LibvirtDriver, "_live_migration")
@mock.patch.object(fake_libvirt_utils, "is_valid_hostname")
def test_live_migration_hostname_invalid(self, mock_hostname, mock_lm):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_hostname.return_value = False
self.assertRaises(exception.InvalidHostname,
drvr.live_migration,
self.context, self.test_instance,
"foo/?com=/bin/sh",
lambda x: x,
lambda x: x)
def test_live_migration_force_complete(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = fake_instance.fake_instance_obj(
None, name='instancename', id=1,
uuid='c83a75d4-4d53-4be5-9a40-04d9c0389ff8')
drvr.active_migrations[instance.uuid] = deque()
drvr.live_migration_force_complete(instance)
self.assertEqual(
1, drvr.active_migrations[instance.uuid].count("force-complete"))
@mock.patch.object(host.Host, "get_connection")
@mock.patch.object(fakelibvirt.virDomain, "abortJob")
def test_live_migration_abort(self, mock_abort, mock_conn):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", False)
guest = libvirt_guest.Guest(dom)
with mock.patch.object(nova.virt.libvirt.host.Host, 'get_guest',
return_value=guest):
drvr.live_migration_abort(self.test_instance)
self.assertTrue(mock_abort.called)
@mock.patch('os.path.exists', return_value=True)
@mock.patch('tempfile.mkstemp')
@mock.patch('os.close', return_value=None)
def test_check_instance_shared_storage_local_raw(self,
mock_close,
mock_mkstemp,
mock_exists):
instance_uuid = str(uuid.uuid4())
self.flags(images_type='raw', group='libvirt')
self.flags(instances_path='/tmp')
mock_mkstemp.return_value = (-1,
'/tmp/{0}/file'.format(instance_uuid))
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
temp_file = driver.check_instance_shared_storage_local(self.context,
instance)
self.assertEqual('/tmp/{0}/file'.format(instance_uuid),
temp_file['filename'])
def test_check_instance_shared_storage_local_rbd(self):
self.flags(images_type='rbd', group='libvirt')
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(**self.test_instance)
self.assertIsNone(driver.
check_instance_shared_storage_local(self.context,
instance))
def test_version_to_string(self):
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
string_ver = driver._version_to_string((4, 33, 173))
self.assertEqual("4.33.173", string_ver)
def test_parallels_min_version_fail(self):
self.flags(virt_type='parallels', group='libvirt')
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(driver._conn, 'getLibVersion',
return_value=1002011):
self.assertRaises(exception.NovaException,
driver.init_host, 'wibble')
def test_parallels_min_version_ok(self):
self.flags(virt_type='parallels', group='libvirt')
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with mock.patch.object(driver._conn, 'getLibVersion',
return_value=1002012):
driver.init_host('wibble')
def test_get_guest_config_parallels_vm(self):
self.flags(virt_type='parallels', group='libvirt')
self.flags(images_type='ploop', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta)
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info)
self.assertEqual("parallels", cfg.virt_type)
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
self.assertEqual(vm_mode.HVM, cfg.os_type)
self.assertIsNone(cfg.os_root)
self.assertEqual(6, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestDisk)
self.assertEqual(cfg.devices[0].driver_format, "ploop")
self.assertIsInstance(cfg.devices[1],
vconfig.LibvirtConfigGuestDisk)
self.assertIsInstance(cfg.devices[2],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[3],
vconfig.LibvirtConfigGuestInput)
self.assertIsInstance(cfg.devices[4],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[5],
vconfig.LibvirtConfigGuestVideo)
def test_get_guest_config_parallels_ct_rescue(self):
self._test_get_guest_config_parallels_ct(rescue=True)
def test_get_guest_config_parallels_ct(self):
self._test_get_guest_config_parallels_ct(rescue=False)
def _test_get_guest_config_parallels_ct(self, rescue=False):
self.flags(virt_type='parallels', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
ct_instance = self.test_instance.copy()
ct_instance["vm_mode"] = vm_mode.EXE
instance_ref = objects.Instance(**ct_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
if rescue:
rescue_data = ct_instance
else:
rescue_data = None
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, {'mapping': {'disk': {}}},
rescue_data)
self.assertEqual("parallels", cfg.virt_type)
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
self.assertEqual(vm_mode.EXE, cfg.os_type)
self.assertEqual("/sbin/init", cfg.os_init_path)
self.assertIsNone(cfg.os_root)
if rescue:
self.assertEqual(5, len(cfg.devices))
else:
self.assertEqual(4, len(cfg.devices))
self.assertIsInstance(cfg.devices[0],
vconfig.LibvirtConfigGuestFilesys)
device_index = 0
fs = cfg.devices[device_index]
self.assertEqual(fs.source_type, "file")
self.assertEqual(fs.driver_type, "ploop")
self.assertEqual(fs.target_dir, "/")
if rescue:
device_index = 1
fs = cfg.devices[device_index]
self.assertEqual(fs.source_type, "file")
self.assertEqual(fs.driver_type, "ploop")
self.assertEqual(fs.target_dir, "/mnt/rescue")
self.assertIsInstance(cfg.devices[device_index + 1],
vconfig.LibvirtConfigGuestInterface)
self.assertIsInstance(cfg.devices[device_index + 2],
vconfig.LibvirtConfigGuestGraphics)
self.assertIsInstance(cfg.devices[device_index + 3],
vconfig.LibvirtConfigGuestVideo)
def _test_get_guest_config_parallels_volume(self, vmmode, devices):
self.flags(virt_type='parallels', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
ct_instance = self.test_instance.copy()
ct_instance["vm_mode"] = vmmode
instance_ref = objects.Instance(**ct_instance)
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
conn_info = {'driver_volume_type': 'fake'}
bdm = objects.BlockDeviceMapping(
self.context,
**fake_block_device.FakeDbBlockDeviceDict(
{'id': 0,
'source_type': 'volume', 'destination_type': 'volume',
'device_name': '/dev/sda'}))
info = {'block_device_mapping': driver_block_device.convert_volumes(
[bdm])}
info['block_device_mapping'][0]['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance_ref,
image_meta,
info)
with mock.patch.object(
driver_block_device.DriverVolumeBlockDevice, 'save'
) as mock_save:
cfg = drvr._get_guest_config(instance_ref,
_fake_network_info(self, 1),
image_meta, disk_info, None, info)
mock_save.assert_called_once_with()
self.assertEqual("parallels", cfg.virt_type)
self.assertEqual(instance_ref["uuid"], cfg.uuid)
self.assertEqual(instance_ref.flavor.memory_mb * units.Ki, cfg.memory)
self.assertEqual(instance_ref.flavor.vcpus, cfg.vcpus)
self.assertEqual(vmmode, cfg.os_type)
self.assertIsNone(cfg.os_root)
self.assertEqual(devices, len(cfg.devices))
disk_found = False
for dev in cfg.devices:
result = isinstance(dev, vconfig.LibvirtConfigGuestFilesys)
self.assertFalse(result)
if (isinstance(dev, vconfig.LibvirtConfigGuestDisk) and
(dev.source_path is None or
'disk.local' not in dev.source_path)):
self.assertEqual("disk", dev.source_device)
self.assertEqual("sda", dev.target_dev)
disk_found = True
self.assertTrue(disk_found)
def test_get_guest_config_parallels_volume(self):
self._test_get_guest_config_parallels_volume(vm_mode.EXE, 4)
self._test_get_guest_config_parallels_volume(vm_mode.HVM, 6)
def test_get_guest_disk_config_rbd_older_config_drive_fall_back(self):
# New config drives are stored in rbd but existing instances have
# config drives in the old location under the instances path.
# Test that the driver falls back to 'flat' for config drive if it
# doesn't exist in rbd.
self.flags(images_type='rbd', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
mock_rbd_image = mock.Mock()
mock_flat_image = mock.Mock()
mock_flat_image.libvirt_info.return_value = mock.sentinel.diskconfig
drvr.image_backend.image.side_effect = [mock_rbd_image,
mock_flat_image]
mock_rbd_image.exists.return_value = False
instance = objects.Instance()
disk_mapping = {'disk.config': {'bus': 'ide',
'dev': 'hdd',
'type': 'file'}}
flavor = objects.Flavor(extra_specs={})
diskconfig = drvr._get_guest_disk_config(
instance, 'disk.config', disk_mapping, flavor,
drvr._get_disk_config_image_type())
self.assertEqual(2, drvr.image_backend.image.call_count)
call1 = mock.call(instance, 'disk.config', 'rbd')
call2 = mock.call(instance, 'disk.config', 'flat')
drvr.image_backend.image.assert_has_calls([call1, call2])
self.assertEqual(mock.sentinel.diskconfig, diskconfig)
def _test_prepare_domain_for_snapshot(self, live_snapshot, state):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance_ref = objects.Instance(**self.test_instance)
with mock.patch.object(drvr, "suspend") as mock_suspend:
drvr._prepare_domain_for_snapshot(
self.context, live_snapshot, state, instance_ref)
return mock_suspend.called
def test_prepare_domain_for_snapshot(self):
# Ensure that suspend() is only called on RUNNING or PAUSED instances
for test_power_state in power_state.STATE_MAP.keys():
if test_power_state in (power_state.RUNNING, power_state.PAUSED):
self.assertTrue(self._test_prepare_domain_for_snapshot(
False, test_power_state))
else:
self.assertFalse(self._test_prepare_domain_for_snapshot(
False, test_power_state))
def test_prepare_domain_for_snapshot_lxc(self):
self.flags(virt_type='lxc', group='libvirt')
# Ensure that suspend() is never called with LXC
for test_power_state in power_state.STATE_MAP.keys():
self.assertFalse(self._test_prepare_domain_for_snapshot(
False, test_power_state))
def test_prepare_domain_for_snapshot_live_snapshots(self):
# Ensure that suspend() is never called for live snapshots
for test_power_state in power_state.STATE_MAP.keys():
self.assertFalse(self._test_prepare_domain_for_snapshot(
True, test_power_state))
@mock.patch('os.walk')
@mock.patch('os.path.exists')
@mock.patch('os.path.getsize')
@mock.patch('os.path.isdir')
@mock.patch('nova.utils.execute')
@mock.patch.object(host.Host, "get_domain")
def test_get_instance_disk_info_parallels_ct(self, mock_get_domain,
mock_execute,
mock_isdir,
mock_getsize,
mock_exists,
mock_walk):
dummyxml = ("<domain type='parallels'><name>instance-0000000a</name>"
"<os><type>exe</type></os>"
"<devices>"
"<filesystem type='file'>"
"<driver format='ploop' type='ploop'/>"
"<source file='/test/disk'/>"
"<target dir='/'/></filesystem>"
"</devices></domain>")
ret = ("image: /test/disk/root.hds\n"
"file format: parallels\n"
"virtual size: 20G (21474836480 bytes)\n"
"disk size: 789M\n")
self.flags(virt_type='parallels', group='libvirt')
instance = objects.Instance(**self.test_instance)
instance.vm_mode = vm_mode.EXE
fake_dom = FakeVirtDomain(fake_xml=dummyxml)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
mock_get_domain.return_value = fake_dom
mock_walk.return_value = [('/test/disk', [],
['DiskDescriptor.xml', 'root.hds'])]
def getsize_sideeffect(*args, **kwargs):
if args[0] == '/test/disk/DiskDescriptor.xml':
return 790
if args[0] == '/test/disk/root.hds':
return 827326464
mock_getsize.side_effect = getsize_sideeffect
mock_exists.return_value = True
mock_isdir.return_value = True
mock_execute.return_value = (ret, '')
info = drvr.get_instance_disk_info(instance)
info = jsonutils.loads(info)
self.assertEqual(info[0]['type'], 'ploop')
self.assertEqual(info[0]['path'], '/test/disk')
self.assertEqual(info[0]['disk_size'], 827327254)
self.assertEqual(info[0]['over_committed_disk_size'], 20647509226)
self.assertEqual(info[0]['virt_disk_size'], 21474836480)
class HostStateTestCase(test.NoDBTestCase):
cpu_info = {"vendor": "Intel", "model": "pentium", "arch": "i686",
"features": ["ssse3", "monitor", "pni", "sse2", "sse",
"fxsr", "clflush", "pse36", "pat", "cmov", "mca", "pge",
"mtrr", "sep", "apic"],
"topology": {"cores": "1", "threads": "1", "sockets": "1"}}
instance_caps = [(arch.X86_64, "kvm", "hvm"),
(arch.I686, "kvm", "hvm")]
pci_devices = [{
"dev_id": "pci_0000_04_00_3",
"address": "0000:04:10.3",
"product_id": '1521',
"vendor_id": '8086',
"dev_type": fields.PciDeviceType.SRIOV_PF,
"phys_function": None}]
numa_topology = objects.NUMATopology(
cells=[objects.NUMACell(
id=1, cpuset=set([1, 2]), memory=1024,
cpu_usage=0, memory_usage=0,
mempages=[], siblings=[],
pinned_cpus=set([])),
objects.NUMACell(
id=2, cpuset=set([3, 4]), memory=1024,
cpu_usage=0, memory_usage=0,
mempages=[], siblings=[],
pinned_cpus=set([]))])
class FakeConnection(libvirt_driver.LibvirtDriver):
"""Fake connection object."""
def __init__(self):
super(HostStateTestCase.FakeConnection,
self).__init__(fake.FakeVirtAPI(), True)
self._host = host.Host("qemu:///system")
def _get_memory_mb_total():
return 497
def _get_memory_mb_used():
return 88
self._host.get_memory_mb_total = _get_memory_mb_total
self._host.get_memory_mb_used = _get_memory_mb_used
def _get_vcpu_total(self):
return 1
def _get_vcpu_used(self):
return 0
def _get_cpu_info(self):
return HostStateTestCase.cpu_info
def _get_disk_over_committed_size_total(self):
return 0
def _get_local_gb_info(self):
return {'total': 100, 'used': 20, 'free': 80}
def get_host_uptime(self):
return ('10:01:16 up 1:36, 6 users, '
'load average: 0.21, 0.16, 0.19')
def _get_disk_available_least(self):
return 13091
def _get_instance_capabilities(self):
return HostStateTestCase.instance_caps
def _get_pci_passthrough_devices(self):
return jsonutils.dumps(HostStateTestCase.pci_devices)
def _get_host_numa_topology(self):
return HostStateTestCase.numa_topology
@mock.patch.object(fakelibvirt, "openAuth")
def test_update_status(self, mock_open):
mock_open.return_value = fakelibvirt.Connection("qemu:///system")
drvr = HostStateTestCase.FakeConnection()
stats = drvr.get_available_resource("compute1")
self.assertEqual(stats["vcpus"], 1)
self.assertEqual(stats["memory_mb"], 497)
self.assertEqual(stats["local_gb"], 100)
self.assertEqual(stats["vcpus_used"], 0)
self.assertEqual(stats["memory_mb_used"], 88)
self.assertEqual(stats["local_gb_used"], 20)
self.assertEqual(stats["hypervisor_type"], 'QEMU')
self.assertEqual(stats["hypervisor_version"],
fakelibvirt.FAKE_QEMU_VERSION)
self.assertEqual(stats["hypervisor_hostname"], 'compute1')
cpu_info = jsonutils.loads(stats["cpu_info"])
self.assertEqual(cpu_info,
{"vendor": "Intel", "model": "pentium",
"arch": arch.I686,
"features": ["ssse3", "monitor", "pni", "sse2", "sse",
"fxsr", "clflush", "pse36", "pat", "cmov",
"mca", "pge", "mtrr", "sep", "apic"],
"topology": {"cores": "1", "threads": "1", "sockets": "1"}
})
self.assertEqual(stats["disk_available_least"], 80)
self.assertEqual(jsonutils.loads(stats["pci_passthrough_devices"]),
HostStateTestCase.pci_devices)
self.assertThat(objects.NUMATopology.obj_from_db_obj(
stats['numa_topology'])._to_dict(),
matchers.DictMatches(
HostStateTestCase.numa_topology._to_dict()))
class LibvirtDriverTestCase(test.NoDBTestCase):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver."""
def setUp(self):
super(LibvirtDriverTestCase, self).setUp()
os_vif.initialize()
self.drvr = libvirt_driver.LibvirtDriver(
fake.FakeVirtAPI(), read_only=True)
self.context = context.get_admin_context()
self.test_image_meta = {
"disk_format": "raw",
}
def _create_instance(self, params=None):
"""Create a test instance."""
if not params:
params = {}
flavor = objects.Flavor(memory_mb=512,
swap=0,
vcpu_weight=None,
root_gb=10,
id=2,
name=u'm1.tiny',
ephemeral_gb=20,
rxtx_factor=1.0,
flavorid=u'1',
vcpus=1,
extra_specs={})
flavor.update(params.pop('flavor', {}))
inst = {}
inst['id'] = 1
inst['uuid'] = '52d3b512-1152-431f-a8f7-28f0288a622b'
inst['os_type'] = 'linux'
inst['image_ref'] = uuids.fake_image_ref
inst['reservation_id'] = 'r-fakeres'
inst['user_id'] = 'fake'
inst['project_id'] = 'fake'
inst['instance_type_id'] = 2
inst['ami_launch_index'] = 0
inst['host'] = 'host1'
inst['root_gb'] = flavor.root_gb
inst['ephemeral_gb'] = flavor.ephemeral_gb
inst['config_drive'] = True
inst['kernel_id'] = 2
inst['ramdisk_id'] = 3
inst['key_data'] = 'ABCDEFG'
inst['system_metadata'] = {}
inst['metadata'] = {}
inst['task_state'] = None
inst.update(params)
instance = fake_instance.fake_instance_obj(
self.context, expected_attrs=['metadata', 'system_metadata',
'pci_devices'],
flavor=flavor, **inst)
# Attributes which we need to be set so they don't touch the db,
# but it's not worth the effort to fake properly
for field in ['numa_topology', 'vcpu_model']:
setattr(instance, field, None)
return instance
def test_migrate_disk_and_power_off_exception(self):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off.
"""
self.counter = 0
self.checked_shared_storage = False
def fake_get_instance_disk_info(instance,
block_device_info=None):
return '[]'
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
def fake_execute(*args, **kwargs):
self.counter += 1
if self.counter == 1:
assert False, "intentional failure"
def fake_os_path_exists(path):
return True
def fake_is_storage_shared(dest, inst_base):
self.checked_shared_storage = True
return False
self.stubs.Set(self.drvr, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.drvr, '_destroy', fake_destroy)
self.stubs.Set(self.drvr, 'get_host_ip_addr',
fake_get_host_ip_addr)
self.stubs.Set(self.drvr, '_is_storage_shared_with',
fake_is_storage_shared)
self.stubs.Set(utils, 'execute', fake_execute)
self.stub_out('os.path.exists', fake_os_path_exists)
ins_ref = self._create_instance()
flavor = {'root_gb': 10, 'ephemeral_gb': 20}
flavor_obj = objects.Flavor(**flavor)
self.assertRaises(AssertionError,
self.drvr.migrate_disk_and_power_off,
context.get_admin_context(), ins_ref, '10.0.0.2',
flavor_obj, None)
def _test_migrate_disk_and_power_off(self, flavor_obj,
block_device_info=None,
params_for_instance=None):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off.
"""
instance = self._create_instance(params=params_for_instance)
disk_info = fake_disk_info_json(instance)
def fake_get_instance_disk_info(instance,
block_device_info=None):
return disk_info
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
def fake_execute(*args, **kwargs):
pass
def fake_copy_image(src, dest, host=None, receive=False,
on_execute=None, on_completion=None,
compression=True):
self.assertIsNotNone(on_execute)
self.assertIsNotNone(on_completion)
self.stubs.Set(self.drvr, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.drvr, '_destroy', fake_destroy)
self.stubs.Set(self.drvr, 'get_host_ip_addr',
fake_get_host_ip_addr)
self.stubs.Set(utils, 'execute', fake_execute)
self.stubs.Set(libvirt_utils, 'copy_image', fake_copy_image)
# dest is different host case
out = self.drvr.migrate_disk_and_power_off(
context.get_admin_context(), instance, '10.0.0.2',
flavor_obj, None, block_device_info=block_device_info)
self.assertEqual(out, disk_info)
# dest is same host case
out = self.drvr.migrate_disk_and_power_off(
context.get_admin_context(), instance, '10.0.0.1',
flavor_obj, None, block_device_info=block_device_info)
self.assertEqual(out, disk_info)
def test_migrate_disk_and_power_off(self):
flavor = {'root_gb': 10, 'ephemeral_gb': 20}
flavor_obj = objects.Flavor(**flavor)
self._test_migrate_disk_and_power_off(flavor_obj)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._disconnect_volume')
def test_migrate_disk_and_power_off_boot_from_volume(self,
disconnect_volume):
info = {'block_device_mapping': [{'boot_index': None,
'mount_device': '/dev/vdd',
'connection_info': None},
{'boot_index': 0,
'mount_device': '/dev/vda',
'connection_info': None}]}
flavor = {'root_gb': 1, 'ephemeral_gb': 0}
flavor_obj = objects.Flavor(**flavor)
# Note(Mike_D): The size of instance's ephemeral_gb is 0 gb.
self._test_migrate_disk_and_power_off(
flavor_obj, block_device_info=info,
params_for_instance={'image_ref': None,
'flavor': {'root_gb': 1,
'ephemeral_gb': 0}})
disconnect_volume.assert_called_with(
info['block_device_mapping'][1]['connection_info'], 'vda')
@mock.patch('nova.utils.execute')
@mock.patch('nova.virt.libvirt.utils.copy_image')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._destroy')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_host_ip_addr')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
def test_migrate_disk_and_power_off_swap(self, mock_get_disk_info,
get_host_ip_addr,
mock_destroy,
mock_copy_image,
mock_execute):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.migrate_disk_and_power_off.
"""
self.copy_or_move_swap_called = False
# Original instance config
instance = self._create_instance({'flavor': {'root_gb': 10,
'ephemeral_gb': 0}})
disk_info = fake_disk_info_json(instance)
mock_get_disk_info.return_value = disk_info
get_host_ip_addr.return_value = '10.0.0.1'
def fake_copy_image(*args, **kwargs):
# disk.swap should not be touched since it is skipped over
if '/test/disk.swap' in list(args):
self.copy_or_move_swap_called = True
def fake_execute(*args, **kwargs):
# disk.swap should not be touched since it is skipped over
if set(['mv', '/test/disk.swap']).issubset(list(args)):
self.copy_or_move_swap_called = True
mock_copy_image.side_effect = fake_copy_image
mock_execute.side_effect = fake_execute
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# Re-size fake instance to 20G root and 1024M swap disk
flavor = {'root_gb': 20, 'ephemeral_gb': 0, 'swap': 1024}
flavor_obj = objects.Flavor(**flavor)
# Destination is same host
out = drvr.migrate_disk_and_power_off(context.get_admin_context(),
instance, '10.0.0.1',
flavor_obj, None)
mock_get_disk_info.assert_called_once_with(instance,
block_device_info=None)
self.assertTrue(get_host_ip_addr.called)
mock_destroy.assert_called_once_with(instance)
self.assertFalse(self.copy_or_move_swap_called)
self.assertEqual(disk_info, out)
def _test_migrate_disk_and_power_off_resize_check(self, expected_exc):
"""Test for nova.virt.libvirt.libvirt_driver.LibvirtConnection
.migrate_disk_and_power_off.
"""
instance = self._create_instance()
disk_info = fake_disk_info_json(instance)
def fake_get_instance_disk_info(instance, xml=None,
block_device_info=None):
return disk_info
def fake_destroy(instance):
pass
def fake_get_host_ip_addr():
return '10.0.0.1'
self.stubs.Set(self.drvr, 'get_instance_disk_info',
fake_get_instance_disk_info)
self.stubs.Set(self.drvr, '_destroy', fake_destroy)
self.stubs.Set(self.drvr, 'get_host_ip_addr',
fake_get_host_ip_addr)
flavor = {'root_gb': 10, 'ephemeral_gb': 20}
flavor_obj = objects.Flavor(**flavor)
# Migration is not implemented for LVM backed instances
self.assertRaises(expected_exc,
self.drvr.migrate_disk_and_power_off,
None, instance, '10.0.0.1', flavor_obj, None)
@mock.patch('nova.utils.execute')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._destroy')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'._is_storage_shared_with')
def _test_migrate_disk_and_power_off_backing_file(self,
shared_storage,
mock_is_shared_storage,
mock_get_disk_info,
mock_destroy,
mock_execute):
self.convert_file_called = False
flavor = {'root_gb': 20, 'ephemeral_gb': 30, 'swap': 0}
flavor_obj = objects.Flavor(**flavor)
disk_info = [{'type': 'qcow2', 'path': '/test/disk',
'virt_disk_size': '10737418240',
'backing_file': '/base/disk',
'disk_size': '83886080'}]
disk_info_text = jsonutils.dumps(disk_info)
mock_get_disk_info.return_value = disk_info_text
mock_is_shared_storage.return_value = shared_storage
def fake_execute(*args, **kwargs):
self.assertNotEqual(args[0:2], ['qemu-img', 'convert'])
mock_execute.side_effect = fake_execute
instance = self._create_instance()
out = self.drvr.migrate_disk_and_power_off(
context.get_admin_context(), instance, '10.0.0.2',
flavor_obj, None)
self.assertTrue(mock_is_shared_storage.called)
mock_destroy.assert_called_once_with(instance)
self.assertEqual(out, disk_info_text)
def test_migrate_disk_and_power_off_shared_storage(self):
self._test_migrate_disk_and_power_off_backing_file(True)
def test_migrate_disk_and_power_off_non_shared_storage(self):
self._test_migrate_disk_and_power_off_backing_file(False)
def test_migrate_disk_and_power_off_lvm(self):
self.flags(images_type='lvm', group='libvirt')
def fake_execute(*args, **kwargs):
pass
self.stubs.Set(utils, 'execute', fake_execute)
expected_exc = exception.InstanceFaultRollback
self._test_migrate_disk_and_power_off_resize_check(expected_exc)
def test_migrate_disk_and_power_off_resize_cannot_ssh(self):
def fake_execute(*args, **kwargs):
raise processutils.ProcessExecutionError()
def fake_is_storage_shared(dest, inst_base):
self.checked_shared_storage = True
return False
self.stubs.Set(self.drvr, '_is_storage_shared_with',
fake_is_storage_shared)
self.stubs.Set(utils, 'execute', fake_execute)
expected_exc = exception.InstanceFaultRollback
self._test_migrate_disk_and_power_off_resize_check(expected_exc)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
def test_migrate_disk_and_power_off_resize_error(self, mock_get_disk_info):
instance = self._create_instance()
flavor = {'root_gb': 5, 'ephemeral_gb': 10}
flavor_obj = objects.Flavor(**flavor)
mock_get_disk_info.return_value = fake_disk_info_json(instance)
self.assertRaises(
exception.InstanceFaultRollback,
self.drvr.migrate_disk_and_power_off,
'ctx', instance, '10.0.0.1', flavor_obj, None)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
def test_migrate_disk_and_power_off_resize_error_default_ephemeral(
self, mock_get_disk_info):
# Note(Mike_D): The size of this instance's ephemeral_gb is 20 gb.
instance = self._create_instance()
flavor = {'root_gb': 10, 'ephemeral_gb': 0}
flavor_obj = objects.Flavor(**flavor)
mock_get_disk_info.return_value = fake_disk_info_json(instance)
self.assertRaises(exception.InstanceFaultRollback,
self.drvr.migrate_disk_and_power_off,
'ctx', instance, '10.0.0.1', flavor_obj, None)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
@mock.patch('nova.virt.driver.block_device_info_get_ephemerals')
def test_migrate_disk_and_power_off_resize_error_eph(self, mock_get,
mock_get_disk_info):
mappings = [
{
'device_name': '/dev/sdb4',
'source_type': 'blank',
'destination_type': 'local',
'device_type': 'disk',
'guest_format': 'swap',
'boot_index': -1,
'volume_size': 1
},
{
'device_name': '/dev/sda1',
'source_type': 'volume',
'destination_type': 'volume',
'device_type': 'disk',
'volume_id': 1,
'guest_format': None,
'boot_index': 1,
'volume_size': 6
},
{
'device_name': '/dev/sda2',
'source_type': 'snapshot',
'destination_type': 'volume',
'snapshot_id': 1,
'device_type': 'disk',
'guest_format': None,
'boot_index': 0,
'volume_size': 4
},
{
'device_name': '/dev/sda3',
'source_type': 'blank',
'destination_type': 'local',
'device_type': 'disk',
'guest_format': None,
'boot_index': -1,
'volume_size': 3
}
]
mock_get.return_value = mappings
instance = self._create_instance()
# Old flavor, eph is 20, real disk is 3, target is 2, fail
flavor = {'root_gb': 10, 'ephemeral_gb': 2}
flavor_obj = objects.Flavor(**flavor)
mock_get_disk_info.return_value = fake_disk_info_json(instance)
self.assertRaises(
exception.InstanceFaultRollback,
self.drvr.migrate_disk_and_power_off,
'ctx', instance, '10.0.0.1', flavor_obj, None)
# Old flavor, eph is 20, real disk is 3, target is 4
flavor = {'root_gb': 10, 'ephemeral_gb': 4}
flavor_obj = objects.Flavor(**flavor)
self._test_migrate_disk_and_power_off(flavor_obj)
@mock.patch('nova.utils.execute')
@mock.patch('nova.virt.libvirt.utils.copy_image')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._destroy')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'._is_storage_shared_with')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver'
'.get_instance_disk_info')
def test_migrate_disk_and_power_off_resize_copy_disk_info(self,
mock_disk_info,
mock_shared,
mock_path,
mock_destroy,
mock_copy,
mock_execuate):
instance = self._create_instance()
disk_info = fake_disk_info_json(instance)
disk_info_text = jsonutils.loads(disk_info)
instance_base = os.path.dirname(disk_info_text[0]['path'])
flavor = {'root_gb': 10, 'ephemeral_gb': 25}
flavor_obj = objects.Flavor(**flavor)
mock_disk_info.return_value = disk_info
mock_path.return_value = instance_base
mock_shared.return_value = False
src_disk_info_path = os.path.join(instance_base + '_resize',
'disk.info')
with mock.patch.object(os.path, 'exists', autospec=True) \
as mock_exists:
# disk.info exists on the source
mock_exists.side_effect = \
lambda path: path == src_disk_info_path
self.drvr.migrate_disk_and_power_off(context.get_admin_context(),
instance, mock.sentinel,
flavor_obj, None)
self.assertTrue(mock_exists.called)
dst_disk_info_path = os.path.join(instance_base, 'disk.info')
mock_copy.assert_any_call(src_disk_info_path, dst_disk_info_path,
host=mock.sentinel, on_execute=mock.ANY,
on_completion=mock.ANY)
def test_wait_for_running(self):
def fake_get_info(instance):
if instance['name'] == "not_found":
raise exception.InstanceNotFound(instance_id=instance['uuid'])
elif instance['name'] == "running":
return hardware.InstanceInfo(state=power_state.RUNNING)
else:
return hardware.InstanceInfo(state=power_state.SHUTDOWN)
self.stubs.Set(self.drvr, 'get_info',
fake_get_info)
# instance not found case
self.assertRaises(exception.InstanceNotFound,
self.drvr._wait_for_running,
{'name': 'not_found',
'uuid': 'not_found_uuid'})
# instance is running case
self.assertRaises(loopingcall.LoopingCallDone,
self.drvr._wait_for_running,
{'name': 'running',
'uuid': 'running_uuid'})
# else case
self.drvr._wait_for_running({'name': 'else',
'uuid': 'other_uuid'})
def test_disk_size_from_instance_disk_info(self):
flavor_data = {'root_gb': 10, 'ephemeral_gb': 20, 'swap_gb': 30}
inst = objects.Instance(flavor=objects.Flavor(**flavor_data))
self.assertEqual(10 * units.Gi,
self.drvr._disk_size_from_instance(inst, 'disk'))
self.assertEqual(20 * units.Gi,
self.drvr._disk_size_from_instance(inst,
'disk.local'))
self.assertEqual(0,
self.drvr._disk_size_from_instance(inst, 'disk.swap'))
@mock.patch('nova.utils.execute')
def test_disk_raw_to_qcow2(self, mock_execute):
path = '/test/disk'
_path_qcow = path + '_qcow'
self.drvr._disk_raw_to_qcow2(path)
mock_execute.assert_has_calls([
mock.call('qemu-img', 'convert', '-f', 'raw',
'-O', 'qcow2', path, _path_qcow),
mock.call('mv', _path_qcow, path)])
@mock.patch('nova.utils.execute')
def test_disk_qcow2_to_raw(self, mock_execute):
path = '/test/disk'
_path_raw = path + '_raw'
self.drvr._disk_qcow2_to_raw(path)
mock_execute.assert_has_calls([
mock.call('qemu-img', 'convert', '-f', 'qcow2',
'-O', 'raw', path, _path_raw),
mock.call('mv', _path_raw, path)])
@mock.patch('nova.virt.disk.api.extend')
def test_disk_resize_raw(self, mock_extend):
image = imgmodel.LocalFileImage("/test/disk",
imgmodel.FORMAT_RAW)
self.drvr._disk_resize(image, 50)
mock_extend.assert_called_once_with(image, 50)
@mock.patch('nova.virt.disk.api.can_resize_image')
@mock.patch('nova.virt.disk.api.is_image_extendable')
@mock.patch('nova.virt.disk.api.extend')
def test_disk_resize_qcow2(
self, mock_extend, mock_can_resize, mock_is_image_extendable):
with test.nested(
mock.patch.object(
self.drvr, '_disk_qcow2_to_raw'),
mock.patch.object(
self.drvr, '_disk_raw_to_qcow2'))\
as (mock_disk_qcow2_to_raw, mock_disk_raw_to_qcow2):
mock_can_resize.return_value = True
mock_is_image_extendable.return_value = True
imageqcow2 = imgmodel.LocalFileImage("/test/disk",
imgmodel.FORMAT_QCOW2)
imageraw = imgmodel.LocalFileImage("/test/disk",
imgmodel.FORMAT_RAW)
self.drvr._disk_resize(imageqcow2, 50)
mock_disk_qcow2_to_raw.assert_called_once_with(imageqcow2.path)
mock_extend.assert_called_once_with(imageraw, 50)
mock_disk_raw_to_qcow2.assert_called_once_with(imageqcow2.path)
def _test_finish_migration(self, power_on, resize_instance=False):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.finish_migration.
"""
powered_on = power_on
self.fake_create_domain_called = False
self.fake_disk_resize_called = False
create_image_called = [False]
def fake_to_xml(context, instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None, write_to_disk=False):
return ""
def fake_plug_vifs(instance, network_info):
pass
def fake_create_image(context, inst,
disk_mapping, suffix='',
disk_images=None, network_info=None,
block_device_info=None, inject_files=True,
fallback_from_host=None):
self.assertFalse(inject_files)
create_image_called[0] = True
def fake_create_domain_and_network(
context, xml, instance, network_info, disk_info,
block_device_info=None, power_on=True, reboot=False,
vifs_already_plugged=False, post_xml_callback=None):
self.fake_create_domain_called = True
self.assertEqual(powered_on, power_on)
self.assertTrue(vifs_already_plugged)
def fake_enable_hairpin():
pass
def fake_execute(*args, **kwargs):
pass
def fake_get_info(instance):
if powered_on:
return hardware.InstanceInfo(state=power_state.RUNNING)
else:
return hardware.InstanceInfo(state=power_state.SHUTDOWN)
def fake_disk_resize(image, size):
# Assert that _create_image is called before disk resize,
# otherwise we might be trying to resize a disk whose backing
# file hasn't been fetched, yet.
self.assertTrue(create_image_called[0])
self.fake_disk_resize_called = True
self.flags(use_cow_images=True)
self.stubs.Set(self.drvr, '_disk_resize',
fake_disk_resize)
self.stubs.Set(self.drvr, '_get_guest_xml', fake_to_xml)
self.stubs.Set(self.drvr, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(self.drvr, '_create_image',
fake_create_image)
self.stubs.Set(self.drvr, '_create_domain_and_network',
fake_create_domain_and_network)
self.stubs.Set(nova.virt.libvirt.guest.Guest, 'enable_hairpin',
fake_enable_hairpin)
self.stubs.Set(utils, 'execute', fake_execute)
fw = base_firewall.NoopFirewallDriver()
self.stubs.Set(self.drvr, 'firewall_driver', fw)
self.stubs.Set(self.drvr, 'get_info',
fake_get_info)
instance = self._create_instance({'config_drive': str(True)})
migration = objects.Migration()
migration.source_compute = 'fake-source-compute'
migration.dest_compute = 'fake-dest-compute'
migration.source_node = 'fake-source-node'
migration.dest_node = 'fake-dest-node'
image_meta = objects.ImageMeta.from_dict(self.test_image_meta)
# Source disks are raw to test conversion
disk_info = fake_disk_info_json(instance, type='raw')
with test.nested(
mock.patch.object(self.drvr, '_disk_raw_to_qcow2',
autospec=True),
mock.patch.object(self.drvr, '_ensure_console_log_for_instance')
) as (mock_raw_to_qcow2, mock_ensure_console_log):
self.drvr.finish_migration(
context.get_admin_context(), migration, instance,
disk_info, [], image_meta,
resize_instance, None, power_on)
mock_ensure_console_log.assert_called_once_with(instance)
# Assert that we converted the root and ephemeral disks
instance_path = libvirt_utils.get_instance_path(instance)
convert_calls = [mock.call(os.path.join(instance_path, name))
for name in ('disk', 'disk.local')]
mock_raw_to_qcow2.assert_has_calls(convert_calls, any_order=True)
# Implicitly assert that we did not convert the config disk
self.assertEqual(len(convert_calls), mock_raw_to_qcow2.call_count)
self.assertTrue(self.fake_create_domain_called)
self.assertEqual(
resize_instance, self.fake_disk_resize_called)
def test_finish_migration_resize(self):
self._test_finish_migration(True, resize_instance=True)
def test_finish_migration_power_on(self):
self._test_finish_migration(True)
def test_finish_migration_power_off(self):
self._test_finish_migration(False)
def _test_finish_revert_migration(self, power_on):
"""Test for nova.virt.libvirt.libvirt_driver.LivirtConnection
.finish_revert_migration.
"""
powered_on = power_on
self.fake_create_domain_called = False
def fake_execute(*args, **kwargs):
pass
def fake_plug_vifs(instance, network_info):
pass
def fake_create_domain(context, xml, instance, network_info,
disk_info, block_device_info=None,
power_on=None,
vifs_already_plugged=None):
self.fake_create_domain_called = True
self.assertEqual(powered_on, power_on)
self.assertTrue(vifs_already_plugged)
return mock.MagicMock()
def fake_enable_hairpin():
pass
def fake_get_info(instance):
if powered_on:
return hardware.InstanceInfo(state=power_state.RUNNING)
else:
return hardware.InstanceInfo(state=power_state.SHUTDOWN)
def fake_to_xml(context, instance, network_info, disk_info,
image_meta=None, rescue=None,
block_device_info=None):
return ""
self.stubs.Set(self.drvr, '_get_guest_xml', fake_to_xml)
self.stubs.Set(self.drvr, 'plug_vifs', fake_plug_vifs)
self.stubs.Set(utils, 'execute', fake_execute)
fw = base_firewall.NoopFirewallDriver()
self.stubs.Set(self.drvr, 'firewall_driver', fw)
self.stubs.Set(self.drvr, '_create_domain_and_network',
fake_create_domain)
self.stubs.Set(nova.virt.libvirt.guest.Guest, 'enable_hairpin',
fake_enable_hairpin)
self.stubs.Set(self.drvr, 'get_info',
fake_get_info)
self.stubs.Set(utils, 'get_image_from_system_metadata',
lambda *a: self.test_image_meta)
with utils.tempdir() as tmpdir:
self.flags(instances_path=tmpdir)
ins_ref = self._create_instance()
os.mkdir(os.path.join(tmpdir, ins_ref['name']))
libvirt_xml_path = os.path.join(tmpdir,
ins_ref['name'],
'libvirt.xml')
f = open(libvirt_xml_path, 'w')
f.close()
self.drvr.finish_revert_migration(
context.get_admin_context(), ins_ref,
[], None, power_on)
self.assertTrue(self.fake_create_domain_called)
def test_finish_revert_migration_power_on(self):
self._test_finish_revert_migration(True)
def test_finish_revert_migration_power_off(self):
self._test_finish_revert_migration(False)
def _test_finish_revert_migration_after_crash(self, backup_made=True,
del_inst_failed=False):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
context = 'fake_context'
ins_ref = self._create_instance()
with test.nested(
mock.patch.object(os.path, 'exists', return_value=backup_made),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(drvr, '_get_guest_xml'),
mock.patch.object(shutil, 'rmtree'),
mock.patch.object(loopingcall, 'FixedIntervalLoopingCall'),
) as (mock_stat, mock_path, mock_exec, mock_cdn, mock_ggx,
mock_rmtree, mock_looping_call):
mock_path.return_value = '/fake/foo'
if del_inst_failed:
mock_rmtree.side_effect = OSError(errno.ENOENT,
'test exception')
drvr.finish_revert_migration(context, ins_ref, [])
if backup_made:
mock_exec.assert_called_once_with('mv', '/fake/foo_resize',
'/fake/foo')
else:
self.assertFalse(mock_exec.called)
def test_finish_revert_migration_after_crash(self):
self._test_finish_revert_migration_after_crash(backup_made=True)
def test_finish_revert_migration_after_crash_before_new(self):
self._test_finish_revert_migration_after_crash(backup_made=True)
def test_finish_revert_migration_after_crash_before_backup(self):
self._test_finish_revert_migration_after_crash(backup_made=False)
def test_finish_revert_migration_after_crash_delete_failed(self):
self._test_finish_revert_migration_after_crash(backup_made=True,
del_inst_failed=True)
def test_finish_revert_migration_preserves_disk_bus(self):
def fake_get_guest_xml(context, instance, network_info, disk_info,
image_meta, block_device_info=None):
self.assertEqual('ide', disk_info['disk_bus'])
image_meta = {"disk_format": "raw",
"properties": {"hw_disk_bus": "ide"}}
instance = self._create_instance()
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(drvr, 'image_backend'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(utils, 'get_image_from_system_metadata',
return_value=image_meta),
mock.patch.object(drvr, '_get_guest_xml',
side_effect=fake_get_guest_xml)):
drvr.finish_revert_migration('', instance, None, power_on=False)
def test_finish_revert_migration_snap_backend(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
ins_ref = self._create_instance()
with test.nested(
mock.patch.object(utils, 'get_image_from_system_metadata'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(drvr, '_get_guest_xml')) as (
mock_image, mock_cdn, mock_ggx):
mock_image.return_value = {'disk_format': 'raw'}
drvr.finish_revert_migration('', ins_ref, None, power_on=False)
drvr.image_backend.rollback_to_snap.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME)
drvr.image_backend.remove_snap.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True)
def test_finish_revert_migration_snap_backend_snapshot_not_found(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
ins_ref = self._create_instance()
with test.nested(
mock.patch.object(rbd_utils, 'RBDDriver'),
mock.patch.object(utils, 'get_image_from_system_metadata'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(drvr, '_get_guest_xml')) as (
mock_rbd, mock_image, mock_cdn, mock_ggx):
mock_image.return_value = {'disk_format': 'raw'}
mock_rbd.rollback_to_snap.side_effect = exception.SnapshotNotFound(
snapshot_id='testing')
drvr.finish_revert_migration('', ins_ref, None, power_on=False)
drvr.image_backend.remove_snap.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True)
def test_finish_revert_migration_snap_backend_image_does_not_exist(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
drvr.image_backend.exists.return_value = False
ins_ref = self._create_instance()
with test.nested(
mock.patch.object(rbd_utils, 'RBDDriver'),
mock.patch.object(utils, 'get_image_from_system_metadata'),
mock.patch.object(drvr, '_create_domain_and_network'),
mock.patch.object(drvr, '_get_guest_xml')) as (
mock_rbd, mock_image, mock_cdn, mock_ggx):
mock_image.return_value = {'disk_format': 'raw'}
drvr.finish_revert_migration('', ins_ref, None, power_on=False)
self.assertFalse(drvr.image_backend.rollback_to_snap.called)
self.assertFalse(drvr.image_backend.remove_snap.called)
def test_cleanup_failed_migration(self):
self.mox.StubOutWithMock(shutil, 'rmtree')
shutil.rmtree('/fake/inst')
self.mox.ReplayAll()
self.drvr._cleanup_failed_migration('/fake/inst')
def test_confirm_migration(self):
ins_ref = self._create_instance()
self.mox.StubOutWithMock(self.drvr, "_cleanup_resize")
self.drvr._cleanup_resize(ins_ref,
_fake_network_info(self, 1))
self.mox.ReplayAll()
self.drvr.confirm_migration("migration_ref", ins_ref,
_fake_network_info(self, 1))
def test_cleanup_resize_same_host(self):
CONF.set_override('policy_dirs', [], group='oslo_policy')
ins_ref = self._create_instance({'host': CONF.host})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
with test.nested(
mock.patch.object(os.path, 'exists'),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute')) as (
mock_exists, mock_get_path, mock_exec):
mock_exists.return_value = True
mock_get_path.return_value = '/fake/inst'
drvr._cleanup_resize(ins_ref, _fake_network_info(self, 1))
mock_get_path.assert_called_once_with(ins_ref)
mock_exec.assert_called_once_with('rm', '-rf', '/fake/inst_resize',
delay_on_retry=True, attempts=5)
def test_cleanup_resize_not_same_host(self):
CONF.set_override('policy_dirs', [], group='oslo_policy')
host = 'not' + CONF.host
ins_ref = self._create_instance({'host': host})
fake_net = _fake_network_info(self, 1)
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
with test.nested(
mock.patch.object(os.path, 'exists'),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr, '_undefine_domain'),
mock.patch.object(drvr, 'unplug_vifs'),
mock.patch.object(drvr, 'unfilter_instance')
) as (mock_exists, mock_get_path, mock_exec, mock_undef,
mock_unplug, mock_unfilter):
mock_exists.return_value = True
mock_get_path.return_value = '/fake/inst'
drvr._cleanup_resize(ins_ref, fake_net)
mock_get_path.assert_called_once_with(ins_ref)
mock_exec.assert_called_once_with('rm', '-rf', '/fake/inst_resize',
delay_on_retry=True, attempts=5)
mock_undef.assert_called_once_with(ins_ref)
mock_unplug.assert_called_once_with(ins_ref, fake_net)
mock_unfilter.assert_called_once_with(ins_ref, fake_net)
def test_cleanup_resize_snap_backend(self):
CONF.set_override('policy_dirs', [], group='oslo_policy')
ins_ref = self._create_instance({'host': CONF.host})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
with test.nested(
mock.patch.object(os.path, 'exists'),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr.image_backend, 'remove_snap')) as (
mock_exists, mock_get_path, mock_exec, mock_remove):
mock_exists.return_value = True
mock_get_path.return_value = '/fake/inst'
drvr._cleanup_resize(ins_ref, _fake_network_info(self, 1))
mock_get_path.assert_called_once_with(ins_ref)
mock_exec.assert_called_once_with('rm', '-rf', '/fake/inst_resize',
delay_on_retry=True, attempts=5)
mock_remove.assert_called_once_with(
libvirt_utils.RESIZE_SNAPSHOT_NAME, ignore_errors=True)
def test_cleanup_resize_snap_backend_image_does_not_exist(self):
CONF.set_override('policy_dirs', [], group='oslo_policy')
ins_ref = self._create_instance({'host': CONF.host})
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
drvr.image_backend = mock.Mock()
drvr.image_backend.image.return_value = drvr.image_backend
drvr.image_backend.exists.return_value = False
with test.nested(
mock.patch.object(os.path, 'exists'),
mock.patch.object(libvirt_utils, 'get_instance_path'),
mock.patch.object(utils, 'execute'),
mock.patch.object(drvr.image_backend, 'remove_snap')) as (
mock_exists, mock_get_path, mock_exec, mock_remove):
mock_exists.return_value = True
mock_get_path.return_value = '/fake/inst'
drvr._cleanup_resize(ins_ref, _fake_network_info(self, 1))
mock_get_path.assert_called_once_with(ins_ref)
mock_exec.assert_called_once_with('rm', '-rf', '/fake/inst_resize',
delay_on_retry=True, attempts=5)
self.assertFalse(mock_remove.called)
def test_get_instance_disk_info_exception(self):
instance = self._create_instance()
class FakeExceptionDomain(FakeVirtDomain):
def __init__(self):
super(FakeExceptionDomain, self).__init__()
def XMLDesc(self, flags):
raise fakelibvirt.libvirtError("Libvirt error")
def fake_get_domain(self, instance):
return FakeExceptionDomain()
self.stubs.Set(host.Host, 'get_domain',
fake_get_domain)
self.assertRaises(exception.InstanceNotFound,
self.drvr.get_instance_disk_info,
instance)
@mock.patch('os.path.exists')
@mock.patch.object(lvm, 'list_volumes')
def test_lvm_disks(self, listlvs, exists):
instance = objects.Instance(uuid=uuids.instance, id=1)
self.flags(images_volume_group='vols', group='libvirt')
exists.return_value = True
listlvs.return_value = ['%s_foo' % uuids.instance,
'other-uuid_foo']
disks = self.drvr._lvm_disks(instance)
self.assertEqual(['/dev/vols/%s_foo' % uuids.instance], disks)
def test_is_booted_from_volume(self):
func = libvirt_driver.LibvirtDriver._is_booted_from_volume
instance, disk_mapping = {}, {}
self.assertTrue(func(instance, disk_mapping))
disk_mapping['disk'] = 'map'
self.assertTrue(func(instance, disk_mapping))
instance['image_ref'] = 'uuid'
self.assertFalse(func(instance, disk_mapping))
@mock.patch('nova.virt.libvirt.driver.imagebackend')
@mock.patch(
'nova.virt.libvirt.driver.LibvirtDriver._try_fetch_image_cache')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._inject_data')
@mock.patch('nova.virt.libvirt.driver.imagecache')
def test_data_not_injects_with_configdrive(self, mock_image, mock_inject,
mock_fetch, mock_backend):
self.flags(inject_partition=-1, group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
# config_drive is True by default, configdrive.required_by()
# returns True
instance_ref = self._create_instance()
disk_images = {'image_id': None}
drvr._create_and_inject_local_root(self.context, instance_ref, False,
'', disk_images, [], None, [], True, None)
self.assertFalse(mock_inject.called)
@mock.patch('nova.virt.netutils.get_injected_network_template')
@mock.patch('nova.virt.disk.api.inject_data')
@mock.patch.object(libvirt_driver.LibvirtDriver, "_conn")
def _test_inject_data(self, driver_params, path, disk_params,
mock_conn, disk_inject_data, inj_network,
called=True):
class ImageBackend(object):
path = '/path'
def get_model(self, connection):
return imgmodel.LocalFileImage(self.path,
imgmodel.FORMAT_RAW)
def fake_inj_network(*args, **kwds):
return args[0] or None
inj_network.side_effect = fake_inj_network
image_backend = ImageBackend()
image_backend.path = path
with mock.patch.object(
self.drvr.image_backend,
'image',
return_value=image_backend):
self.flags(inject_partition=0, group='libvirt')
self.drvr._inject_data(image_backend, **driver_params)
if called:
disk_inject_data.assert_called_once_with(
mock.ANY,
*disk_params,
partition=None, mandatory=('files',))
self.assertEqual(disk_inject_data.called, called)
def _test_inject_data_default_driver_params(self, **params):
return {
'instance': self._create_instance(params=params),
'network_info': None,
'admin_pass': None,
'files': None
}
def test_inject_data_adminpass(self):
self.flags(inject_password=True, group='libvirt')
driver_params = self._test_inject_data_default_driver_params()
driver_params['admin_pass'] = 'foobar'
disk_params = [
None, # key
None, # net
{}, # metadata
'foobar', # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/path", disk_params)
# Test with the configuration setted to false.
self.flags(inject_password=False, group='libvirt')
self._test_inject_data(driver_params, "/path",
disk_params, called=False)
def test_inject_data_key(self):
driver_params = self._test_inject_data_default_driver_params()
driver_params['instance']['key_data'] = 'key-content'
self.flags(inject_key=True, group='libvirt')
disk_params = [
'key-content', # key
None, # net
{}, # metadata
None, # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/path", disk_params)
# Test with the configuration setted to false.
self.flags(inject_key=False, group='libvirt')
self._test_inject_data(driver_params, "/path",
disk_params, called=False)
def test_inject_data_metadata(self):
instance_metadata = {'metadata': {'data': 'foo'}}
driver_params = self._test_inject_data_default_driver_params(
**instance_metadata
)
disk_params = [
None, # key
None, # net
{'data': 'foo'}, # metadata
None, # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/path", disk_params)
def test_inject_data_files(self):
driver_params = self._test_inject_data_default_driver_params()
driver_params['files'] = ['file1', 'file2']
disk_params = [
None, # key
None, # net
{}, # metadata
None, # admin_pass
['file1', 'file2'], # files
]
self._test_inject_data(driver_params, "/path", disk_params)
def test_inject_data_net(self):
driver_params = self._test_inject_data_default_driver_params()
driver_params['network_info'] = {'net': 'eno1'}
disk_params = [
None, # key
{'net': 'eno1'}, # net
{}, # metadata
None, # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/path", disk_params)
def test_inject_not_exist_image(self):
driver_params = self._test_inject_data_default_driver_params()
disk_params = [
'key-content', # key
None, # net
None, # metadata
None, # admin_pass
None, # files
]
self._test_inject_data(driver_params, "/fail/path",
disk_params, called=False)
def _test_attach_detach_interface(self, method, power_state,
expected_flags):
instance = self._create_instance()
network_info = _fake_network_info(self, 1)
domain = FakeVirtDomain()
self.mox.StubOutWithMock(host.Host, 'get_domain')
self.mox.StubOutWithMock(self.drvr.firewall_driver,
'setup_basic_filtering')
self.mox.StubOutWithMock(domain, 'attachDeviceFlags')
self.mox.StubOutWithMock(domain, 'info')
host.Host.get_domain(instance).AndReturn(domain)
if method == 'attach_interface':
self.drvr.firewall_driver.setup_basic_filtering(
instance, [network_info[0]])
fake_image_meta = objects.ImageMeta.from_dict(
{'id': instance.image_ref})
expected = self.drvr.vif_driver.get_config(
instance, network_info[0], fake_image_meta, instance.flavor,
CONF.libvirt.virt_type, self.drvr._host)
self.mox.StubOutWithMock(self.drvr.vif_driver,
'get_config')
self.drvr.vif_driver.get_config(
instance, network_info[0],
mox.IsA(objects.ImageMeta),
mox.IsA(objects.Flavor),
CONF.libvirt.virt_type,
self.drvr._host).AndReturn(expected)
domain.info().AndReturn([power_state, 1, 2, 3, 4])
if method == 'attach_interface':
domain.attachDeviceFlags(expected.to_xml(), flags=expected_flags)
elif method == 'detach_interface':
domain.detachDeviceFlags(expected.to_xml(), expected_flags)
self.mox.ReplayAll()
if method == 'attach_interface':
self.drvr.attach_interface(
instance, fake_image_meta, network_info[0])
elif method == 'detach_interface':
self.drvr.detach_interface(
instance, network_info[0])
self.mox.VerifyAll()
def test_attach_interface_with_running_instance(self):
self._test_attach_detach_interface(
'attach_interface', power_state.RUNNING,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def test_attach_interface_with_pause_instance(self):
self._test_attach_detach_interface(
'attach_interface', power_state.PAUSED,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def test_attach_interface_with_shutdown_instance(self):
self._test_attach_detach_interface(
'attach_interface', power_state.SHUTDOWN,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG))
def test_detach_interface_with_running_instance(self):
self._test_attach_detach_interface(
'detach_interface', power_state.RUNNING,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def test_detach_interface_with_pause_instance(self):
self._test_attach_detach_interface(
'detach_interface', power_state.PAUSED,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG |
fakelibvirt.VIR_DOMAIN_AFFECT_LIVE))
def test_detach_interface_with_shutdown_instance(self):
self._test_attach_detach_interface(
'detach_interface', power_state.SHUTDOWN,
expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG))
@mock.patch('nova.virt.libvirt.driver.LOG')
def test_detach_interface_device_not_found(self, mock_log):
# Asserts that we don't log an error when the interface device is not
# found on the guest after a libvirt error during detach.
instance = self._create_instance()
vif = _fake_network_info(self, 1)[0]
guest = mock.Mock(spec='nova.virt.libvirt.guest.Guest')
guest.get_power_state = mock.Mock()
self.drvr._host.get_guest = mock.Mock(return_value=guest)
self.drvr.vif_driver = mock.Mock()
error = fakelibvirt.libvirtError(
'no matching network device was found')
error.err = (fakelibvirt.VIR_ERR_OPERATION_FAILED,)
guest.detach_device = mock.Mock(side_effect=error)
# mock out that get_interface_by_mac doesn't find the interface
guest.get_interface_by_mac = mock.Mock(return_value=None)
self.drvr.detach_interface(instance, vif)
guest.get_interface_by_mac.assert_called_once_with(vif['address'])
# an error shouldn't be logged, but a warning should be logged
self.assertFalse(mock_log.error.called)
self.assertEqual(1, mock_log.warning.call_count)
self.assertIn('the device is no longer found on the guest',
six.text_type(mock_log.warning.call_args[0]))
@mock.patch('nova.virt.libvirt.utils.write_to_file')
# NOTE(mdbooth): The following 4 mocks are required to execute
# get_guest_xml().
@mock.patch.object(libvirt_driver.LibvirtDriver, '_set_host_enabled')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_build_device_metadata')
@mock.patch.object(libvirt_driver.LibvirtDriver, '_supports_direct_io')
@mock.patch('nova.api.metadata.base.InstanceMetadata')
def _test_rescue(self, instance,
mock_instance_metadata, mock_supports_direct_io,
mock_build_device_metadata, mock_set_host_enabled,
mock_write_to_file,
exists=None):
self.flags(instances_path=self.useFixture(fixtures.TempDir()).path)
mock_build_device_metadata.return_value = None
mock_supports_direct_io.return_value = True
backend = self.useFixture(
fake_imagebackend.ImageBackendFixture(exists=exists))
image_meta = objects.ImageMeta.from_dict(
{'id': uuids.image_id, 'name': 'fake'})
network_info = _fake_network_info(self, 1)
rescue_password = 'fake_password'
domain_xml = [None]
def fake_create_domain(xml=None, domain=None, power_on=True,
pause=False, post_xml_callback=None):
domain_xml[0] = xml
if post_xml_callback is not None:
post_xml_callback()
with mock.patch.object(
self.drvr, '_create_domain',
side_effect=fake_create_domain) as mock_create_domain:
self.drvr.rescue(self.context, instance,
network_info, image_meta, rescue_password)
self.assertTrue(mock_create_domain.called)
return backend, etree.fromstring(domain_xml[0])
def test_rescue(self):
instance = self._create_instance({'config_drive': None})
backend, doc = self._test_rescue(instance)
# Assert that we created the expected set of disks, and no others
self.assertEqual(['disk.rescue', 'kernel.rescue', 'ramdisk.rescue'],
sorted(backend.created_disks.keys()))
disks = backend.disks
kernel_ramdisk = [disks[name + '.rescue']
for name in ('kernel', 'ramdisk')]
# Assert that kernel and ramdisk were both created as raw
for disk in kernel_ramdisk:
self.assertEqual('raw', disk.image_type)
# Assert that the root rescue disk was created as the default type
self.assertIsNone(disks['disk.rescue'].image_type)
# We expect the generated domain to contain disk.rescue and
# disk, in that order
expected_domain_disk_paths = map(
lambda name: disks[name].path, ('disk.rescue', 'disk'))
domain_disk_paths = doc.xpath('devices/disk/source/@file')
self.assertEqual(expected_domain_disk_paths, domain_disk_paths)
# The generated domain xml should contain the rescue kernel
# and ramdisk
expected_kernel_ramdisk_paths = map(
lambda disk: os.path.join(CONF.instances_path, disk.path),
kernel_ramdisk)
kernel_ramdisk_paths = \
doc.xpath('os/*[self::initrd|self::kernel]/text()')
self.assertEqual(expected_kernel_ramdisk_paths,
kernel_ramdisk_paths)
@mock.patch('nova.virt.configdrive.ConfigDriveBuilder._make_iso9660')
def test_rescue_config_drive(self, mock_mkisofs):
instance = self._create_instance({'config_drive': str(True)})
backend, doc = self._test_rescue(
instance, exists=lambda name: name != 'disk.config.rescue')
# Assert that we created the expected set of disks, and no others
self.assertEqual(['disk.config.rescue', 'disk.rescue', 'kernel.rescue',
'ramdisk.rescue'],
sorted(backend.created_disks.keys()))
disks = backend.disks
config_disk = disks['disk.config.rescue']
kernel_ramdisk = [disks[name + '.rescue']
for name in ('kernel', 'ramdisk')]
# Assert that we imported the config disk
self.assertTrue(config_disk.import_file.called)
# Assert that the config disk, kernel and ramdisk were created as raw
for disk in [config_disk] + kernel_ramdisk:
self.assertEqual('raw', disk.image_type)
# Assert that the root rescue disk was created as the default type
self.assertIsNone(disks['disk.rescue'].image_type)
# We expect the generated domain to contain disk.rescue, disk, and
# disk.config.rescue in that order
expected_domain_disk_paths = map(
lambda name: disks[name].path, ('disk.rescue', 'disk',
'disk.config.rescue'))
domain_disk_paths = doc.xpath('devices/disk/source/@file')
self.assertEqual(expected_domain_disk_paths, domain_disk_paths)
# The generated domain xml should contain the rescue kernel
# and ramdisk
expected_kernel_ramdisk_paths = map(
lambda disk: os.path.join(CONF.instances_path, disk.path),
kernel_ramdisk)
kernel_ramdisk_paths = \
doc.xpath('os/*[self::initrd|self::kernel]/text()')
self.assertEqual(expected_kernel_ramdisk_paths,
kernel_ramdisk_paths)
@mock.patch.object(libvirt_utils, 'get_instance_path')
@mock.patch.object(libvirt_utils, 'load_file')
@mock.patch.object(host.Host, "get_domain")
def test_unrescue(self, mock_get_domain, mock_load_file,
mock_get_instance_path):
dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>"
"<devices>"
"<disk type='block' device='disk'>"
"<source dev='/dev/some-vg/some-lv'/>"
"<target dev='vda' bus='virtio'/></disk>"
"</devices></domain>")
mock_get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
fake_dom = FakeVirtDomain(fake_xml=dummyxml)
mock_get_domain.return_value = fake_dom
mock_load_file.return_value = "fake_unrescue_xml"
unrescue_xml_path = os.path.join('/path', 'unrescue.xml')
xml_path = os.path.join('/path', 'libvirt.xml')
rescue_file = os.path.join('/path', 'rescue.file')
rescue_dir = os.path.join('/path', 'rescue.dir')
def isdir_sideeffect(*args, **kwargs):
if args[0] == '/path/rescue.file':
return False
if args[0] == '/path/rescue.dir':
return True
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
with test.nested(
mock.patch.object(libvirt_utils, 'write_to_file'),
mock.patch.object(drvr, '_destroy'),
mock.patch.object(drvr, '_create_domain'),
mock.patch.object(libvirt_utils, 'file_delete'),
mock.patch.object(shutil, 'rmtree'),
mock.patch.object(os.path, "isdir",
side_effect=isdir_sideeffect),
mock.patch.object(drvr, '_lvm_disks',
return_value=['lvm.rescue']),
mock.patch.object(lvm, 'remove_volumes'),
mock.patch.object(glob, 'iglob',
return_value=[rescue_file, rescue_dir])
) as (mock_write, mock_destroy, mock_create, mock_del,
mock_rmtree, mock_isdir, mock_lvm_disks,
mock_remove_volumes, mock_glob):
drvr.unrescue(instance, None)
mock_write.assert_called_once_with(xml_path, "fake_unrescue_xml")
mock_destroy.assert_called_once_with(instance)
mock_create.assert_called_once_with("fake_unrescue_xml",
fake_dom)
self.assertEqual(2, mock_del.call_count)
self.assertEqual(unrescue_xml_path,
mock_del.call_args_list[0][0][0])
self.assertEqual(1, mock_rmtree.call_count)
self.assertEqual(rescue_dir, mock_rmtree.call_args_list[0][0][0])
self.assertEqual(rescue_file, mock_del.call_args_list[1][0][0])
mock_remove_volumes.assert_called_once_with(['lvm.rescue'])
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files(self, get_instance_path, exists, exe,
shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
exe.assert_called_with('mv', '/path', '/path_del')
shutil.assert_called_with('/path_del')
self.assertTrue(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('os.kill')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_kill_running(
self, get_instance_path, kill, exists, exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
self.drvr.job_tracker.jobs[instance.uuid] = [3, 4]
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
exe.assert_called_with('mv', '/path', '/path_del')
kill.assert_has_calls([mock.call(3, signal.SIGKILL), mock.call(3, 0),
mock.call(4, signal.SIGKILL), mock.call(4, 0)])
shutil.assert_called_with('/path_del')
self.assertTrue(result)
self.assertNotIn(instance.uuid, self.drvr.job_tracker.jobs)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_resize(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = [Exception(), None]
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')]
self.assertEqual(expected, exe.mock_calls)
shutil.assert_called_with('/path_del')
self.assertTrue(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_failed(self, get_instance_path, exists, exe,
shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
exists.side_effect = [False, False, True, True]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
exe.assert_called_with('mv', '/path', '/path_del')
shutil.assert_called_with('/path_del')
self.assertFalse(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_mv_failed(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = Exception()
exists.side_effect = [True, True]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')] * 2
self.assertEqual(expected, exe.mock_calls)
self.assertFalse(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_resume(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = Exception()
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')] * 2
self.assertEqual(expected, exe.mock_calls)
self.assertTrue(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_none(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = Exception()
exists.side_effect = [False, False, False, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')] * 2
self.assertEqual(expected, exe.mock_calls)
self.assertEqual(0, len(shutil.mock_calls))
self.assertTrue(result)
@mock.patch('shutil.rmtree')
@mock.patch('nova.utils.execute')
@mock.patch('os.path.exists')
@mock.patch('nova.virt.libvirt.utils.get_instance_path')
def test_delete_instance_files_concurrent(self, get_instance_path, exists,
exe, shutil):
get_instance_path.return_value = '/path'
instance = objects.Instance(uuid=uuids.instance, id=1)
nova.utils.execute.side_effect = [Exception(), Exception(), None]
exists.side_effect = [False, False, True, False]
result = self.drvr.delete_instance_files(instance)
get_instance_path.assert_called_with(instance)
expected = [mock.call('mv', '/path', '/path_del'),
mock.call('mv', '/path_resize', '/path_del')]
expected.append(expected[0])
self.assertEqual(expected, exe.mock_calls)
shutil.assert_called_with('/path_del')
self.assertTrue(result)
def _assert_on_id_map(self, idmap, klass, start, target, count):
self.assertIsInstance(idmap, klass)
self.assertEqual(start, idmap.start)
self.assertEqual(target, idmap.target)
self.assertEqual(count, idmap.count)
def test_get_id_maps(self):
self.flags(virt_type="lxc", group="libvirt")
CONF.libvirt.virt_type = "lxc"
CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"]
CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"]
idmaps = self.drvr._get_guest_idmaps()
self.assertEqual(len(idmaps), 4)
self._assert_on_id_map(idmaps[0],
vconfig.LibvirtConfigGuestUIDMap,
0, 10000, 1)
self._assert_on_id_map(idmaps[1],
vconfig.LibvirtConfigGuestUIDMap,
1, 20000, 10)
self._assert_on_id_map(idmaps[2],
vconfig.LibvirtConfigGuestGIDMap,
0, 10000, 1)
self._assert_on_id_map(idmaps[3],
vconfig.LibvirtConfigGuestGIDMap,
1, 20000, 10)
def test_get_id_maps_not_lxc(self):
CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"]
CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"]
idmaps = self.drvr._get_guest_idmaps()
self.assertEqual(0, len(idmaps))
def test_get_id_maps_only_uid(self):
self.flags(virt_type="lxc", group="libvirt")
CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"]
CONF.libvirt.gid_maps = []
idmaps = self.drvr._get_guest_idmaps()
self.assertEqual(2, len(idmaps))
self._assert_on_id_map(idmaps[0],
vconfig.LibvirtConfigGuestUIDMap,
0, 10000, 1)
self._assert_on_id_map(idmaps[1],
vconfig.LibvirtConfigGuestUIDMap,
1, 20000, 10)
def test_get_id_maps_only_gid(self):
self.flags(virt_type="lxc", group="libvirt")
CONF.libvirt.uid_maps = []
CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"]
idmaps = self.drvr._get_guest_idmaps()
self.assertEqual(2, len(idmaps))
self._assert_on_id_map(idmaps[0],
vconfig.LibvirtConfigGuestGIDMap,
0, 10000, 1)
self._assert_on_id_map(idmaps[1],
vconfig.LibvirtConfigGuestGIDMap,
1, 20000, 10)
def test_instance_on_disk(self):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(uuid=uuids.instance, id=1)
self.assertFalse(drvr.instance_on_disk(instance))
def test_instance_on_disk_rbd(self):
self.flags(images_type='rbd', group='libvirt')
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
instance = objects.Instance(uuid=uuids.instance, id=1)
self.assertTrue(drvr.instance_on_disk(instance))
def test_get_disk_xml(self):
dom_xml = """
<domain type="kvm">
<devices>
<disk type="file">
<source file="disk1_file"/>
<target dev="vda" bus="virtio"/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
<disk type="block">
<source dev="/path/to/dev/1"/>
<target dev="vdb" bus="virtio" serial="1234"/>
</disk>
</devices>
</domain>
"""
diska_xml = """<disk type="file" device="disk">
<source file="disk1_file"/>
<target bus="virtio" dev="vda"/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>"""
diskb_xml = """<disk type="block" device="disk">
<source dev="/path/to/dev/1"/>
<target bus="virtio" dev="vdb"/>
</disk>"""
dom = mock.MagicMock()
dom.XMLDesc.return_value = dom_xml
guest = libvirt_guest.Guest(dom)
# NOTE(gcb): etree.tostring(node) returns an extra line with
# some white spaces, need to strip it.
actual_diska_xml = guest.get_disk('vda').to_xml()
self.assertEqual(diska_xml.strip(), actual_diska_xml.strip())
actual_diskb_xml = guest.get_disk('vdb').to_xml()
self.assertEqual(diskb_xml.strip(), actual_diskb_xml.strip())
self.assertIsNone(guest.get_disk('vdc'))
def test_vcpu_model_from_config(self):
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
vcpu_model = drv._cpu_config_to_vcpu_model(None, None)
self.assertIsNone(vcpu_model)
cpu = vconfig.LibvirtConfigGuestCPU()
feature1 = vconfig.LibvirtConfigGuestCPUFeature()
feature2 = vconfig.LibvirtConfigGuestCPUFeature()
feature1.name = 'sse'
feature1.policy = cpumodel.POLICY_REQUIRE
feature2.name = 'aes'
feature2.policy = cpumodel.POLICY_REQUIRE
cpu.features = set([feature1, feature2])
cpu.mode = cpumodel.MODE_CUSTOM
cpu.sockets = 1
cpu.cores = 2
cpu.threads = 4
vcpu_model = drv._cpu_config_to_vcpu_model(cpu, None)
self.assertEqual(cpumodel.MATCH_EXACT, vcpu_model.match)
self.assertEqual(cpumodel.MODE_CUSTOM, vcpu_model.mode)
self.assertEqual(4, vcpu_model.topology.threads)
self.assertEqual(set(['sse', 'aes']),
set([f.name for f in vcpu_model.features]))
cpu.mode = cpumodel.MODE_HOST_MODEL
vcpu_model_1 = drv._cpu_config_to_vcpu_model(cpu, vcpu_model)
self.assertEqual(cpumodel.MODE_HOST_MODEL, vcpu_model.mode)
self.assertEqual(vcpu_model, vcpu_model_1)
@mock.patch.object(lvm, 'get_volume_size', return_value=10)
@mock.patch.object(host.Host, "get_guest")
@mock.patch.object(dmcrypt, 'delete_volume')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.unfilter_instance')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain')
@mock.patch.object(objects.Instance, 'save')
def test_cleanup_lvm_encrypted(self, mock_save, mock_undefine_domain,
mock_unfilter, mock_delete_volume,
mock_get_guest, mock_get_size):
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance = objects.Instance(
uuid=uuids.instance, id=1,
ephemeral_key_uuid=uuids.ephemeral_key_uuid)
instance.system_metadata = {}
block_device_info = {'root_device_name': '/dev/vda',
'ephemerals': [],
'block_device_mapping': []}
self.flags(images_type="lvm",
group='libvirt')
dom_xml = """
<domain type="kvm">
<devices>
<disk type="block">
<driver name='qemu' type='raw' cache='none'/>
<source dev="/dev/mapper/fake-dmcrypt"/>
<target dev="vda" bus="virtio" serial="1234"/>
</disk>
</devices>
</domain>
"""
dom = mock.MagicMock()
dom.XMLDesc.return_value = dom_xml
guest = libvirt_guest.Guest(dom)
mock_get_guest.return_value = guest
drv.cleanup(self.context, instance, 'fake_network', destroy_vifs=False,
block_device_info=block_device_info)
mock_delete_volume.assert_called_once_with('/dev/mapper/fake-dmcrypt')
@mock.patch.object(lvm, 'get_volume_size', return_value=10)
@mock.patch.object(host.Host, "get_guest")
@mock.patch.object(dmcrypt, 'delete_volume')
def _test_cleanup_lvm(self, mock_delete_volume, mock_get_guest, mock_size,
encrypted=False):
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance = objects.Instance(
uuid=uuids.instance, id=1,
ephemeral_key_uuid=uuids.ephemeral_key_uuid)
block_device_info = {'root_device_name': '/dev/vda',
'ephemerals': [],
'block_device_mapping': []}
dev_name = 'fake-dmcrypt' if encrypted else 'fake'
dom_xml = """
<domain type="kvm">
<devices>
<disk type="block">
<driver name='qemu' type='raw' cache='none'/>
<source dev="/dev/mapper/%s"/>
<target dev="vda" bus="virtio" serial="1234"/>
</disk>
</devices>
</domain>
""" % dev_name
dom = mock.MagicMock()
dom.XMLDesc.return_value = dom_xml
guest = libvirt_guest.Guest(dom)
mock_get_guest.return_value = guest
drv._cleanup_lvm(instance, block_device_info)
if encrypted:
mock_delete_volume.assert_called_once_with(
'/dev/mapper/fake-dmcrypt')
else:
self.assertFalse(mock_delete_volume.called)
def test_cleanup_lvm(self):
self._test_cleanup_lvm()
def test_cleanup_encrypted_lvm(self):
self._test_cleanup_lvm(encrypted=True)
def test_vcpu_model_to_config(self):
drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
feature = objects.VirtCPUFeature(policy=cpumodel.POLICY_REQUIRE,
name='sse')
feature_1 = objects.VirtCPUFeature(policy=cpumodel.POLICY_FORBID,
name='aes')
topo = objects.VirtCPUTopology(sockets=1, cores=2, threads=4)
vcpu_model = objects.VirtCPUModel(mode=cpumodel.MODE_HOST_MODEL,
features=[feature, feature_1],
topology=topo)
cpu = drv._vcpu_model_to_cpu_config(vcpu_model)
self.assertEqual(cpumodel.MODE_HOST_MODEL, cpu.mode)
self.assertEqual(1, cpu.sockets)
self.assertEqual(4, cpu.threads)
self.assertEqual(2, len(cpu.features))
self.assertEqual(set(['sse', 'aes']),
set([f.name for f in cpu.features]))
self.assertEqual(set([cpumodel.POLICY_REQUIRE,
cpumodel.POLICY_FORBID]),
set([f.policy for f in cpu.features]))
def test_trigger_crash_dump(self):
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
instance = objects.Instance(uuid=uuids.instance, id=1)
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.drvr.trigger_crash_dump(instance)
def test_trigger_crash_dump_not_running(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'Requested operation is not valid: domain is not running',
error_code=fakelibvirt.VIR_ERR_OPERATION_INVALID)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.inject_nmi = mock.Mock(side_effect=ex)
instance = objects.Instance(uuid=uuids.instance, id=1)
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.assertRaises(exception.InstanceNotRunning,
self.drvr.trigger_crash_dump, instance)
def test_trigger_crash_dump_not_supported(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'',
error_code=fakelibvirt.VIR_ERR_NO_SUPPORT)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.inject_nmi = mock.Mock(side_effect=ex)
instance = objects.Instance(uuid=uuids.instance, id=1)
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.assertRaises(exception.TriggerCrashDumpNotSupported,
self.drvr.trigger_crash_dump, instance)
def test_trigger_crash_dump_unexpected_error(self):
ex = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError,
'UnexpectedError',
error_code=fakelibvirt.VIR_ERR_SYSTEM_ERROR)
mock_guest = mock.Mock(libvirt_guest.Guest, id=1)
mock_guest.inject_nmi = mock.Mock(side_effect=ex)
instance = objects.Instance(uuid=uuids.instance, id=1)
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.assertRaises(fakelibvirt.libvirtError,
self.drvr.trigger_crash_dump, instance)
class LibvirtVolumeUsageTestCase(test.NoDBTestCase):
"""Test for LibvirtDriver.get_all_volume_usage."""
def setUp(self):
super(LibvirtVolumeUsageTestCase, self).setUp()
self.drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.c = context.get_admin_context()
self.ins_ref = objects.Instance(
id=1729,
uuid='875a8070-d0b9-4949-8b31-104d125c9a64'
)
# verify bootable volume device path also
self.bdms = [{'volume_id': 1,
'device_name': '/dev/vde'},
{'volume_id': 2,
'device_name': 'vda'}]
def test_get_all_volume_usage(self):
def fake_block_stats(instance_name, disk):
return (169, 688640, 0, 0, -1)
self.stubs.Set(self.drvr, 'block_stats', fake_block_stats)
vol_usage = self.drvr.get_all_volume_usage(self.c,
[dict(instance=self.ins_ref, instance_bdms=self.bdms)])
expected_usage = [{'volume': 1,
'instance': self.ins_ref,
'rd_bytes': 688640, 'wr_req': 0,
'rd_req': 169, 'wr_bytes': 0},
{'volume': 2,
'instance': self.ins_ref,
'rd_bytes': 688640, 'wr_req': 0,
'rd_req': 169, 'wr_bytes': 0}]
self.assertEqual(vol_usage, expected_usage)
def test_get_all_volume_usage_device_not_found(self):
def fake_get_domain(self, instance):
raise exception.InstanceNotFound(instance_id="fakedom")
self.stubs.Set(host.Host, 'get_domain', fake_get_domain)
vol_usage = self.drvr.get_all_volume_usage(self.c,
[dict(instance=self.ins_ref, instance_bdms=self.bdms)])
self.assertEqual(vol_usage, [])
class LibvirtNonblockingTestCase(test.NoDBTestCase):
"""Test libvirtd calls are nonblocking."""
def setUp(self):
super(LibvirtNonblockingTestCase, self).setUp()
self.flags(connection_uri="test:///default",
group='libvirt')
def test_connection_to_primitive(self):
# Test bug 962840.
import nova.virt.libvirt.driver as libvirt_driver
drvr = libvirt_driver.LibvirtDriver('')
drvr.set_host_enabled = mock.Mock()
jsonutils.to_primitive(drvr._conn, convert_instances=True)
@mock.patch.object(objects.Service, 'get_by_compute_host')
def test_tpool_execute_calls_libvirt(self, mock_svc):
conn = fakelibvirt.virConnect()
conn.is_expected = True
self.mox.StubOutWithMock(eventlet.tpool, 'execute')
eventlet.tpool.execute(
fakelibvirt.openAuth,
'test:///default',
mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(conn)
eventlet.tpool.execute(
conn.domainEventRegisterAny,
None,
fakelibvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
mox.IgnoreArg(),
mox.IgnoreArg())
if hasattr(fakelibvirt.virConnect, 'registerCloseCallback'):
eventlet.tpool.execute(
conn.registerCloseCallback,
mox.IgnoreArg(),
mox.IgnoreArg())
self.mox.ReplayAll()
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
c = driver._get_connection()
self.assertTrue(c.is_expected)
class LibvirtVolumeSnapshotTestCase(test.NoDBTestCase):
"""Tests for libvirtDriver.volume_snapshot_create/delete."""
def setUp(self):
super(LibvirtVolumeSnapshotTestCase, self).setUp()
self.drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.c = context.get_admin_context()
self.flags(instance_name_template='instance-%s')
self.flags(qemu_allowed_storage_drivers=[], group='libvirt')
# creating instance
self.inst = {}
self.inst['uuid'] = uuidutils.generate_uuid()
self.inst['id'] = '1'
# create domain info
self.dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='disk1_file'/>
<target dev='vda' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
<disk type='block'>
<source dev='/path/to/dev/1'/>
<target dev='vdb' bus='virtio' serial='1234'/>
</disk>
</devices>
</domain>"""
# alternate domain info with network-backed snapshot chain
self.dom_netdisk_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='disk1_file'/>
<target dev='vda' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67eaffffff</serial>
</disk>
<disk type='network' device='disk'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/root.img'>
<host name='server1' port='24007'/>
</source>
<backingStore type='network' index='1'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/snap.img'>
<host name='server1' port='24007'/>
</source>
<backingStore type='network' index='2'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/snap-b.img'>
<host name='server1' port='24007'/>
</source>
<backingStore/>
</backingStore>
</backingStore>
<target dev='vdb' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
</devices>
</domain>
"""
# XML with netdisk attached, and 1 snapshot taken
self.dom_netdisk_xml_2 = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='disk1_file'/>
<target dev='vda' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67eaffffff</serial>
</disk>
<disk type='network' device='disk'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/snap.img'>
<host name='server1' port='24007'/>
</source>
<backingStore type='network' index='1'>
<driver name='qemu' type='qcow2'/>
<source protocol='gluster' name='vol1/root.img'>
<host name='server1' port='24007'/>
</source>
<backingStore/>
</backingStore>
<target dev='vdb' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
</devices>
</domain>
"""
self.create_info = {'type': 'qcow2',
'snapshot_id': '1234-5678',
'new_file': 'new-file'}
self.volume_uuid = '0e38683e-f0af-418f-a3f1-6b67ea0f919d'
self.snapshot_id = '9c3ca9f4-9f4e-4dba-bedd-5c5e4b52b162'
self.delete_info_1 = {'type': 'qcow2',
'file_to_merge': 'snap.img',
'merge_target_file': None}
self.delete_info_2 = {'type': 'qcow2',
'file_to_merge': 'snap.img',
'merge_target_file': 'other-snap.img'}
self.delete_info_3 = {'type': 'qcow2',
'file_to_merge': None,
'merge_target_file': None}
self.delete_info_netdisk = {'type': 'qcow2',
'file_to_merge': 'snap.img',
'merge_target_file': 'root.img'}
self.delete_info_invalid_type = {'type': 'made_up_type',
'file_to_merge': 'some_file',
'merge_target_file':
'some_other_file'}
def tearDown(self):
super(LibvirtVolumeSnapshotTestCase, self).tearDown()
@mock.patch('nova.virt.block_device.DriverVolumeBlockDevice.'
'refresh_connection_info')
@mock.patch('nova.objects.block_device.BlockDeviceMapping.'
'get_by_volume_and_instance')
def test_volume_refresh_connection_info(self,
mock_get_by_volume_and_instance,
mock_refresh_connection_info):
instance = objects.Instance(**self.inst)
fake_bdm = fake_block_device.FakeDbBlockDeviceDict({
'id': 123,
'instance_uuid': uuids.instance,
'device_name': '/dev/sdb',
'source_type': 'volume',
'destination_type': 'volume',
'volume_id': 'fake-volume-id-1',
'connection_info': '{"fake": "connection_info"}'})
fake_bdm = objects.BlockDeviceMapping(self.c, **fake_bdm)
mock_get_by_volume_and_instance.return_value = fake_bdm
self.drvr._volume_refresh_connection_info(self.c, instance,
self.volume_uuid)
mock_get_by_volume_and_instance.assert_called_once_with(
self.c, self.volume_uuid, instance.uuid)
mock_refresh_connection_info.assert_called_once_with(self.c, instance,
self.drvr._volume_api, self.drvr)
def test_volume_snapshot_create(self, quiesce=True):
"""Test snapshot creation with file-based disk."""
self.flags(instance_name_template='instance-%s')
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
instance = objects.Instance(**self.inst)
new_file = 'new-file'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
self.mox.StubOutWithMock(domain, 'snapshotCreateXML')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
snap_xml_src = (
'<domainsnapshot>\n'
' <disks>\n'
' <disk name="disk1_file" snapshot="external" type="file">\n'
' <source file="new-file"/>\n'
' </disk>\n'
' <disk name="vdb" snapshot="no"/>\n'
' </disks>\n'
'</domainsnapshot>\n')
# Older versions of libvirt may be missing these.
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT = 32
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE = 64
snap_flags = (fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT)
snap_flags_q = (snap_flags |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE)
if quiesce:
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags_q)
else:
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags_q).\
AndRaise(fakelibvirt.libvirtError(
'quiescing failed, no qemu-ga'))
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags)
self.mox.ReplayAll()
guest = libvirt_guest.Guest(domain)
self.drvr._volume_snapshot_create(self.c, instance, guest,
self.volume_uuid, new_file)
self.mox.VerifyAll()
def test_volume_snapshot_create_libgfapi(self, quiesce=True):
"""Test snapshot creation with libgfapi network disk."""
self.flags(instance_name_template = 'instance-%s')
self.flags(qemu_allowed_storage_drivers = ['gluster'], group='libvirt')
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.dom_xml = """
<domain type='kvm'>
<devices>
<disk type='file'>
<source file='disk1_file'/>
<target dev='vda' bus='virtio'/>
<serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial>
</disk>
<disk type='block'>
<source protocol='gluster' name='gluster1/volume-1234'>
<host name='127.3.4.5' port='24007'/>
</source>
<target dev='vdb' bus='virtio' serial='1234'/>
</disk>
</devices>
</domain>"""
instance = objects.Instance(**self.inst)
new_file = 'new-file'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
self.mox.StubOutWithMock(domain, 'snapshotCreateXML')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
snap_xml_src = (
'<domainsnapshot>\n'
' <disks>\n'
' <disk name="disk1_file" snapshot="external" type="file">\n'
' <source file="new-file"/>\n'
' </disk>\n'
' <disk name="vdb" snapshot="no"/>\n'
' </disks>\n'
'</domainsnapshot>\n')
# Older versions of libvirt may be missing these.
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT = 32
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE = 64
snap_flags = (fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT)
snap_flags_q = (snap_flags |
fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE)
if quiesce:
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags_q)
else:
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags_q).\
AndRaise(fakelibvirt.libvirtError(
'quiescing failed, no qemu-ga'))
domain.snapshotCreateXML(snap_xml_src, flags=snap_flags)
self.mox.ReplayAll()
guest = libvirt_guest.Guest(domain)
self.drvr._volume_snapshot_create(self.c, instance, guest,
self.volume_uuid, new_file)
self.mox.VerifyAll()
def test_volume_snapshot_create_noquiesce(self):
self.test_volume_snapshot_create(quiesce=False)
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_can_quiesce(self, ver):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.inst)
image_meta = objects.ImageMeta.from_dict(
{"properties": {
"hw_qemu_guest_agent": "yes"}})
self.assertIsNone(self.drvr._can_quiesce(instance, image_meta))
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_can_quiesce_bad_hyp(self, ver):
self.flags(virt_type='lxc', group='libvirt')
instance = objects.Instance(**self.inst)
image_meta = objects.ImageMeta.from_dict(
{"properties": {
"hw_qemu_guest_agent": "yes"}})
self.assertRaises(exception.InstanceQuiesceNotSupported,
self.drvr._can_quiesce, instance, image_meta)
@mock.patch.object(host.Host,
'has_min_version', return_value=False)
def test_can_quiesce_bad_ver(self, ver):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.inst)
image_meta = {"properties": {
"hw_qemu_guest_agent": "yes"}}
self.assertRaises(exception.InstanceQuiesceNotSupported,
self.drvr._can_quiesce, instance, image_meta)
@mock.patch.object(host.Host,
'has_min_version', return_value=True)
def test_can_quiesce_agent_not_enable(self, ver):
self.flags(virt_type='kvm', group='libvirt')
instance = objects.Instance(**self.inst)
image_meta = objects.ImageMeta.from_dict({})
self.assertRaises(exception.QemuGuestAgentNotEnabled,
self.drvr._can_quiesce, instance, image_meta)
@mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_volume_snapshot_create')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver.'
'_volume_refresh_connection_info')
def test_volume_snapshot_create_outer_success(self, mock_refresh,
mock_snap_create, mock_loop):
class FakeLoopingCall(object):
def __init__(self, func):
self.func = func
def start(self, *a, **k):
try:
self.func()
except loopingcall.LoopingCallDone:
pass
return self
def wait(self):
return None
mock_loop.side_effect = FakeLoopingCall
instance = objects.Instance(**self.inst)
domain = FakeVirtDomain(fake_xml=self.dom_xml, id=1)
guest = libvirt_guest.Guest(domain)
@mock.patch.object(self.drvr, '_volume_api')
@mock.patch.object(self.drvr._host, 'get_guest')
def _test(mock_get_guest, mock_vol_api):
mock_get_guest.return_value = guest
mock_vol_api.get_snapshot.return_value = {'status': 'available'}
self.drvr.volume_snapshot_create(self.c, instance,
self.volume_uuid,
self.create_info)
mock_get_guest.assert_called_once_with(instance)
mock_snap_create.assert_called_once_with(
self.c, instance, guest, self.volume_uuid,
self.create_info['new_file'])
mock_vol_api.update_snapshot_status.assert_called_once_with(
self.c, self.create_info['snapshot_id'], 'creating')
mock_vol_api.get_snapshot.assert_called_once_with(
self.c, self.create_info['snapshot_id'])
mock_refresh.assert_called_once_with(
self.c, instance, self.volume_uuid)
_test()
def test_volume_snapshot_create_outer_failure(self):
instance = objects.Instance(**self.inst)
domain = FakeVirtDomain(fake_xml=self.dom_xml, id=1)
guest = libvirt_guest.Guest(domain)
self.mox.StubOutWithMock(self.drvr._host, 'get_guest')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_create')
self.drvr._host.get_guest(instance).AndReturn(guest)
self.drvr._volume_snapshot_create(self.c,
instance,
guest,
self.volume_uuid,
self.create_info['new_file']).\
AndRaise(exception.NovaException('oops'))
self.drvr._volume_api.update_snapshot_status(
self.c, self.create_info['snapshot_id'], 'error')
self.mox.ReplayAll()
self.assertRaises(exception.NovaException,
self.drvr.volume_snapshot_create,
self.c,
instance,
self.volume_uuid,
self.create_info)
def test_volume_snapshot_delete_1(self):
"""Deleting newest snapshot -- blockRebase."""
# libvirt lib doesn't have VIR_DOMAIN_BLOCK_REBASE_RELATIVE flag
fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_REBASE_RELATIVE')
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockRebase('vda', 'snap.img', 0, flags=0)
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.mox.VerifyAll()
fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_REBASE_RELATIVE': 8})
def test_volume_snapshot_delete_relative_1(self):
"""Deleting newest snapshot -- blockRebase using relative flag"""
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
guest = libvirt_guest.Guest(domain)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_guest')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_guest(instance).AndReturn(guest)
domain.blockRebase('vda', 'snap.img', 0,
flags=fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE)
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.mox.VerifyAll()
def _setup_block_rebase_domain_and_guest_mocks(self, dom_xml):
mock_domain = mock.Mock(spec=fakelibvirt.virDomain)
mock_domain.XMLDesc.return_value = dom_xml
guest = libvirt_guest.Guest(mock_domain)
exc = fakelibvirt.make_libvirtError(
fakelibvirt.libvirtError, 'virDomainBlockRebase() failed',
error_code=fakelibvirt.VIR_ERR_OPERATION_INVALID)
mock_domain.blockRebase.side_effect = exc
return mock_domain, guest
@mock.patch.object(host.Host, "has_min_version",
mock.Mock(return_value=True))
@mock.patch("nova.virt.libvirt.guest.Guest.is_active",
mock.Mock(return_value=False))
@mock.patch('nova.virt.images.qemu_img_info',
return_value=mock.Mock(file_format="fake_fmt"))
@mock.patch('nova.utils.execute')
def test_volume_snapshot_delete_when_dom_not_running(self, mock_execute,
mock_qemu_img_info):
"""Deleting newest snapshot of a file-based image when the domain is
not running should trigger a blockRebase using qemu-img not libvirt.
In this test, we rebase the image with another image as backing file.
"""
mock_domain, guest = self._setup_block_rebase_domain_and_guest_mocks(
self.dom_xml)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=guest):
self.drvr._volume_snapshot_delete(self.c, instance,
self.volume_uuid, snapshot_id,
self.delete_info_1)
mock_qemu_img_info.assert_called_once_with("snap.img")
mock_execute.assert_called_once_with('qemu-img', 'rebase',
'-b', 'snap.img', '-F',
'fake_fmt', 'disk1_file')
@mock.patch.object(host.Host, "has_min_version",
mock.Mock(return_value=True))
@mock.patch("nova.virt.libvirt.guest.Guest.is_active",
mock.Mock(return_value=False))
@mock.patch('nova.virt.images.qemu_img_info',
return_value=mock.Mock(file_format="fake_fmt"))
@mock.patch('nova.utils.execute')
def test_volume_snapshot_delete_when_dom_not_running_and_no_rebase_base(
self, mock_execute, mock_qemu_img_info):
"""Deleting newest snapshot of a file-based image when the domain is
not running should trigger a blockRebase using qemu-img not libvirt.
In this test, the image is rebased onto no backing file (i.e.
it will exist independently of any backing file)
"""
mock_domain, mock_guest = (
self._setup_block_rebase_domain_and_guest_mocks(self.dom_xml))
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
self.drvr._volume_snapshot_delete(self.c, instance,
self.volume_uuid, snapshot_id,
self.delete_info_3)
self.assertEqual(0, mock_qemu_img_info.call_count)
mock_execute.assert_called_once_with('qemu-img', 'rebase',
'-b', '', 'disk1_file')
@mock.patch.object(host.Host, "has_min_version",
mock.Mock(return_value=True))
@mock.patch("nova.virt.libvirt.guest.Guest.is_active",
mock.Mock(return_value=False))
def test_volume_snapshot_delete_when_dom_with_nw_disk_not_running(self):
"""Deleting newest snapshot of a network disk when the domain is not
running should raise a NovaException.
"""
mock_domain, mock_guest = (
self._setup_block_rebase_domain_and_guest_mocks(
self.dom_netdisk_xml))
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
with mock.patch.object(self.drvr._host, 'get_guest',
return_value=mock_guest):
ex = self.assertRaises(exception.NovaException,
self.drvr._volume_snapshot_delete,
self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.assertIn('has not been fully tested', six.text_type(ex))
def test_volume_snapshot_delete_2(self):
"""Deleting older snapshot -- blockCommit."""
# libvirt lib doesn't have VIR_DOMAIN_BLOCK_COMMIT_RELATIVE
fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_COMMIT_RELATIVE')
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
self.mox.ReplayAll()
self.assertRaises(exception.Invalid,
self.drvr._volume_snapshot_delete,
self.c,
instance,
self.volume_uuid,
snapshot_id,
self.delete_info_2)
fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_COMMIT_RELATIVE': 4})
def test_volume_snapshot_delete_relative_2(self):
"""Deleting older snapshot -- blockCommit using relative flag"""
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockCommit('vda', 'other-snap.img', 'snap.img', 0,
flags=fakelibvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE)
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vda', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_2)
self.mox.VerifyAll()
def test_volume_snapshot_delete_nonrelative_null_base(self):
# Deleting newest and last snapshot of a volume
# with blockRebase. So base of the new image will be null.
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_xml)
guest = libvirt_guest.Guest(domain)
with test.nested(
mock.patch.object(domain, 'XMLDesc', return_value=self.dom_xml),
mock.patch.object(self.drvr._host, 'get_guest',
return_value=guest),
mock.patch.object(domain, 'blockRebase'),
mock.patch.object(domain, 'blockJobInfo',
return_value={
'type': 4, # See virDomainBlockJobType enum
'bandwidth': 0,
'cur': 1000,
'end': 1000})
) as (mock_xmldesc, mock_get_guest,
mock_rebase, mock_job_info):
self.drvr._volume_snapshot_delete(self.c, instance,
self.volume_uuid, snapshot_id,
self.delete_info_3)
mock_xmldesc.assert_called_once_with(flags=0)
mock_get_guest.assert_called_once_with(instance)
mock_rebase.assert_called_once_with('vda', None, 0, flags=0)
mock_job_info.assert_called_once_with('vda', flags=0)
def test_volume_snapshot_delete_netdisk_nonrelative_null_base(self):
# Deleting newest and last snapshot of a network attached volume
# with blockRebase. So base of the new image will be null.
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeVirtDomain(fake_xml=self.dom_netdisk_xml_2)
guest = libvirt_guest.Guest(domain)
with test.nested(
mock.patch.object(domain, 'XMLDesc',
return_value=self.dom_netdisk_xml_2),
mock.patch.object(self.drvr._host, 'get_guest',
return_value=guest),
mock.patch.object(domain, 'blockRebase'),
mock.patch.object(domain, 'blockJobInfo',
return_value={
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
) as (mock_xmldesc, mock_get_guest,
mock_rebase, mock_job_info):
self.drvr._volume_snapshot_delete(self.c, instance,
self.volume_uuid, snapshot_id,
self.delete_info_3)
mock_xmldesc.assert_called_once_with(flags=0)
mock_get_guest.assert_called_once_with(instance)
mock_rebase.assert_called_once_with('vdb', None, 0, flags=0)
mock_job_info.assert_called_once_with('vdb', flags=0)
def test_volume_snapshot_delete_outer_success(self):
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_delete')
self.drvr._volume_snapshot_delete(self.c,
instance,
self.volume_uuid,
snapshot_id,
delete_info=self.delete_info_1)
self.drvr._volume_api.update_snapshot_status(
self.c, snapshot_id, 'deleting')
self.mox.StubOutWithMock(self.drvr, '_volume_refresh_connection_info')
self.drvr._volume_refresh_connection_info(self.c, instance,
self.volume_uuid)
self.mox.ReplayAll()
self.drvr.volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id,
self.delete_info_1)
self.mox.VerifyAll()
def test_volume_snapshot_delete_outer_failure(self):
instance = objects.Instance(**self.inst)
snapshot_id = '1234-9876'
FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_delete')
self.drvr._volume_snapshot_delete(self.c,
instance,
self.volume_uuid,
snapshot_id,
delete_info=self.delete_info_1).\
AndRaise(exception.NovaException('oops'))
self.drvr._volume_api.update_snapshot_status(
self.c, snapshot_id, 'error_deleting')
self.mox.ReplayAll()
self.assertRaises(exception.NovaException,
self.drvr.volume_snapshot_delete,
self.c,
instance,
self.volume_uuid,
snapshot_id,
self.delete_info_1)
self.mox.VerifyAll()
def test_volume_snapshot_delete_invalid_type(self):
instance = objects.Instance(**self.inst)
FakeVirtDomain(fake_xml=self.dom_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(self.drvr, '_volume_api')
self.drvr._volume_api.update_snapshot_status(
self.c, self.snapshot_id, 'error_deleting')
self.mox.ReplayAll()
self.assertRaises(exception.NovaException,
self.drvr.volume_snapshot_delete,
self.c,
instance,
self.volume_uuid,
self.snapshot_id,
self.delete_info_invalid_type)
def test_volume_snapshot_delete_netdisk_1(self):
"""Delete newest snapshot -- blockRebase for libgfapi/network disk."""
class FakeNetdiskDomain(FakeVirtDomain):
def __init__(self, *args, **kwargs):
super(FakeNetdiskDomain, self).__init__(*args, **kwargs)
def XMLDesc(self, flags):
return self.dom_netdisk_xml
# libvirt lib doesn't have VIR_DOMAIN_BLOCK_REBASE_RELATIVE
fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_REBASE_RELATIVE')
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockRebase('vdb', 'vdb[1]', 0, flags=0)
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.mox.VerifyAll()
fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_REBASE_RELATIVE': 8})
def test_volume_snapshot_delete_netdisk_relative_1(self):
"""Delete newest snapshot -- blockRebase for libgfapi/network disk."""
class FakeNetdiskDomain(FakeVirtDomain):
def __init__(self, *args, **kwargs):
super(FakeNetdiskDomain, self).__init__(*args, **kwargs)
def XMLDesc(self, flags):
return self.dom_netdisk_xml
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockRebase('vdb', 'vdb[1]', 0,
flags=fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE)
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id, self.delete_info_1)
self.mox.VerifyAll()
def test_volume_snapshot_delete_netdisk_2(self):
"""Delete older snapshot -- blockCommit for libgfapi/network disk."""
class FakeNetdiskDomain(FakeVirtDomain):
def __init__(self, *args, **kwargs):
super(FakeNetdiskDomain, self).__init__(*args, **kwargs)
def XMLDesc(self, flags):
return self.dom_netdisk_xml
# libvirt lib doesn't have VIR_DOMAIN_BLOCK_COMMIT_RELATIVE
fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_COMMIT_RELATIVE')
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
self.mox.ReplayAll()
self.assertRaises(exception.Invalid,
self.drvr._volume_snapshot_delete,
self.c,
instance,
self.volume_uuid,
snapshot_id,
self.delete_info_netdisk)
fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_COMMIT_RELATIVE': 4})
def test_volume_snapshot_delete_netdisk_relative_2(self):
"""Delete older snapshot -- blockCommit for libgfapi/network disk."""
class FakeNetdiskDomain(FakeVirtDomain):
def __init__(self, *args, **kwargs):
super(FakeNetdiskDomain, self).__init__(*args, **kwargs)
def XMLDesc(self, flags):
return self.dom_netdisk_xml
self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt)
instance = objects.Instance(**self.inst)
snapshot_id = 'snapshot-1234'
domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml)
self.mox.StubOutWithMock(domain, 'XMLDesc')
domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml)
self.mox.StubOutWithMock(self.drvr._host, 'get_domain')
self.mox.StubOutWithMock(domain, 'blockRebase')
self.mox.StubOutWithMock(domain, 'blockCommit')
self.mox.StubOutWithMock(domain, 'blockJobInfo')
self.drvr._host.get_domain(instance).AndReturn(domain)
domain.blockCommit('vdb', 'vdb[0]', 'vdb[1]', 0,
flags=fakelibvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE)
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1,
'end': 1000})
domain.blockJobInfo('vdb', flags=0).AndReturn({
'type': 0,
'bandwidth': 0,
'cur': 1000,
'end': 1000})
self.mox.ReplayAll()
self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid,
snapshot_id,
self.delete_info_netdisk)
self.mox.VerifyAll()
def _fake_convert_image(source, dest, in_format, out_format,
run_as_root=True):
libvirt_driver.libvirt_utils.files[dest] = ''
class _BaseSnapshotTests(test.NoDBTestCase):
def setUp(self):
super(_BaseSnapshotTests, self).setUp()
self.flags(snapshots_directory='./', group='libvirt')
self.context = context.get_admin_context()
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.libvirt_utils',
fake_libvirt_utils))
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.imagebackend.libvirt_utils',
fake_libvirt_utils))
self.image_service = nova.tests.unit.image.fake.stub_out_image_service(
self)
self.mock_update_task_state = mock.Mock()
test_instance = _create_test_instance()
self.instance_ref = objects.Instance(**test_instance)
self.instance_ref.info_cache = objects.InstanceInfoCache(
network_info=None)
def _assert_snapshot(self, snapshot, disk_format,
expected_properties=None):
self.mock_update_task_state.assert_has_calls([
mock.call(task_state=task_states.IMAGE_PENDING_UPLOAD),
mock.call(task_state=task_states.IMAGE_UPLOADING,
expected_state=task_states.IMAGE_PENDING_UPLOAD)])
props = snapshot['properties']
self.assertEqual(props['image_state'], 'available')
self.assertEqual(snapshot['status'], 'active')
self.assertEqual(snapshot['disk_format'], disk_format)
self.assertEqual(snapshot['name'], 'test-snap')
if expected_properties:
for expected_key, expected_value in \
six.iteritems(expected_properties):
self.assertEqual(expected_value, props[expected_key])
def _create_image(self, extra_properties=None):
properties = {'instance_id': self.instance_ref['id'],
'user_id': str(self.context.user_id)}
if extra_properties:
properties.update(extra_properties)
sent_meta = {'name': 'test-snap',
'is_public': False,
'status': 'creating',
'properties': properties}
# Create new image. It will be updated in snapshot method
# To work with it from snapshot, the single image_service is needed
recv_meta = self.image_service.create(self.context, sent_meta)
return recv_meta
@mock.patch.object(host.Host, 'has_min_version')
@mock.patch.object(imagebackend.Image, 'resolve_driver_format')
@mock.patch.object(host.Host, 'get_domain')
def _snapshot(self, image_id, mock_get_domain, mock_resolve, mock_version):
mock_get_domain.return_value = FakeVirtDomain()
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
driver.snapshot(self.context, self.instance_ref, image_id,
self.mock_update_task_state)
snapshot = self.image_service.show(self.context, image_id)
return snapshot
def _test_snapshot(self, disk_format, extra_properties=None):
recv_meta = self._create_image(extra_properties=extra_properties)
snapshot = self._snapshot(recv_meta['id'])
self._assert_snapshot(snapshot, disk_format=disk_format,
expected_properties=extra_properties)
class LibvirtSnapshotTests(_BaseSnapshotTests):
def test_ami(self):
# Assign different image_ref from nova/images/fakes for testing ami
self.instance_ref.image_ref = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77'
self.instance_ref.system_metadata = \
utils.get_system_metadata_from_image(
{'disk_format': 'ami'})
self._test_snapshot(disk_format='ami')
@mock.patch.object(fake_libvirt_utils, 'disk_type', new='raw')
@mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image)
def test_raw(self, mock_convert_image):
self._test_snapshot(disk_format='raw')
def test_qcow2(self):
self._test_snapshot(disk_format='qcow2')
@mock.patch.object(fake_libvirt_utils, 'disk_type', new='ploop')
@mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image)
def test_ploop(self, mock_convert_image):
self._test_snapshot(disk_format='ploop')
def test_no_image_architecture(self):
self.instance_ref.image_ref = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'
self._test_snapshot(disk_format='qcow2')
def test_no_original_image(self):
self.instance_ref.image_ref = '661122aa-1234-dede-fefe-babababababa'
self._test_snapshot(disk_format='qcow2')
def test_snapshot_metadata_image(self):
# Assign an image with an architecture defined (x86_64)
self.instance_ref.image_ref = 'a440c04b-79fa-479c-bed1-0b816eaec379'
extra_properties = {'architecture': 'fake_arch',
'key_a': 'value_a',
'key_b': 'value_b',
'os_type': 'linux'}
self._test_snapshot(disk_format='qcow2',
extra_properties=extra_properties)
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone(self, mock_rbd, mock_driver):
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(return_value=['test-pool', '', ''])
rbd.parse_url = mock.Mock(return_value=['a', 'b', 'c', 'd'])
with mock.patch.object(fake_libvirt_utils, 'find_disk',
return_value=('rbd://some/fake/rbd/image',
'raw')):
with mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd'):
self._test_snapshot(disk_format='raw')
rbd.clone.assert_called_with(mock.ANY, mock.ANY, dest_pool='test-pool')
rbd.flatten.assert_called_with(mock.ANY, pool='test-pool')
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone_graceful_fallback(self, mock_rbd, mock_driver):
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(side_effect=exception.ImageUnacceptable(
image_id='fake_id', reason='rbd testing'))
with test.nested(
mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image),
mock.patch.object(fake_libvirt_utils, 'find_disk',
return_value=('rbd://some/fake/rbd/image',
'raw')),
mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd')):
self._test_snapshot(disk_format='raw')
self.assertFalse(rbd.clone.called)
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone_eperm(self, mock_rbd, mock_driver):
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(return_value=['test-pool', '', ''])
rbd.parse_url = mock.Mock(return_value=['a', 'b', 'c', 'd'])
rbd.clone = mock.Mock(side_effect=exception.Forbidden(
image_id='fake_id', reason='rbd testing'))
with test.nested(
mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image),
mock.patch.object(fake_libvirt_utils, 'find_disk',
return_value=('rbd://some/fake/rbd/image',
'raw')),
mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd')):
self._test_snapshot(disk_format='raw')
# Ensure that the direct_snapshot attempt was cleaned up
rbd.remove_snap.assert_called_with('c', 'd', ignore_errors=False,
pool='b', force=True)
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone_post_process_fails(self, mock_rbd,
mock_driver):
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(return_value=['test-pool', '', ''])
rbd.parse_url = mock.Mock(return_value=['a', 'b', 'c', 'd'])
with test.nested(
mock.patch.object(fake_libvirt_utils, 'find_disk',
return_value=('rbd://some/fake/rbd/image',
'raw')),
mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd'),
mock.patch.object(self.image_service, 'update',
side_effect=test.TestingException)):
self.assertRaises(test.TestingException, self._test_snapshot,
disk_format='raw')
rbd.clone.assert_called_with(mock.ANY, mock.ANY, dest_pool='test-pool')
rbd.flatten.assert_called_with(mock.ANY, pool='test-pool')
# Ensure that the direct_snapshot attempt was cleaned up
rbd.remove_snap.assert_called_with('c', 'd', ignore_errors=True,
pool='b', force=True)
@mock.patch.object(imagebackend.Image, 'direct_snapshot')
@mock.patch.object(imagebackend.Image, 'resolve_driver_format')
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(host.Host, 'get_guest')
def test_raw_with_rbd_clone_is_live_snapshot(self,
mock_get_guest,
mock_version,
mock_resolve,
mock_snapshot):
self.flags(disable_libvirt_livesnapshot=False, group='workarounds')
self.flags(images_type='rbd', group='libvirt')
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_guest._domain = mock.Mock()
mock_get_guest.return_value = mock_guest
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
recv_meta = self._create_image()
with mock.patch.object(driver, "suspend") as mock_suspend:
driver.snapshot(self.context, self.instance_ref, recv_meta['id'],
self.mock_update_task_state)
self.assertFalse(mock_suspend.called)
@mock.patch.object(libvirt_driver.imagebackend.images, 'convert_image',
side_effect=_fake_convert_image)
@mock.patch.object(fake_libvirt_utils, 'find_disk')
@mock.patch.object(imagebackend.Image, 'resolve_driver_format')
@mock.patch.object(host.Host, 'has_min_version', return_value=True)
@mock.patch.object(host.Host, 'get_guest')
@mock.patch.object(rbd_utils, 'RBDDriver')
@mock.patch.object(rbd_utils, 'rbd')
def test_raw_with_rbd_clone_failure_does_cold_snapshot(self,
mock_rbd,
mock_driver,
mock_get_guest,
mock_version,
mock_resolve,
mock_find_disk,
mock_convert):
self.flags(disable_libvirt_livesnapshot=False, group='workarounds')
self.flags(images_type='rbd', group='libvirt')
rbd = mock_driver.return_value
rbd.parent_info = mock.Mock(side_effect=exception.ImageUnacceptable(
image_id='fake_id', reason='rbd testing'))
mock_find_disk.return_value = ('rbd://some/fake/rbd/image', 'raw')
mock_guest = mock.Mock(spec=libvirt_guest.Guest)
mock_guest.get_power_state.return_value = power_state.RUNNING
mock_guest._domain = mock.Mock()
mock_get_guest.return_value = mock_guest
driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
recv_meta = self._create_image()
with mock.patch.object(fake_libvirt_utils, 'disk_type', new='rbd'):
with mock.patch.object(driver, "suspend") as mock_suspend:
driver.snapshot(self.context, self.instance_ref,
recv_meta['id'], self.mock_update_task_state)
self.assertTrue(mock_suspend.called)
class LXCSnapshotTests(LibvirtSnapshotTests):
"""Repeat all of the Libvirt snapshot tests, but with LXC enabled"""
def setUp(self):
super(LXCSnapshotTests, self).setUp()
self.flags(virt_type='lxc', group='libvirt')
def test_raw_with_rbd_clone_failure_does_cold_snapshot(self):
self.skipTest("managedSave is not supported with LXC")
class LVMSnapshotTests(_BaseSnapshotTests):
@mock.patch.object(fake_libvirt_utils, 'disk_type', new='lvm')
@mock.patch.object(libvirt_driver.imagebackend.images,
'convert_image',
side_effect=_fake_convert_image)
@mock.patch.object(libvirt_driver.imagebackend.lvm, 'volume_info')
def _test_lvm_snapshot(self, disk_format, mock_volume_info,
mock_convert_image):
self.flags(images_type='lvm',
images_volume_group='nova-vg', group='libvirt')
self._test_snapshot(disk_format=disk_format)
mock_volume_info.assert_has_calls([mock.call('/dev/nova-vg/lv')])
mock_convert_image.assert_called_once_with(
'/dev/nova-vg/lv', mock.ANY, 'raw', disk_format,
run_as_root=True)
def test_raw(self):
self._test_lvm_snapshot('raw')
def test_qcow2(self):
self.flags(snapshot_image_format='qcow2', group='libvirt')
self._test_lvm_snapshot('qcow2')<|fim▁end|>
|
device_path='/dev/disk/by-path/'
'ip-1.2.3.4:3260-iqn.'
|
<|file_name|>derivations.cc<|end_file_name|><|fim▁begin|>#include "derivations.hh"
#include "store-api.hh"
#include "globals.hh"
#include "util.hh"
#include "worker-protocol.hh"
#include "fs-accessor.hh"
#include "istringstream_nocopy.hh"
namespace nix {<|fim▁hole|> recursive = false;
string algo = hashAlgo;
if (string(algo, 0, 2) == "r:") {
recursive = true;
algo = string(algo, 2);
}
HashType hashType = parseHashType(algo);
if (hashType == htUnknown)
throw Error(format("unknown hash algorithm ‘%1%’") % algo);
hash = parseHash(hashType, this->hash);
}
Path BasicDerivation::findOutput(const string & id) const
{
auto i = outputs.find(id);
if (i == outputs.end())
throw Error(format("derivation has no output ‘%1%’") % id);
return i->second.path;
}
bool BasicDerivation::willBuildLocally() const
{
return get(env, "preferLocalBuild") == "1" && canBuildLocally();
}
bool BasicDerivation::substitutesAllowed() const
{
return get(env, "allowSubstitutes", "1") == "1";
}
bool BasicDerivation::isBuiltin() const
{
return string(builder, 0, 8) == "builtin:";
}
bool BasicDerivation::canBuildLocally() const
{
return platform == settings.thisSystem
|| isBuiltin()
#if __linux__
|| (platform == "i686-linux" && settings.thisSystem == "x86_64-linux")
|| (platform == "armv6l-linux" && settings.thisSystem == "armv7l-linux")
|| (platform == "armv5tel-linux" && (settings.thisSystem == "armv7l-linux" || settings.thisSystem == "armv6l-linux"))
#elif __FreeBSD__
|| (platform == "i686-linux" && settings.thisSystem == "x86_64-freebsd")
|| (platform == "i686-linux" && settings.thisSystem == "i686-freebsd")
#endif
;
}
Path writeDerivation(ref<Store> store,
const Derivation & drv, const string & name, bool repair)
{
PathSet references;
references.insert(drv.inputSrcs.begin(), drv.inputSrcs.end());
for (auto & i : drv.inputDrvs)
references.insert(i.first);
/* Note that the outputs of a derivation are *not* references
(that can be missing (of course) and should not necessarily be
held during a garbage collection). */
string suffix = name + drvExtension;
string contents = drv.unparse();
return settings.readOnlyMode
? store->computeStorePathForText(suffix, contents, references)
: store->addTextToStore(suffix, contents, references, repair);
}
/* Read string `s' from stream `str'. */
static void expect(std::istream & str, const string & s)
{
char s2[s.size()];
str.read(s2, s.size());
if (string(s2, s.size()) != s)
throw FormatError(format("expected string ‘%1%’") % s);
}
/* Read a C-style string from stream `str'. */
static string parseString(std::istream & str)
{
string res;
expect(str, "\"");
int c;
while ((c = str.get()) != '"')
if (c == '\\') {
c = str.get();
if (c == 'n') res += '\n';
else if (c == 'r') res += '\r';
else if (c == 't') res += '\t';
else res += c;
}
else res += c;
return res;
}
static Path parsePath(std::istream & str)
{
string s = parseString(str);
if (s.size() == 0 || s[0] != '/')
throw FormatError(format("bad path ‘%1%’ in derivation") % s);
return s;
}
static bool endOfList(std::istream & str)
{
if (str.peek() == ',') {
str.get();
return false;
}
if (str.peek() == ']') {
str.get();
return true;
}
return false;
}
static StringSet parseStrings(std::istream & str, bool arePaths)
{
StringSet res;
while (!endOfList(str))
res.insert(arePaths ? parsePath(str) : parseString(str));
return res;
}
static Derivation parseDerivation(const string & s)
{
Derivation drv;
istringstream_nocopy str(s);
expect(str, "Derive([");
/* Parse the list of outputs. */
while (!endOfList(str)) {
DerivationOutput out;
expect(str, "("); string id = parseString(str);
expect(str, ","); out.path = parsePath(str);
expect(str, ","); out.hashAlgo = parseString(str);
expect(str, ","); out.hash = parseString(str);
expect(str, ")");
drv.outputs[id] = out;
}
/* Parse the list of input derivations. */
expect(str, ",[");
while (!endOfList(str)) {
expect(str, "(");
Path drvPath = parsePath(str);
expect(str, ",[");
drv.inputDrvs[drvPath] = parseStrings(str, false);
expect(str, ")");
}
expect(str, ",["); drv.inputSrcs = parseStrings(str, true);
expect(str, ","); drv.platform = parseString(str);
expect(str, ","); drv.builder = parseString(str);
/* Parse the builder arguments. */
expect(str, ",[");
while (!endOfList(str))
drv.args.push_back(parseString(str));
/* Parse the environment variables. */
expect(str, ",[");
while (!endOfList(str)) {
expect(str, "("); string name = parseString(str);
expect(str, ","); string value = parseString(str);
expect(str, ")");
drv.env[name] = value;
}
expect(str, ")");
return drv;
}
Derivation readDerivation(const Path & drvPath)
{
try {
return parseDerivation(readFile(drvPath));
} catch (FormatError & e) {
throw Error(format("error parsing derivation ‘%1%’: %2%") % drvPath % e.msg());
}
}
Derivation Store::derivationFromPath(const Path & drvPath)
{
assertStorePath(drvPath);
ensurePath(drvPath);
auto accessor = getFSAccessor();
try {
return parseDerivation(accessor->readFile(drvPath));
} catch (FormatError & e) {
throw Error(format("error parsing derivation ‘%1%’: %2%") % drvPath % e.msg());
}
}
static void printString(string & res, const string & s)
{
res += '"';
for (const char * i = s.c_str(); *i; i++)
if (*i == '\"' || *i == '\\') { res += "\\"; res += *i; }
else if (*i == '\n') res += "\\n";
else if (*i == '\r') res += "\\r";
else if (*i == '\t') res += "\\t";
else res += *i;
res += '"';
}
template<class ForwardIterator>
static void printStrings(string & res, ForwardIterator i, ForwardIterator j)
{
res += '[';
bool first = true;
for ( ; i != j; ++i) {
if (first) first = false; else res += ',';
printString(res, *i);
}
res += ']';
}
string Derivation::unparse() const
{
string s;
s.reserve(65536);
s += "Derive([";
bool first = true;
for (auto & i : outputs) {
if (first) first = false; else s += ',';
s += '('; printString(s, i.first);
s += ','; printString(s, i.second.path);
s += ','; printString(s, i.second.hashAlgo);
s += ','; printString(s, i.second.hash);
s += ')';
}
s += "],[";
first = true;
for (auto & i : inputDrvs) {
if (first) first = false; else s += ',';
s += '('; printString(s, i.first);
s += ','; printStrings(s, i.second.begin(), i.second.end());
s += ')';
}
s += "],";
printStrings(s, inputSrcs.begin(), inputSrcs.end());
s += ','; printString(s, platform);
s += ','; printString(s, builder);
s += ','; printStrings(s, args.begin(), args.end());
s += ",[";
first = true;
for (auto & i : env) {
if (first) first = false; else s += ',';
s += '('; printString(s, i.first);
s += ','; printString(s, i.second);
s += ')';
}
s += "])";
return s;
}
bool isDerivation(const string & fileName)
{
return hasSuffix(fileName, drvExtension);
}
bool BasicDerivation::isFixedOutput() const
{
return outputs.size() == 1 &&
outputs.begin()->first == "out" &&
outputs.begin()->second.hash != "";
}
DrvHashes drvHashes;
/* Returns the hash of a derivation modulo fixed-output
subderivations. A fixed-output derivation is a derivation with one
output (`out') for which an expected hash and hash algorithm are
specified (using the `outputHash' and `outputHashAlgo'
attributes). We don't want changes to such derivations to
propagate upwards through the dependency graph, changing output
paths everywhere.
For instance, if we change the url in a call to the `fetchurl'
function, we do not want to rebuild everything depending on it
(after all, (the hash of) the file being downloaded is unchanged).
So the *output paths* should not change. On the other hand, the
*derivation paths* should change to reflect the new dependency
graph.
That's what this function does: it returns a hash which is just the
hash of the derivation ATerm, except that any input derivation
paths have been replaced by the result of a recursive call to this
function, and that for fixed-output derivations we return a hash of
its output path. */
Hash hashDerivationModulo(Store & store, Derivation drv)
{
/* Return a fixed hash for fixed-output derivations. */
if (drv.isFixedOutput()) {
DerivationOutputs::const_iterator i = drv.outputs.begin();
return hashString(htSHA256, "fixed:out:"
+ i->second.hashAlgo + ":"
+ i->second.hash + ":"
+ i->second.path);
}
/* For other derivations, replace the inputs paths with recursive
calls to this function.*/
DerivationInputs inputs2;
for (auto & i : drv.inputDrvs) {
Hash h = drvHashes[i.first];
if (!h) {
assert(store.isValidPath(i.first));
Derivation drv2 = readDerivation(i.first);
h = hashDerivationModulo(store, drv2);
drvHashes[i.first] = h;
}
inputs2[printHash(h)] = i.second;
}
drv.inputDrvs = inputs2;
return hashString(htSHA256, drv.unparse());
}
DrvPathWithOutputs parseDrvPathWithOutputs(const string & s)
{
size_t n = s.find("!");
return n == s.npos
? DrvPathWithOutputs(s, std::set<string>())
: DrvPathWithOutputs(string(s, 0, n), tokenizeString<std::set<string> >(string(s, n + 1), ","));
}
Path makeDrvPathWithOutputs(const Path & drvPath, const std::set<string> & outputs)
{
return outputs.empty()
? drvPath
: drvPath + "!" + concatStringsSep(",", outputs);
}
bool wantOutput(const string & output, const std::set<string> & wanted)
{
return wanted.empty() || wanted.find(output) != wanted.end();
}
PathSet BasicDerivation::outputPaths() const
{
PathSet paths;
for (auto & i : outputs)
paths.insert(i.second.path);
return paths;
}
Source & readDerivation(Source & in, Store & store, BasicDerivation & drv)
{
drv.outputs.clear();
auto nr = readNum<size_t>(in);
for (size_t n = 0; n < nr; n++) {
auto name = readString(in);
DerivationOutput o;
in >> o.path >> o.hashAlgo >> o.hash;
store.assertStorePath(o.path);
drv.outputs[name] = o;
}
drv.inputSrcs = readStorePaths<PathSet>(store, in);
in >> drv.platform >> drv.builder;
drv.args = readStrings<Strings>(in);
nr = readNum<size_t>(in);
for (size_t n = 0; n < nr; n++) {
auto key = readString(in);
auto value = readString(in);
drv.env[key] = value;
}
return in;
}
Sink & operator << (Sink & out, const BasicDerivation & drv)
{
out << drv.outputs.size();
for (auto & i : drv.outputs)
out << i.first << i.second.path << i.second.hashAlgo << i.second.hash;
out << drv.inputSrcs << drv.platform << drv.builder << drv.args;
out << drv.env.size();
for (auto & i : drv.env)
out << i.first << i.second;
return out;
}
std::string hashPlaceholder(const std::string & outputName)
{
// FIXME: memoize?
return "/" + printHash32(hashString(htSHA256, "nix-output:" + outputName));
}
}<|fim▁end|>
|
void DerivationOutput::parseHashInfo(bool & recursive, Hash & hash) const
{
|
<|file_name|>filenotfound.rs<|end_file_name|><|fim▁begin|>use std::fs::File;
fn main() {
let f = File::open("main.jpg"); // main.jpg doesn't exist<|fim▁hole|> Err(e)=> {
println!("file not found \n{:?}",e); //handled error
}
}
println!("end of main");
}<|fim▁end|>
|
match f {
Ok(f)=> {
println!("file found {:?}",f);
},
|
<|file_name|>resources.go<|end_file_name|><|fim▁begin|>package main
import (
"net/http"
"github.com/gorilla/mux"
"github.com/lxc/lxd/lxd/resources"
"github.com/lxc/lxd/lxd/response"
storagePools "github.com/lxc/lxd/lxd/storage"
"github.com/lxc/lxd/shared/api"
)
var api10ResourcesCmd = APIEndpoint{
Path: "resources",
Get: APIEndpointAction{Handler: api10ResourcesGet, AccessHandler: allowAuthenticated},
}
var storagePoolResourcesCmd = APIEndpoint{
Path: "storage-pools/{name}/resources",
Get: APIEndpointAction{Handler: storagePoolResourcesGet, AccessHandler: allowAuthenticated},
}
// /1.0/resources
// Get system resources
func api10ResourcesGet(d *Daemon, r *http.Request) response.Response {
// If a target was specified, forward the request to the relevant node.
resp := forwardedResponseIfTargetIsRemote(d, r)
if resp != nil {
return resp
}
// Get the local resource usage
res, err := resources.GetResources()
if err != nil {
return response.SmartError(err)
}
return response.SyncResponse(true, res)
}
// /1.0/storage-pools/{name}/resources
// Get resources for a specific storage pool
func storagePoolResourcesGet(d *Daemon, r *http.Request) response.Response {
// If a target was specified, forward the request to the relevant node.
resp := forwardedResponseIfTargetIsRemote(d, r)
if resp != nil {
return resp
}
// Get the existing storage pool
poolName := mux.Vars(r)["name"]
var res *api.ResourcesStoragePool
pool, err := storagePools.GetPoolByName(d.State(), poolName)
if err != nil {
return response.InternalError(err)
}
res, err = pool.GetResources()
if err != nil {
return response.InternalError(err)<|fim▁hole|> }
return response.SyncResponse(true, res)
}<|fim▁end|>
| |
<|file_name|>ethcore.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use util::log::RotatingLogger;
use util::U256;
use ethsync::ManageNetwork;
use ethcore::client::{TestBlockChainClient};
use ethstore::ethkey::{Generator, Random};
use jsonrpc_core::IoHandler;
use v1::{Ethcore, EthcoreClient};
use v1::helpers::{SignerService, NetworkSettings};
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestFetch};
use super::manage_network::TestManageNetwork;
pub type TestEthcoreClient = EthcoreClient<TestBlockChainClient, TestMinerService, TestSyncProvider, TestFetch>;
pub struct Dependencies {
pub miner: Arc<TestMinerService>,
pub client: Arc<TestBlockChainClient>,
pub sync: Arc<TestSyncProvider>,
pub logger: Arc<RotatingLogger>,
pub settings: Arc<NetworkSettings>,
pub network: Arc<ManageNetwork>,
pub dapps_port: Option<u16>,
}
impl Dependencies {
pub fn new() -> Self {
Dependencies {
miner: Arc::new(TestMinerService::default()),
client: Arc::new(TestBlockChainClient::default()),
sync: Arc::new(TestSyncProvider::new(Config {
network_id: U256::from(3),
num_peers: 120,
})),
logger: Arc::new(RotatingLogger::new("rpc=trace".to_owned())),
settings: Arc::new(NetworkSettings {
name: "mynode".to_owned(),
chain: "testchain".to_owned(),
network_port: 30303,
rpc_enabled: true,
rpc_interface: "all".to_owned(),
rpc_port: 8545,
}),
network: Arc::new(TestManageNetwork),
dapps_port: Some(18080),
}
}
pub fn client(&self, signer: Option<Arc<SignerService>>) -> TestEthcoreClient {
EthcoreClient::with_fetch(
&self.client,
&self.miner,
&self.sync,
&self.network,
self.logger.clone(),
self.settings.clone(),
signer,
self.dapps_port,
)
}
fn default_client(&self) -> IoHandler {
let io = IoHandler::new();
io.add_delegate(self.client(None).to_delegate());
io
}
fn with_signer(&self, signer: SignerService) -> IoHandler {
let io = IoHandler::new();
io.add_delegate(self.client(Some(Arc::new(signer))).to_delegate());
io
}
}
#[test]
fn rpc_ethcore_extra_data() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_extraData", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x01020304","id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_default_extra_data() {
use util::misc;
use util::ToPretty;
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_defaultExtraData", "params": [], "id": 1}"#;
let response = format!(r#"{{"jsonrpc":"2.0","result":"0x{}","id":1}}"#, misc::version_data().to_hex());
assert_eq!(io.handle_request_sync(request), Some(response));
}
#[test]
fn rpc_ethcore_gas_floor_target() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_gasFloorTarget", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x3039","id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_min_gas_price() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_minGasPrice", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x1312d00","id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_dev_logs() {
let deps = Dependencies::new();
deps.logger.append("a".to_owned());
deps.logger.append("b".to_owned());
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_devLogs", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":["b","a"],"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_dev_logs_levels() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_devLogsLevels", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"rpc=trace","id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_transactions_limit() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_transactionsLimit", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":1024,"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_net_chain() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netChain", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"testchain","id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_net_peers() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netPeers", "params":[], "id": 1}"#;
let response = "{\"jsonrpc\":\"2.0\",\"result\":{\"active\":0,\"connected\":120,\"max\":50,\"peers\":[{\"caps\":[\"eth/62\",\"eth/63\"],\
\"id\":\"node1\",\"name\":\"Parity/1\",\"network\":{\"localAddress\":\"127.0.0.1:8888\",\"remoteAddress\":\"127.0.0.1:7777\"}\
,\"protocols\":{\"eth\":{\"difficulty\":\"0x28\",\"head\":\"0000000000000000000000000000000000000000000000000000000000000032\"\
,\"version\":62}}},{\"caps\":[\"eth/63\",\"eth/64\"],\"id\":null,\"name\":\"Parity/2\",\"network\":{\"localAddress\":\
\"127.0.0.1:3333\",\"remoteAddress\":\"Handshake\"},\"protocols\":{\"eth\":{\"difficulty\":null,\"head\":\
\"000000000000000000000000000000000000000000000000000000000000003c\",\"version\":64}}}]},\"id\":1}";
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_net_port() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netPort", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":30303,"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_rpc_settings() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_rpcSettings", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":{"enabled":true,"interface":"all","port":8545},"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_node_name() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_nodeName", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"mynode","id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_unsigned_transactions_count() {
let deps = Dependencies::new();
let io = deps.with_signer(SignerService::new_test(Some(18180)));
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_unsignedTransactionsCount", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":0,"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_unsigned_transactions_count_when_signer_disabled() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_unsignedTransactionsCount", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32030,"message":"Trusted Signer is disabled. This API is not available.","data":null},"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_hash_content() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_hashContent", "params":["https://ethcore.io/assets/images/ethcore-black-horizontal.png"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x2be00befcf008bc0e7d9cdefc194db9c75352e8632f48498b5a6bfce9f02c88e","id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_pending_transactions() {
let deps = Dependencies::new();
let io = deps.default_client();
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_pendingTransactions", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":[],"id":1}"#;
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn rpc_ethcore_encrypt() {
let deps = Dependencies::new();
let io = deps.default_client();
let key = format!("{:?}", Random.generate().unwrap().public());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_encryptMessage", "params":["0x"#.to_owned() + &key + r#"", "0x01"], "id": 1}"#;
assert!(io.handle_request_sync(&request).unwrap().contains("result"), "Should return success.");
}
#[test]
fn rpc_ethcore_signer_port() {
// given
let deps = Dependencies::new();<|fim▁hole|>
// when
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_signerPort", "params": [], "id": 1}"#;
let response1 = r#"{"jsonrpc":"2.0","result":18180,"id":1}"#;
let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32030,"message":"Trusted Signer is disabled. This API is not available.","data":null},"id":1}"#;
// then
assert_eq!(io1.handle_request_sync(request), Some(response1.to_owned()));
assert_eq!(io2.handle_request_sync(request), Some(response2.to_owned()));
}
#[test]
fn rpc_ethcore_dapps_port() {
// given
let mut deps = Dependencies::new();
let io1 = deps.default_client();
deps.dapps_port = None;
let io2 = deps.default_client();
// when
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_dappsPort", "params": [], "id": 1}"#;
let response1 = r#"{"jsonrpc":"2.0","result":18080,"id":1}"#;
let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32031,"message":"Dapps Server is disabled. This API is not available.","data":null},"id":1}"#;
// then
assert_eq!(io1.handle_request_sync(request), Some(response1.to_owned()));
assert_eq!(io2.handle_request_sync(request), Some(response2.to_owned()));
}<|fim▁end|>
|
let io1 = deps.with_signer(SignerService::new_test(Some(18180)));
let io2 = deps.default_client();
|
<|file_name|>metadata.pb.go<|end_file_name|><|fim▁begin|>// Code generated by protoc-gen-go. DO NOT EDIT.
// source: hapi/chart/metadata.proto
package chart
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type Metadata_Engine int32
const (
Metadata_UNKNOWN Metadata_Engine = 0
Metadata_GOTPL Metadata_Engine = 1
)
var Metadata_Engine_name = map[int32]string{
0: "UNKNOWN",
1: "GOTPL",
}
var Metadata_Engine_value = map[string]int32{
"UNKNOWN": 0,
"GOTPL": 1,
}
func (x Metadata_Engine) String() string {
return proto.EnumName(Metadata_Engine_name, int32(x))
}
func (Metadata_Engine) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_metadata_d6c714c73a051dcb, []int{1, 0}
}
// Maintainer describes a Chart maintainer.
type Maintainer struct {
// Name is a user name or organization name
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// Email is an optional email address to contact the named maintainer
Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"`
// Url is an optional URL to an address for the named maintainer<|fim▁hole|> XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Maintainer) Reset() { *m = Maintainer{} }
func (m *Maintainer) String() string { return proto.CompactTextString(m) }
func (*Maintainer) ProtoMessage() {}
func (*Maintainer) Descriptor() ([]byte, []int) {
return fileDescriptor_metadata_d6c714c73a051dcb, []int{0}
}
func (m *Maintainer) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Maintainer.Unmarshal(m, b)
}
func (m *Maintainer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Maintainer.Marshal(b, m, deterministic)
}
func (dst *Maintainer) XXX_Merge(src proto.Message) {
xxx_messageInfo_Maintainer.Merge(dst, src)
}
func (m *Maintainer) XXX_Size() int {
return xxx_messageInfo_Maintainer.Size(m)
}
func (m *Maintainer) XXX_DiscardUnknown() {
xxx_messageInfo_Maintainer.DiscardUnknown(m)
}
var xxx_messageInfo_Maintainer proto.InternalMessageInfo
func (m *Maintainer) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *Maintainer) GetEmail() string {
if m != nil {
return m.Email
}
return ""
}
func (m *Maintainer) GetUrl() string {
if m != nil {
return m.Url
}
return ""
}
// Metadata for a Chart file. This models the structure of a Chart.yaml file.
//
// Spec: https://k8s.io/helm/blob/master/docs/design/chart_format.md#the-chart-file
type Metadata struct {
// The name of the chart
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// The URL to a relevant project page, git repo, or contact person
Home string `protobuf:"bytes,2,opt,name=home,proto3" json:"home,omitempty"`
// Source is the URL to the source code of this chart
Sources []string `protobuf:"bytes,3,rep,name=sources,proto3" json:"sources,omitempty"`
// A SemVer 2 conformant version string of the chart
Version string `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"`
// A one-sentence description of the chart
Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty"`
// A list of string keywords
Keywords []string `protobuf:"bytes,6,rep,name=keywords,proto3" json:"keywords,omitempty"`
// A list of name and URL/email address combinations for the maintainer(s)
Maintainers []*Maintainer `protobuf:"bytes,7,rep,name=maintainers,proto3" json:"maintainers,omitempty"`
// The name of the template engine to use. Defaults to 'gotpl'.
Engine string `protobuf:"bytes,8,opt,name=engine,proto3" json:"engine,omitempty"`
// The URL to an icon file.
Icon string `protobuf:"bytes,9,opt,name=icon,proto3" json:"icon,omitempty"`
// The API Version of this chart.
ApiVersion string `protobuf:"bytes,10,opt,name=apiVersion,proto3" json:"apiVersion,omitempty"`
// The condition to check to enable chart
Condition string `protobuf:"bytes,11,opt,name=condition,proto3" json:"condition,omitempty"`
// The tags to check to enable chart
Tags string `protobuf:"bytes,12,opt,name=tags,proto3" json:"tags,omitempty"`
// The version of the application enclosed inside of this chart.
AppVersion string `protobuf:"bytes,13,opt,name=appVersion,proto3" json:"appVersion,omitempty"`
// Whether or not this chart is deprecated
Deprecated bool `protobuf:"varint,14,opt,name=deprecated,proto3" json:"deprecated,omitempty"`
// TillerVersion is a SemVer constraints on what version of Tiller is required.
// See SemVer ranges here: https://github.com/Masterminds/semver#basic-comparisons
TillerVersion string `protobuf:"bytes,15,opt,name=tillerVersion,proto3" json:"tillerVersion,omitempty"`
// Annotations are additional mappings uninterpreted by Tiller,
// made available for inspection by other applications.
Annotations map[string]string `protobuf:"bytes,16,rep,name=annotations,proto3" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
// KubeVersion is a SemVer constraint specifying the version of Kubernetes required.
KubeVersion string `protobuf:"bytes,17,opt,name=kubeVersion,proto3" json:"kubeVersion,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Metadata) Reset() { *m = Metadata{} }
func (m *Metadata) String() string { return proto.CompactTextString(m) }
func (*Metadata) ProtoMessage() {}
func (*Metadata) Descriptor() ([]byte, []int) {
return fileDescriptor_metadata_d6c714c73a051dcb, []int{1}
}
func (m *Metadata) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Metadata.Unmarshal(m, b)
}
func (m *Metadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Metadata.Marshal(b, m, deterministic)
}
func (dst *Metadata) XXX_Merge(src proto.Message) {
xxx_messageInfo_Metadata.Merge(dst, src)
}
func (m *Metadata) XXX_Size() int {
return xxx_messageInfo_Metadata.Size(m)
}
func (m *Metadata) XXX_DiscardUnknown() {
xxx_messageInfo_Metadata.DiscardUnknown(m)
}
var xxx_messageInfo_Metadata proto.InternalMessageInfo
func (m *Metadata) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *Metadata) GetHome() string {
if m != nil {
return m.Home
}
return ""
}
func (m *Metadata) GetSources() []string {
if m != nil {
return m.Sources
}
return nil
}
func (m *Metadata) GetVersion() string {
if m != nil {
return m.Version
}
return ""
}
func (m *Metadata) GetDescription() string {
if m != nil {
return m.Description
}
return ""
}
func (m *Metadata) GetKeywords() []string {
if m != nil {
return m.Keywords
}
return nil
}
func (m *Metadata) GetMaintainers() []*Maintainer {
if m != nil {
return m.Maintainers
}
return nil
}
func (m *Metadata) GetEngine() string {
if m != nil {
return m.Engine
}
return ""
}
func (m *Metadata) GetIcon() string {
if m != nil {
return m.Icon
}
return ""
}
func (m *Metadata) GetApiVersion() string {
if m != nil {
return m.ApiVersion
}
return ""
}
func (m *Metadata) GetCondition() string {
if m != nil {
return m.Condition
}
return ""
}
func (m *Metadata) GetTags() string {
if m != nil {
return m.Tags
}
return ""
}
func (m *Metadata) GetAppVersion() string {
if m != nil {
return m.AppVersion
}
return ""
}
func (m *Metadata) GetDeprecated() bool {
if m != nil {
return m.Deprecated
}
return false
}
func (m *Metadata) GetTillerVersion() string {
if m != nil {
return m.TillerVersion
}
return ""
}
func (m *Metadata) GetAnnotations() map[string]string {
if m != nil {
return m.Annotations
}
return nil
}
func (m *Metadata) GetKubeVersion() string {
if m != nil {
return m.KubeVersion
}
return ""
}
func init() {
proto.RegisterType((*Maintainer)(nil), "hapi.chart.Maintainer")
proto.RegisterType((*Metadata)(nil), "hapi.chart.Metadata")
proto.RegisterMapType((map[string]string)(nil), "hapi.chart.Metadata.AnnotationsEntry")
proto.RegisterEnum("hapi.chart.Metadata_Engine", Metadata_Engine_name, Metadata_Engine_value)
}
func init() { proto.RegisterFile("hapi/chart/metadata.proto", fileDescriptor_metadata_d6c714c73a051dcb) }
var fileDescriptor_metadata_d6c714c73a051dcb = []byte{
// 435 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x52, 0x5d, 0x6b, 0xd4, 0x40,
0x14, 0x35, 0xcd, 0x66, 0x77, 0x73, 0x63, 0x35, 0x0e, 0x52, 0xc6, 0x22, 0x12, 0x16, 0x85, 0x7d,
0xda, 0x82, 0xbe, 0x14, 0x1f, 0x04, 0x85, 0x52, 0x41, 0xbb, 0x95, 0xe0, 0x07, 0xf8, 0x36, 0x4d,
0x2e, 0xdd, 0x61, 0x93, 0x99, 0x30, 0x99, 0xad, 0xec, 0xaf, 0xf0, 0x2f, 0xcb, 0xdc, 0x64, 0x9a,
0xac, 0xf4, 0xed, 0x9e, 0x73, 0x66, 0xce, 0xcc, 0xbd, 0xf7, 0xc0, 0x8b, 0x8d, 0x68, 0xe4, 0x59,
0xb1, 0x11, 0xc6, 0x9e, 0xd5, 0x68, 0x45, 0x29, 0xac, 0x58, 0x35, 0x46, 0x5b, 0xcd, 0xc0, 0x49,
0x2b, 0x92, 0x16, 0x9f, 0x01, 0xae, 0x84, 0x54, 0x56, 0x48, 0x85, 0x86, 0x31, 0x98, 0x28, 0x51,
0x23, 0x0f, 0xb2, 0x60, 0x19, 0xe7, 0x54, 0xb3, 0xe7, 0x10, 0x61, 0x2d, 0x64, 0xc5, 0x8f, 0x88,
0xec, 0x00, 0x4b, 0x21, 0xdc, 0x99, 0x8a, 0x87, 0xc4, 0xb9, 0x72, 0xf1, 0x37, 0x82, 0xf9, 0x55,
0xff, 0xd0, 0x83, 0x46, 0x0c, 0x26, 0x1b, 0x5d, 0x63, 0xef, 0x43, 0x35, 0xe3, 0x30, 0x6b, 0xf5,
0xce, 0x14, 0xd8, 0xf2, 0x30, 0x0b, 0x97, 0x71, 0xee, 0xa1, 0x53, 0xee, 0xd0, 0xb4, 0x52, 0x2b,
0x3e, 0xa1, 0x0b, 0x1e, 0xb2, 0x0c, 0x92, 0x12, 0xdb, 0xc2, 0xc8, 0xc6, 0x3a, 0x35, 0x22, 0x75,
0x4c, 0xb1, 0x53, 0x98, 0x6f, 0x71, 0xff, 0x47, 0x9b, 0xb2, 0xe5, 0x53, 0xb2, 0xbd, 0xc7, 0xec,
0x1c, 0x92, 0xfa, 0xbe, 0xe1, 0x96, 0xcf, 0xb2, 0x70, 0x99, 0xbc, 0x3d, 0x59, 0x0d, 0x23, 0x59,
0x0d, 0xf3, 0xc8, 0xc7, 0x47, 0xd9, 0x09, 0x4c, 0x51, 0xdd, 0x4a, 0x85, 0x7c, 0x4e, 0x4f, 0xf6,
0xc8, 0xf5, 0x25, 0x0b, 0xad, 0x78, 0xdc, 0xf5, 0xe5, 0x6a, 0xf6, 0x0a, 0x40, 0x34, 0xf2, 0x67,
0xdf, 0x00, 0x90, 0x32, 0x62, 0xd8, 0x4b, 0x88, 0x0b, 0xad, 0x4a, 0x49, 0x1d, 0x24, 0x24, 0x0f,
0x84, 0x73, 0xb4, 0xe2, 0xb6, 0xe5, 0x8f, 0x3b, 0x47, 0x57, 0x77, 0x8e, 0x8d, 0x77, 0x3c, 0xf6,
0x8e, 0x9e, 0x71, 0x7a, 0x89, 0x8d, 0xc1, 0x42, 0x58, 0x2c, 0xf9, 0x93, 0x2c, 0x58, 0xce, 0xf3,
0x11, 0xc3, 0x5e, 0xc3, 0xb1, 0x95, 0x55, 0x85, 0xc6, 0x5b, 0x3c, 0x25, 0x8b, 0x43, 0x92, 0x5d,
0x42, 0x22, 0x94, 0xd2, 0x56, 0xb8, 0x7f, 0xb4, 0x3c, 0xa5, 0xe9, 0xbc, 0x39, 0x98, 0x8e, 0xcf,
0xd2, 0xc7, 0xe1, 0xdc, 0x85, 0xb2, 0x66, 0x9f, 0x8f, 0x6f, 0xba, 0x25, 0x6d, 0x77, 0x37, 0xe8,
0x1f, 0x7b, 0xd6, 0x2d, 0x69, 0x44, 0x9d, 0x7e, 0x80, 0xf4, 0x7f, 0x0b, 0x97, 0xaa, 0x2d, 0xee,
0xfb, 0xd4, 0xb8, 0xd2, 0xa5, 0xef, 0x4e, 0x54, 0x3b, 0x9f, 0x9a, 0x0e, 0xbc, 0x3f, 0x3a, 0x0f,
0x16, 0x19, 0x4c, 0x2f, 0xba, 0x05, 0x24, 0x30, 0xfb, 0xb1, 0xfe, 0xb2, 0xbe, 0xfe, 0xb5, 0x4e,
0x1f, 0xb1, 0x18, 0xa2, 0xcb, 0xeb, 0xef, 0xdf, 0xbe, 0xa6, 0xc1, 0xa7, 0xd9, 0xef, 0x88, 0xfe,
0x7c, 0x33, 0xa5, 0xdc, 0xbf, 0xfb, 0x17, 0x00, 0x00, 0xff, 0xff, 0x36, 0xf9, 0x0d, 0xa6, 0x14,
0x03, 0x00, 0x00,
}<|fim▁end|>
|
Url string `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty"`
|
<|file_name|>admin.py<|end_file_name|><|fim▁begin|># encoding: utf-8
from django.contrib import admin<|fim▁hole|><|fim▁end|>
|
# Register your models here.
|
<|file_name|>transport.py<|end_file_name|><|fim▁begin|>"""
Read/Write AMQP frames over network transports.
2009-01-14 Barry Pederson <[email protected]>
"""
# Copyright (C) 2009 Barry Pederson <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
import re
import socket
#
# See if Python 2.6+ SSL support is available
#
try:
import ssl
HAVE_PY26_SSL = True
except:
HAVE_PY26_SSL = False
try:
bytes
except:
# Python 2.5 and lower
bytes = str
from struct import pack, unpack
AMQP_PORT = 5672
# Yes, Advanced Message Queuing Protocol Protocol is redundant
AMQP_PROTOCOL_HEADER = 'AMQP\x01\x01\x09\x01'.encode('latin_1')
# Match things like: [fe80::1]:5432, from RFC 2732
IPV6_LITERAL = re.compile(r'\[([\.0-9a-f:]+)\](?::(\d+))?')
class _AbstractTransport(object):
"""
Common superclass for TCP and SSL transports
"""
def __init__(self, host, connect_timeout):
msg = 'socket.getaddrinfo() for %s returned an empty list' % host
port = AMQP_PORT
m = IPV6_LITERAL.match(host)
if m:
host = m.group(1)
if m.group(2):
port = int(m.group(2))
else:
if ':' in host:
host, port = host.rsplit(':', 1)
port = int(port)
self.sock = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.SOL_TCP):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
self.sock.settimeout(connect_timeout)
self.sock.connect(sa)
except socket.error, msg:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
# Didn't connect, return the most recent error message
raise socket.error, msg
self.sock.settimeout(None)
self.sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self._setup_transport()
self._write(AMQP_PROTOCOL_HEADER)
def __del__(self):
self.close()
def _read(self, n):
"""
Read exactly n bytes from the peer
"""
raise NotImplementedError('Must be overriden in subclass')
def _setup_transport(self):
"""
Do any additional initialization of the class (used
by the subclasses).
"""
pass
def _shutdown_transport(self):
"""
Do any preliminary work in shutting down the connection.
"""
pass
def _write(self, s):
"""
Completely write a string to the peer.
"""
raise NotImplementedError('Must be overriden in subclass')
def close(self):
if self.sock is not None:
self._shutdown_transport()
# Call shutdown first to make sure that pending messages
# reach the AMQP broker if the program exits after
# calling this method.
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
self.sock = None
def read_frame(self):
"""
Read an AMQP frame.
"""
frame_type, channel, size = unpack('>BHI', self._read(7))
payload = self._read(size)
ch = ord(self._read(1))
if ch == 206: # '\xce'
return frame_type, channel, payload
else:
raise Exception('Framing Error, received 0x%02x while expecting 0xce' % ch)
def write_frame(self, frame_type, channel, payload):
"""
Write out an AMQP frame.
"""
size = len(payload)
self._write(pack('>BHI%dsB' % size,
frame_type, channel, size, payload, 0xce))
class SSLTransport(_AbstractTransport):
"""
Transport that works over SSL
"""
def __init__(self, host, connect_timeout, ssl):
if isinstance(ssl, dict):
self.sslopts = ssl
self.sslobj = None
super(SSLTransport, self).__init__(host, connect_timeout)
def _setup_transport(self):
"""
Wrap the socket in an SSL object, either the
new Python 2.6 version, or the older Python 2.5 and
lower version.
"""
if HAVE_PY26_SSL:
if hasattr(self, 'sslopts'):
self.sslobj = ssl.wrap_socket(self.sock, **self.sslopts)
else:
self.sslobj = ssl.wrap_socket(self.sock)
self.sslobj.do_handshake()
else:
self.sslobj = socket.ssl(self.sock)
def _shutdown_transport(self):
"""
Unwrap a Python 2.6 SSL socket, so we can call shutdown()
"""
if HAVE_PY26_SSL and (self.sslobj is not None):
self.sock = self.sslobj.unwrap()
self.sslobj = None
def _read(self, n):
"""
It seems that SSL Objects read() method may not supply as much
as you're asking for, at least with extremely large messages.
somewhere > 16K - found this in the test_channel.py test_large
unittest.
"""
result = self.sslobj.read(n)
while len(result) < n:
s = self.sslobj.read(n - len(result))
if not s:
raise IOError('Socket closed')
result += s
return result
def _write(self, s):
"""
Write a string out to the SSL socket fully.
"""
while s:
n = self.sslobj.write(s)
if not n:
raise IOError('Socket closed')
s = s[n:]
class TCPTransport(_AbstractTransport):
"""
Transport that deals directly with TCP socket.
"""
def _setup_transport(self):
"""
Setup to _write() directly to the socket, and
do our own buffered reads.
"""
self._write = self.sock.sendall
self._read_buffer = bytes()
def _read(self, n):
"""
Read exactly n bytes from the socket
"""
while len(self._read_buffer) < n:
s = self.sock.recv(65536)
if not s:
raise IOError('Socket closed')
self._read_buffer += s
result = self._read_buffer[:n]
self._read_buffer = self._read_buffer[n:]
return result
def create_transport(host, connect_timeout, ssl=False):
"""<|fim▁hole|> select and create a subclass of _AbstractTransport.
"""
if ssl:
return SSLTransport(host, connect_timeout, ssl)
else:
return TCPTransport(host, connect_timeout)<|fim▁end|>
|
Given a few parameters from the Connection constructor,
|
<|file_name|>inventory_work_unit.py<|end_file_name|><|fim▁begin|># =============================================================================
# Copyright (c) 2016, Cisco Systems, 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:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.<|fim▁hole|># AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
from models import Host
from models import InventoryJob
from models import InventoryJobHistory
from constants import JobStatus
from handlers.loader import get_inventory_handler_class
from context import InventoryContext
from utils import create_log_directory
from multi_process import WorkUnit
import traceback
import sys
class InventoryWorkUnit(WorkUnit):
def __init__(self, host_id, job_id):
WorkUnit.__init__(self)
self.host_id = host_id
self.job_id = job_id
def get_unique_key(self):
return self.host_id
def start(self, db_session, logger, process_name):
host = None
inventory_job = None
try:
inventory_job = db_session.query(InventoryJob).filter(InventoryJob.id == self.job_id).first()
if inventory_job is None:
logger.error('Unable to retrieve inventory job: %s' % self.job_id)
return
host_id = inventory_job.host_id
host = db_session.query(Host).filter(Host.id == host_id).first()
if host is None:
logger.error('Unable to retrieve host: %s' % host_id)
ctx = InventoryContext(db_session, host, inventory_job)
handler_class = get_inventory_handler_class(ctx)
if handler_class is None:
logger.error('Unable to get handler for %s, inventory job %s', host.software_platform, self.job_id)
inventory_job.set_status(JobStatus.IN_PROGRESS)
inventory_job.session_log = create_log_directory(host.connection_param[0].host_or_ip, inventory_job.id)
db_session.commit()
handler = handler_class()
handler.execute(ctx)
if ctx.success:
self.archive_inventory_job(db_session, inventory_job, JobStatus.COMPLETED)
else:
# removes the host object as host.packages may have been modified.
db_session.expunge(host)
self.archive_inventory_job(db_session, inventory_job, JobStatus.FAILED)
# Reset the pending retrieval flag
inventory_job.request_update = False
db_session.commit()
except Exception:
try:
self.log_exception(logger, host)
self.archive_inventory_job(db_session, inventory_job, JobStatus.FAILED, trace=sys.exc_info)
# Reset the pending retrieval flag
inventory_job.request_update = False
db_session.commit()
except Exception:
self.log_exception(logger, host)
finally:
db_session.close()
def log_exception(self, logger, host):
logger.exception('InventoryManager hit exception - hostname = %s, inventory job = %s',
host.hostname if host is not None else 'Unknown', self.job_id)
def archive_inventory_job(self, db_session, inventory_job, job_status, trace=None):
inventory_job.set_status(job_status)
hist = InventoryJobHistory()
hist.host_id = inventory_job.host_id
hist.set_status(job_status)
hist.session_log = inventory_job.session_log
if trace is not None:
hist.trace = traceback.format_exc()
db_session.add(hist)<|fim▁end|>
|
# 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"
|
<|file_name|>Annotation.ts<|end_file_name|><|fim▁begin|>/// <reference path="../../src/CaseModel.ts" />
/// <reference path="../../src/CaseViewer.ts" />
/// <reference path="../../src/PlugInManager.ts" />
class AnnotationPlugIn extends AssureIt.PlugInSet {
constructor(public plugInManager: AssureIt.PlugInManager) {
super(plugInManager);
this.HTMLRenderPlugIn = new AnnotationHTMLRenderPlugIn(plugInManager);
}
}
class AnnotationHTMLRenderPlugIn extends AssureIt.HTMLRenderPlugIn {
IsEnabled(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel) : boolean {
return true;
}
Delegate(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel, element: JQuery) : boolean {
if(caseModel.Annotations.length == 0) return;
var text : string = "";
var p : {top: number; left: number} = element.position();
for(var i : number = 0; i < caseModel.Annotations.length; i++) {
text += "@" + caseModel.Annotations[i].Name + "<br>";
}
$('<div class="anno">' +
'<p>' + text + '</p>' +
'</div>')
.css({position: 'absolute', 'font-size': 25, color: 'gray', top: p.top - 20, left: p.left + 80}).appendTo(element);
return true;<|fim▁hole|><|fim▁end|>
|
}
}
|
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyKiwisolver(PythonPackage):
"""A fast implementation of the Cassowary constraint solver"""
homepage = "https://github.com/nucleic/kiwi"
pypi = "kiwisolver/kiwisolver-1.1.0.tar.gz"
version('1.3.2', sha256='fc4453705b81d03568d5b808ad8f09c77c47534f6ac2e72e733f9ca4714aa75c')<|fim▁hole|> version('1.0.1', sha256='ce3be5d520b4d2c3e5eeb4cd2ef62b9b9ab8ac6b6fedbaa0e39cdb6f50644278')
depends_on('[email protected]:2.8,3.4:', type=('build', 'run'))
depends_on('[email protected]:', type=('build', 'run'), when='@1.2.0:')
depends_on('[email protected]:', type=('build', 'run'), when='@1.3.0:')
depends_on('[email protected]:', type=('build', 'run'), when='@1.3.2:')
depends_on('py-setuptools', type='build')
depends_on('[email protected]:', type='build', when='@1.2.0:')<|fim▁end|>
|
version('1.3.1', sha256='950a199911a8d94683a6b10321f9345d5a3a8433ec58b217ace979e18f16e248')
version('1.3.0', sha256='14f81644e1f3bf01fbc8b9c990a7889e9bb4400c4d0ff9155aa0bdd19cce24a9')
version('1.2.0', sha256='247800260cd38160c362d211dcaf4ed0f7816afb5efe56544748b21d6ad6d17f')
version('1.1.0', sha256='53eaed412477c836e1b9522c19858a8557d6e595077830146182225613b11a75')
|
<|file_name|>MicroSortRuntimeFactory.java<|end_file_name|><|fim▁begin|>/*
* 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.
*/
package org.apache.hyracks.algebricks.runtime.operators.sort;
import java.nio.ByteBuffer;
import java.util.List;
import org.apache.hyracks.algebricks.common.exceptions.NotImplementedException;
import org.apache.hyracks.algebricks.runtime.operators.base.AbstractOneInputOneOutputPushRuntime;
import org.apache.hyracks.algebricks.runtime.operators.base.AbstractOneInputOneOutputRuntimeFactory;
import org.apache.hyracks.api.comm.IFrameWriter;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.value.IBinaryComparator;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputer;
import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputerFactory;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.resources.IDeallocatable;
import org.apache.hyracks.api.util.CleanupUtils;
import org.apache.hyracks.dataflow.common.io.GeneratedRunFileReader;
import org.apache.hyracks.dataflow.std.buffermanager.EnumFreeSlotPolicy;
import org.apache.hyracks.dataflow.std.sort.Algorithm;
import org.apache.hyracks.dataflow.std.sort.ExternalSortRunGenerator;
import org.apache.hyracks.dataflow.std.sort.ExternalSortRunMerger;
public class MicroSortRuntimeFactory extends AbstractOneInputOneOutputRuntimeFactory {
private static final long serialVersionUID = 1L;
private final int framesLimit;
private final int[] sortFields;
private final INormalizedKeyComputerFactory[] keyNormalizerFactories;
private final IBinaryComparatorFactory[] comparatorFactories;
public MicroSortRuntimeFactory(int[] sortFields, INormalizedKeyComputerFactory firstKeyNormalizerFactory,
IBinaryComparatorFactory[] comparatorFactories, int[] projectionList, int framesLimit) {
this(sortFields, firstKeyNormalizerFactory != null
? new INormalizedKeyComputerFactory[] { firstKeyNormalizerFactory } : null, comparatorFactories,
projectionList, framesLimit);
}
public MicroSortRuntimeFactory(int[] sortFields, INormalizedKeyComputerFactory[] keyNormalizerFactories,
IBinaryComparatorFactory[] comparatorFactories, int[] projectionList, int framesLimit) {
super(projectionList);
// Obs: the projection list is currently ignored.
if (projectionList != null) {
throw new NotImplementedException("Cannot push projection into InMemorySortRuntime.");
}
this.sortFields = sortFields;<|fim▁hole|> this.comparatorFactories = comparatorFactories;
this.framesLimit = framesLimit;
}
@Override
public AbstractOneInputOneOutputPushRuntime createOneOutputPushRuntime(final IHyracksTaskContext ctx)
throws HyracksDataException {
InMemorySortPushRuntime pushRuntime = new InMemorySortPushRuntime(ctx);
ctx.registerDeallocatable(pushRuntime);
return pushRuntime;
}
private class InMemorySortPushRuntime extends AbstractOneInputOneOutputPushRuntime implements IDeallocatable {
final IHyracksTaskContext ctx;
ExternalSortRunGenerator runsGenerator = null;
ExternalSortRunMerger runsMerger = null;
IFrameWriter wrappingWriter = null;
private InMemorySortPushRuntime(IHyracksTaskContext ctx) {
this.ctx = ctx;
}
@Override
public void open() throws HyracksDataException {
if (runsGenerator == null) {
runsGenerator = new ExternalSortRunGenerator(ctx, sortFields, keyNormalizerFactories,
comparatorFactories, outputRecordDesc, Algorithm.MERGE_SORT, EnumFreeSlotPolicy.LAST_FIT,
framesLimit, Integer.MAX_VALUE);
}
// next writer will be opened later when preparing the merger
isOpen = true;
runsGenerator.open();
runsGenerator.getSorter().reset();
}
@Override
public void nextFrame(ByteBuffer buffer) throws HyracksDataException {
runsGenerator.nextFrame(buffer);
}
@Override
public void close() throws HyracksDataException {
Throwable failure = null;
if (isOpen) {
try {
if (!failed) {
runsGenerator.close();
createOrResetRunsMerger();
if (runsGenerator.getRuns().isEmpty()) {
wrappingWriter = runsMerger.prepareSkipMergingFinalResultWriter(writer);
wrappingWriter.open();
if (runsGenerator.getSorter().hasRemaining()) {
runsGenerator.getSorter().flush(wrappingWriter);
}
} else {
wrappingWriter = runsMerger.prepareFinalMergeResultWriter(writer);
wrappingWriter.open();
runsMerger.process(wrappingWriter);
}
}
} catch (Throwable th) {
failure = th;
fail(th);
} finally {
failure = CleanupUtils.close(wrappingWriter, failure);
wrappingWriter = null;
}
}
isOpen = false;
if (failure != null) {
throw HyracksDataException.create(failure);
}
}
@Override
public void fail() throws HyracksDataException {
failed = true;
// clean up the runs if some have been generated. double close should be idempotent.
if (runsGenerator != null) {
List<GeneratedRunFileReader> runs = runsGenerator.getRuns();
for (int i = 0, size = runs.size(); i < size; i++) {
try {
runs.get(i).close();
} catch (Throwable th) {
// ignore
}
}
}
if (wrappingWriter != null) {
wrappingWriter.fail();
}
}
@Override
public void deallocate() {
if (runsGenerator != null) {
try {
runsGenerator.getSorter().close();
} catch (Exception e) {
// ignore
}
}
}
private void createOrResetRunsMerger() {
if (runsMerger == null) {
IBinaryComparator[] comparators = new IBinaryComparator[comparatorFactories.length];
for (int i = 0; i < comparatorFactories.length; ++i) {
comparators[i] = comparatorFactories[i].createBinaryComparator();
}
INormalizedKeyComputer nmkComputer =
keyNormalizerFactories == null ? null : keyNormalizerFactories[0].createNormalizedKeyComputer();
runsMerger = new ExternalSortRunMerger(ctx, runsGenerator.getRuns(), sortFields, comparators,
nmkComputer, outputRecordDesc, framesLimit, Integer.MAX_VALUE);
} else {
runsMerger.reset(runsGenerator.getRuns());
}
}
}
}<|fim▁end|>
|
this.keyNormalizerFactories = keyNormalizerFactories;
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Numeric traits and functions for the built-in numeric types.
#![stable(feature = "rust1", since = "1.0.0")]
#![allow(missing_docs)]
use self::wrapping::OverflowingOps;
use char::CharExt;
use cmp::{Eq, PartialOrd};
use fmt;
use intrinsics;
use marker::{Copy, Sized};
use mem::size_of;
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
use str::{FromStr, StrExt};
use slice::SliceExt;
/// Provides intentionally-wrapped arithmetic on `T`.
///
/// Operations like `+` on `u32` values is intended to never overflow,
/// and in some debug configurations overflow is detected and results
/// in a panic. While most arithmetic falls into this category, some
/// code explicitly expects and relies upon modular arithmetic (e.g.,
/// hashing).
///
/// Wrapping arithmetic can be achieved either through methods like
/// `wrapping_add`, or through the `Wrapping<T>` type, which says that
/// all standard arithmetic operations on the underlying value are
/// intended to have wrapping semantics.
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
pub mod wrapping;
// All these modules are technically private and only exposed for libcoretest:
pub mod flt2dec;
pub mod dec2flt;
pub mod bignum;
pub mod diy_float;
/// Types that have a "zero" value.
///
/// This trait is intended for use in conjunction with `Add`, as an identity:
/// `x + T::zero() == x`.
#[unstable(feature = "zero_one",
reason = "unsure of placement, wants to use associated constants",
issue = "27739")]
pub trait Zero {
/// The "zero" (usually, additive identity) for this type.
fn zero() -> Self;
}
/// Types that have a "one" value.
///
/// This trait is intended for use in conjunction with `Mul`, as an identity:
/// `x * T::one() == x`.
#[unstable(feature = "zero_one",
reason = "unsure of placement, wants to use associated constants",
issue = "27739")]
pub trait One {
/// The "one" (usually, multiplicative identity) for this type.
fn one() -> Self;
}
macro_rules! zero_one_impl {
($($t:ty)*) => ($(
impl Zero for $t {
#[inline]
fn zero() -> Self { 0 }
}
impl One for $t {
#[inline]
fn one() -> Self { 1 }
}
)*)
}
zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
macro_rules! zero_one_impl_float {
($($t:ty)*) => ($(
impl Zero for $t {
#[inline]
fn zero() -> Self { 0.0 }
}
impl One for $t {
#[inline]
fn one() -> Self { 1.0 }
}
)*)
}
zero_one_impl_float! { f32 f64 }
macro_rules! checked_op {
($U:ty, $op:path, $x:expr, $y:expr) => {{
let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
if overflowed { None } else { Some(result as Self) }
}}
}
/// Swapping a single byte is a no-op. This is marked as `unsafe` for
/// consistency with the other `bswap` intrinsics.
unsafe fn bswap8(x: u8) -> u8 { x }
// `Int` + `SignedInt` implemented for signed integers
macro_rules! int_impl {
($ActualT:ty, $UnsignedT:ty, $BITS:expr,
$add_with_overflow:path,
$sub_with_overflow:path,
$mul_with_overflow:path) => {
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn min_value() -> Self {
(-1 as Self) << ($BITS - 1)
}
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn max_value() -> Self {
let min = Self::min_value(); !min
}
/// Converts a string slice in a given base to an integer.
///
/// Leading and trailing whitespace represent an error.
///
/// # Examples
///
/// ```
/// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
from_str_radix(src, radix)
}
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```rust
/// let n = 0b01001100u8;
///
/// assert_eq!(n.count_ones(), 3);
/// ```<|fim▁hole|> /// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```rust
/// let n = 0b01001100u8;
///
/// assert_eq!(n.count_zeros(), 5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn count_zeros(self) -> u32 {
(!self).count_ones()
}
/// Returns the number of leading zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```rust
/// let n = 0b0101000u16;
///
/// assert_eq!(n.leading_zeros(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn leading_zeros(self) -> u32 {
(self as $UnsignedT).leading_zeros()
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```rust
/// let n = 0b0101000u16;
///
/// assert_eq!(n.trailing_zeros(), 3);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn trailing_zeros(self) -> u32 {
(self as $UnsignedT).trailing_zeros()
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
/// let m = 0x3456789ABCDEF012u64;
///
/// assert_eq!(n.rotate_left(12), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn rotate_left(self, n: u32) -> Self {
(self as $UnsignedT).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
/// let m = 0xDEF0123456789ABCu64;
///
/// assert_eq!(n.rotate_right(12), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn rotate_right(self, n: u32) -> Self {
(self as $UnsignedT).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
/// let m = 0xEFCDAB8967452301u64;
///
/// assert_eq!(n.swap_bytes(), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn swap_bytes(self) -> Self {
(self as $UnsignedT).swap_bytes() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(u64::from_be(n), n)
/// } else {
/// assert_eq!(u64::from_be(n), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn from_be(x: Self) -> Self {
if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
}
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(u64::from_le(n), n)
/// } else {
/// assert_eq!(u64::from_le(n), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn from_le(x: Self) -> Self {
if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
}
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_be(self) -> Self { // or not to be?
if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
}
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_le(self) -> Self {
if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
}
/// Checked integer addition. Computes `self + other`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```rust
/// assert_eq!(5u16.checked_add(65530), Some(65535));
/// assert_eq!(6u16.checked_add(65530), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_add(self, other: Self) -> Option<Self> {
checked_op!($ActualT, $add_with_overflow, self, other)
}
/// Checked integer subtraction. Computes `self - other`, returning
/// `None` if underflow occurred.
///
/// # Examples
///
/// ```rust
/// assert_eq!((-127i8).checked_sub(1), Some(-128));
/// assert_eq!((-128i8).checked_sub(1), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_sub(self, other: Self) -> Option<Self> {
checked_op!($ActualT, $sub_with_overflow, self, other)
}
/// Checked integer multiplication. Computes `self * other`, returning
/// `None` if underflow or overflow occurred.
///
/// # Examples
///
/// ```rust
/// assert_eq!(5u8.checked_mul(51), Some(255));
/// assert_eq!(5u8.checked_mul(52), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_mul(self, other: Self) -> Option<Self> {
checked_op!($ActualT, $mul_with_overflow, self, other)
}
/// Checked integer division. Computes `self / other`, returning `None`
/// if `other == 0` or the operation results in underflow or overflow.
///
/// # Examples
///
/// ```rust
/// assert_eq!((-127i8).checked_div(-1), Some(127));
/// assert_eq!((-128i8).checked_div(-1), None);
/// assert_eq!((1i8).checked_div(0), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_div(self, v: Self) -> Option<Self> {
match v {
0 => None,
-1 if self == Self::min_value()
=> None,
v => Some(self / v),
}
}
/// Saturating integer addition. Computes `self + other`, saturating at
/// the numeric bounds instead of overflowing.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn saturating_add(self, other: Self) -> Self {
match self.checked_add(other) {
Some(x) => x,
None if other >= Self::zero() => Self::max_value(),
None => Self::min_value(),
}
}
/// Saturating integer subtraction. Computes `self - other`, saturating
/// at the numeric bounds instead of overflowing.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn saturating_sub(self, other: Self) -> Self {
match self.checked_sub(other) {
Some(x) => x,
None if other >= Self::zero() => Self::min_value(),
None => Self::max_value(),
}
}
/// Wrapping (modular) addition. Computes `self + other`,
/// wrapping around at the boundary of the type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_add(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_add(self, rhs)
}
}
/// Wrapping (modular) subtraction. Computes `self - other`,
/// wrapping around at the boundary of the type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_sub(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_sub(self, rhs)
}
}
/// Wrapping (modular) multiplication. Computes `self *
/// other`, wrapping around at the boundary of the type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_mul(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_mul(self, rhs)
}
}
/// Wrapping (modular) division. Computes `self / other`,
/// wrapping around at the boundary of the type.
///
/// The only case where such wrapping can occur is when one
/// divides `MIN / -1` on a signed type (where `MIN` is the
/// negative minimal value for the type); this is equivalent
/// to `-MIN`, a positive value that is too large to represent
/// in the type. In such a case, this function returns `MIN`
/// itself.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % other`,
/// wrapping around at the boundary of the type.
///
/// Such wrap-around never actually occurs mathematically;
/// implementation artifacts make `x % y` invalid for `MIN /
/// -1` on a signed type (where `MIN` is the negative
/// minimal value). In such a case, this function returns `0`.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// The only case where such wrapping can occur is when one
/// negates `MIN` on a signed type (where `MIN` is the
/// negative minimal value for the type); this is a positive
/// value that is too large to represent in the type. In such
/// a case, this function returns `MIN` itself.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_neg(self) -> Self {
self.overflowing_neg().0
}
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_shl(self, rhs: u32) -> Self {
self.overflowing_shl(rhs).0
}
/// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_shr(self, rhs: u32) -> Self {
self.overflowing_shr(rhs).0
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
/// let x: i32 = 2; // or any other integer type
///
/// assert_eq!(x.pow(4), 16);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn pow(self, mut exp: u32) -> Self {
let mut base = self;
let mut acc = Self::one();
while exp > 1 {
if (exp & 1) == 1 {
acc = acc * base;
}
exp /= 2;
base = base * base;
}
// Deal with the final bit of the exponent separately, since
// squaring the base afterwards is not necessary and may cause a
// needless overflow.
if exp == 1 {
acc = acc * base;
}
acc
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of `i32::min_value()` cannot be represented as an
/// `i32`, and attempting to calculate it will cause an overflow. This
/// means that code in debug mode will trigger a panic on this case and
/// optimized code will return `i32::min_value()` without a panic.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn abs(self) -> Self {
if self.is_negative() {
// Note that the #[inline] above means that the overflow
// semantics of this negation depend on the crate we're being
// inlined into.
-self
} else {
self
}
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn signum(self) -> Self {
match self {
n if n > 0 => 1,
0 => 0,
_ => -1,
}
}
/// Returns `true` if `self` is positive and `false` if the number
/// is zero or negative.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number
/// is zero or positive.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_negative(self) -> bool { self < 0 }
}
}
#[lang = "i8"]
impl i8 {
int_impl! { i8, u8, 8,
intrinsics::i8_add_with_overflow,
intrinsics::i8_sub_with_overflow,
intrinsics::i8_mul_with_overflow }
}
#[lang = "i16"]
impl i16 {
int_impl! { i16, u16, 16,
intrinsics::i16_add_with_overflow,
intrinsics::i16_sub_with_overflow,
intrinsics::i16_mul_with_overflow }
}
#[lang = "i32"]
impl i32 {
int_impl! { i32, u32, 32,
intrinsics::i32_add_with_overflow,
intrinsics::i32_sub_with_overflow,
intrinsics::i32_mul_with_overflow }
}
#[lang = "i64"]
impl i64 {
int_impl! { i64, u64, 64,
intrinsics::i64_add_with_overflow,
intrinsics::i64_sub_with_overflow,
intrinsics::i64_mul_with_overflow }
}
#[cfg(target_pointer_width = "32")]
#[lang = "isize"]
impl isize {
int_impl! { i32, u32, 32,
intrinsics::i32_add_with_overflow,
intrinsics::i32_sub_with_overflow,
intrinsics::i32_mul_with_overflow }
}
#[cfg(target_pointer_width = "64")]
#[lang = "isize"]
impl isize {
int_impl! { i64, u64, 64,
intrinsics::i64_add_with_overflow,
intrinsics::i64_sub_with_overflow,
intrinsics::i64_mul_with_overflow }
}
// `Int` + `UnsignedInt` implemented for signed integers
macro_rules! uint_impl {
($ActualT:ty, $BITS:expr,
$ctpop:path,
$ctlz:path,
$cttz:path,
$bswap:path,
$add_with_overflow:path,
$sub_with_overflow:path,
$mul_with_overflow:path) => {
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn min_value() -> Self { 0 }
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn max_value() -> Self { !0 }
/// Converts a string slice in a given base to an integer.
///
/// Leading and trailing whitespace represent an error.
///
/// # Arguments
///
/// * src - A string slice
/// * radix - The base to use. Must lie in the range [2 .. 36]
///
/// # Return value
///
/// `Err(ParseIntError)` if the string did not represent a valid number.
/// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
from_str_radix(src, radix)
}
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```rust
/// let n = 0b01001100u8;
///
/// assert_eq!(n.count_ones(), 3);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn count_ones(self) -> u32 {
unsafe { $ctpop(self as $ActualT) as u32 }
}
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```rust
/// let n = 0b01001100u8;
///
/// assert_eq!(n.count_zeros(), 5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn count_zeros(self) -> u32 {
(!self).count_ones()
}
/// Returns the number of leading zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```rust
/// let n = 0b0101000u16;
///
/// assert_eq!(n.leading_zeros(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn leading_zeros(self) -> u32 {
unsafe { $ctlz(self as $ActualT) as u32 }
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```rust
/// let n = 0b0101000u16;
///
/// assert_eq!(n.trailing_zeros(), 3);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn trailing_zeros(self) -> u32 {
// As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
// emits two conditional moves on x86_64. By promoting the value to
// u16 and setting bit 8, we get better code without any conditional
// operations.
// FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
// pending, remove this workaround once LLVM generates better code
// for cttz8.
unsafe {
if $BITS == 8 {
intrinsics::cttz16(self as u16 | 0x100) as u32
} else {
$cttz(self as $ActualT) as u32
}
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
/// let m = 0x3456789ABCDEF012u64;
///
/// assert_eq!(n.rotate_left(12), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn rotate_left(self, n: u32) -> Self {
// Protect against undefined behaviour for over-long bit shifts
let n = n % $BITS;
(self << n) | (self >> (($BITS - n) % $BITS))
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
/// let m = 0xDEF0123456789ABCu64;
///
/// assert_eq!(n.rotate_right(12), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn rotate_right(self, n: u32) -> Self {
// Protect against undefined behaviour for over-long bit shifts
let n = n % $BITS;
(self >> n) | (self << (($BITS - n) % $BITS))
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
/// let m = 0xEFCDAB8967452301u64;
///
/// assert_eq!(n.swap_bytes(), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn swap_bytes(self) -> Self {
unsafe { $bswap(self as $ActualT) as Self }
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(u64::from_be(n), n)
/// } else {
/// assert_eq!(u64::from_be(n), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn from_be(x: Self) -> Self {
if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
}
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(u64::from_le(n), n)
/// } else {
/// assert_eq!(u64::from_le(n), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn from_le(x: Self) -> Self {
if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
}
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_be(self) -> Self { // or not to be?
if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
}
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```rust
/// let n = 0x0123456789ABCDEFu64;
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_le(self) -> Self {
if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
}
/// Checked integer addition. Computes `self + other`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```rust
/// assert_eq!(5u16.checked_add(65530), Some(65535));
/// assert_eq!(6u16.checked_add(65530), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_add(self, other: Self) -> Option<Self> {
checked_op!($ActualT, $add_with_overflow, self, other)
}
/// Checked integer subtraction. Computes `self - other`, returning
/// `None` if underflow occurred.
///
/// # Examples
///
/// ```rust
/// assert_eq!((-127i8).checked_sub(1), Some(-128));
/// assert_eq!((-128i8).checked_sub(1), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_sub(self, other: Self) -> Option<Self> {
checked_op!($ActualT, $sub_with_overflow, self, other)
}
/// Checked integer multiplication. Computes `self * other`, returning
/// `None` if underflow or overflow occurred.
///
/// # Examples
///
/// ```rust
/// assert_eq!(5u8.checked_mul(51), Some(255));
/// assert_eq!(5u8.checked_mul(52), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_mul(self, other: Self) -> Option<Self> {
checked_op!($ActualT, $mul_with_overflow, self, other)
}
/// Checked integer division. Computes `self / other`, returning `None`
/// if `other == 0` or the operation results in underflow or overflow.
///
/// # Examples
///
/// ```rust
/// assert_eq!((-127i8).checked_div(-1), Some(127));
/// assert_eq!((-128i8).checked_div(-1), None);
/// assert_eq!((1i8).checked_div(0), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn checked_div(self, v: Self) -> Option<Self> {
match v {
0 => None,
v => Some(self / v),
}
}
/// Saturating integer addition. Computes `self + other`, saturating at
/// the numeric bounds instead of overflowing.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn saturating_add(self, other: Self) -> Self {
match self.checked_add(other) {
Some(x) => x,
None if other >= Self::zero() => Self::max_value(),
None => Self::min_value(),
}
}
/// Saturating integer subtraction. Computes `self - other`, saturating
/// at the numeric bounds instead of overflowing.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn saturating_sub(self, other: Self) -> Self {
match self.checked_sub(other) {
Some(x) => x,
None if other >= Self::zero() => Self::min_value(),
None => Self::max_value(),
}
}
/// Wrapping (modular) addition. Computes `self + other`,
/// wrapping around at the boundary of the type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_add(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_add(self, rhs)
}
}
/// Wrapping (modular) subtraction. Computes `self - other`,
/// wrapping around at the boundary of the type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_sub(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_sub(self, rhs)
}
}
/// Wrapping (modular) multiplication. Computes `self *
/// other`, wrapping around at the boundary of the type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn wrapping_mul(self, rhs: Self) -> Self {
unsafe {
intrinsics::overflowing_mul(self, rhs)
}
}
/// Wrapping (modular) division. Computes `self / other`,
/// wrapping around at the boundary of the type.
///
/// The only case where such wrapping can occur is when one
/// divides `MIN / -1` on a signed type (where `MIN` is the
/// negative minimal value for the type); this is equivalent
/// to `-MIN`, a positive value that is too large to represent
/// in the type. In such a case, this function returns `MIN`
/// itself.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % other`,
/// wrapping around at the boundary of the type.
///
/// Such wrap-around never actually occurs mathematically;
/// implementation artifacts make `x % y` invalid for `MIN /
/// -1` on a signed type (where `MIN` is the negative
/// minimal value). In such a case, this function returns `0`.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// The only case where such wrapping can occur is when one
/// negates `MIN` on a signed type (where `MIN` is the
/// negative minimal value for the type); this is a positive
/// value that is too large to represent in the type. In such
/// a case, this function returns `MIN` itself.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_neg(self) -> Self {
self.overflowing_neg().0
}
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_shl(self, rhs: u32) -> Self {
self.overflowing_shl(rhs).0
}
/// Panic-free bitwise shift-left; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
pub fn wrapping_shr(self, rhs: u32) -> Self {
self.overflowing_shr(rhs).0
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```rust
/// assert_eq!(2i32.pow(4), 16);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn pow(self, mut exp: u32) -> Self {
let mut base = self;
let mut acc = Self::one();
let mut prev_base = self;
let mut base_oflo = false;
while exp > 0 {
if (exp & 1) == 1 {
if base_oflo {
// ensure overflow occurs in the same manner it
// would have otherwise (i.e. signal any exception
// it would have otherwise).
acc = acc * (prev_base * prev_base);
} else {
acc = acc * base;
}
}
prev_base = base;
let (new_base, new_base_oflo) = base.overflowing_mul(base);
base = new_base;
base_oflo = new_base_oflo;
exp /= 2;
}
acc
}
/// Returns `true` if and only if `self == 2^k` for some `k`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_power_of_two(self) -> bool {
(self.wrapping_sub(Self::one())) & self == Self::zero() &&
!(self == Self::zero())
}
/// Returns the smallest power of two greater than or equal to `self`.
/// Unspecified behavior on overflow.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn next_power_of_two(self) -> Self {
let bits = size_of::<Self>() * 8;
let one: Self = Self::one();
one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn checked_next_power_of_two(self) -> Option<Self> {
let npot = self.next_power_of_two();
if npot >= self {
Some(npot)
} else {
None
}
}
}
}
#[lang = "u8"]
impl u8 {
uint_impl! { u8, 8,
intrinsics::ctpop8,
intrinsics::ctlz8,
intrinsics::cttz8,
bswap8,
intrinsics::u8_add_with_overflow,
intrinsics::u8_sub_with_overflow,
intrinsics::u8_mul_with_overflow }
}
#[lang = "u16"]
impl u16 {
uint_impl! { u16, 16,
intrinsics::ctpop16,
intrinsics::ctlz16,
intrinsics::cttz16,
intrinsics::bswap16,
intrinsics::u16_add_with_overflow,
intrinsics::u16_sub_with_overflow,
intrinsics::u16_mul_with_overflow }
}
#[lang = "u32"]
impl u32 {
uint_impl! { u32, 32,
intrinsics::ctpop32,
intrinsics::ctlz32,
intrinsics::cttz32,
intrinsics::bswap32,
intrinsics::u32_add_with_overflow,
intrinsics::u32_sub_with_overflow,
intrinsics::u32_mul_with_overflow }
}
#[lang = "u64"]
impl u64 {
uint_impl! { u64, 64,
intrinsics::ctpop64,
intrinsics::ctlz64,
intrinsics::cttz64,
intrinsics::bswap64,
intrinsics::u64_add_with_overflow,
intrinsics::u64_sub_with_overflow,
intrinsics::u64_mul_with_overflow }
}
#[cfg(target_pointer_width = "32")]
#[lang = "usize"]
impl usize {
uint_impl! { u32, 32,
intrinsics::ctpop32,
intrinsics::ctlz32,
intrinsics::cttz32,
intrinsics::bswap32,
intrinsics::u32_add_with_overflow,
intrinsics::u32_sub_with_overflow,
intrinsics::u32_mul_with_overflow }
}
#[cfg(target_pointer_width = "64")]
#[lang = "usize"]
impl usize {
uint_impl! { u64, 64,
intrinsics::ctpop64,
intrinsics::ctlz64,
intrinsics::cttz64,
intrinsics::bswap64,
intrinsics::u64_add_with_overflow,
intrinsics::u64_sub_with_overflow,
intrinsics::u64_mul_with_overflow }
}
/// Used for representing the classification of floating point numbers
#[derive(Copy, Clone, PartialEq, Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum FpCategory {
/// "Not a Number", often obtained by dividing by zero
#[stable(feature = "rust1", since = "1.0.0")]
Nan,
/// Positive or negative infinity
#[stable(feature = "rust1", since = "1.0.0")]
Infinite ,
/// Positive or negative zero
#[stable(feature = "rust1", since = "1.0.0")]
Zero,
/// De-normalized floating point representation (less precise than `Normal`)
#[stable(feature = "rust1", since = "1.0.0")]
Subnormal,
/// A regular floating point number
#[stable(feature = "rust1", since = "1.0.0")]
Normal,
}
/// A built-in floating point number.
#[doc(hidden)]
#[unstable(feature = "core_float",
reason = "stable interface is via `impl f{32,64}` in later crates",
issue = "27702")]
pub trait Float: Sized {
/// Returns the NaN value.
fn nan() -> Self;
/// Returns the infinite value.
fn infinity() -> Self;
/// Returns the negative infinite value.
fn neg_infinity() -> Self;
/// Returns -0.0.
fn neg_zero() -> Self;
/// Returns 0.0.
fn zero() -> Self;
/// Returns 1.0.
fn one() -> Self;
/// Parses the string `s` with the radix `r` as a float.
fn from_str_radix(s: &str, r: u32) -> Result<Self, ParseFloatError>;
/// Returns true if this value is NaN and false otherwise.
fn is_nan(self) -> bool;
/// Returns true if this value is positive infinity or negative infinity and
/// false otherwise.
fn is_infinite(self) -> bool;
/// Returns true if this number is neither infinite nor NaN.
fn is_finite(self) -> bool;
/// Returns true if this number is neither zero, infinite, denormal, or NaN.
fn is_normal(self) -> bool;
/// Returns the category that this number falls into.
fn classify(self) -> FpCategory;
/// Returns the mantissa, exponent and sign as integers, respectively.
fn integer_decode(self) -> (u64, i16, i8);
/// Computes the absolute value of `self`. Returns `Float::nan()` if the
/// number is `Float::nan()`.
fn abs(self) -> Self;
/// Returns a number that represents the sign of `self`.
///
/// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
/// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
/// - `Float::nan()` if the number is `Float::nan()`
fn signum(self) -> Self;
/// Returns `true` if `self` is positive, including `+0.0` and
/// `Float::infinity()`.
fn is_positive(self) -> bool;
/// Returns `true` if `self` is negative, including `-0.0` and
/// `Float::neg_infinity()`.
fn is_negative(self) -> bool;
/// Take the reciprocal (inverse) of a number, `1/x`.
fn recip(self) -> Self;
/// Raise a number to an integer power.
///
/// Using this function is generally faster than using `powf`
fn powi(self, n: i32) -> Self;
/// Convert radians to degrees.
fn to_degrees(self) -> Self;
/// Convert degrees to radians.
fn to_radians(self) -> Self;
}
macro_rules! from_str_radix_int_impl {
($($t:ty)*) => {$(
#[stable(feature = "rust1", since = "1.0.0")]
impl FromStr for $t {
type Err = ParseIntError;
fn from_str(src: &str) -> Result<Self, ParseIntError> {
from_str_radix(src, 10)
}
}
)*}
}
from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
#[doc(hidden)]
trait FromStrRadixHelper: PartialOrd + Copy {
fn min_value() -> Self;
fn from_u32(u: u32) -> Self;
fn checked_mul(&self, other: u32) -> Option<Self>;
fn checked_sub(&self, other: u32) -> Option<Self>;
fn checked_add(&self, other: u32) -> Option<Self>;
}
macro_rules! doit {
($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
fn min_value() -> Self { Self::min_value() }
fn from_u32(u: u32) -> Self { u as Self }
fn checked_mul(&self, other: u32) -> Option<Self> {
Self::checked_mul(*self, other as Self)
}
fn checked_sub(&self, other: u32) -> Option<Self> {
Self::checked_sub(*self, other as Self)
}
fn checked_add(&self, other: u32) -> Option<Self> {
Self::checked_add(*self, other as Self)
}
})*)
}
doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
-> Result<T, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
assert!(radix >= 2 && radix <= 36,
"from_str_radix_int: must lie in the range `[2, 36]` - found {}",
radix);
if src.is_empty() {
return Err(PIE { kind: Empty });
}
let is_signed_ty = T::from_u32(0) > T::min_value();
// all valid digits are ascii, so we will just iterate over the utf8 bytes
// and cast them to chars. .to_digit() will safely return None for anything
// other than a valid ascii digit for a the given radix, including the first-byte
// of multi-byte sequences
let src = src.as_bytes();
match (src[0], &src[1..]) {
(b'-', digits) if digits.is_empty() => Err(PIE { kind: Empty }),
(b'-', digits) if is_signed_ty => {
// The number is negative
let mut result = T::from_u32(0);
for &c in digits {
let x = match (c as char).to_digit(radix) {
Some(x) => x,
None => return Err(PIE { kind: InvalidDigit }),
};
result = match result.checked_mul(radix) {
Some(result) => result,
None => return Err(PIE { kind: Underflow }),
};
result = match result.checked_sub(x) {
Some(result) => result,
None => return Err(PIE { kind: Underflow }),
};
}
Ok(result)
},
(c, digits) => {
// The number is signed
let mut result = match (c as char).to_digit(radix) {
Some(x) => T::from_u32(x),
None => return Err(PIE { kind: InvalidDigit }),
};
for &c in digits {
let x = match (c as char).to_digit(radix) {
Some(x) => x,
None => return Err(PIE { kind: InvalidDigit }),
};
result = match result.checked_mul(radix) {
Some(result) => result,
None => return Err(PIE { kind: Overflow }),
};
result = match result.checked_add(x) {
Some(result) => result,
None => return Err(PIE { kind: Overflow }),
};
}
Ok(result)
}
}
}
/// An error which can be returned when parsing an integer.
#[derive(Debug, Clone, PartialEq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct ParseIntError { kind: IntErrorKind }
#[derive(Debug, Clone, PartialEq)]
enum IntErrorKind {
Empty,
InvalidDigit,
Overflow,
Underflow,
}
impl ParseIntError {
#[unstable(feature = "int_error_internals",
reason = "available through Error trait and this method should \
not be exposed publicly",
issue = "0")]
#[doc(hidden)]
pub fn __description(&self) -> &str {
match self.kind {
IntErrorKind::Empty => "cannot parse integer from empty string",
IntErrorKind::InvalidDigit => "invalid digit found in string",
IntErrorKind::Overflow => "number too large to fit in target type",
IntErrorKind::Underflow => "number too small to fit in target type",
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for ParseIntError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.__description().fmt(f)
}
}
pub use num::dec2flt::ParseFloatError;<|fim▁end|>
|
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
|
<|file_name|>L2EngineVarRef2.java<|end_file_name|><|fim▁begin|>/*
* The MIT License
*
* Copyright 2014 Kamnev Georgiy ([email protected]).
*
* Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного
* обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное Обеспечение"),
* использовать Программное Обеспечение без ограничений, включая неограниченное право на
* использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование
* и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется
* данное Программное Обеспечение, при соблюдении следующих условий:
*
* Вышеупомянутый копирайт и данные условия должны быть включены во все копии
* или значимые части данного Программного Обеспечения.
*
* ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ,
* ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ,
* СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ
* ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ
* ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ
* ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
* ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
*/
package xyz.cofe.lang2.parser.vref;
import java.net.URL;
import xyz.cofe.lang2.parser.BasicParserTest;
import xyz.cofe.lang2.parser.L2Engine;
import xyz.cofe.lang2.vm.Callable;
import xyz.cofe.lang2.vm.Value;
import org.junit.Test;
import xyz.cofe.log.CLILoggers;
/**
* Тестирование парсера
* @author gocha
*/
public class L2EngineVarRef2 extends BasicParserTest
{
protected L2Engine l2Engine = null;
@Override
protected Value parseExpressions(String source) {
if( l2Engine==null ){
l2Engine = new L2Engine();
l2Engine.setMemory(memory);
}
return l2Engine.parse(source);
}
@Test
public void varRef2(){
return;
// TODO используется альтернативный способ поиска переменных
//
// String src = "var v = \"abc\";\n"
// + "var obj = \n"
// + " {\n"
// + " f : function ( a )\n"
// + " {\n"
// + " a + v\n"<|fim▁hole|>// + "obj.f( \"xcv\" )";
// String must = "xcvabc";
//
// CLILoggers logger = new CLILoggers();
// URL logConf = L2EngineVarRefTest.class.getResource("L2EngineVarRefTest2.logconf.xml");
// logger.parseXmlConfig(logConf);
//
// assertParseExpressions(src, must);
//
// if( logger.getNamedHandler().containsKey("console") ){
// logger.removeHandlerFromRoot(logger.getNamedHandler().get("console"));
// }
}
}<|fim▁end|>
|
// + " }\n"
// + " };\n"
// + "v = \"def\";\n"
|
<|file_name|>test_column.py<|end_file_name|><|fim▁begin|>import numpy as np
import pandas as pd
import pytest
ROWID_ZERO_INDEXED_BACKENDS = ('omniscidb',)
@pytest.mark.parametrize(
'column',
[
'string_col',
'double_col',
'date_string_col',
pytest.param('timestamp_col', marks=pytest.mark.skip(reason='hangs')),
],
)
@pytest.mark.xfail_unsupported
def test_distinct_column(backend, alltypes, df, column):
expr = alltypes[column].distinct()
result = expr.execute()
expected = df[column].unique()
assert set(result) == set(expected)
@pytest.mark.xfail_unsupported<|fim▁hole|> t = con.table('functional_alltypes')
result = t[t.rowid()].execute()
first_value = 0 if backend.name() in ROWID_ZERO_INDEXED_BACKENDS else 1
expected = pd.Series(
range(first_value, first_value + len(result)),
dtype=np.int64,
name='rowid',
)
pd.testing.assert_series_equal(result.iloc[:, 0], expected)
@pytest.mark.xfail_unsupported
def test_named_rowid(con, backend):
t = con.table('functional_alltypes')
result = t[t.rowid().name('number')].execute()
first_value = 0 if backend.name() in ROWID_ZERO_INDEXED_BACKENDS else 1
expected = pd.Series(
range(first_value, first_value + len(result)),
dtype=np.int64,
name='number',
)
pd.testing.assert_series_equal(result.iloc[:, 0], expected)<|fim▁end|>
|
def test_rowid(con, backend):
|
<|file_name|>mappers.py<|end_file_name|><|fim▁begin|># This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
from indico.core.config import Config
from indico.modules.rb.views.admin import WPRoomsBase
from MaKaC.roomMapping import RoomMapperHolder
from MaKaC.webinterface import urlHandlers
from MaKaC.webinterface.wcomponents import WTemplated
class WPRoomMapperBase(WPRoomsBase):
def _setActiveTab(self):
self._subTabRoomMappers.setActive()
<|fim▁hole|> self._params = params
def _getTabContent(self, params):
criteria = {}
if filter(lambda x: self._params[x], self._params):
criteria['name'] = self._params.get('sName', '')
return WRoomMapperList(criteria).getHTML()
class WRoomMapperList(WTemplated):
def __init__(self, criteria):
self._criteria = criteria
def _performSearch(self, criteria):
return RoomMapperHolder().match(criteria)
def getVars(self):
wvars = WTemplated.getVars(self)
wvars['createRoomMapperURL'] = urlHandlers.UHNewRoomMapper.getURL()
wvars['searchRoomMappersURL'] = urlHandlers.UHRoomMappers.getURL()
wvars['roomMappers'] = self._performSearch(self._criteria) if self._criteria else []
return wvars
class WPRoomMapperDetails(WPRoomMapperBase):
def __init__(self, rh, roomMapper):
WPRoomMapperBase.__init__(self, rh)
self._roomMapper = roomMapper
def _getTabContent(self, params):
return WRoomMapperDetails(self._roomMapper).getHTML({
'modifyURL': urlHandlers.UHRoomMapperModification.getURL(self._roomMapper)
})
class WRoomMapperDetails(WTemplated):
def __init__(self, rm):
WTemplated.__init__(self)
self._roomMapper = rm
def getVars(self):
wvars = WTemplated.getVars(self)
wvars['name'] = self._roomMapper.getName()
wvars['description'] = self._roomMapper.getDescription()
wvars['url'] = self._roomMapper.getBaseMapURL()
wvars['placeName'] = self._roomMapper.getPlaceName()
wvars['regexps'] = self._roomMapper.getRegularExpressions()
return wvars
class WPRoomMapperCreation(WPRoomMapperBase):
def _getTabContent(self, params):
return WRoomMapperEdit().getHTML({
'postURL': urlHandlers.UHRoomMapperPerformCreation.getURL()
})
class WPRoomMapperModification(WPRoomMapperBase):
def __init__(self, rh, domain):
WPRoomMapperBase.__init__(self, rh)
self._domain = domain
def _getTabContent(self, params):
return WRoomMapperEdit(self._domain).getHTML({
'postURL': urlHandlers.UHRoomMapperPerformModification.getURL(self._domain)
})
class WRoomMapperEdit(WTemplated):
def __init__(self, rm=None):
self._roomMapper = rm
def getVars(self):
wvars = WTemplated.getVars(self)
wvars['name'] = wvars['description'] = wvars['url'] = \
wvars['placeName'] = wvars['regexps'] = wvars['locator'] = ''
wvars['is_rb_active'] = Config.getInstance().getIsRoomBookingActive()
if self._roomMapper:
wvars['name'] = self._roomMapper.getName()
wvars['description'] = self._roomMapper.getDescription()
wvars['url'] = self._roomMapper.getBaseMapURL()
wvars['placeName'] = self._roomMapper.getPlaceName()
wvars['regexps'] = '\r\n'.join(self._roomMapper.getRegularExpressions())
wvars['locator'] = self._roomMapper.getLocator().getWebForm()
return wvars<|fim▁end|>
|
class WPRoomMapperList(WPRoomMapperBase):
def __init__(self, rh, params):
WPRoomMapperBase.__init__(self, rh)
|
<|file_name|>user.controller.js<|end_file_name|><|fim▁begin|>import User from '../models/user.model';
import Post from '../models/post.model';
import UserPost from '../models/users_posts.model';
import fs from 'fs';
import path from 'path';
/**
* Load user and append to req.
*/
function load(req, res, next, id) {
User.get(id)
.then((user) => {
req.user = user; // eslint-disable-line no-param-reassign
return next();
})
.catch(e => next(e));
}
/**
* Get user
* @returns {User}
*/
function get(req, res) {
req.user.password = "";
var user = JSON.parse(JSON.stringify(req.user));
Post.count({
userId: req.user._id
}).exec()
.then(postCount => {
user.postCount = postCount;
User.count({
following: req.user._id
}).exec()
.then(followedByCount => {
user.followedByCount = followedByCount;
return res.json({
data: user,
result: 0
});
})
})
.catch(err => {
return res.json({
data: err,
result: 1
});
})
}
/**
* Update basic info;firstname lastname profie.bio description title
* @returns {User}
*/
function updateBasicinfo(req, res, next) {
var user = req.user;
user.firstname = req.body.firstname;
user.lastname = req.body.lastname;
user.profile.bio = req.body.profile.bio;
user.profile.title = req.body.profile.title;
user.profile.description = req.body.profile.description;
user.save()
.then(savedUser => res.json({
data: savedUser,
result: 0
}))
.catch(e => next(e));
}
/**
* Update basic info;firstname lastname profie.bio description title
* @returns {User}
*/
function uploadUserimg(req, res, next) {
var user = req.user;
var file = req.files.file;
fs.readFile(file.path, function(err, original_data) {
if (err) {
next(err);
}
// save image in db as base64 encoded - this limits the image size
// to there should be size checks here and in client
var newPath = path.join(__filename, '../../../../public/uploads/avatar/');
fs.writeFile(newPath + user._id + path.extname(file.path), original_data, function(err) {
if (err)
next(err);
console.log("write file" + newPath + user._id + path.extname(file.path));
fs.unlink(file.path, function(err) {
if (err) {
console.log('failed to delete ' + file.path);
} else {
console.log('successfully deleted ' + file.path);
}
});
user.image = '/uploads/avatar/' + user._id + path.extname(file.path);
user.save(function(err) {
if (err) {
next(err);
} else {
res.json({
data: user,
result: 1
});
}
});
});
});
}
/**
* Create new user
* @property {string} req.body.username - The username of user.
* @property {string} req.body.mobileNumber - The mobileNumber of user.
* @returns {User}
*/
function create(req, res, next) {
const user = new User({
username: req.body.username,
mobileNumber: req.body.mobileNumber
});
user.save()
.then(savedUser => res.json(savedUser))
.catch(e => next(e));
}
/**
* Update existing user
* @property {string} req.body.username - The username of user.
* @property {string} req.body.mobileNumber - The mobileNumber of user.
* @returns {User}
*/
function update(req, res, next) {
const user = req.user;
user.username = req.body.username;
user.mobileNumber = req.body.mobileNumber;
user.save()
.then(savedUser => res.json(savedUser))
.catch(e => next(e));
}
/**
* Get user list.
req.params.query : search string
req.params.
* @returns {User[]}
*/
function list(req, res, next) {
var params = req.query;
var condition;
if (params.query == "")
condition = {};
else {
condition = {
$or: [{
"firstname": new RegExp(params.query, 'i')
}, {<|fim▁hole|> User.count(condition).exec()
.then(total => {
if (params.page * params.item_per_page > total) {
params.users = [];
throw {
data: params,
result: 1
};
}
params.total = total;
return User.find(condition)
.sort({
createdAt: -1
})
.skip(params.page * params.item_per_page)
.limit(parseInt(params.item_per_page))
.exec();
})
.then(users => {
params.users = users;
res.json({
data: params,
result: 0
});
})
.catch(err => next(err));
}
/**
* Delete user.
* @returns {User}
*/
function remove(req, res, next) {
const user = req.user;
user.remove()
.then(deletedUser => res.json(deletedUser))
.catch(e => next(e));
}
/**
* get post of ther user
* @returns {User}
*/
function getPosts(req, res, next) {
var user = req.user;
Post.find({
userId: user._id
})
.sort({
createdAt: -1
})
.populate('userId')
.populate({
path: 'comments',
// Get friends of friends - populate the 'friends' array for every friend
populate: {
path: 'author'
}
})
.exec()
.then(posts => {
console.log(posts);
res.json({
data: posts,
result: 0
})
})
.catch(e => next(e));
}
/**
* get post of ther user
* @returns {User}
*/
function addPost(req, res, next) {
var user = req.user;
var post = new Post({
userId: user._id,
title: req.body.title,
content: req.body.content,
});
post.save()
.then(post => {
console.log(post);
res.json({
data: post,
result: 0
})
})
.catch(e => next(e));
}
function followUser(req, res, next) {
var user = req.user;
User.get(req.body.user_follow_to)
.then((user_follow_to) => {
if (user.following.indexOf(user_follow_to._id) == -1)
user.following.push(user_follow_to._id);
user.save()
.then(result => {
res.json({
result: 0,
data: result
});
})
.catch(e => next(e));
})
.catch(e => next(e));
}
function disconnectUser(req, res, next) {
var user = req.user;
User.get(req.body.user_disconnect_to)
.then(user_disconnect_to => {
var index = user.following.indexOf(user_disconnect_to._id)
if (index > -1)
user.following.splice(index, 1);
user.save()
.then(result => {
res.json({
result: 0,
data: result
});
})
.catch(e => next(e));
})
.catch(e => next(e));
}
function myFeeds(req, res, next) {
var user = req.user;
Post.find({
userId: {
$in: user.following
}
})
.populate('userId')
.populate({
path: 'comments',
// Get friends of friends - populate the 'friends' array for every friend
populate: {
path: 'author'
}
})
// .populate('likeUsers')
.exec()
.then(feeds => {
res.json({
data: feeds,
result: 0
});
})
.catch(e => next(e));
}
// function allUsers(req, res, next) {
// var user = req.user;
// User.find()
// .sort({ createdAt: -1 })
// .exec()
// .then(users => {
// res.json(users)
// })
// .catch(e => next(e));
// }
//----------------------Like system----------------
function likePost(req, res, next) {
// UserPost.find({
// user: req.current_user,
// post: req.body.post_id
// })
// .exec()
// .then(userpost => {
// if(userpost.length == 0){
// new UserPost({
// user: req.current_user,
// post: req.body.post_id
// }).save().then((userpost)=>{
// res.json({
// result:0,
// data:userpost
// });
// })
// }
// else
// {
// res.json({
// result:0,
// data:"You already like it"
// })
// }
// })
// .catch(e => {
// res.json({
// result: 1,
// data: e
// })
// });
Post.get(req.body.post_id)
.then((post) => {
if (post.likeUsers.indexOf(req.current_user._id) == -1)
post.likeUsers.push(req.current_user._id);
post.save()
.then(result => {
res.json({
result: 0,
data: result
});
})
.catch(e => next(e));
})
.catch(e => next(e));
}
function dislikePost(req, res, next) {
// UserPost.remove({
// user: req.current_user,
// post: req.body.post_id
// })
// .exec()
// .then(userpost => {
// res.json({
// result:0,
// data:userpost
// })
// })
// .catch(e => {
// res.json({
// result: 1,
// data: e.message
// })
// });
Post.get(req.body.post_id)
.then((post) => {
if (post.likeUsers.indexOf(req.current_user._id) != -1)
post.likeUsers.splice(post.likeUsers.indexOf(req.current_user._id), 1);
post.save()
.then(result => {
res.json({
result: 0,
data: result
});
})
.catch(e => next(e));
})
.catch(e => next(e));
}
export default {
load,
get,
create,
update,
list,
remove,
updateBasicinfo,
uploadUserimg,
getPosts,
addPost,
followUser,
disconnectUser,
myFeeds,
likePost,
dislikePost
};<|fim▁end|>
|
"lastname": new RegExp(params.query, 'i')
}]
};
}
|
<|file_name|>group.list.resolver.ts<|end_file_name|><|fim▁begin|>import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { GroupService } from '../services/GroupService';
import { Observable } from 'rxjs/Rx';
<|fim▁hole|>
constructor(private groupService: GroupService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
// let id = route.params['id'];
// let id = '106540182994763924496';
return this.groupService.getGroups(0, 100).then(groupsList => {
if (groupsList) {
return groupsList;
} else { // id not found
// this.router.navigate(['/dashboard']);
return null;
};
});
}
}<|fim▁end|>
|
@Injectable()
export class GroupListResolver implements Resolve<any> {
|
<|file_name|>continue_run.hpp<|end_file_name|><|fim▁begin|>/*
* continue_run.hpp
*
* Created on: Aug 14, 2014
* Author: joost
*/
#ifndef CONTINUE_RUN_HPP_
#define CONTINUE_RUN_HPP_
#include <boost/fusion/container.hpp>
#include <boost/fusion/include/vector.hpp>
#include <sferes/dbg/dbg.hpp>
#include "global_options.hpp"
#include <exp/images/stat/stat_map_image.hpp>
namespace sferes
{
namespace cont
{
template<typename EAType, typename Params>
class Continuator
{
public:
typedef typename EAType::raw_pop_t pop_t;
bool enabled()
{
return options::vm.count("continue");
}
/*
* Load the population from the gen file.
* sferes::ea::RankSimple and sferes::ea::MapElites need this method.
*/
pop_t getPopulationFromFile(EAType& ea)
{
ea.load(options::vm["continue"].as<std::string>());
return boost::fusion::at_c<Params::cont::getPopIndex>(ea.stat()).getPopulation();
}
/*
* Load the population from the gen file.
* sferes::ea::RankSimple and sferes::ea::MapElites need this method.
*/
pop_t getPopulationFromFile(EAType& ea, const std::string& path_gen_file)
{
ea.load(path_gen_file);
return boost::fusion::at_c<Params::cont::getPopIndex>(ea.stat()).getPopulation();
}
/*
* Load the population from the gen file.
* sferes::ea::Nsga2 need this method.
*/
pop_t getArchiveFromFile(EAType& ea)
{
ea.load(options::vm["continue"].as<std::string>());
return boost::fusion::at_c<Params::cont::getPopIndex>(ea.stat()).getArchive();
}
/*
* Load the population from the gen file.<|fim▁hole|> pop_t getArchiveFromFile(EAType& ea, const std::string& path_gen_file)
{
ea.load(path_gen_file);
return boost::fusion::at_c<Params::cont::getPopIndex>(ea.stat()).getArchive();
}
void run_with_current_population(EAType& ea, const std::string filename)
{
// Read the number of generation from gen file. Ex: gen_450
int start = 0;
std::string gen_prefix("gen_");
std::size_t pos = filename.rfind(gen_prefix) + gen_prefix.size();
std::string gen_number = filename.substr(pos);
std::istringstream ss(gen_number);
ss >> start;
start++;
dbg::out(dbg::info, "continue") << "File name: " << filename << " number start: " << pos << " gen number: " << gen_number << " result: " << start << std::endl;
// Similar to the run() function in <sferes/ea/ea.hpp>
for (int _gen = start; _gen < Params::pop::nb_gen; ++_gen)
{
ea.setGen(_gen);
ea.epoch();
ea.update_stats();
if (_gen % Params::pop::dump_period == 0)
{
ea.write();
}
}
std::cout << "Finished all the runs.\n";
exit(0);
}
void run_with_current_population(EAType& ea)
{
const std::string filename = options::vm["continue"].as<std::string>();
run_with_current_population(ea, filename);
}
};
}
}
#endif /* CONTINUE_RUN_HPP_ */<|fim▁end|>
|
* sferes::ea::Nsga2 need this method.
*/
|
<|file_name|>pipelines.py<|end_file_name|><|fim▁begin|># Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting<|fim▁hole|> def process_item(self, item, spider):
return item<|fim▁end|>
|
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class Mycar168Pipeline(object):
|
<|file_name|>slack.go<|end_file_name|><|fim▁begin|>package services
import (
"github.com/nlopes/slack"
"fmt"
)
type slackService struct {
token string
channel string
channelId string
serviceName string
api *slack.Client
rtm *slack.RTM
userCache map[string]*slack.User
sent map[string]bool
}
func NewSlack(token, channel, channelId string) slackService {
api := slack.New(token)
rtm := api.NewRTM()
go rtm.ManageConnection()
cache := make(map[string]*slack.User)<|fim▁hole|>func (sl slackService) ExposePortal() Portal {
in := make(chan PortalMessage)
out := make(chan PortalMessage)
go func() {
for {
select {
case msg := <-sl.rtm.IncomingEvents:
sending := sl.triggerMessages(msg, sl.channelId)
if sending.Kind == PORTAL_MESSAGE {
out <- sending
}
case msg := <-in:
sl.listenToMessages(msg)
}
}
}()
return Portal{in, out}
}
func (sl slackService) listenToMessages(msg PortalMessage) {
if (msg.Kind == PORTAL_MESSAGE) {
params := slack.PostMessageParameters{}
params.Username = msg.Author
_, time, err := sl.api.PostMessage(sl.channel, msg.Data, params)
if err != nil {
fmt.Println(err)
}
sl.sent[time] = true
}
}
func (sl slackService) triggerMessages(msg slack.RTMEvent, channel string) PortalMessage {
switch ev := msg.Data.(type) {
case *slack.MessageEvent:
_, hasMessage := sl.sent[ev.Timestamp]
if channel == ev.Channel && !hasMessage {
user, ok := sl.userCache[ev.User]
if !ok {
info, err := sl.api.GetUserInfo(ev.User)
if err != nil {
fmt.Println(err)
}
sl.userCache[ev.User] = info
user = info
}
return PortalMessage{ev.Text, user.Name, sl.serviceName, PORTAL_MESSAGE}
}
}
return PortalMessage{"", "", "", PORTAL_NOOP}
}<|fim▁end|>
|
return slackService{token, channel, channelId, "slack", api, rtm, cache, make(map[string]bool)}
}
|
<|file_name|>challengeboard.py<|end_file_name|><|fim▁begin|>from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from edctf.api.models import challengeboard, category, challenge
from edctf.api.serializers import challengeboard_serializer, category_serializer, challenge_serializer
class challengeboard_view(APIView):
"""
Manages challengeboard requests
"""
permission_classes = (IsAuthenticated,)
def get(self, request, id=None, format=None):
"""
Gets all challengeboards or gets one challengeboard via
challengeboards/:id.
"""
# If challengeboard id was requested, return that challengeboard
# else return list of all challengeboards in the database.
if id:
# Retrieve and serialize the requested challengeboard data.
challengeboards = challengeboard.objects.filter(id=id)
challengeboards_serializer = challengeboard_serializer(challengeboards, many=True, context={'request': request})
# Retrieve and serialize the categories in the challengeboard.
categories = category.objects.filter(challengeboard=challengeboards.first())
categories_serializer = category_serializer(categories, many=True, context={'request': request})
# Retrieve and serialize the challenges in each category.
challenges = []<|fim▁hole|> challenges_serializer = challenge_serializer(challenges, many=True, context={'request': request})
# Return the serialized data.
return Response({
'challengeboards': challengeboards_serializer.data,
'categories': categories_serializer.data,
'challenges': challenges_serializer.data,
})
else:
# Retrieve and serialize the requested challengeboard data.
challengeboards = challengeboard.objects.all()
serializer = challengeboard_serializer(challengeboards, many=True, context={'request': request})
# Return the serialized data.
return Response({
'challengeboards': serializer.data,
})<|fim▁end|>
|
for cat in categories:
challenges += challenge.objects.filter(category=cat)
|
<|file_name|>test_parsers.py<|end_file_name|><|fim▁begin|>import json
from unittest.mock import patch
from federation.hostmeta.parsers import (
parse_nodeinfo_document, parse_nodeinfo2_document, parse_statisticsjson_document, int_or_none,
parse_mastodon_document, parse_matrix_document)
from federation.tests.fixtures.hostmeta import (
NODEINFO2_10_DOC, NODEINFO_10_DOC, NODEINFO_20_DOC, STATISTICS_JSON_DOC, MASTODON_DOC, MASTODON_ACTIVITY_DOC,
MASTODON_RC_DOC, MASTODON_DOC_NULL_CONTACT, MATRIX_SYNAPSE_DOC, PLEROMA_MASTODON_API_DOC,
NODEINFO_21_DOC_INVALID_USAGE_COUNTS, MASTODON_DOC_3)
class TestIntOrNone:
def test_returns_negative_values_as_none(self):
assert int_or_none(-1) is None
class TestParseMastodonDocument:
@patch('federation.hostmeta.fetchers.fetch_nodeinfo_document', autospec=True)
def test_calls_nodeinfo_fetcher_if_pleroma(self, mock_fetch):
parse_mastodon_document(json.loads(PLEROMA_MASTODON_API_DOC), 'example.com')
mock_fetch.assert_called_once_with('example.com')
@patch('federation.hostmeta.parsers.fetch_document')
def test_parse_mastodon_document(self, mock_fetch):
mock_fetch.return_value = MASTODON_ACTIVITY_DOC, 200, None
result = parse_mastodon_document(json.loads(MASTODON_DOC), 'example.com')
assert result == {
'organization': {
'account': 'https://mastodon.local/@Admin',
'contact': '[email protected]',
'name': 'Admin dude',
},
'host': 'example.com',
'name': 'Mastodon',
'open_signups': True,
'protocols': ["ostatus", "activitypub"],
'relay': False,
'server_meta': {},
'services': [],
'platform': 'mastodon',
'version': '2.4.0',
'features': {},
'activity': {
'users': {
'total': 159726,
'half_year': 90774,
'monthly': 27829,
'weekly': 8779,
},
'local_posts': 6059606,
'local_comments': None,
},
}
@patch('federation.hostmeta.parsers.fetch_document')
def test_parse_mastodon_document__null_contact_account(self, mock_fetch):
mock_fetch.return_value = MASTODON_ACTIVITY_DOC, 200, None
result = parse_mastodon_document(json.loads(MASTODON_DOC_NULL_CONTACT), 'example.com')
assert result == {
'organization': {
'account': '',
'contact': '',
'name': '',
},
'host': 'example.com',
'name': 'Mastodon',
'open_signups': True,
'protocols': ["ostatus", "activitypub"],
'relay': False,
'server_meta': {},
'services': [],
'platform': 'mastodon',
'version': '2.4.0',
'features': {},
'activity': {
'users': {
'total': 159726,
'half_year': 90774,
'monthly': 27829,
'weekly': 8779,
},
'local_posts': 6059606,
'local_comments': None,
},
}
@patch('federation.hostmeta.parsers.fetch_document')
def test_parse_mastodon_document__rc_version(self, mock_fetch):
mock_fetch.return_value = MASTODON_ACTIVITY_DOC, 200, None
result = parse_mastodon_document(json.loads(MASTODON_RC_DOC), 'example.com')
assert result == {
'organization': {
'account': 'https://mastodon.local/@Admin',
'contact': '[email protected]',
'name': 'Admin dude',
},
'host': 'example.com',
'name': 'Mastodon',
'open_signups': True,
'protocols': ["ostatus", "activitypub"],
'relay': False,
'server_meta': {},
'services': [],
'platform': 'mastodon',
'version': '2.4.1rc1',
'features': {},
'activity': {
'users': {
'total': 159726,
'half_year': 90774,
'monthly': 27829,
'weekly': 8779,
},
'local_posts': 6059606,
'local_comments': None,
},
}
@patch('federation.hostmeta.parsers.fetch_document')
def test_parse_mastodon_document__protocols(self, mock_fetch):
mock_fetch.return_value = MASTODON_ACTIVITY_DOC, 200, None
result = parse_mastodon_document(json.loads(MASTODON_DOC_3), 'example.com')
assert result == {
'organization': {
'account': 'https://mastodon.local/@Admin',
'contact': '[email protected]',
'name': 'Admin dude',
},
'host': 'example.com',
'name': 'Mastodon',
'open_signups': True,
'protocols': ["activitypub"],
'relay': False,
'server_meta': {},
'services': [],
'platform': 'mastodon',
'version': '3.0.0',
'features': {},
'activity': {
'users': {
'total': 159726,
'half_year': 90774,
'monthly': 27829,
'weekly': 8779,
},
'local_posts': 6059606,
'local_comments': None,
},
}
class TestParseMatrixDocument:
@patch('federation.hostmeta.parsers.send_document', autospec=True, return_value=(403, None))
def test_parse_matrix_document__signups_closed(self, mock_send):
result = parse_matrix_document(json.loads(MATRIX_SYNAPSE_DOC), 'feneas.org')
assert result == {
'organization': {
'account': '',
'contact': '',
'name': '',
},
'host': 'feneas.org',
'name': 'feneas.org',
'open_signups': False,
'protocols': ['matrix'],
'relay': '',
'server_meta': {},
'services': [],
'platform': 'matrix|synapse',
'version': '0.33.8',
'features': {},
'activity': {
'users': {
'total': None,
'half_year': None,
'monthly': None,
'weekly': None,
},
'local_posts': None,
'local_comments': None,
},
}
@patch('federation.hostmeta.parsers.send_document', autospec=True, return_value=(401, None))
def test_parse_matrix_document__signups_open(self, mock_send):
result = parse_matrix_document(json.loads(MATRIX_SYNAPSE_DOC), 'feneas.org')
assert result == {
'organization': {
'account': '',
'contact': '',
'name': '',
},
'host': 'feneas.org',
'name': 'feneas.org',
'open_signups': True,
'protocols': ['matrix'],
'relay': '',
'server_meta': {},
'services': [],
'platform': 'matrix|synapse',
'version': '0.33.8',
'features': {},
'activity': {
'users': {
'total': None,
'half_year': None,
'monthly': None,
'weekly': None,
},
'local_posts': None,
'local_comments': None,
},
}
class TestParseNodeInfoDocument:
def test_parse_nodeinfo_10_document(self):
result = parse_nodeinfo_document(json.loads(NODEINFO_10_DOC), 'iliketoast.net')
assert result == {
'organization': {
'account': '[email protected]',
'contact': '',
'name': '',
},
'host': 'iliketoast.net',
'name': 'I Like Toast',
'open_signups': True,
'protocols': ["diaspora"],
'relay': '',
'server_meta': {},
'services': ["tumblr", "twitter"],
'platform': 'diaspora',
'version': '0.7.4.0-pd0313756',
'features': {
"nodeName": "I Like Toast",
"xmppChat": False,
"camo": {
"markdown": False,
"opengraph": False,
"remotePods": False
},
"adminAccount": "podmin",
},
'activity': {
'users': {
'total': 348,
'half_year': 123,
'monthly': 62,
'weekly': 19,
},
'local_posts': 8522,
'local_comments': 17671,
},
}
def test_parse_nodeinfo_20_document(self):
result = parse_nodeinfo_document(json.loads(NODEINFO_20_DOC), 'iliketoast.net')
assert result == {
'organization': {
'account': '[email protected]',
'contact': '',
'name': '',
},
'host': 'iliketoast.net',
'name': 'I Like Toast',
'open_signups': True,
'protocols': ["diaspora"],
'relay': '',
'server_meta': {},
'services': ["tumblr", "twitter"],
'platform': 'diaspora',
'version': '0.7.4.0-pd0313756',
'features': {
"nodeName": "I Like Toast",
"xmppChat": False,
"camo": {
"markdown": False,
"opengraph": False,
"remotePods": False
},
"adminAccount": "podmin",
},
'activity': {
'users': {
'total': 348,
'half_year': 123,
'monthly': 62,
'weekly': 19,
},
'local_posts': 8522,
'local_comments': 17671,
},
}
def test_parse_nodeinfo_21_document__invalid_usage_counts(self):
result = parse_nodeinfo_document(json.loads(NODEINFO_21_DOC_INVALID_USAGE_COUNTS), 'pleroma.local')
assert result == {
'organization': {
'account': '',
'contact': '',
'name': '',
},
'host': 'pleroma.local',
'name': 'pleroma.local',
'open_signups': True,
'protocols': ["activitypub"],
'relay': '',
'server_meta': {},
'services': [],
'platform': 'pleroma',
'version': '0.7.4.0-pd0313756',
'features': {},
'activity': {
'users': {
'total': 348,
'half_year': None,
'monthly': None,
'weekly': None,
},
'local_posts': None,
'local_comments': None,
},
}
class TestParseNodeInfo2Document:
def test_parse_nodeinfo2_10_document(self):
result = parse_nodeinfo2_document(json.loads(NODEINFO2_10_DOC), 'example.com')
assert result == {
'organization': {
'account': 'https://example.com/u/admin',
'contact': '[email protected]',
'name': 'Example organization',
},
'host': 'example.com',
'name': 'Example server',
'open_signups': True,
'protocols': ["diaspora", "zot"],
'relay': "tags",
'server_meta': {},
'services': ["facebook", "gnusocial", "twitter"],
'platform': 'example',
'version': '0.5.0',
'features': {},
'activity': {
'users': {
'total': 123,
'half_year': 42,
'monthly': 23,
'weekly': 10,
},
'local_posts': 500,
'local_comments': 1000,
},
}
def test_parse_nodeinfo2_10_document__cleans_port_from_host(self):
response = json.loads(NODEINFO2_10_DOC)
response["server"]["baseUrl"] = "https://example.com:5221"
result = parse_nodeinfo2_document(response, 'example.com')
assert result == {
'organization': {
'account': 'https://example.com/u/admin',
'contact': '[email protected]',
'name': 'Example organization',
},
'host': 'example.com',
'name': 'Example server',
'open_signups': True,
'protocols': ["diaspora", "zot"],
'relay': "tags",
'server_meta': {},
'services': ["facebook", "gnusocial", "twitter"],
'platform': 'example',
'version': '0.5.0',
'features': {},
'activity': {
'users': {
'total': 123,
'half_year': 42,
'monthly': 23,
'weekly': 10,
},
'local_posts': 500,
'local_comments': 1000,
},
}<|fim▁hole|> def test_parse_statisticsjson_document(self):
result = parse_statisticsjson_document(json.loads(STATISTICS_JSON_DOC), 'example.com')
assert result == {
'organization': {
'account': '',
'contact': '',
'name': '',
},
'host': 'example.com',
'name': 'diaspora*',
'open_signups': True,
'protocols': ["diaspora"],
'relay': '',
'server_meta': {},
'services': [],
'platform': 'diaspora',
'version': '0.5.7.0-p56ebcc76',
'features': {},
'activity': {
'users': {
'total': None,
'half_year': None,
'monthly': None,
'weekly': None,
},
'local_posts': None,
'local_comments': None,
},
}<|fim▁end|>
|
class TestParseStatisticsJSONDocument:
|
<|file_name|>extract_references.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os, sys, codecs, re
def usage():
print "Usage info for extract_references.py"
print " extract_references.py ref_sgml ref_prefix"
print
sys.exit()
def main():
if (len(sys.argv) < 3 or sys.argv[1] == "-h"):
usage()
sgml = codecs.open(sys.argv[1], "r", "utf-8")
prefix = sys.argv[2]<|fim▁hole|> ref_sets = []
cur_ref_set = []
cur_doc = ""
cur_seg = ""
cur_txt = ""
for line in sgml.readlines():
line_tc = line.strip()
line = line_tc.lower()
if ("<doc " in line):
cur_doc = doc_pattern.search(line).groups()[0]
if ("</refset " in line or
("<doc " in line and cur_doc in map(lambda x: x[0], cur_ref_set))):
ref_sets.append(cur_ref_set)
cur_ref_set = []
if ("<seg " in line):
cur_seg = seg_pattern.search(line).groups()[0]
cur_txt = re.sub("<[^>]*>", "", line_tc)
cur_ref_set.append((cur_doc, cur_seg, cur_txt))
ref_files = []
ref_count = len(ref_sets[0])
for i, ref_set in enumerate(ref_sets):
if (ref_count != len(ref_set)):
print "[ERR] reference lengths do not match: " + str(ref_count) \
+ " vs. " + str(len(ref_set)) + " (ref " + str(i) + ")"
ref_files.append(codecs.open(prefix + "_ref." + str(i), "w", "utf-8"))
for j in range(ref_count):
(cur_doc, cur_seg, cur_txt) = ref_sets[0][j]
for i in range(len(ref_sets)):
if (j >= len(ref_sets[i])):
continue
(doc, seg, txt) = ref_sets[i][j]
if (doc != cur_doc or seg != cur_seg):
print "[ERR] document, segment ids don't match up: "
print "\t" + doc + " vs. " + cur_doc
print "\t" + seg + " vs. " + cur_seg
ref_files[i].write(txt + "\n")
for ref_file in ref_files:
ref_file.close()
if __name__ == "__main__":
main()<|fim▁end|>
|
doc_pattern = re.compile('.* docid="([^"]*).*"')
seg_pattern = re.compile('.* id="([^"]*)".*')
|
<|file_name|>test_plotter.py<|end_file_name|><|fim▁begin|># Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import json
import os
import unittest
from monty.json import MontyDecoder
from pymatgen.apps.battery.conversion_battery import ConversionElectrode
from pymatgen.apps.battery.insertion_battery import InsertionElectrode
from pymatgen.apps.battery.plotter import VoltageProfilePlotter
from pymatgen.core.composition import Composition
from pymatgen.entries.computed_entries import ComputedEntry
from pymatgen.util.testing import PymatgenTest
class VoltageProfilePlotterTest(unittest.TestCase):
def setUp(self):
entry_Li = ComputedEntry("Li", -1.90753119)
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "LiTiO2_batt.json")) as f:
entries_LTO = json.load(f, cls=MontyDecoder)
self.ie_LTO = InsertionElectrode.from_entries(entries_LTO, entry_Li)
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "FeF3_batt.json")) as fid:
entries = json.load(fid, cls=MontyDecoder)
self.ce_FF = ConversionElectrode.from_composition_and_entries(Composition("FeF3"), entries)
def testName(self):
plotter = VoltageProfilePlotter(xaxis="frac_x")
plotter.add_electrode(self.ie_LTO, "LTO insertion")
plotter.add_electrode(self.ce_FF, "FeF3 conversion")
self.assertIsNotNone(plotter.get_plot_data(self.ie_LTO))
self.assertIsNotNone(plotter.get_plot_data(self.ce_FF))
def testPlotly(self):
plotter = VoltageProfilePlotter(xaxis="frac_x")
plotter.add_electrode(self.ie_LTO, "LTO insertion")
plotter.add_electrode(self.ce_FF, "FeF3 conversion")
fig = plotter.get_plotly_figure()
self.assertEqual(fig.layout.xaxis.title.text, "Atomic Fraction of Li")
plotter = VoltageProfilePlotter(xaxis="x_form")
plotter.add_electrode(self.ce_FF, "FeF3 conversion")
fig = plotter.get_plotly_figure()<|fim▁hole|> self.assertEqual(fig.layout.xaxis.title.text, "x in Li<sub>x</sub>FeF3")
plotter.add_electrode(self.ie_LTO, "LTO insertion")
fig = plotter.get_plotly_figure()
self.assertEqual(fig.layout.xaxis.title.text, "x Workion Ion per Host F.U.")
if __name__ == "__main__":
unittest.main()<|fim▁end|>
| |
<|file_name|>mxHandle.js<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2006-2015, JGraph Ltd
* Copyright (c) 2006-2015, Gaudenz Alder
*/
/**
* Class: mxHandle
*
* Implements a single custom handle for vertices.
*
* Constructor: mxHandle
*
* Constructs a new handle for the given state.
*
* Parameters:
*
* state - <mxCellState> of the cell to be handled.
*/
function mxHandle(state, cursor, image)
{
this.graph = state.view.graph;
this.state = state;
this.cursor = (cursor != null) ? cursor : this.cursor;
this.image = (image != null) ? image : this.image;
this.init();
};
/**
* Variable: cursor
*
* Specifies the cursor to be used for this handle. Default is 'default'.
*/
mxHandle.prototype.cursor = 'default';
/**
* Variable: image
*
* Specifies the <mxImage> to be used to render the handle. Default is null.
*/
mxHandle.prototype.image = null;
/**
* Variable: image
*
* Specifies the <mxImage> to be used to render the handle. Default is null.
*/
mxHandle.prototype.ignoreGrid = false;
/**
* Function: getPosition
*
* Hook for subclassers to return the current position of the handle.
*/
mxHandle.prototype.getPosition = function(bounds) { };
/**
* Function: setPosition
*
* Hooks for subclassers to update the style in the <state>.
*/
mxHandle.prototype.setPosition = function(bounds, pt, me) { };
/**
* Function: execute
*
* Hook for subclassers to execute the handle.
*/
mxHandle.prototype.execute = function() { };
/**
* Function: copyStyle
*
* Sets the cell style with the given name to the corresponding value in <state>.
*/
mxHandle.prototype.copyStyle = function(key)
{
this.graph.setCellStyles(key, this.state.style[key], [this.state.cell]);
};
/**
* Function: processEvent
*
* Processes the given <mxMouseEvent> and invokes <setPosition>.
*/
mxHandle.prototype.processEvent = function(me)
{
var scale = this.graph.view.scale;
var tr = this.graph.view.translate;
var pt = new mxPoint(me.getGraphX() / scale - tr.x, me.getGraphY() / scale - tr.y);
// Center shape on mouse cursor
if (this.shape != null && this.shape.bounds != null)
{
pt.x -= this.shape.bounds.width / scale / 4;
pt.y -= this.shape.bounds.height / scale / 4;
}
// Snaps to grid for the rotated position then applies the rotation for the direction after that
var alpha1 = -mxUtils.toRadians(this.getRotation());
var alpha2 = -mxUtils.toRadians(this.getTotalRotation()) - alpha1;
pt = this.flipPoint(this.rotatePoint(this.snapPoint(this.rotatePoint(pt, alpha1),
this.ignoreGrid || !this.graph.isGridEnabledEvent(me.getEvent())), alpha2));
this.setPosition(this.state.getPaintBounds(), pt, me);
this.positionChanged();
this.redraw();
};
/**
* Function: positionChanged<|fim▁hole|> */
mxHandle.prototype.positionChanged = function()
{
if (this.state.text != null)
{
this.state.text.apply(this.state);
}
if (this.state.shape != null)
{
this.state.shape.apply(this.state);
}
this.graph.cellRenderer.redraw(this.state, true);
};
/**
* Function: getRotation
*
* Returns the rotation defined in the style of the cell.
*/
mxHandle.prototype.getRotation = function()
{
if (this.state.shape != null)
{
return this.state.shape.getRotation();
}
return 0;
};
/**
* Function: getTotalRotation
*
* Returns the rotation from the style and the rotation from the direction of
* the cell.
*/
mxHandle.prototype.getTotalRotation = function()
{
if (this.state.shape != null)
{
return this.state.shape.getShapeRotation();
}
return 0;
};
/**
* Function: init
*
* Creates and initializes the shapes required for this handle.
*/
mxHandle.prototype.init = function()
{
var html = this.isHtmlRequired();
if (this.image != null)
{
this.shape = new mxImageShape(new mxRectangle(0, 0, this.image.width, this.image.height), this.image.src);
this.shape.preserveImageAspect = false;
}
else
{
this.shape = this.createShape(html);
}
this.initShape(html);
};
/**
* Function: createShape
*
* Creates and returns the shape for this handle.
*/
mxHandle.prototype.createShape = function(html)
{
var bounds = new mxRectangle(0, 0, mxConstants.HANDLE_SIZE, mxConstants.HANDLE_SIZE);
return new mxRectangleShape(bounds, mxConstants.HANDLE_FILLCOLOR, mxConstants.HANDLE_STROKECOLOR);
};
/**
* Function: initShape
*
* Initializes <shape> and sets its cursor.
*/
mxHandle.prototype.initShape = function(html)
{
if (html && this.shape.isHtmlAllowed())
{
this.shape.dialect = mxConstants.DIALECT_STRICTHTML;
this.shape.init(this.graph.container);
}
else
{
this.shape.dialect = (this.graph.dialect != mxConstants.DIALECT_SVG) ? mxConstants.DIALECT_MIXEDHTML : mxConstants.DIALECT_SVG;
if (this.cursor != null)
{
this.shape.init(this.graph.getView().getOverlayPane());
}
}
mxEvent.redirectMouseEvents(this.shape.node, this.graph, this.state);
this.shape.node.style.cursor = this.cursor;
};
/**
* Function: redraw
*
* Renders the shape for this handle.
*/
mxHandle.prototype.redraw = function()
{
if (this.shape != null && this.state.shape != null)
{
var pt = this.getPosition(this.state.getPaintBounds());
if (pt != null)
{
var alpha = mxUtils.toRadians(this.getTotalRotation());
pt = this.rotatePoint(this.flipPoint(pt), alpha);
var scale = this.graph.view.scale;
var tr = this.graph.view.translate;
this.shape.bounds.x = Math.floor((pt.x + tr.x) * scale - this.shape.bounds.width / 2);
this.shape.bounds.y = Math.floor((pt.y + tr.y) * scale - this.shape.bounds.height / 2);
// Needed to force update of text bounds
this.state.unscaledWidth = null;
this.shape.redraw();
}
}
};
/**
* Function: isHtmlRequired
*
* Returns true if this handle should be rendered in HTML. This returns true if
* the text node is in the graph container.
*/
mxHandle.prototype.isHtmlRequired = function()
{
return this.state.text != null && this.state.text.node.parentNode == this.graph.container;
};
/**
* Function: rotatePoint
*
* Rotates the point by the given angle.
*/
mxHandle.prototype.rotatePoint = function(pt, alpha)
{
var bounds = this.state.getCellBounds();
var cx = new mxPoint(bounds.getCenterX(), bounds.getCenterY());
var cos = Math.cos(alpha);
var sin = Math.sin(alpha);
return mxUtils.getRotatedPoint(pt, cos, sin, cx);
};
/**
* Function: flipPoint
*
* Flips the given point vertically and/or horizontally.
*/
mxHandle.prototype.flipPoint = function(pt)
{
if (this.state.shape != null)
{
var bounds = this.state.getCellBounds();
if (this.state.shape.flipH)
{
pt.x = 2 * bounds.x + bounds.width - pt.x;
}
if (this.state.shape.flipV)
{
pt.y = 2 * bounds.y + bounds.height - pt.y;
}
}
return pt;
};
/**
* Function: snapPoint
*
* Snaps the given point to the grid if ignore is false. This modifies
* the given point in-place and also returns it.
*/
mxHandle.prototype.snapPoint = function(pt, ignore)
{
if (!ignore)
{
pt.x = this.graph.snap(pt.x);
pt.y = this.graph.snap(pt.y);
}
return pt;
};
/**
* Function: setVisible
*
* Shows or hides this handle.
*/
mxHandle.prototype.setVisible = function(visible)
{
if (this.shape != null && this.shape.node != null)
{
this.shape.node.style.display = (visible) ? '' : 'none';
}
};
/**
* Function: reset
*
* Resets the state of this handle by setting its visibility to true.
*/
mxHandle.prototype.reset = function()
{
this.setVisible(true);
this.state.style = this.graph.getCellStyle(this.state.cell);
this.positionChanged();
};
/**
* Function: destroy
*
* Destroys this handle.
*/
mxHandle.prototype.destroy = function()
{
if (this.shape != null)
{
this.shape.destroy();
this.shape = null;
}
};<|fim▁end|>
|
*
* Called after <setPosition> has been called in <processEvent>. This repaints
* the state using <mxCellRenderer>.
|
<|file_name|>mount_da_DK.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="da_DK">
<context>
<name>DeviceActionInfo</name>
<message>
<location filename="../actions/deviceaction_info.cpp" line="45"/>
<source>The device <b><nobr>"%1"</nobr></b> is connected.</source>
<translation type="unfinished">Enheden <b><nobr>"%1"</nobr></b> er forbundet.</translation>
</message>
<message>
<location filename="../actions/deviceaction_info.cpp" line="53"/>
<source>The device <b><nobr>"%1"</nobr></b> is removed.</source>
<translation type="unfinished">Enheden <b><nobr>"%1"</nobr></b> er fjernet.</translation>
</message>
<message>
<location filename="../actions/deviceaction_info.cpp" line="59"/>
<source>Removable media/devices manager</source>
<translation type="unfinished">Håndtering af flytbare medier</translation>
</message>
</context>
<context>
<name>LxQtMountConfiguration</name>
<message>
<source>LxQt Removable media manager settings</source>
<translation type="vanished">Indstillinger til håndtering af flytbare enheder</translation>
</message>
<message>
<location filename="../lxqtmountconfiguration.ui" line="14"/>
<source>Removable Media Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqtmountconfiguration.ui" line="20"/><|fim▁hole|> <message>
<location filename="../lxqtmountconfiguration.ui" line="26"/>
<source>When a device is connected </source>
<translation>Når en enhed tilsluttes </translation>
</message>
<message>
<location filename="../lxqtmountconfiguration.cpp" line="44"/>
<source>Popup menu</source>
<translation>Popup menu</translation>
</message>
<message>
<location filename="../lxqtmountconfiguration.cpp" line="45"/>
<source>Show info</source>
<translation>Vis info</translation>
</message>
<message>
<location filename="../lxqtmountconfiguration.cpp" line="46"/>
<source>Do nothing</source>
<translation>Gør ingenting</translation>
</message>
</context>
<context>
<name>MenuDiskItem</name>
<message>
<source>Click to access this device from other applications.</source>
<translation type="vanished">Klik for at give adgang fra andre programmer.</translation>
</message>
<message>
<source>Click to eject this disc.</source>
<translation type="vanished">Skub ud.</translation>
</message>
</context>
<context>
<name>MountButton</name>
<message>
<location filename="../mountbutton.cpp" line="39"/>
<source>Removable media/devices manager</source>
<translation>Håndtering af flytbare medier</translation>
</message>
<message>
<source>The device <b><nobr>"%1"</nobr></b> is connected.</source>
<translation type="vanished">Enheden <b><nobr>"%1"</nobr></b> er forbundet.</translation>
</message>
<message>
<source>The device <b><nobr>"%1"</nobr></b> is removed.</source>
<translation type="vanished">Enheden <b><nobr>"%1"</nobr></b> er fjernet.</translation>
</message>
<message>
<source>No devices Available.</source>
<translation type="vanished">Ingen enheder tilgængelige.</translation>
</message>
</context>
<context>
<name>Popup</name>
<message>
<location filename="../popup.cpp" line="56"/>
<source>No devices are available</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS><|fim▁end|>
|
<source>Behaviour</source>
<translation>Adfærd</translation>
</message>
|
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>"""
Django settings for huts project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""<|fim▁hole|>
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1&1@xh%(guq+b#1&jv$e6pa9n6sm_w#9cia1)(+idj1)omok(*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
CORS_ORIGIN_ALLOW_ALL = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hut',
'rest_framework',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
MIDDLEWARE_CLASSES = []
ROOT_URLCONF = 'huts.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'huts.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': dj_database_url.config(default='postgres://nxhxalrlqkckbd:1f8179624d9a773c8de38b1303b149283dfd58238fb10d0509cb85be49edcc2a@ec2-54-247-99-159.eu-west-1.compute.amazonaws.com:5432/d9tipol4jem759')
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# # Static files (CSS, JavaScript, Images)
# # https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(os.path.dirname(__file__), '../static_cdn')
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '../media_cdn')
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 2,
}<|fim▁end|>
|
import os
import dj_database_url
|
<|file_name|>gtk.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# 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 datetime
import thread, time, ast, sys, re
import socket, traceback
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject, cairo
from decimal import Decimal
from electrum.util import print_error, InvalidPassword
from electrum.bitcoin import is_valid, COIN
from electrum.wallet import NotEnoughFunds
from electrum import WalletStorage, Wallet
Gdk.threads_init()
APP_NAME = "Electrum"
import platform
MONOSPACE_FONT = 'Lucida Console' if platform.system() == 'Windows' else 'monospace'
from electrum.util import format_satoshis, parse_URI
from electrum.bitcoin import MIN_RELAY_TX_FEE
def numbify(entry, is_int = False):
text = entry.get_text().strip()
chars = '0123456789'
if not is_int: chars +='.'
s = ''.join([i for i in text if i in chars])
if not is_int:
if '.' in s:
p = s.find('.')
s = s.replace('.','')
s = s[:p] + '.' + s[p:p+8]
try:
amount = int(Decimal(s) * COIN)
except Exception:
amount = None
else:
try:
amount = int( s )
except Exception:
amount = None
entry.set_text(s)
return amount
def show_seed_dialog(seed, parent):
if not seed:
show_message("No seed")
return
dialog = Gtk.MessageDialog(
parent = parent,
flags = Gtk.DialogFlags.MODAL,
buttons = Gtk.ButtonsType.OK,
message_format = "Your wallet generation seed is:\n\n" + '"' + seed + '"'\
+ "\n\nPlease keep it in a safe place; if you lose it, you will not be able to restore your wallet.\n\n" )
dialog.set_title("Seed")
dialog.show()
dialog.run()
dialog.destroy()
def restore_create_dialog():
# ask if the user wants to create a new wallet, or recover from a seed.
# if he wants to recover, and nothing is found, do not create wallet
dialog = Gtk.Dialog("electrum", parent=None,
flags=Gtk.DialogFlags.MODAL,
buttons= ("create", 0, "restore",1, "cancel",2) )
label = Gtk.Label("Wallet file not found.\nDo you want to create a new wallet,\n or to restore an existing one?" )
label.show()
dialog.vbox.pack_start(label, True, True, 0)
dialog.show()
r = dialog.run()
dialog.destroy()
if r==2: return False
return 'restore' if r==1 else 'create'
def run_recovery_dialog():
message = "Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet."
dialog = Gtk.MessageDialog(
parent = None,
flags = Gtk.DialogFlags.MODAL,
buttons = Gtk.ButtonsType.OK_CANCEL,
message_format = message)
vbox = dialog.vbox
dialog.set_default_response(Gtk.ResponseType.OK)
# ask seed, server and gap in the same dialog
seed_box = Gtk.HBox()
seed_label = Gtk.Label(label='Seed or mnemonic:')
seed_label.set_size_request(150,-1)
seed_box.pack_start(seed_label, False, False, 10)
seed_label.show()
seed_entry = Gtk.Entry()
seed_entry.show()
seed_entry.set_size_request(450,-1)
seed_box.pack_start(seed_entry, False, False, 10)
add_help_button(seed_box, '.')
seed_box.show()
vbox.pack_start(seed_box, False, False, 5)
<|fim▁hole|> dialog.show()
r = dialog.run()
seed = seed_entry.get_text()
dialog.destroy()
if r==Gtk.ResponseType.CANCEL:
return False
if Wallet.is_seed(seed):
return seed
show_message("no seed")
return False
def run_settings_dialog(self):
message = "Here are the settings of your wallet. For more explanations, click on the question mark buttons next to each input field."
dialog = Gtk.MessageDialog(
parent = self.window,
flags = Gtk.DialogFlags.MODAL,
buttons = Gtk.ButtonsType.OK_CANCEL,
message_format = message)
image = Gtk.Image()
image.set_from_stock(Gtk.STOCK_PREFERENCES, Gtk.IconSize.DIALOG)
image.show()
dialog.set_image(image)
dialog.set_title("Settings")
vbox = dialog.vbox
dialog.set_default_response(Gtk.ResponseType.OK)
fee = Gtk.HBox()
fee_entry = Gtk.Entry()
fee_label = Gtk.Label(label='Transaction fee:')
fee_label.set_size_request(150,10)
fee_label.show()
fee.pack_start(fee_label,False, False, 10)
fee_entry.set_text(str(Decimal(self.wallet.fee_per_kb) / COIN))
fee_entry.connect('changed', numbify, False)
fee_entry.show()
fee.pack_start(fee_entry,False,False, 10)
add_help_button(fee, 'Fee per kilobyte of transaction. Recommended value:0.0001')
fee.show()
vbox.pack_start(fee, False,False, 5)
nz = Gtk.HBox()
nz_entry = Gtk.Entry()
nz_label = Gtk.Label(label='Display zeros:')
nz_label.set_size_request(150,10)
nz_label.show()
nz.pack_start(nz_label,False, False, 10)
nz_entry.set_text( str( self.num_zeros ))
nz_entry.connect('changed', numbify, True)
nz_entry.show()
nz.pack_start(nz_entry,False,False, 10)
add_help_button(nz, "Number of zeros displayed after the decimal point.\nFor example, if this number is 2, then '5.' is displayed as '5.00'")
nz.show()
vbox.pack_start(nz, False,False, 5)
dialog.show()
r = dialog.run()
fee = fee_entry.get_text()
nz = nz_entry.get_text()
dialog.destroy()
if r==Gtk.ResponseType.CANCEL:
return
try:
fee = int(COIN * Decimal(fee))
except Exception:
show_message("error")
return
self.config.set_key('fee_per_kb', fee)
try:
nz = int( nz )
if nz>8: nz = 8
except Exception:
show_message("error")
return
if self.num_zeros != nz:
self.num_zeros = nz
self.config.set_key('num_zeros',nz,True)
self.update_history_tab()
def run_network_dialog( network, parent ):
image = Gtk.Image()
image.set_from_stock(Gtk.STOCK_NETWORK, Gtk.IconSize.DIALOG)
host, port, protocol, proxy_config, auto_connect = network.get_parameters()
server = "%s:%s:%s"%(host, port, protocol)
if parent:
if network.is_connected():
status = "Connected to %s\n%d blocks"%(host, network.get_local_height())
else:
status = "Not connected"
else:
import random
status = "Please choose a server.\nSelect cancel if you are offline."
servers = network.get_servers()
dialog = Gtk.MessageDialog( parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.QUESTION, Gtk.ButtonsType.OK_CANCEL, status)
dialog.set_title("Server")
dialog.set_image(image)
image.show()
vbox = dialog.vbox
host_box = Gtk.HBox()
host_label = Gtk.Label(label='Connect to:')
host_label.set_size_request(100,-1)
host_label.show()
host_box.pack_start(host_label, False, False, 10)
host_entry = Gtk.Entry()
host_entry.set_size_request(200,-1)
if network.is_connected():
host_entry.set_text(server)
else:
host_entry.set_text("Not Connected")
host_entry.show()
host_box.pack_start(host_entry, False, False, 10)
add_help_button(host_box, 'The name, port number and protocol of your Electrum server, separated by a colon. Example: "ecdsa.org:50002:s". Some servers allow you to connect through http (port 80) or https (port 443)')
host_box.show()
p_box = Gtk.HBox(False, 10)
p_box.show()
p_label = Gtk.Label(label='Protocol:')
p_label.set_size_request(100,-1)
p_label.show()
p_box.pack_start(p_label, False, False, 10)
combobox = Gtk.ComboBoxText()
combobox.show()
combobox.append_text("TCP")
combobox.append_text("SSL")
combobox.append_text("HTTP")
combobox.append_text("HTTPS")
p_box.pack_start(combobox, True, True, 0)
def current_line():
return unicode(host_entry.get_text()).split(':')
def set_combobox(protocol):
combobox.set_active('tshg'.index(protocol))
def set_protocol(protocol):
host = current_line()[0]
pp = servers[host]
if protocol not in pp.keys():
protocol = pp.keys()[0]
set_combobox(protocol)
port = pp[protocol]
host_entry.set_text( host + ':' + port + ':' + protocol)
combobox.connect("changed", lambda x:set_protocol('tshg'[combobox.get_active()]))
if network.is_connected():
set_combobox(protocol)
server_list = Gtk.ListStore(str)
for host in servers.keys():
server_list.append([host])
treeview = Gtk.TreeView(model=server_list)
treeview.show()
label = 'Active Servers' if network.is_connected() else 'Default Servers'
tvcolumn = Gtk.TreeViewColumn(label)
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
tvcolumn.pack_start(cell, False)
tvcolumn.add_attribute(cell, 'text', 0)
vbox.pack_start(host_box, False,False, 5)
vbox.pack_start(p_box, True, True, 0)
#scroll = Gtk.ScrolledWindow()
#scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS)
#scroll.add_with_viewport(treeview)
#scroll.show()
#vbox.pack_start(scroll, True)
vbox.pack_start(treeview, True, True, 0)
def my_treeview_cb(treeview):
path, view_column = treeview.get_cursor()
host = server_list.get_value( server_list.get_iter(path), 0)
pp = servers[host]
if 't' in pp.keys():
protocol = 't'
else:
protocol = pp.keys()[0]
port = pp[protocol]
host_entry.set_text( host + ':' + port + ':' + protocol)
set_combobox(protocol)
treeview.connect('cursor-changed', my_treeview_cb)
dialog.show_all()
r = dialog.run()
server = host_entry.get_text()
dialog.destroy()
if r==Gtk.ResponseType.CANCEL:
return False
try:
host, port, protocol = server.split(':')
except Exception:
show_message("error:" + server)
return False
network.set_parameters(host, port, protocol, proxy_config, auto_connect)
def show_message(message, parent=None):
dialog = Gtk.MessageDialog(
parent = parent,
flags = Gtk.DialogFlags.MODAL,
buttons = Gtk.ButtonsType.CLOSE,
message_format = message )
dialog.show()
dialog.run()
dialog.destroy()
def password_line(label):
password = Gtk.HBox()
password_label = Gtk.Label(label=label)
password_label.set_size_request(120,10)
password_label.show()
password.pack_start(password_label,False, False, 10)
password_entry = Gtk.Entry()
password_entry.set_size_request(300,-1)
password_entry.set_visibility(False)
password_entry.show()
password.pack_start(password_entry,False,False, 10)
password.show()
return password, password_entry
def password_dialog(parent):
dialog = Gtk.MessageDialog( parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.QUESTION, Gtk.ButtonsType.OK_CANCEL, "Please enter your password.")
dialog.get_image().set_visible(False)
current_pw, current_pw_entry = password_line('Password:')
current_pw_entry.connect("activate", lambda entry, dialog, response: dialog.response(response), dialog, Gtk.ResponseType.OK)
dialog.vbox.pack_start(current_pw, False, True, 0)
dialog.show()
result = dialog.run()
pw = current_pw_entry.get_text()
dialog.destroy()
if result != Gtk.ResponseType.CANCEL: return pw
def change_password_dialog(is_encrypted, parent):
if parent:
msg = 'Your wallet is encrypted. Use this dialog to change the password. To disable wallet encryption, enter an empty new password.' if is_encrypted else 'Your wallet keys are not encrypted'
else:
msg = "Please choose a password to encrypt your wallet keys"
dialog = Gtk.MessageDialog( parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.QUESTION, Gtk.ButtonsType.OK_CANCEL, msg)
dialog.set_title("Change password")
image = Gtk.Image()
image.set_from_stock(Gtk.STOCK_DIALOG_AUTHENTICATION, Gtk.IconSize.DIALOG)
image.show()
dialog.set_image(image)
if is_encrypted:
current_pw, current_pw_entry = password_line('Current password:')
dialog.vbox.pack_start(current_pw, False, True, 0)
password, password_entry = password_line('New password:')
dialog.vbox.pack_start(password, False, True, 5)
password2, password2_entry = password_line('Confirm password:')
dialog.vbox.pack_start(password2, False, True, 5)
dialog.show()
result = dialog.run()
password = current_pw_entry.get_text() if is_encrypted else None
new_password = password_entry.get_text()
new_password2 = password2_entry.get_text()
dialog.destroy()
if result == Gtk.ResponseType.CANCEL:
return
if new_password != new_password2:
show_message("passwords do not match")
return change_password_dialog(is_encrypted, parent)
if not new_password:
new_password = None
return True, password, new_password
def add_help_button(hbox, message):
button = Gtk.Button('?')
button.connect("clicked", lambda x: show_message(message))
button.show()
hbox.pack_start(button,False, False, 0)
class ElectrumWindow:
def show_message(self, msg):
show_message(msg, self.window)
def on_key(self, w, event):
if Gdk.ModifierType.CONTROL_MASK & event.state and event.keyval in [113,119]:
Gtk.main_quit()
return True
def __init__(self, wallet, config, network):
self.config = config
self.wallet = wallet
self.network = network
self.funds_error = False # True if not enough funds
self.num_zeros = int(self.config.get('num_zeros',0))
self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
self.window.connect('key-press-event', self.on_key)
title = 'Electrum ' + self.wallet.electrum_version + ' - ' + self.config.path
if not self.wallet.seed: title += ' [seedless]'
self.window.set_title(title)
self.window.connect("destroy", Gtk.main_quit)
self.window.set_border_width(0)
#self.window.connect('mykeypress', Gtk.main_quit)
self.window.set_default_size(720, 350)
self.wallet_updated = False
from electrum.util import StoreDict
self.contacts = StoreDict(self.config, 'contacts')
vbox = Gtk.VBox()
self.notebook = Gtk.Notebook()
self.create_history_tab()
if self.wallet.seed:
self.create_send_tab()
self.create_recv_tab()
self.create_book_tab()
self.create_about_tab()
self.notebook.show()
vbox.pack_start(self.notebook, True, True, 2)
self.status_bar = Gtk.Statusbar()
vbox.pack_start(self.status_bar, False, False, 0)
self.status_image = Gtk.Image()
self.status_image.set_from_stock(Gtk.STOCK_NO, Gtk.IconSize.MENU)
self.status_image.set_alignment(True, 0.5 )
self.status_image.show()
self.network_button = Gtk.Button()
self.network_button.connect("clicked", lambda x: run_network_dialog(self.network, self.window) )
self.network_button.add(self.status_image)
self.network_button.set_relief(Gtk.ReliefStyle.NONE)
self.network_button.show()
self.status_bar.pack_end(self.network_button, False, False, 0)
if self.wallet.seed:
def seedb(w, wallet):
if wallet.use_encryption:
password = password_dialog(self.window)
if not password: return
else: password = None
seed = wallet.get_mnemonic(password)
show_seed_dialog(seed, self.window)
button = Gtk.Button('S')
button.connect("clicked", seedb, self.wallet )
button.set_relief(Gtk.ReliefStyle.NONE)
button.show()
self.status_bar.pack_end(button,False, False, 0)
settings_icon = Gtk.Image()
settings_icon.set_from_stock(Gtk.STOCK_PREFERENCES, Gtk.IconSize.MENU)
settings_icon.set_alignment(0.5, 0.5)
settings_icon.set_size_request(16,16 )
settings_icon.show()
prefs_button = Gtk.Button()
prefs_button.connect("clicked", lambda x: run_settings_dialog(self) )
prefs_button.add(settings_icon)
prefs_button.set_tooltip_text("Settings")
prefs_button.set_relief(Gtk.ReliefStyle.NONE)
prefs_button.show()
self.status_bar.pack_end(prefs_button,False,False, 0)
self.pw_icon = Gtk.Image()
self.pw_icon.set_from_stock(Gtk.STOCK_DIALOG_AUTHENTICATION, Gtk.IconSize.MENU)
self.pw_icon.set_alignment(0.5, 0.5)
self.pw_icon.set_size_request(16,16 )
self.pw_icon.show()
if self.wallet.seed:
if self.wallet.use_encryption:
self.pw_icon.set_tooltip_text('Wallet is encrypted')
else:
self.pw_icon.set_tooltip_text('Wallet is unencrypted')
password_button = Gtk.Button()
password_button.connect("clicked", self.do_update_password, self.wallet)
password_button.add(self.pw_icon)
password_button.set_relief(Gtk.ReliefStyle.NONE)
password_button.show()
self.status_bar.pack_end(password_button,False,False, 0)
self.window.add(vbox)
self.window.show_all()
#self.fee_box.hide()
self.context_id = self.status_bar.get_context_id("statusbar")
self.update_status_bar()
self.network.register_callback('updated', self.update_callback)
def update_status_bar_thread():
while True:
GObject.idle_add( self.update_status_bar )
time.sleep(0.5)
def check_recipient_thread():
old_r = ''
while True:
time.sleep(0.5)
if self.payto_entry.is_focus():
continue
r = self.payto_entry.get_text()
if r != old_r:
old_r = r
r = r.strip()
if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r):
try:
to_address = self.wallet.get_alias(r, interactive=False)
except Exception:
continue
if to_address:
s = r + ' <' + to_address + '>'
GObject.idle_add( lambda: self.payto_entry.set_text(s) )
thread.start_new_thread(update_status_bar_thread, ())
if self.wallet.seed:
thread.start_new_thread(check_recipient_thread, ())
self.notebook.set_current_page(0)
def update_callback(self):
self.wallet_updated = True
def do_update_password(self, button, wallet):
if not wallet.seed:
show_message("No seed")
return
res = change_password_dialog(wallet.use_encryption, self.window)
if res:
_, password, new_password = res
try:
wallet.get_seed(password)
except InvalidPassword:
show_message("Incorrect password")
return
wallet.update_password(password, new_password)
if wallet.use_encryption:
self.pw_icon.set_tooltip_text('Wallet is encrypted')
else:
self.pw_icon.set_tooltip_text('Wallet is unencrypted')
def add_tab(self, page, name):
tab_label = Gtk.Label(label=name)
tab_label.show()
self.notebook.append_page(page, tab_label)
def create_send_tab(self):
page = vbox = Gtk.VBox()
page.show()
payto = Gtk.HBox()
payto_label = Gtk.Label(label='Pay to:')
payto_label.set_size_request(100,-1)
payto.pack_start(payto_label, False, False, 0)
payto_entry = Gtk.Entry()
payto_entry.set_size_request(450, 26)
payto.pack_start(payto_entry, False, False, 0)
vbox.pack_start(payto, False, False, 5)
message = Gtk.HBox()
message_label = Gtk.Label(label='Description:')
message_label.set_size_request(100,-1)
message.pack_start(message_label, False, False, 0)
message_entry = Gtk.Entry()
message_entry.set_size_request(450, 26)
message.pack_start(message_entry, False, False, 0)
vbox.pack_start(message, False, False, 5)
amount_box = Gtk.HBox()
amount_label = Gtk.Label(label='Amount:')
amount_label.set_size_request(100,-1)
amount_box.pack_start(amount_label, False, False, 0)
amount_entry = Gtk.Entry()
amount_entry.set_size_request(120, -1)
amount_box.pack_start(amount_entry, False, False, 0)
vbox.pack_start(amount_box, False, False, 5)
self.fee_box = fee_box = Gtk.HBox()
fee_label = Gtk.Label(label='Fee:')
fee_label.set_size_request(100,-1)
fee_box.pack_start(fee_label, False, False, 0)
fee_entry = Gtk.Entry()
fee_entry.set_size_request(60, 26)
fee_box.pack_start(fee_entry, False, False, 0)
vbox.pack_start(fee_box, False, False, 5)
end_box = Gtk.HBox()
empty_label = Gtk.Label(label='')
empty_label.set_size_request(100,-1)
end_box.pack_start(empty_label, False, False, 0)
send_button = Gtk.Button("Send")
send_button.show()
end_box.pack_start(send_button, False, False, 0)
clear_button = Gtk.Button("Clear")
clear_button.show()
end_box.pack_start(clear_button, False, False, 15)
send_button.connect("clicked", self.do_send, (payto_entry, message_entry, amount_entry, fee_entry))
clear_button.connect("clicked", self.do_clear, (payto_entry, message_entry, amount_entry, fee_entry))
vbox.pack_start(end_box, False, False, 5)
# display this line only if there is a signature
payto_sig = Gtk.HBox()
payto_sig_id = Gtk.Label(label='')
payto_sig.pack_start(payto_sig_id, False, False, 0)
vbox.pack_start(payto_sig, True, True, 5)
self.user_fee = False
def entry_changed( entry, is_fee ):
amount = numbify(amount_entry)
fee = numbify(fee_entry)
if not is_fee: fee = None
if amount is None:
return
coins = self.wallet.get_spendable_coins()
try:
tx = self.wallet.make_unsigned_transaction(coins, [('op_return', 'dummy_tx', amount)], self.config, fee)
self.funds_error = False
except NotEnoughFunds:
self.funds_error = True
if not self.funds_error:
if not is_fee:
fee = tx.get_fee()
fee_entry.set_text(str(Decimal(fee) / COIN))
self.fee_box.show()
amount_entry.modify_text(Gtk.StateType.NORMAL, Gdk.color_parse("#000000"))
fee_entry.modify_text(Gtk.StateType.NORMAL, Gdk.color_parse("#000000"))
send_button.set_sensitive(True)
else:
send_button.set_sensitive(False)
amount_entry.modify_text(Gtk.StateType.NORMAL, Gdk.color_parse("#cc0000"))
fee_entry.modify_text(Gtk.StateType.NORMAL, Gdk.color_parse("#cc0000"))
amount_entry.connect('changed', entry_changed, False)
fee_entry.connect('changed', entry_changed, True)
self.payto_entry = payto_entry
self.payto_fee_entry = fee_entry
self.payto_sig_id = payto_sig_id
self.payto_sig = payto_sig
self.amount_entry = amount_entry
self.message_entry = message_entry
self.add_tab(page, 'Send')
def set_frozen(self,entry,frozen):
if frozen:
entry.set_editable(False)
entry.set_has_frame(False)
entry.modify_base(Gtk.StateType.NORMAL, Gdk.color_parse("#eeeeee"))
else:
entry.set_editable(True)
entry.set_has_frame(True)
entry.modify_base(Gtk.StateType.NORMAL, Gdk.color_parse("#ffffff"))
def set_url(self, url):
out = parse_URI(url)
address = out.get('address')
message = out.get('message')
amount = out.get('amount')
self.notebook.set_current_page(1)
self.payto_entry.set_text(address)
self.message_entry.set_text(message)
self.amount_entry.set_text(amount)
self.payto_sig.set_visible(False)
def create_about_tab(self):
from gi.repository import Pango
page = Gtk.VBox()
page.show()
tv = Gtk.TextView()
tv.set_editable(False)
tv.set_cursor_visible(False)
tv.modify_font(Pango.FontDescription(MONOSPACE_FONT))
scroll = Gtk.ScrolledWindow()
scroll.add(tv)
page.pack_start(scroll, True, True, 0)
self.info = tv.get_buffer()
self.add_tab(page, 'Wall')
def do_clear(self, w, data):
self.payto_sig.set_visible(False)
self.payto_fee_entry.set_text('')
for entry in [self.payto_entry,self.amount_entry,self.message_entry]:
self.set_frozen(entry,False)
entry.set_text('')
def question(self,msg):
dialog = Gtk.MessageDialog( self.window, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.QUESTION, Gtk.ButtonsType.OK_CANCEL, msg)
dialog.show()
result = dialog.run()
dialog.destroy()
return result == Gtk.ResponseType.OK
def do_send(self, w, data):
payto_entry, label_entry, amount_entry, fee_entry = data
label = label_entry.get_text()
r = payto_entry.get_text()
r = r.strip()
m1 = re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r)
m2 = re.match('(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+) \<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
if m1:
to_address = self.wallet.get_alias(r, True, self.show_message, self.question)
if not to_address:
return
else:
self.update_sending_tab()
elif m2:
to_address = m2.group(5)
else:
to_address = r
if not is_valid(to_address):
self.show_message( "invalid bitcoin address:\n"+to_address)
return
try:
amount = int(Decimal(amount_entry.get_text()) * COIN)
except Exception:
self.show_message( "invalid amount")
return
try:
fee = int(Decimal(fee_entry.get_text()) * COIN)
except Exception:
self.show_message( "invalid fee")
return
if self.wallet.use_encryption:
password = password_dialog(self.window)
if not password:
return
else:
password = None
try:
tx = self.wallet.mktx( [(to_address, amount)], password, self.config, fee)
except Exception as e:
self.show_message(str(e))
return
if tx.requires_fee(self.wallet) and fee < MIN_RELAY_TX_FEE:
self.show_message( "This transaction requires a higher fee, or it will not be propagated by the network." )
return
if label:
self.wallet.labels[tx.hash()] = label
status, msg = self.wallet.sendtx( tx )
if status:
self.show_message( "payment sent.\n" + msg )
payto_entry.set_text("")
label_entry.set_text("")
amount_entry.set_text("")
fee_entry.set_text("")
#self.fee_box.hide()
self.update_sending_tab()
else:
self.show_message( msg )
def treeview_button_press(self, treeview, event):
if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS:
c = treeview.get_cursor()[0]
if treeview == self.history_treeview:
tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8)
self.show_message(tx_details)
elif treeview == self.contacts_treeview:
m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0)
#a = self.wallet.aliases.get(m)
#if a:
# if a[0] in self.wallet.authorities.keys():
# s = self.wallet.authorities.get(a[0])
# else:
# s = "self-signed"
# msg = 'Alias: '+ m + '\nTarget address: '+ a[1] + '\n\nSigned by: ' + s + '\nSigning address:' + a[0]
# self.show_message(msg)
def treeview_key_press(self, treeview, event):
c = treeview.get_cursor()[0]
if event.keyval == Gdk.KEY_Up:
if c and c[0] == 0:
treeview.parent.grab_focus()
treeview.set_cursor((0,))
elif event.keyval == Gdk.KEY_Return:
if treeview == self.history_treeview:
tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8)
self.show_message(tx_details)
elif treeview == self.contacts_treeview:
m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0)
#a = self.wallet.aliases.get(m)
#if a:
# if a[0] in self.wallet.authorities.keys():
# s = self.wallet.authorities.get(a[0])
# else:
# s = "self"
# msg = 'Alias:'+ m + '\n\nTarget: '+ a[1] + '\nSigned by: ' + s + '\nSigning address:' + a[0]
# self.show_message(msg)
return False
def create_history_tab(self):
self.history_list = Gtk.ListStore(str, str, str, str, 'gboolean', str, str, str, str)
treeview = Gtk.TreeView(model=self.history_list)
self.history_treeview = treeview
treeview.set_tooltip_column(7)
treeview.show()
treeview.connect('key-press-event', self.treeview_key_press)
treeview.connect('button-press-event', self.treeview_button_press)
tvcolumn = Gtk.TreeViewColumn('')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererPixbuf()
tvcolumn.pack_start(cell, False)
tvcolumn.set_attributes(cell, stock_id=1)
tvcolumn = Gtk.TreeViewColumn('Date')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
tvcolumn.pack_start(cell, False)
tvcolumn.add_attribute(cell, 'text', 2)
tvcolumn = Gtk.TreeViewColumn('Description')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
cell.set_property('foreground', 'grey')
cell.set_property('family', MONOSPACE_FONT)
cell.set_property('editable', True)
def edited_cb(cell, path, new_text, h_list):
tx = h_list.get_value( h_list.get_iter(path), 0)
self.wallet.set_label(tx,new_text)
self.update_history_tab()
cell.connect('edited', edited_cb, self.history_list)
def editing_started(cell, entry, path, h_list):
tx = h_list.get_value( h_list.get_iter(path), 0)
if not self.wallet.labels.get(tx): entry.set_text('')
cell.connect('editing-started', editing_started, self.history_list)
tvcolumn.set_expand(True)
tvcolumn.pack_start(cell, True)
tvcolumn.set_attributes(cell, text=3, foreground_set = 4)
tvcolumn = Gtk.TreeViewColumn('Amount')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
cell.set_alignment(1, 0.5)
cell.set_property('family', MONOSPACE_FONT)
tvcolumn.pack_start(cell, False)
tvcolumn.add_attribute(cell, 'text', 5)
tvcolumn = Gtk.TreeViewColumn('Balance')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
cell.set_alignment(1, 0.5)
cell.set_property('family', MONOSPACE_FONT)
tvcolumn.pack_start(cell, False)
tvcolumn.add_attribute(cell, 'text', 6)
tvcolumn = Gtk.TreeViewColumn('Tooltip')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
tvcolumn.pack_start(cell, False)
tvcolumn.add_attribute(cell, 'text', 7)
tvcolumn.set_visible(False)
scroll = Gtk.ScrolledWindow()
scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
scroll.add(treeview)
self.add_tab(scroll, 'History')
self.update_history_tab()
def create_recv_tab(self):
self.recv_list = Gtk.ListStore(str, str, str, str, str)
self.add_tab( self.make_address_list(True), 'Receive')
self.update_receiving_tab()
def create_book_tab(self):
self.addressbook_list = Gtk.ListStore(str, str, str)
self.add_tab( self.make_address_list(False), 'Contacts')
self.update_sending_tab()
def make_address_list(self, is_recv):
liststore = self.recv_list if is_recv else self.addressbook_list
treeview = Gtk.TreeView(model= liststore)
treeview.connect('key-press-event', self.treeview_key_press)
treeview.connect('button-press-event', self.treeview_button_press)
treeview.show()
if not is_recv:
self.contacts_treeview = treeview
tvcolumn = Gtk.TreeViewColumn('Address')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
cell.set_property('family', MONOSPACE_FONT)
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 0)
tvcolumn = Gtk.TreeViewColumn('Label')
tvcolumn.set_expand(True)
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
cell.set_property('editable', True)
def edited_cb2(cell, path, new_text, liststore):
address = liststore.get_value( liststore.get_iter(path), 0)
self.wallet.set_label(address, new_text)
self.update_receiving_tab()
self.update_sending_tab()
self.update_history_tab()
cell.connect('edited', edited_cb2, liststore)
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 1)
tvcolumn = Gtk.TreeViewColumn('Tx')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 2)
if is_recv:
tvcolumn = Gtk.TreeViewColumn('Balance')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 3)
tvcolumn = Gtk.TreeViewColumn('Type')
treeview.append_column(tvcolumn)
cell = Gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 4)
scroll = Gtk.ScrolledWindow()
scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
scroll.add(treeview)
hbox = Gtk.HBox()
if not is_recv:
button = Gtk.Button("New")
button.connect("clicked", self.newaddress_dialog)
button.show()
hbox.pack_start(button,False, False, 0)
def showqrcode(w, treeview, liststore):
import qrcode
path, col = treeview.get_cursor()
if not path: return
address = liststore.get_value(liststore.get_iter(path), 0)
qr = qrcode.QRCode()
qr.add_data(address)
boxsize = 7
matrix = qr.get_matrix()
boxcount_row = len(matrix)
size = (boxcount_row + 4) * boxsize
def area_expose_cb(area, cr):
style = area.get_style()
Gdk.cairo_set_source_color(cr, style.white)
cr.rectangle(0, 0, size, size)
cr.fill()
Gdk.cairo_set_source_color(cr, style.black)
for r in range(boxcount_row):
for c in range(boxcount_row):
if matrix[r][c]:
cr.rectangle((c + 2) * boxsize, (r + 2) * boxsize, boxsize, boxsize)
cr.fill()
area = Gtk.DrawingArea()
area.set_size_request(size, size)
area.connect("draw", area_expose_cb)
area.show()
dialog = Gtk.Dialog(address, parent=self.window, flags=Gtk.DialogFlags.MODAL, buttons = ("ok",1))
dialog.vbox.add(area)
dialog.run()
dialog.destroy()
button = Gtk.Button("QR")
button.connect("clicked", showqrcode, treeview, liststore)
button.show()
hbox.pack_start(button,False, False, 0)
button = Gtk.Button("Copy to clipboard")
def copy2clipboard(w, treeview, liststore):
import platform
path, col = treeview.get_cursor()
if path:
address = liststore.get_value( liststore.get_iter(path), 0)
if platform.system() == 'Windows':
from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append( address )
r.destroy()
else:
atom = Gdk.atom_intern('CLIPBOARD', True)
c = Gtk.Clipboard.get(atom)
c.set_text( address, len(address) )
button.connect("clicked", copy2clipboard, treeview, liststore)
button.show()
hbox.pack_start(button,False, False, 0)
if is_recv:
button = Gtk.Button("Freeze")
def freeze_address(w, treeview, liststore, wallet):
path, col = treeview.get_cursor()
if path:
address = liststore.get_value( liststore.get_iter(path), 0)
wallet.set_frozen_state([address], not wallet.is_frozen(address))
self.update_receiving_tab()
button.connect("clicked", freeze_address, treeview, liststore, self.wallet)
button.show()
hbox.pack_start(button,False, False, 0)
if not is_recv:
button = Gtk.Button("Pay to")
def payto(w, treeview, liststore):
path, col = treeview.get_cursor()
if path:
address = liststore.get_value( liststore.get_iter(path), 0)
self.payto_entry.set_text( address )
self.notebook.set_current_page(1)
self.amount_entry.grab_focus()
button.connect("clicked", payto, treeview, liststore)
button.show()
hbox.pack_start(button,False, False, 0)
vbox = Gtk.VBox()
vbox.pack_start(scroll,True, True, 0)
vbox.pack_start(hbox, False, False, 0)
return vbox
def update_status_bar(self):
if self.funds_error:
text = "Not enough funds"
elif self.network.is_connected():
host, port, _,_,_ = self.network.get_parameters()
port = int(port)
height = self.network.get_local_height()
self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks"%(host, port, height))
if not self.wallet.up_to_date:
self.status_image.set_from_stock(Gtk.STOCK_REFRESH, Gtk.IconSize.MENU)
text = "Synchronizing..."
else:
self.status_image.set_from_stock(Gtk.STOCK_YES, Gtk.IconSize.MENU)
c, u, x = self.wallet.get_balance()
text = "Balance: %s "%(format_satoshis(c, False, self.num_zeros))
if u:
text += "[%s unconfirmed]"%(format_satoshis(u, True, self.num_zeros).strip())
if x:
text += "[%s unmatured]"%(format_satoshis(x, True, self.num_zeros).strip())
else:
self.status_image.set_from_stock(Gtk.STOCK_NO, Gtk.IconSize.MENU)
self.network_button.set_tooltip_text("Not connected.")
text = "Not connected"
self.status_bar.pop(self.context_id)
self.status_bar.push(self.context_id, text)
if self.wallet.up_to_date and self.wallet_updated:
self.update_history_tab()
self.update_receiving_tab()
# addressbook too...
self.info.set_text( self.network.banner )
self.wallet_updated = False
def update_receiving_tab(self):
self.recv_list.clear()
for address in self.wallet.addresses(True):
Type = "R"
c = u = 0
if self.wallet.is_change(address): Type = "C"
if address in self.wallet.imported_keys.keys():
Type = "I"
c, u, x = self.wallet.get_addr_balance(address)
if self.wallet.is_frozen(address): Type = Type + "F"
label = self.wallet.labels.get(address)
h = self.wallet.history.get(address,[])
n = len(h)
tx = "0" if n==0 else "%d"%n
self.recv_list.append((address, label, tx, format_satoshis(c+u+x, False, self.num_zeros), Type ))
def update_sending_tab(self):
self.addressbook_list.clear()
for k, v in self.contacts.items():
t, v = v
self.addressbook_list.append((k, v, t))
def update_history_tab(self):
cursor = self.history_treeview.get_cursor()[0]
self.history_list.clear()
for item in self.wallet.get_history():
tx_hash, conf, value, timestamp, balance = item
if conf > 0:
try:
time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
except Exception:
time_str = "------"
conf_icon = Gtk.STOCK_APPLY
elif conf == -1:
time_str = 'unverified'
conf_icon = None
else:
time_str = 'pending'
conf_icon = Gtk.STOCK_EXECUTE
label, is_default_label = self.wallet.get_label(tx_hash)
tooltip = tx_hash + "\n%d confirmations"%conf if tx_hash else ''
details = self.get_tx_details(tx_hash)
self.history_list.prepend( [tx_hash, conf_icon, time_str, label, is_default_label,
format_satoshis(value,True,self.num_zeros, whitespaces=True),
format_satoshis(balance,False,self.num_zeros, whitespaces=True), tooltip, details] )
if cursor: self.history_treeview.set_cursor( cursor )
def get_tx_details(self, tx_hash):
import datetime
if not tx_hash: return ''
tx = self.wallet.transactions.get(tx_hash)
tx.deserialize()
is_relevant, is_mine, v, fee = self.wallet.get_wallet_delta(tx)
conf, timestamp = self.wallet.get_confirmations(tx_hash)
if timestamp:
time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3]
else:
time_str = 'pending'
inputs = map(lambda x: x.get('address'), tx.inputs)
outputs = map(lambda x: x[0], tx.get_outputs())
tx_details = "Transaction Details" +"\n\n" \
+ "Transaction ID:\n" + tx_hash + "\n\n" \
+ "Status: %d confirmations\n"%conf
if is_mine:
if fee:
tx_details += "Amount sent: %s\n"% format_satoshis(v-fee, False) \
+ "Transaction fee: %s\n"% format_satoshis(fee, False)
else:
tx_details += "Amount sent: %s\n"% format_satoshis(v, False) \
+ "Transaction fee: unknown\n"
else:
tx_details += "Amount received: %s\n"% format_satoshis(v, False) \
tx_details += "Date: %s\n\n"%time_str \
+ "Inputs:\n-"+ '\n-'.join(inputs) + "\n\n" \
+ "Outputs:\n-"+ '\n-'.join(outputs)
return tx_details
def newaddress_dialog(self, w):
title = "New Contact"
dialog = Gtk.Dialog(title, parent=self.window,
flags=Gtk.DialogFlags.MODAL,
buttons= ("cancel", 0, "ok",1) )
dialog.show()
label = Gtk.HBox()
label_label = Gtk.Label(label='Label:')
label_label.set_size_request(120,10)
label_label.show()
label.pack_start(label_label, True, True, 0)
label_entry = Gtk.Entry()
label_entry.show()
label.pack_start(label_entry, True, True, 0)
label.show()
dialog.vbox.pack_start(label, False, True, 5)
address = Gtk.HBox()
address_label = Gtk.Label(label='Address:')
address_label.set_size_request(120,10)
address_label.show()
address.pack_start(address_label, True, True, 0)
address_entry = Gtk.Entry()
address_entry.show()
address.pack_start(address_entry, True, True, 0)
address.show()
dialog.vbox.pack_start(address, False, True, 5)
result = dialog.run()
address = address_entry.get_text()
label = label_entry.get_text()
dialog.destroy()
if result == 1:
if is_valid(address):
self.contacts[label] = address
self.update_sending_tab()
else:
errorDialog = Gtk.MessageDialog(
parent=self.window,
flags=Gtk.DialogFlags.MODAL,
buttons= Gtk.ButtonsType.CLOSE,
message_format = "Invalid address")
errorDialog.show()
errorDialog.run()
errorDialog.destroy()
class ElectrumGui():
def __init__(self, config, network):
self.network = network
self.config = config
def main(self, url=None):
storage = WalletStorage(self.config.get_wallet_path())
if not storage.file_exists:
action = self.restore_or_create()
if not action:
exit()
self.wallet = wallet = Wallet(storage)
gap = self.config.get('gap_limit', 5)
if gap != 5:
wallet.gap_limit = gap
wallet.storage.put('gap_limit', gap, True)
if action == 'create':
seed = wallet.make_seed()
show_seed_dialog(seed, None)
r = change_password_dialog(False, None)
password = r[2] if r else None
wallet.add_seed(seed, password)
wallet.create_master_keys(password)
wallet.create_main_account(password)
wallet.synchronize() # generate first addresses offline
elif action == 'restore':
seed = self.seed_dialog()
if not seed:
exit()
r = change_password_dialog(False, None)
password = r[2] if r else None
wallet.add_seed(seed, password)
wallet.create_master_keys(password)
wallet.create_main_account(password)
else:
exit()
else:
self.wallet = Wallet(storage)
action = None
self.wallet.start_threads(self.network)
if action == 'restore':
self.restore_wallet(wallet)
w = ElectrumWindow(self.wallet, self.config, self.network)
if url: w.set_url(url)
Gtk.main()
def restore_or_create(self):
return restore_create_dialog()
def seed_dialog(self):
return run_recovery_dialog()
def network_dialog(self):
return run_network_dialog( self.network, parent=None )
def restore_wallet(self, wallet):
dialog = Gtk.MessageDialog(
parent = None,
flags = Gtk.DialogFlags.MODAL,
buttons = Gtk.ButtonsType.CANCEL,
message_format = "Please wait..." )
dialog.show()
def recover_thread( wallet, dialog ):
wallet.restore(lambda x:x)
GObject.idle_add( dialog.destroy )
thread.start_new_thread( recover_thread, ( wallet, dialog ) )
r = dialog.run()
dialog.destroy()
if r==Gtk.ResponseType.CANCEL: return False
if not wallet.is_found():
show_message("No transactions found for this seed")
return True<|fim▁end|>
| |
<|file_name|>term.rs<|end_file_name|><|fim▁begin|>/*
* Copyright 2016-2019 Ben Ashford
*
* 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.
*/
//! Specific Term level queries
use serde::{Serialize, Serializer};
use crate::{
json::{NoOuter, ShouldSkip},
units::{JsonPotential, JsonVal, OneOrMany},
};
use super::{common::FieldBasedQuery, Flags, Fuzziness, Query};
/// Values of the rewrite option used by multi-term queries
#[derive(Debug)]
pub enum Rewrite {
ConstantScoreAuto,
ScoringBoolean,
ConstantScoreBoolean,
ConstantScoreFilter,
TopTerms(i64),
TopTermsBoost(i64),
TopTermsBlendedFreqs(i64),
}
impl Serialize for Rewrite {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use self::Rewrite::*;
match self {
ConstantScoreAuto => "constant_score_auto".serialize(serializer),
ScoringBoolean => "scoring_boolean".serialize(serializer),
ConstantScoreBoolean => "constant_score_boolean".serialize(serializer),
ConstantScoreFilter => "constant_score_filter".serialize(serializer),
TopTerms(n) => format!("top_terms_{}", n).serialize(serializer),
TopTermsBoost(n) => format!("top_terms_boost_{}", n).serialize(serializer),
TopTermsBlendedFreqs(n) => {
format!("top_terms_blended_freqs_{}", n).serialize(serializer)
}
}
}
}
/// Term query
#[derive(Debug, Default, Serialize)]
pub struct TermQueryInner {
value: JsonVal,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
boost: Option<f64>,
}
impl TermQueryInner {
fn new(value: JsonVal) -> Self {
TermQueryInner {
value,
..Default::default()
}
}
}
#[derive(Debug, Serialize)]
pub struct TermQuery(FieldBasedQuery<TermQueryInner, NoOuter>);
impl Query {
pub fn build_term<A, B>(field: A, value: B) -> TermQuery<|fim▁hole|> A: Into<String>,
B: Into<JsonVal>,
{
TermQuery(FieldBasedQuery::new(
field.into(),
TermQueryInner::new(value.into()),
NoOuter,
))
}
}
impl TermQuery {
add_inner_field!(with_boost, boost, f64);
build!(Term);
}
// Terms query
/// Terms Query Lookup
#[derive(Debug, Default, Serialize)]
pub struct TermsQueryLookup {
id: JsonVal,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
index: Option<String>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
doc_type: Option<String>,
path: String,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
routing: Option<String>,
}
impl<'a> TermsQueryLookup {
pub fn new<A, B>(id: A, path: B) -> TermsQueryLookup
where
A: Into<JsonVal>,
B: Into<String>,
{
TermsQueryLookup {
id: id.into(),
path: path.into(),
..Default::default()
}
}
add_field!(with_index, index, String);
add_field!(with_type, doc_type, String);
add_field!(with_routing, routing, String);
}
/// TermsQueryIn
#[derive(Debug)]
pub enum TermsQueryIn {
/// A `Vec` of values
Values(Vec<JsonVal>),
/// An indirect reference to another document
Lookup(TermsQueryLookup),
}
// TODO - if this looks useful it can be extracted into a macro
impl Serialize for TermsQueryIn {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
TermsQueryIn::Values(ref q) => q.serialize(serializer),
TermsQueryIn::Lookup(ref q) => q.serialize(serializer),
}
}
}
impl Default for TermsQueryIn {
fn default() -> Self {
TermsQueryIn::Values(Default::default())
}
}
impl From<TermsQueryLookup> for TermsQueryIn {
fn from(from: TermsQueryLookup) -> TermsQueryIn {
TermsQueryIn::Lookup(from)
}
}
impl From<Vec<JsonVal>> for TermsQueryIn {
fn from(from: Vec<JsonVal>) -> TermsQueryIn {
TermsQueryIn::Values(from)
}
}
impl<'a, A> From<&'a [A]> for TermsQueryIn
where
A: JsonPotential,
{
fn from(from: &'a [A]) -> Self {
TermsQueryIn::Values(from.iter().map(JsonPotential::to_json_val).collect())
}
}
impl<A> From<Vec<A>> for TermsQueryIn
where
A: JsonPotential,
{
fn from(from: Vec<A>) -> TermsQueryIn {
(&from[..]).into()
}
}
/// Terms Query
#[derive(Debug, Serialize)]
pub struct TermsQuery(FieldBasedQuery<TermsQueryIn, NoOuter>);
impl Query {
pub fn build_terms<A>(field: A) -> TermsQuery
where
A: Into<String>,
{
TermsQuery(FieldBasedQuery::new(
field.into(),
Default::default(),
NoOuter,
))
}
}
impl TermsQuery {
pub fn with_values<T>(mut self, values: T) -> Self
where
T: Into<TermsQueryIn>,
{
self.0.inner = values.into();
self
}
build!(Terms);
}
/// Range query
/// TODO: Check all possible combinations: gt, gte, lte, lt, from, to, include_upper, include_lower
/// and share with other range queries
#[derive(Debug, Default, Serialize)]
pub struct RangeQueryInner {
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
gte: Option<JsonVal>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
gt: Option<JsonVal>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
lte: Option<JsonVal>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
lt: Option<JsonVal>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
boost: Option<f64>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
time_zone: Option<String>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
format: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct RangeQuery(FieldBasedQuery<RangeQueryInner, NoOuter>);
impl Query {
pub fn build_range<A>(field: A) -> RangeQuery
where
A: Into<String>,
{
RangeQuery(FieldBasedQuery::new(
field.into(),
Default::default(),
NoOuter,
))
}
}
impl RangeQuery {
add_inner_field!(with_gte, gte, JsonVal);
add_inner_field!(with_gt, gt, JsonVal);
add_inner_field!(with_lte, lte, JsonVal);
add_inner_field!(with_lt, lt, JsonVal);
add_inner_field!(with_boost, boost, f64);
add_inner_field!(with_time_zone, time_zone, String);
add_inner_field!(with_format, format, String);
build!(Range);
}
/// Exists query
#[derive(Debug, Serialize)]
pub struct ExistsQuery {
field: String,
}
impl Query {
pub fn build_exists<A>(field: A) -> ExistsQuery
where
A: Into<String>,
{
ExistsQuery {
field: field.into(),
}
}
}
impl ExistsQuery {
build!(Exists);
}
/// Prefix query
#[derive(Debug, Serialize)]
pub struct PrefixQuery(FieldBasedQuery<PrefixQueryInner, NoOuter>);
#[derive(Debug, Default, Serialize)]
pub struct PrefixQueryInner {
value: String,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
boost: Option<f64>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
rewrite: Option<Rewrite>,
}
impl Query {
pub fn build_prefix<A, B>(field: A, value: B) -> PrefixQuery
where
A: Into<String>,
B: Into<String>,
{
PrefixQuery(FieldBasedQuery::new(
field.into(),
PrefixQueryInner {
value: value.into(),
..Default::default()
},
NoOuter,
))
}
}
impl PrefixQuery {
add_inner_field!(with_boost, boost, f64);
add_inner_field!(with_rewrite, rewrite, Rewrite);
build!(Prefix);
}
/// Wildcard query
#[derive(Debug, Serialize)]
pub struct WildcardQuery(FieldBasedQuery<WildcardQueryInner, NoOuter>);
#[derive(Debug, Default, Serialize)]
pub struct WildcardQueryInner {
value: String,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
boost: Option<f64>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
rewrite: Option<Rewrite>,
}
impl Query {
pub fn build_wildcard<A, B>(field: A, value: B) -> WildcardQuery
where
A: Into<String>,
B: Into<String>,
{
WildcardQuery(FieldBasedQuery::new(
field.into(),
WildcardQueryInner {
value: value.into(),
..Default::default()
},
NoOuter,
))
}
}
impl WildcardQuery {
add_inner_field!(with_boost, boost, f64);
add_inner_field!(with_rewrite, rewrite, Rewrite);
build!(Wildcard);
}
// Regexp query
/// Flags for the Regexp query
#[derive(Debug)]
pub enum RegexpQueryFlags {
All,
Anystring,
Complement,
Empty,
Intersection,
Interval,
None,
}
impl AsRef<str> for RegexpQueryFlags {
fn as_ref(&self) -> &str {
match self {
RegexpQueryFlags::All => "ALL",
RegexpQueryFlags::Anystring => "ANYSTRING",
RegexpQueryFlags::Complement => "COMPLEMENT",
RegexpQueryFlags::Empty => "EMPTY",
RegexpQueryFlags::Intersection => "INTERSECTION",
RegexpQueryFlags::Interval => "INTERVAL",
RegexpQueryFlags::None => "NONE",
}
}
}
/// Regexp query
#[derive(Debug, Serialize)]
pub struct RegexpQuery(FieldBasedQuery<RegexpQueryInner, NoOuter>);
#[derive(Debug, Default, Serialize)]
pub struct RegexpQueryInner {
value: String,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
boost: Option<f64>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
flags: Option<Flags<RegexpQueryFlags>>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
max_determined_states: Option<u64>,
}
impl Query {
pub fn build_query<A, B>(field: A, value: B) -> RegexpQuery
where
A: Into<String>,
B: Into<String>,
{
RegexpQuery(FieldBasedQuery::new(
field.into(),
RegexpQueryInner {
value: value.into(),
..Default::default()
},
NoOuter,
))
}
}
impl RegexpQuery {
add_inner_field!(with_boost, boost, f64);
add_inner_field!(with_flags, flags, Flags<RegexpQueryFlags>);
add_inner_field!(with_max_determined_states, max_determined_states, u64);
build!(Regexp);
}
/// Fuzzy query
#[derive(Debug, Serialize)]
pub struct FuzzyQuery(FieldBasedQuery<FuzzyQueryInner, NoOuter>);
#[derive(Debug, Default, Serialize)]
pub struct FuzzyQueryInner {
value: String,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
boost: Option<f64>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
fuzziness: Option<Fuzziness>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
prefix_length: Option<u64>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
max_expansions: Option<u64>,
}
impl Query {
pub fn build_fuzzy<A, B>(field: A, value: B) -> FuzzyQuery
where
A: Into<String>,
B: Into<String>,
{
FuzzyQuery(FieldBasedQuery::new(
field.into(),
FuzzyQueryInner {
value: value.into(),
..Default::default()
},
NoOuter,
))
}
}
impl FuzzyQuery {
add_inner_field!(with_boost, boost, f64);
add_inner_field!(with_fuzziness, fuzziness, Fuzziness);
add_inner_field!(with_prefix_length, prefix_length, u64);
add_inner_field!(with_max_expansions, max_expansions, u64);
build!(Fuzzy);
}
/// Type query
#[derive(Debug, Serialize)]
pub struct TypeQuery {
value: String,
}
impl Query {
pub fn build_type<A>(value: A) -> TypeQuery
where
A: Into<String>,
{
TypeQuery {
value: value.into(),
}
}
}
impl TypeQuery {
build!(Type);
}
/// Ids query
#[derive(Debug, Default, Serialize)]
pub struct IdsQuery {
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
doc_type: Option<OneOrMany<String>>,
values: Vec<JsonVal>,
}
impl Query {
pub fn build_ids<A>(values: A) -> IdsQuery
where
A: Into<Vec<JsonVal>>,
{
IdsQuery {
values: values.into(),
..Default::default()
}
}
}
impl IdsQuery {
add_field!(with_type, doc_type, OneOrMany<String>);
build!(Ids);
}<|fim▁end|>
|
where
|
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>"""
WSGI config for my_doku_application project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_doku_application.settings")
<|fim▁hole|>application = get_wsgi_application()<|fim▁end|>
|
from django.core.wsgi import get_wsgi_application
|
<|file_name|>uutils.rs<|end_file_name|><|fim▁begin|>#![crate_name = "uutils"]
#![feature(exit_status, rustc_private)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
@CRATES@
use std::env;
use std::collections::hash_map::HashMap;
use std::path::Path;
static NAME: &'static str = "uutils";
static VERSION: &'static str = "1.0.0";
fn util_map() -> HashMap<&'static str, fn(Vec<String>) -> i32> {
let mut map = HashMap::new();
@UTIL_MAP@
map
}
fn usage(cmap: &HashMap<&'static str, fn(Vec<String>) -> i32>) {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [util [arguments...]]\n", NAME);
println!("Currently defined functions:");
let mut utils: Vec<&str> = cmap.keys().map(|&s| s).collect();
utils.sort();
for util in utils.iter() {
println!("\t{}", util);
}
}
fn main() {
let umap = util_map();
let mut args : Vec<String> = env::args().collect();
// try binary name as util name.
let args0 = args[0].clone();
let binary = Path::new(&args0[..]);
let binary_as_util = binary.file_name().unwrap().to_str().unwrap();
match umap.get(binary_as_util) {
Some(&uumain) => {
env::set_exit_status(uumain(args));
return
}
None => (),
}
if binary_as_util.ends_with("uutils") || binary_as_util.starts_with("uutils") ||
binary_as_util.ends_with("busybox") || binary_as_util.starts_with("busybox") {
// uutils can be called as either "uutils", "busybox"<|fim▁hole|> env::set_exit_status(1);
return
}
// try first arg as util name.
if args.len() >= 2 {
args.remove(0);
let util = &args[0][..];
match umap.get(util) {
Some(&uumain) => {
env::set_exit_status(uumain(args.clone()));
return
}
None => {
if &args[0][..] == "--help" {
// see if they want help on a specific util
if args.len() >= 2 {
let util = &args[1][..];
match umap.get(util) {
Some(&uumain) => {
env::set_exit_status(uumain(vec![util.to_string(), "--help".to_string()]));
return
}
None => {
println!("{}: applet not found", util);
env::set_exit_status(1);
return
}
}
}
usage(&umap);
env::set_exit_status(0);
return
} else {
println!("{}: applet not found", util);
env::set_exit_status(1);
return
}
}
}
} else {
// no arguments provided
usage(&umap);
env::set_exit_status(0);
return
}
}<|fim▁end|>
|
// "uutils-suffix" or "busybox-suffix". Not sure
// what busybox uses the -suffix pattern for.
} else {
println!("{}: applet not found", binary_as_util);
|
<|file_name|>controllers.py<|end_file_name|><|fim▁begin|># This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import timedelta
from flask import flash, redirect, request, session
from indico.core.db import db
from indico.modules.admin import RHAdminBase
from indico.modules.news import logger, news_settings
from indico.modules.news.forms import NewsForm, NewsSettingsForm
from indico.modules.news.models.news import NewsItem
from indico.modules.news.util import get_recent_news
from indico.modules.news.views import WPManageNews, WPNews
from indico.util.date_time import now_utc
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.forms.base import FormDefaults
from indico.web.rh import RH
from indico.web.util import jsonify_data, jsonify_form
class RHNews(RH):
@staticmethod
def _is_new(item):
days = news_settings.get('new_days')
if not days:
return False
return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date()
def _process(self):
news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all()
return WPNews.render_template('news.html', news=news, _is_new=self._is_new)
class RHNewsItem(RH):
normalize_url_spec = {
'locators': {
lambda self: self.item.locator.slugged
}
}
def _process_args(self):
self.item = NewsItem.get_or_404(request.view_args['news_id'])
def _process(self):
return WPNews.render_template('news_item.html', item=self.item)
class RHManageNewsBase(RHAdminBase):
pass
class RHManageNews(RHManageNewsBase):
def _process(self):
news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all()
return WPManageNews.render_template('admin/news.html', 'news', news=news)
class RHNewsSettings(RHManageNewsBase):
def _process(self):
form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all()))
if form.validate_on_submit():
news_settings.set_multi(form.data)
get_recent_news.clear_cached()
flash(_('Settings have been saved'), 'success')
return jsonify_data()
return jsonify_form(form)
<|fim▁hole|> if form.validate_on_submit():
item = NewsItem()
form.populate_obj(item)
db.session.add(item)
db.session.flush()
get_recent_news.clear_cached()
logger.info('News %r created by %s', item, session.user)
flash(_("News '{title}' has been posted").format(title=item.title), 'success')
return jsonify_data(flash=False)
return jsonify_form(form)
class RHManageNewsItemBase(RHManageNewsBase):
def _process_args(self):
RHManageNewsBase._process_args(self)
self.item = NewsItem.get_or_404(request.view_args['news_id'])
class RHEditNews(RHManageNewsItemBase):
def _process(self):
form = NewsForm(obj=self.item)
if form.validate_on_submit():
old_title = self.item.title
form.populate_obj(self.item)
db.session.flush()
get_recent_news.clear_cached()
logger.info('News %r modified by %s', self.item, session.user)
flash(_("News '{title}' has been updated").format(title=old_title), 'success')
return jsonify_data(flash=False)
return jsonify_form(form)
class RHDeleteNews(RHManageNewsItemBase):
def _process(self):
db.session.delete(self.item)
get_recent_news.clear_cached()
flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success')
logger.info('News %r deleted by %r', self.item, session.user)
return redirect(url_for('news.manage'))<|fim▁end|>
|
class RHCreateNews(RHManageNewsBase):
def _process(self):
form = NewsForm()
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Structured communication between timely dataflow operators.
pub use self::message::Message;
pub use self::message::Content;
/// A collection of types that may be pushed at.
pub mod pushers;
/// A collection of types that may be pulled from.
pub mod pullers;
/// Types relating to batching of timestamped records.
pub mod message;
/// Parallelization contracts, describing how data must be exchanged between operators.<|fim▁hole|><|fim▁end|>
|
pub mod pact;
|
<|file_name|>membro.py<|end_file_name|><|fim▁begin|>class Membro(object):
nome = None<|fim▁hole|> self.nome = nome
self.cargo = cargo<|fim▁end|>
|
cargo = None
def __init__(self, nome, cargo):
|
<|file_name|>DeactivatePipelineResultJsonUnmarshaller.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package com.amazonaws.services.datapipeline.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.datapipeline.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DeactivatePipelineResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeactivatePipelineResultJsonUnmarshaller implements Unmarshaller<DeactivatePipelineResult, JsonUnmarshallerContext> {
public DeactivatePipelineResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DeactivatePipelineResult deactivatePipelineResult = new DeactivatePipelineResult();
return deactivatePipelineResult;
}
private static DeactivatePipelineResultJsonUnmarshaller instance;
<|fim▁hole|> return instance;
}
}<|fim▁end|>
|
public static DeactivatePipelineResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DeactivatePipelineResultJsonUnmarshaller();
|
<|file_name|>SemaExprCXX.cpp<|end_file_name|><|fim▁begin|>//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for C++ expressions.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/TemplateDeduction.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/STLExtras.h"
using namespace clang;
using namespace sema;
ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II,
SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectTypePtr,
bool EnteringContext) {
// Determine where to perform name lookup.
// FIXME: This area of the standard is very messy, and the current
// wording is rather unclear about which scopes we search for the
// destructor name; see core issues 399 and 555. Issue 399 in
// particular shows where the current description of destructor name
// lookup is completely out of line with existing practice, e.g.,
// this appears to be ill-formed:
//
// namespace N {
// template <typename T> struct S {
// ~S();
// };
// }
//
// void f(N::S<int>* s) {
// s->N::S<int>::~S();
// }
//
// See also PR6358 and PR6359.
// For this reason, we're currently only doing the C++03 version of this
// code; the C++0x version has to wait until we get a proper spec.
QualType SearchType;
DeclContext *LookupCtx = 0;
bool isDependent = false;
bool LookInScope = false;
// If we have an object type, it's because we are in a
// pseudo-destructor-expression or a member access expression, and
// we know what type we're looking for.
if (ObjectTypePtr)
SearchType = GetTypeFromParser(ObjectTypePtr);
if (SS.isSet()) {
NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
bool AlreadySearched = false;
bool LookAtPrefix = true;
// C++ [basic.lookup.qual]p6:
// If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
// the type-names are looked up as types in the scope designated by the
// nested-name-specifier. In a qualified-id of the form:
//
// ::[opt] nested-name-specifier ̃ class-name
//
// where the nested-name-specifier designates a namespace scope, and in
// a qualified-id of the form:
//
// ::opt nested-name-specifier class-name :: ̃ class-name
//
// the class-names are looked up as types in the scope designated by
// the nested-name-specifier.
//
// Here, we check the first case (completely) and determine whether the
// code below is permitted to look at the prefix of the
// nested-name-specifier.
DeclContext *DC = computeDeclContext(SS, EnteringContext);
if (DC && DC->isFileContext()) {
AlreadySearched = true;
LookupCtx = DC;
isDependent = false;
} else if (DC && isa<CXXRecordDecl>(DC))
LookAtPrefix = false;
// The second case from the C++03 rules quoted further above.
NestedNameSpecifier *Prefix = 0;
if (AlreadySearched) {
// Nothing left to do.
} else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
CXXScopeSpec PrefixSS;
PrefixSS.setScopeRep(Prefix);
LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
isDependent = isDependentScopeSpecifier(PrefixSS);
} else if (ObjectTypePtr) {
LookupCtx = computeDeclContext(SearchType);
isDependent = SearchType->isDependentType();
} else {
LookupCtx = computeDeclContext(SS, EnteringContext);
isDependent = LookupCtx && LookupCtx->isDependentContext();
}
LookInScope = false;
} else if (ObjectTypePtr) {
// C++ [basic.lookup.classref]p3:
// If the unqualified-id is ~type-name, the type-name is looked up
// in the context of the entire postfix-expression. If the type T
// of the object expression is of a class type C, the type-name is
// also looked up in the scope of class C. At least one of the
// lookups shall find a name that refers to (possibly
// cv-qualified) T.
LookupCtx = computeDeclContext(SearchType);
isDependent = SearchType->isDependentType();
assert((isDependent || !SearchType->isIncompleteType()) &&
"Caller should have completed object type");
LookInScope = true;
} else {
// Perform lookup into the current scope (only).
LookInScope = true;
}
LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
for (unsigned Step = 0; Step != 2; ++Step) {
// Look for the name first in the computed lookup context (if we
// have one) and, if that fails to find a match, in the sope (if
// we're allowed to look there).
Found.clear();
if (Step == 0 && LookupCtx)
LookupQualifiedName(Found, LookupCtx);
else if (Step == 1 && LookInScope && S)
LookupName(Found, S);
else
continue;
// FIXME: Should we be suppressing ambiguities here?
if (Found.isAmbiguous())
return ParsedType();
if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
QualType T = Context.getTypeDeclType(Type);
if (SearchType.isNull() || SearchType->isDependentType() ||
Context.hasSameUnqualifiedType(T, SearchType)) {
// We found our type!
return ParsedType::make(T);
}
}
// If the name that we found is a class template name, and it is
// the same name as the template name in the last part of the
// nested-name-specifier (if present) or the object type, then
// this is the destructor for that class.
// FIXME: This is a workaround until we get real drafting for core
// issue 399, for which there isn't even an obvious direction.
if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
QualType MemberOfType;
if (SS.isSet()) {
if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
// Figure out the type of the context, if it has one.
if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
MemberOfType = Context.getTypeDeclType(Record);
}
}
if (MemberOfType.isNull())
MemberOfType = SearchType;
if (MemberOfType.isNull())
continue;
// We're referring into a class template specialization. If the
// class template we found is the same as the template being
// specialized, we found what we are looking for.
if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
if (ClassTemplateSpecializationDecl *Spec
= dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
Template->getCanonicalDecl())
return ParsedType::make(MemberOfType);
}
continue;
}
// We're referring to an unresolved class template
// specialization. Determine whether we class template we found
// is the same as the template being specialized or, if we don't
// know which template is being specialized, that it at least
// has the same name.
if (const TemplateSpecializationType *SpecType
= MemberOfType->getAs<TemplateSpecializationType>()) {
TemplateName SpecName = SpecType->getTemplateName();
// The class template we found is the same template being
// specialized.
if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
return ParsedType::make(MemberOfType);
continue;
}
// The class template we found has the same name as the
// (dependent) template name being specialized.
if (DependentTemplateName *DepTemplate
= SpecName.getAsDependentTemplateName()) {
if (DepTemplate->isIdentifier() &&
DepTemplate->getIdentifier() == Template->getIdentifier())
return ParsedType::make(MemberOfType);
continue;
}
}
}
}
if (isDependent) {
// We didn't find our type, but that's okay: it's dependent
// anyway.
NestedNameSpecifier *NNS = 0;
SourceRange Range;
if (SS.isSet()) {
NNS = (NestedNameSpecifier *)SS.getScopeRep();
Range = SourceRange(SS.getRange().getBegin(), NameLoc);
} else {
NNS = NestedNameSpecifier::Create(Context, &II);
Range = SourceRange(NameLoc);
}
QualType T = CheckTypenameType(ETK_None, NNS, II,
SourceLocation(),
Range, NameLoc);
return ParsedType::make(T);
}
if (ObjectTypePtr)
Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
<< &II;
else
Diag(NameLoc, diag::err_destructor_class_name);
return ParsedType();
}
/// \brief Build a C++ typeid expression with a type operand.
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc) {
// C++ [expr.typeid]p4:
// The top-level cv-qualifiers of the lvalue expression or the type-id
// that is the operand of typeid are always ignored.
// If the type of the type-id is a class type or a reference to a class
// type, the class shall be completely-defined.
Qualifiers Quals;
QualType T
= Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
Quals);
if (T->getAs<RecordType>() &&
RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
return ExprError();
return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
Operand,
SourceRange(TypeidLoc, RParenLoc)));
}
/// \brief Build a C++ typeid expression with an expression operand.
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *E,
SourceLocation RParenLoc) {
bool isUnevaluatedOperand = true;
if (E && !E->isTypeDependent()) {
QualType T = E->getType();
if (const RecordType *RecordT = T->getAs<RecordType>()) {
CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
// C++ [expr.typeid]p3:
// [...] If the type of the expression is a class type, the class
// shall be completely-defined.
if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
return ExprError();
// C++ [expr.typeid]p3:
// When typeid is applied to an expression other than an glvalue of a
// polymorphic class type [...] [the] expression is an unevaluated
// operand. [...]
if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
isUnevaluatedOperand = false;
// We require a vtable to query the type at run time.
MarkVTableUsed(TypeidLoc, RecordD);
}
}
// C++ [expr.typeid]p4:
// [...] If the type of the type-id is a reference to a possibly
// cv-qualified type, the result of the typeid expression refers to a
// std::type_info object representing the cv-unqualified referenced
// type.
Qualifiers Quals;
QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
if (!Context.hasSameType(T, UnqualT)) {
T = UnqualT;
ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
}
}
// If this is an unevaluated operand, clear out the set of
// declaration references we have been computing and eliminate any
// temporaries introduced in its computation.
if (isUnevaluatedOperand)
ExprEvalContexts.back().Context = Unevaluated;
return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
E,
SourceRange(TypeidLoc, RParenLoc)));
}
/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
ExprResult
Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
// Find the std::type_info type.
if (!StdNamespace)
return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
LookupQualifiedName(R, getStdNamespace());
RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
if (!TypeInfoRecordDecl)
return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
if (isType) {
// The operand is a type; handle it as such.
TypeSourceInfo *TInfo = 0;
QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
&TInfo);
if (T.isNull())
return ExprError();
if (!TInfo)
TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
}
// The operand is an expression.
return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
}
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult
Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
"Unknown C++ Boolean value!");
return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
Context.BoolTy, OpLoc));
}
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult
Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
}
/// ActOnCXXThrow - Parse throw expressions.
ExprResult
Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
return ExprError();
return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
}
/// CheckCXXThrowOperand - Validate the operand of a throw.
bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
// C++ [except.throw]p3:
// A throw-expression initializes a temporary object, called the exception
// object, the type of which is determined by removing any top-level
// cv-qualifiers from the static type of the operand of throw and adjusting
// the type from "array of T" or "function returning T" to "pointer to T"
// or "pointer to function returning T", [...]
if (E->getType().hasQualifiers())
ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
CastCategory(E));
DefaultFunctionArrayConversion(E);
// If the type of the exception would be an incomplete type or a pointer
// to an incomplete type other than (cv) void the program is ill-formed.
QualType Ty = E->getType();
bool isPointer = false;
if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Ty = Ptr->getPointeeType();
isPointer = true;
}
if (!isPointer || !Ty->isVoidType()) {
if (RequireCompleteType(ThrowLoc, Ty,
PDiag(isPointer ? diag::err_throw_incomplete_ptr
: diag::err_throw_incomplete)
<< E->getSourceRange()))
return true;
if (RequireNonAbstractType(ThrowLoc, E->getType(),
PDiag(diag::err_throw_abstract_type)
<< E->getSourceRange()))
return true;
}
// Initialize the exception result. This implicitly weeds out
// abstract types or types with inaccessible copy constructors.
// FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
InitializedEntity Entity =
InitializedEntity::InitializeException(ThrowLoc, E->getType(),
/*NRVO=*/false);
ExprResult Res = PerformCopyInitialization(Entity,
SourceLocation(),
Owned(E));
if (Res.isInvalid())
return true;
E = Res.takeAs<Expr>();
// If the exception has class type, we need additional handling.
const RecordType *RecordTy = Ty->getAs<RecordType>();
if (!RecordTy)
return false;
CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
// If we are throwing a polymorphic class type or pointer thereof,
// exception handling will make use of the vtable.
MarkVTableUsed(ThrowLoc, RD);
// If the class has a non-trivial destructor, we must be able to call it.
if (RD->hasTrivialDestructor())
return false;
CXXDestructorDecl *Destructor
= const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
if (!Destructor)
return false;
MarkDeclarationReferenced(E->getExprLoc(), Destructor);
CheckDestructorAccess(E->getExprLoc(), Destructor,
PDiag(diag::err_access_dtor_exception) << Ty);
return false;
}
ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
/// C++ 9.3.2: In the body of a non-static member function, the keyword this
/// is a non-lvalue expression whose value is the address of the object for
/// which the function is called.
DeclContext *DC = getFunctionLevelDeclContext();
if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
if (MD->isInstance())
return Owned(new (Context) CXXThisExpr(ThisLoc,
MD->getThisType(Context),
/*isImplicit=*/false));
return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
}
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult
Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, ParsedType TypeRep,
SourceLocation LParenLoc,
MultiExprArg exprs,
SourceLocation *CommaLocs,
SourceLocation RParenLoc) {
if (!TypeRep)
return ExprError();
TypeSourceInfo *TInfo;
QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
if (!TInfo)
TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
unsigned NumExprs = exprs.size();
Expr **Exprs = (Expr**)exprs.get();
SourceLocation TyBeginLoc = TypeRange.getBegin();
SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
if (Ty->isDependentType() ||
CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
exprs.release();
return Owned(CXXUnresolvedConstructExpr::Create(Context,
TypeRange.getBegin(), Ty,
LParenLoc,
Exprs, NumExprs,
RParenLoc));
}
if (Ty->isArrayType())
return ExprError(Diag(TyBeginLoc,
diag::err_value_init_for_array_type) << FullRange);
if (!Ty->isVoidType() &&
RequireCompleteType(TyBeginLoc, Ty,
PDiag(diag::err_invalid_incomplete_type_use)
<< FullRange))
return ExprError();
if (RequireNonAbstractType(TyBeginLoc, Ty,
diag::err_allocation_of_abstract_type))
return ExprError();
// C++ [expr.type.conv]p1:
// If the expression list is a single expression, the type conversion
// expression is equivalent (in definedness, and if defined in meaning) to the
// corresponding cast expression.
//
if (NumExprs == 1) {
CastKind Kind = CK_Unknown;
CXXCastPath BasePath;
if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
/*FunctionalStyle=*/true))
return ExprError();
exprs.release();
return Owned(CXXFunctionalCastExpr::Create(Context,
Ty.getNonLValueExprType(Context),
TInfo, TyBeginLoc, Kind,
Exprs[0], &BasePath,
RParenLoc));
}
if (Ty->isRecordType()) {
InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
InitializationKind Kind
= NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
LParenLoc, RParenLoc)
: InitializationKind::CreateValue(TypeRange.getBegin(),
LParenLoc, RParenLoc);
InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
move(exprs));
// FIXME: Improve AST representation?
return move(Result);
}
// C++ [expr.type.conv]p1:
// If the expression list specifies more than a single value, the type shall
// be a class with a suitably declared constructor.
//
if (NumExprs > 1)
return ExprError(Diag(CommaLocs[0],
diag::err_builtin_func_cast_more_than_one_arg)
<< FullRange);
assert(NumExprs == 0 && "Expected 0 expressions");
// C++ [expr.type.conv]p2:
// The expression T(), where T is a simple-type-specifier for a non-array
// complete object type or the (possibly cv-qualified) void type, creates an
// rvalue of the specified type, which is value-initialized.
//
exprs.release();
return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc));
}
/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
/// @code new (memory) int[size][4] @endcode
/// or
/// @code ::new Foo(23, "hello") @endcode
/// For the interpretation of this heap of arguments, consult the base version.
ExprResult
Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
SourceLocation PlacementRParen, SourceRange TypeIdParens,
Declarator &D, SourceLocation ConstructorLParen,
MultiExprArg ConstructorArgs,
SourceLocation ConstructorRParen) {
Expr *ArraySize = 0;
// If the specified type is an array, unwrap it and save the expression.
if (D.getNumTypeObjects() > 0 &&
D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
DeclaratorChunk &Chunk = D.getTypeObject(0);
if (Chunk.Arr.hasStatic)
return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
<< D.getSourceRange());
if (!Chunk.Arr.NumElts)
return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
<< D.getSourceRange());
ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
D.DropFirstTypeObject();
}
// Every dimension shall be of constant size.
if (ArraySize) {
for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
break;
DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
if (Expr *NumElts = (Expr *)Array.NumElts) {
if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
!NumElts->isIntegerConstantExpr(Context)) {
Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
<< NumElts->getSourceRange();
return ExprError();
}
}
}
}
//FIXME: Store TypeSourceInfo in CXXNew expression.
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
QualType AllocType = TInfo->getType();
if (D.isInvalidType())
return ExprError();
SourceRange R = TInfo->getTypeLoc().getSourceRange();
return BuildCXXNew(StartLoc, UseGlobal,
PlacementLParen,
move(PlacementArgs),
PlacementRParen,
TypeIdParens,
AllocType,
D.getSourceRange().getBegin(),
R,
ArraySize,
ConstructorLParen,
move(ConstructorArgs),
ConstructorRParen);
}
ExprResult
Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
SourceLocation TypeLoc,
SourceRange TypeRange,
Expr *ArraySize,
SourceLocation ConstructorLParen,
MultiExprArg ConstructorArgs,
SourceLocation ConstructorRParen) {
if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
return ExprError();
// Per C++0x [expr.new]p5, the type being constructed may be a
// typedef of an array type.
if (!ArraySize) {
if (const ConstantArrayType *Array
= Context.getAsConstantArrayType(AllocType)) {
ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
Context.getSizeType(),
TypeRange.getEnd());
AllocType = Array->getElementType();
}
}
QualType ResultType = Context.getPointerType(AllocType);
// C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
// or enumeration type with a non-negative value."
if (ArraySize && !ArraySize->isTypeDependent()) {
QualType SizeType = ArraySize->getType();
ExprResult ConvertedSize
= ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
PDiag(diag::err_array_size_not_integral),
PDiag(diag::err_array_size_incomplete_type)
<< ArraySize->getSourceRange(),
PDiag(diag::err_array_size_explicit_conversion),
PDiag(diag::note_array_size_conversion),
PDiag(diag::err_array_size_ambiguous_conversion),
PDiag(diag::note_array_size_conversion),
PDiag(getLangOptions().CPlusPlus0x? 0
: diag::ext_array_size_conversion));
if (ConvertedSize.isInvalid())
return ExprError();
ArraySize = ConvertedSize.take();
SizeType = ArraySize->getType();
if (!SizeType->isIntegralOrEnumerationType())
return ExprError();
// Let's see if this is a constant < 0. If so, we reject it out of hand.
// We don't care about special rules, so we tell the machinery it's not
// evaluated - it gives us a result in more cases.
if (!ArraySize->isValueDependent()) {
llvm::APSInt Value;
if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
if (Value < llvm::APSInt(
llvm::APInt::getNullValue(Value.getBitWidth()),
Value.isUnsigned()))
return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
diag::err_typecheck_negative_array_size)
<< ArraySize->getSourceRange());
if (!AllocType->isDependentType()) {
unsigned ActiveSizeBits
= ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
Diag(ArraySize->getSourceRange().getBegin(),
diag::err_array_too_large)
<< Value.toString(10)
<< ArraySize->getSourceRange();
return ExprError();
}
}
} else if (TypeIdParens.isValid()) {
// Can't have dynamic array size when the type-id is in parentheses.
Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
<< ArraySize->getSourceRange()
<< FixItHint::CreateRemoval(TypeIdParens.getBegin())
<< FixItHint::CreateRemoval(TypeIdParens.getEnd());
TypeIdParens = SourceRange();
}
}
ImpCastExprToType(ArraySize, Context.getSizeType(),
CK_IntegralCast);
}
FunctionDecl *OperatorNew = 0;
FunctionDecl *OperatorDelete = 0;
Expr **PlaceArgs = (Expr**)PlacementArgs.get();
unsigned NumPlaceArgs = PlacementArgs.size();
if (!AllocType->isDependentType() &&
!Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
FindAllocationFunctions(StartLoc,
SourceRange(PlacementLParen, PlacementRParen),
UseGlobal, AllocType, ArraySize, PlaceArgs,
NumPlaceArgs, OperatorNew, OperatorDelete))
return ExprError();
llvm::SmallVector<Expr *, 8> AllPlaceArgs;
if (OperatorNew) {
// Add default arguments, if any.
const FunctionProtoType *Proto =
OperatorNew->getType()->getAs<FunctionProtoType>();
VariadicCallType CallType =
Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
Proto, 1, PlaceArgs, NumPlaceArgs,
AllPlaceArgs, CallType))
return ExprError();
NumPlaceArgs = AllPlaceArgs.size();
if (NumPlaceArgs > 0)
PlaceArgs = &AllPlaceArgs[0];
}
bool Init = ConstructorLParen.isValid();
// --- Choosing a constructor ---
CXXConstructorDecl *Constructor = 0;
Expr **ConsArgs = (Expr**)ConstructorArgs.get();
unsigned NumConsArgs = ConstructorArgs.size();
ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
// Array 'new' can't have any initializers.
if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
SourceRange InitRange(ConsArgs[0]->getLocStart(),
ConsArgs[NumConsArgs - 1]->getLocEnd());
Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
return ExprError();
}
if (!AllocType->isDependentType() &&
!Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
// C++0x [expr.new]p15:
// A new-expression that creates an object of type T initializes that
// object as follows:
InitializationKind Kind
// - If the new-initializer is omitted, the object is default-
// initialized (8.5); if no initialization is performed,
// the object has indeterminate value
= !Init? InitializationKind::CreateDefault(TypeLoc)
// - Otherwise, the new-initializer is interpreted according to the
// initialization rules of 8.5 for direct-initialization.
: InitializationKind::CreateDirect(TypeLoc,
ConstructorLParen,
ConstructorRParen);
InitializedEntity Entity
= InitializedEntity::InitializeNew(StartLoc, AllocType);
InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
move(ConstructorArgs));
if (FullInit.isInvalid())
return ExprError();
// FullInit is our initializer; walk through it to determine if it's a
// constructor call, which CXXNewExpr handles directly.
if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
if (CXXBindTemporaryExpr *Binder
= dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
FullInitExpr = Binder->getSubExpr();
if (CXXConstructExpr *Construct
= dyn_cast<CXXConstructExpr>(FullInitExpr)) {
Constructor = Construct->getConstructor();
for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
AEnd = Construct->arg_end();
A != AEnd; ++A)
ConvertedConstructorArgs.push_back(A->Retain());
} else {
// Take the converted initializer.
ConvertedConstructorArgs.push_back(FullInit.release());
}
} else {
// No initialization required.
}
// Take the converted arguments and use them for the new expression.
NumConsArgs = ConvertedConstructorArgs.size();
ConsArgs = (Expr **)ConvertedConstructorArgs.take();
}
// Mark the new and delete operators as referenced.
if (OperatorNew)
MarkDeclarationReferenced(StartLoc, OperatorNew);
if (OperatorDelete)
MarkDeclarationReferenced(StartLoc, OperatorDelete);
// FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
PlacementArgs.release();
ConstructorArgs.release();
// FIXME: The TypeSourceInfo should also be included in CXXNewExpr.
return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
PlaceArgs, NumPlaceArgs, TypeIdParens,
ArraySize, Constructor, Init,
ConsArgs, NumConsArgs, OperatorDelete,
ResultType, StartLoc,
Init ? ConstructorRParen :
TypeRange.getEnd()));
}
/// CheckAllocatedType - Checks that a type is suitable as the allocated type
/// in a new-expression.
/// dimension off and stores the size expression in ArraySize.
bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R) {
// C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
// abstract class type or array thereof.
if (AllocType->isFunctionType())
return Diag(Loc, diag::err_bad_new_type)
<< AllocType << 0 << R;
else if (AllocType->isReferenceType())
return Diag(Loc, diag::err_bad_new_type)
<< AllocType << 1 << R;
else if (!AllocType->isDependentType() &&
RequireCompleteType(Loc, AllocType,
PDiag(diag::err_new_incomplete_type)
<< R))
return true;
else if (RequireNonAbstractType(Loc, AllocType,
diag::err_allocation_of_abstract_type))
return true;
return false;
}
/// \brief Determine whether the given function is a non-placement
/// deallocation function.
static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
if (FD->isInvalidDecl())
return false;
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
return Method->isUsualDeallocationFunction();
return ((FD->getOverloadedOperator() == OO_Delete ||
FD->getOverloadedOperator() == OO_Array_Delete) &&
FD->getNumParams() == 1);
}
/// FindAllocationFunctions - Finds the overloads of operator new and delete
/// that are appropriate for the allocation.
bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
bool UseGlobal, QualType AllocType,
bool IsArray, Expr **PlaceArgs,
unsigned NumPlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete) {
// --- Choosing an allocation function ---
// C++ 5.3.4p8 - 14 & 18
// 1) If UseGlobal is true, only look in the global scope. Else, also look
// in the scope of the allocated class.
// 2) If an array size is given, look for operator new[], else look for
// operator new.
// 3) The first argument is always size_t. Append the arguments from the
// placement form.
llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
// We don't care about the actual value of this argument.
// FIXME: Should the Sema create the expression and embed it in the syntax
// tree? Or should the consumer just recalculate the value?
IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Context.Target.getPointerWidth(0)),
Context.getSizeType(),
SourceLocation());
AllocArgs[0] = &Size;
std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
// C++ [expr.new]p8:
// If the allocated type is a non-array type, the allocation
// function’s name is operator new and the deallocation function’s
// name is operator delete. If the allocated type is an array
// type, the allocation function’s name is operator new[] and the
// deallocation function’s name is operator delete[].
DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
IsArray ? OO_Array_New : OO_New);
DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
IsArray ? OO_Array_Delete : OO_Delete);
QualType AllocElemType = Context.getBaseElementType(AllocType);
if (AllocElemType->isRecordType() && !UseGlobal) {
CXXRecordDecl *Record
= cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
AllocArgs.size(), Record, /*AllowMissing=*/true,
OperatorNew))
return true;
}
if (!OperatorNew) {
// Didn't find a member overload. Look for a global one.
DeclareGlobalNewDelete();
DeclContext *TUDecl = Context.getTranslationUnitDecl();
if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
OperatorNew))
return true;
}
// We don't need an operator delete if we're running under
// -fno-exceptions.
if (!getLangOptions().Exceptions) {
OperatorDelete = 0;
return false;
}
// FindAllocationOverload can change the passed in arguments, so we need to
// copy them back.
if (NumPlaceArgs > 0)
std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
// C++ [expr.new]p19:
//
// If the new-expression begins with a unary :: operator, the
// deallocation function’s name is looked up in the global
// scope. Otherwise, if the allocated type is a class type T or an
// array thereof, the deallocation function’s name is looked up in
// the scope of T. If this lookup fails to find the name, or if
// the allocated type is not a class type or array thereof, the
// deallocation function’s name is looked up in the global scope.
LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
if (AllocElemType->isRecordType() && !UseGlobal) {
CXXRecordDecl *RD
= cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
LookupQualifiedName(FoundDelete, RD);
}
if (FoundDelete.isAmbiguous())
return true; // FIXME: clean up expressions?
if (FoundDelete.empty()) {
DeclareGlobalNewDelete();
LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
}
FoundDelete.suppressDiagnostics();
llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
if (NumPlaceArgs > 0) {
// C++ [expr.new]p20:
// A declaration of a placement deallocation function matches the
// declaration of a placement allocation function if it has the
// same number of parameters and, after parameter transformations
// (8.3.5), all parameter types except the first are
// identical. [...]
//
// To perform this comparison, we compute the function type that
// the deallocation function should have, and use that type both
// for template argument deduction and for comparison purposes.
QualType ExpectedFunctionType;
{
const FunctionProtoType *Proto
= OperatorNew->getType()->getAs<FunctionProtoType>();
llvm::SmallVector<QualType, 4> ArgTypes;
ArgTypes.push_back(Context.VoidPtrTy);
for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
ArgTypes.push_back(Proto->getArgType(I));
ExpectedFunctionType
= Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
ArgTypes.size(),
Proto->isVariadic(),
0, false, false, 0, 0,
FunctionType::ExtInfo());
}
for (LookupResult::iterator D = FoundDelete.begin(),
DEnd = FoundDelete.end();
D != DEnd; ++D) {
FunctionDecl *Fn = 0;
if (FunctionTemplateDecl *FnTmpl
= dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
// Perform template argument deduction to try to match the
// expected function type.
TemplateDeductionInfo Info(Context, StartLoc);
if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
continue;
} else
Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
Matches.push_back(std::make_pair(D.getPair(), Fn));
}
} else {
// C++ [expr.new]p20:
// [...] Any non-placement deallocation function matches a
// non-placement allocation function. [...]
for (LookupResult::iterator D = FoundDelete.begin(),
DEnd = FoundDelete.end();
D != DEnd; ++D) {
if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
if (isNonPlacementDeallocationFunction(Fn))
Matches.push_back(std::make_pair(D.getPair(), Fn));
}
}
// C++ [expr.new]p20:
// [...] If the lookup finds a single matching deallocation
// function, that function will be called; otherwise, no
// deallocation function will be called.
if (Matches.size() == 1) {
OperatorDelete = Matches[0].second;
// C++0x [expr.new]p20:
// If the lookup finds the two-parameter form of a usual
// deallocation function (3.7.4.2) and that function, considered
// as a placement deallocation function, would have been
// selected as a match for the allocation function, the program
// is ill-formed.
if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
isNonPlacementDeallocationFunction(OperatorDelete)) {
Diag(StartLoc, diag::err_placement_new_non_placement_delete)
<< SourceRange(PlaceArgs[0]->getLocStart(),
PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
<< DeleteName;
} else {
CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
Matches[0].first);
}
}
return false;
}
/// FindAllocationOverload - Find an fitting overload for the allocation
/// function in the specified scope.
bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
DeclarationName Name, Expr** Args,
unsigned NumArgs, DeclContext *Ctx,
bool AllowMissing, FunctionDecl *&Operator) {
LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
LookupQualifiedName(R, Ctx);
if (R.empty()) {
if (AllowMissing)
return false;
return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
<< Name << Range;
}
if (R.isAmbiguous())
return true;
R.suppressDiagnostics();
OverloadCandidateSet Candidates(StartLoc);
for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Alloc != AllocEnd; ++Alloc) {
// Even member operator new/delete are implicitly treated as
// static, so don't use AddMemberCandidate.
NamedDecl *D = (*Alloc)->getUnderlyingDecl();
if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
/*ExplicitTemplateArgs=*/0, Args, NumArgs,
Candidates,
/*SuppressUserConversions=*/false);
continue;
}
FunctionDecl *Fn = cast<FunctionDecl>(D);
AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
/*SuppressUserConversions=*/false);
}
// Do the resolution.
OverloadCandidateSet::iterator Best;
switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
case OR_Success: {
// Got one!
FunctionDecl *FnDecl = Best->Function;
// The first argument is size_t, and the first parameter must be size_t,
// too. This is checked on declaration and can be assumed. (It can't be
// asserted on, though, since invalid decls are left in there.)
// Watch out for variadic allocator function.
unsigned NumArgsInFnDecl = FnDecl->getNumParams();
for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
ExprResult Result
= PerformCopyInitialization(InitializedEntity::InitializeParameter(
FnDecl->getParamDecl(i)),
SourceLocation(),
Owned(Args[i]->Retain()));
if (Result.isInvalid())
return true;
Args[i] = Result.takeAs<Expr>();
}
Operator = FnDecl;
CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
return false;
}
case OR_No_Viable_Function:
Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
<< Name << Range;
Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
return true;
case OR_Ambiguous:
Diag(StartLoc, diag::err_ovl_ambiguous_call)
<< Name << Range;
Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
return true;
case OR_Deleted:
Diag(StartLoc, diag::err_ovl_deleted_call)
<< Best->Function->isDeleted()
<< Name << Range;
Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
return true;
}
assert(false && "Unreachable, bad result from BestViableFunction");
return true;
}
/// DeclareGlobalNewDelete - Declare the global forms of operator new and
/// delete. These are:
/// @code
/// void* operator new(std::size_t) throw(std::bad_alloc);
/// void* operator new[](std::size_t) throw(std::bad_alloc);
/// void operator delete(void *) throw();
/// void operator delete[](void *) throw();
/// @endcode
/// Note that the placement and nothrow forms of new are *not* implicitly
/// declared. Their use requires including \<new\>.
void Sema::DeclareGlobalNewDelete() {
if (GlobalNewDeleteDeclared)
return;
// C++ [basic.std.dynamic]p2:
// [...] The following allocation and deallocation functions (18.4) are
// implicitly declared in global scope in each translation unit of a
// program
//
// void* operator new(std::size_t) throw(std::bad_alloc);
// void* operator new[](std::size_t) throw(std::bad_alloc);
// void operator delete(void*) throw();
// void operator delete[](void*) throw();
//
// These implicit declarations introduce only the function names operator
// new, operator new[], operator delete, operator delete[].
//
// Here, we need to refer to std::bad_alloc, so we will implicitly declare
// "std" or "bad_alloc" as necessary to form the exception specification.
// However, we do not make these implicit declarations visible to name
// lookup.
if (!StdBadAlloc) {
// The "std::bad_alloc" class has not yet been declared, so build it
// implicitly.
StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
getOrCreateStdNamespace(),
SourceLocation(),
&PP.getIdentifierTable().get("bad_alloc"),
SourceLocation(), 0);
getStdBadAlloc()->setImplicit(true);
}
GlobalNewDeleteDeclared = true;
QualType VoidPtr = Context.getPointerType(Context.VoidTy);
QualType SizeT = Context.getSizeType();
bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
DeclareGlobalAllocationFunction(
Context.DeclarationNames.getCXXOperatorName(OO_New),
VoidPtr, SizeT, AssumeSaneOperatorNew);
DeclareGlobalAllocationFunction(
Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
VoidPtr, SizeT, AssumeSaneOperatorNew);
DeclareGlobalAllocationFunction(
Context.DeclarationNames.getCXXOperatorName(OO_Delete),
Context.VoidTy, VoidPtr);
DeclareGlobalAllocationFunction(
Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
Context.VoidTy, VoidPtr);
}
/// DeclareGlobalAllocationFunction - Declares a single implicit global
/// allocation function if it doesn't already exist.
void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
QualType Return, QualType Argument,
bool AddMallocAttr) {
DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
// Check if this function is already declared.
{
DeclContext::lookup_iterator Alloc, AllocEnd;
for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Alloc != AllocEnd; ++Alloc) {
// Only look at non-template functions, as it is the predefined,
// non-templated allocation function we are trying to declare here.
if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
QualType InitialParamType =
Context.getCanonicalType(
Func->getParamDecl(0)->getType().getUnqualifiedType());
// FIXME: Do we need to check for default arguments here?
if (Func->getNumParams() == 1 && InitialParamType == Argument) {
if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
return;
}
}
}
}
QualType BadAllocType;
bool HasBadAllocExceptionSpec
= (Name.getCXXOverloadedOperator() == OO_New ||
Name.getCXXOverloadedOperator() == OO_Array_New);
if (HasBadAllocExceptionSpec) {
assert(StdBadAlloc && "Must have std::bad_alloc declared");
BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
}
QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
true, false,
HasBadAllocExceptionSpec? 1 : 0,
&BadAllocType,
FunctionType::ExtInfo());
FunctionDecl *Alloc =
FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
FnType, /*TInfo=*/0, SC_None,
SC_None, false, true);
Alloc->setImplicit();
if (AddMallocAttr)
Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
0, Argument, /*TInfo=*/0,
SC_None,
SC_None, 0);
Alloc->setParams(&Param, 1);
// FIXME: Also add this declaration to the IdentifierResolver, but
// make sure it is at the end of the chain to coincide with the
// global scope.
Context.getTranslationUnitDecl()->addDecl(Alloc);
}
bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name,
FunctionDecl* &Operator) {
LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
// Try to find operator delete/operator delete[] in class scope.
LookupQualifiedName(Found, RD);
if (Found.isAmbiguous())
return true;
Found.suppressDiagnostics();
llvm::SmallVector<DeclAccessPair,4> Matches;
for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
F != FEnd; ++F) {
NamedDecl *ND = (*F)->getUnderlyingDecl();
// Ignore template operator delete members from the check for a usual
// deallocation function.
if (isa<FunctionTemplateDecl>(ND))
continue;
if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
Matches.push_back(F.getPair());
}
// There's exactly one suitable operator; pick it.
if (Matches.size() == 1) {
Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Matches[0]);
return false;
// We found multiple suitable operators; complain about the ambiguity.
} else if (!Matches.empty()) {
Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
<< Name << RD;
for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
Diag((*F)->getUnderlyingDecl()->getLocation(),
diag::note_member_declared_here) << Name;
return true;
}
// We did find operator delete/operator delete[] declarations, but
// none of them were suitable.
if (!Found.empty()) {
Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
<< Name << RD;
for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
F != FEnd; ++F)
Diag((*F)->getUnderlyingDecl()->getLocation(),
diag::note_member_declared_here) << Name;
return true;
}
// Look for a global declaration.
DeclareGlobalNewDelete();
DeclContext *TUDecl = Context.getTranslationUnitDecl();
CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
Expr* DeallocArgs[1];
DeallocArgs[0] = &Null;
if (FindAllocationOverload(StartLoc, SourceRange(), Name,
DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
Operator))
return true;
assert(Operator && "Did not find a deallocation function!");
return false;
}
/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
/// @code ::delete ptr; @endcode
/// or
/// @code delete [] ptr; @endcode
ExprResult
Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
bool ArrayForm, Expr *Ex) {
// C++ [expr.delete]p1:
// The operand shall have a pointer type, or a class type having a single
// conversion function to a pointer type. The result has type void.
//
// DR599 amends "pointer type" to "pointer to object type" in both cases.
FunctionDecl *OperatorDelete = 0;
if (!Ex->isTypeDependent()) {
QualType Type = Ex->getType();
if (const RecordType *Record = Type->getAs<RecordType>()) {
if (RequireCompleteType(StartLoc, Type,
PDiag(diag::err_delete_incomplete_class_type)))
return ExprError();
llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
for (UnresolvedSetImpl::iterator I = Conversions->begin(),
E = Conversions->end(); I != E; ++I) {
NamedDecl *D = I.getDecl();
if (isa<UsingShadowDecl>(D))
D = cast<UsingShadowDecl>(D)->getTargetDecl();
// Skip over templated conversion functions; they aren't considered.
if (isa<FunctionTemplateDecl>(D))
continue;
CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
QualType ConvType = Conv->getConversionType().getNonReferenceType();
if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
ObjectPtrConversions.push_back(Conv);
}
if (ObjectPtrConversions.size() == 1) {
// We have a single conversion to a pointer-to-object type. Perform
// that conversion.
// TODO: don't redo the conversion calculation.
if (!PerformImplicitConversion(Ex,
ObjectPtrConversions.front()->getConversionType(),
AA_Converting)) {
Type = Ex->getType();
}
}
else if (ObjectPtrConversions.size() > 1) {
Diag(StartLoc, diag::err_ambiguous_delete_operand)
<< Type << Ex->getSourceRange();
for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
NoteOverloadCandidate(ObjectPtrConversions[i]);
return ExprError();
}
}
if (!Type->isPointerType())
return ExprError(Diag(StartLoc, diag::err_delete_operand)
<< Type << Ex->getSourceRange());
QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
if (Pointee->isVoidType() && !isSFINAEContext()) {
// The C++ standard bans deleting a pointer to a non-object type, which
// effectively bans deletion of "void*". However, most compilers support
// this, so we treat it as a warning unless we're in a SFINAE context.
Diag(StartLoc, diag::ext_delete_void_ptr_operand)
<< Type << Ex->getSourceRange();
} else if (Pointee->isFunctionType() || Pointee->isVoidType())
return ExprError(Diag(StartLoc, diag::err_delete_operand)
<< Type << Ex->getSourceRange());
else if (!Pointee->isDependentType() &&
RequireCompleteType(StartLoc, Pointee,
PDiag(diag::warn_delete_incomplete)
<< Ex->getSourceRange()))
return ExprError();
// C++ [expr.delete]p2:
// [Note: a pointer to a const type can be the operand of a
// delete-expression; it is not necessary to cast away the constness
// (5.2.11) of the pointer expression before it is used as the operand
// of the delete-expression. ]
ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
CK_NoOp);
DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
ArrayForm ? OO_Array_Delete : OO_Delete);
QualType PointeeElem = Context.getBaseElementType(Pointee);
if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
if (!UseGlobal &&
FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
return ExprError();
if (!RD->hasTrivialDestructor())
if (const CXXDestructorDecl *Dtor = LookupDestructor(RD))
MarkDeclarationReferenced(StartLoc,
const_cast<CXXDestructorDecl*>(Dtor));
}
if (!OperatorDelete) {
// Look for a global declaration.
DeclareGlobalNewDelete();
DeclContext *TUDecl = Context.getTranslationUnitDecl();
if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
&Ex, 1, TUDecl, /*AllowMissing=*/false,
OperatorDelete))
return ExprError();
}
MarkDeclarationReferenced(StartLoc, OperatorDelete);
// FIXME: Check access and ambiguity of operator delete and destructor.
}
return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
OperatorDelete, Ex, StartLoc));
}
/// \brief Check the use of the given variable as a C++ condition in an if,
/// while, do-while, or switch statement.
ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
bool ConvertToBoolean) {
QualType T = ConditionVar->getType();
// C++ [stmt.select]p2:
// The declarator shall not specify a function or an array.
if (T->isFunctionType())
return ExprError(Diag(ConditionVar->getLocation(),
diag::err_invalid_use_of_function_type)
<< ConditionVar->getSourceRange());
else if (T->isArrayType())
return ExprError(Diag(ConditionVar->getLocation(),
diag::err_invalid_use_of_array_type)
<< ConditionVar->getSourceRange());
Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
ConditionVar->getLocation(),
ConditionVar->getType().getNonReferenceType());
if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
return ExprError();
return Owned(Condition);
}
/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
// C++ 6.4p4:
// The value of a condition that is an initialized declaration in a statement
// other than a switch statement is the value of the declared variable
// implicitly converted to type bool. If that conversion is ill-formed, the
// program is ill-formed.
// The value of a condition that is an expression is the value of the
// expression, implicitly converted to bool.
//
return PerformContextuallyConvertToBool(CondExpr);
}
/// Helper function to determine whether this is the (deprecated) C++
/// conversion from a string literal to a pointer to non-const char or
/// non-const wchar_t (for narrow and wide string literals,
/// respectively).
bool
Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
// Look inside the implicit cast, if it exists.
if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
From = Cast->getSubExpr();
// A string literal (2.13.4) that is not a wide string literal can
// be converted to an rvalue of type "pointer to char"; a wide
// string literal can be converted to an rvalue of type "pointer
// to wchar_t" (C++ 4.2p2).
if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
if (const BuiltinType *ToPointeeType
= ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
// This conversion is considered only when there is an
// explicit appropriate pointer target type (C++ 4.2p2).
if (!ToPtrType->getPointeeType().hasQualifiers() &&
((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
(!StrLit->isWide() &&
(ToPointeeType->getKind() == BuiltinType::Char_U ||
ToPointeeType->getKind() == BuiltinType::Char_S))))
return true;
}
return false;
}
static ExprResult BuildCXXCastArgument(Sema &S,
SourceLocation CastLoc,
QualType Ty,
CastKind Kind,
CXXMethodDecl *Method,
Expr *From) {
switch (Kind) {
default: assert(0 && "Unhandled cast kind!");
case CK_ConstructorConversion: {
ASTOwningVector<Expr*> ConstructorArgs(S);
if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
MultiExprArg(&From, 1),
CastLoc, ConstructorArgs))
return ExprError();
ExprResult Result =
S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
move_arg(ConstructorArgs),
/*ZeroInit*/ false, CXXConstructExpr::CK_Complete);
if (Result.isInvalid())
return ExprError();
return S.MaybeBindToTemporary(Result.takeAs<Expr>());
}
case CK_UserDefinedConversion: {
assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
// Create an implicit call expr that calls it.
// FIXME: pass the FoundDecl for the user-defined conversion here
CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
return S.MaybeBindToTemporary(CE);
}
}
}
/// PerformImplicitConversion - Perform an implicit conversion of the
/// expression From to the type ToType using the pre-computed implicit
/// conversion sequence ICS. Returns true if there was an error, false
/// otherwise. The expression From is replaced with the converted
/// expression. Action is the kind of conversion we're performing,
/// used in the error message.
bool
Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
const ImplicitConversionSequence &ICS,
AssignmentAction Action, bool IgnoreBaseAccess) {
switch (ICS.getKind()) {
case ImplicitConversionSequence::StandardConversion:
if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
IgnoreBaseAccess))
return true;
break;
case ImplicitConversionSequence::UserDefinedConversion: {
FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
CastKind CastKind = CK_Unknown;
QualType BeforeToType;
if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
CastKind = CK_UserDefinedConversion;
// If the user-defined conversion is specified by a conversion function,
// the initial standard conversion sequence converts the source type to
// the implicit object parameter of the conversion function.
BeforeToType = Context.getTagDeclType(Conv->getParent());
} else if (const CXXConstructorDecl *Ctor =
dyn_cast<CXXConstructorDecl>(FD)) {
CastKind = CK_ConstructorConversion;
// Do no conversion if dealing with ... for the first conversion.
if (!ICS.UserDefined.EllipsisConversion) {
// If the user-defined conversion is specified by a constructor, the
// initial standard conversion sequence converts the source type to the
// type required by the argument of the constructor
BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
}
}
else
assert(0 && "Unknown conversion function kind!");
// Whatch out for elipsis conversion.
if (!ICS.UserDefined.EllipsisConversion) {
if (PerformImplicitConversion(From, BeforeToType,
ICS.UserDefined.Before, AA_Converting,
IgnoreBaseAccess))
return true;
}
ExprResult CastArg
= BuildCXXCastArgument(*this,
From->getLocStart(),
ToType.getNonReferenceType(),
CastKind, cast<CXXMethodDecl>(FD),
From);
if (CastArg.isInvalid())
return true;
From = CastArg.takeAs<Expr>();
return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
AA_Converting, IgnoreBaseAccess);
}
case ImplicitConversionSequence::AmbiguousConversion:
ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
PDiag(diag::err_typecheck_ambiguous_condition)
<< From->getSourceRange());
return true;
case ImplicitConversionSequence::EllipsisConversion:
assert(false && "Cannot perform an ellipsis conversion");
return false;
case ImplicitConversionSequence::BadConversion:
return true;
}
// Everything went well.
return false;
}
/// PerformImplicitConversion - Perform an implicit conversion of the
/// expression From to the type ToType by following the standard
/// conversion sequence SCS. Returns true if there was an error, false
/// otherwise. The expression From is replaced with the converted
/// expression. Flavor is the context in which we're performing this
/// conversion, for use in error messages.
bool
Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action, bool IgnoreBaseAccess) {
// Overall FIXME: we are recomputing too many types here and doing far too
// much extra work. What this means is that we need to keep track of more
// information that is computed when we try the implicit conversion initially,
// so that we don't need to recompute anything here.
QualType FromType = From->getType();
if (SCS.CopyConstructor) {
// FIXME: When can ToType be a reference type?
assert(!ToType->isReferenceType());
if (SCS.Second == ICK_Derived_To_Base) {
ASTOwningVector<Expr*> ConstructorArgs(*this);
if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
MultiExprArg(*this, &From, 1),
/*FIXME:ConstructLoc*/SourceLocation(),
ConstructorArgs))
return true;
ExprResult FromResult =
BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
ToType, SCS.CopyConstructor,
move_arg(ConstructorArgs),
/*ZeroInit*/ false,
CXXConstructExpr::CK_Complete);
if (FromResult.isInvalid())
return true;
From = FromResult.takeAs<Expr>();
return false;
}
ExprResult FromResult =
BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
ToType, SCS.CopyConstructor,
MultiExprArg(*this, &From, 1),
/*ZeroInit*/ false,
CXXConstructExpr::CK_Complete);
if (FromResult.isInvalid())
return true;
From = FromResult.takeAs<Expr>();
return false;
}
// Resolve overloaded function references.
if (Context.hasSameType(FromType, Context.OverloadTy)) {
DeclAccessPair Found;
FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
true, Found);
if (!Fn)
return true;
if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
return true;
From = FixOverloadedFunctionReference(From, Found, Fn);
FromType = From->getType();
}
// Perform the first implicit conversion.
switch (SCS.First) {
case ICK_Identity:
case ICK_Lvalue_To_Rvalue:
// Nothing to do.
break;
case ICK_Array_To_Pointer:
FromType = Context.getArrayDecayedType(FromType);
ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
break;
case ICK_Function_To_Pointer:
FromType = Context.getPointerType(FromType);
ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
break;
default:
assert(false && "Improper first standard conversion");
break;
}
// Perform the second implicit conversion
switch (SCS.Second) {
case ICK_Identity:
// If both sides are functions (or pointers/references to them), there could
// be incompatible exception declarations.
if (CheckExceptionSpecCompatibility(From, ToType))
return true;
// Nothing else to do.
break;
case ICK_NoReturn_Adjustment:
// If both sides are functions (or pointers/references to them), there could
// be incompatible exception declarations.
if (CheckExceptionSpecCompatibility(From, ToType))
return true;
ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
CK_NoOp);
break;
case ICK_Integral_Promotion:
case ICK_Integral_Conversion:
ImpCastExprToType(From, ToType, CK_IntegralCast);
break;
case ICK_Floating_Promotion:
case ICK_Floating_Conversion:
ImpCastExprToType(From, ToType, CK_FloatingCast);
break;
case ICK_Complex_Promotion:
case ICK_Complex_Conversion:
ImpCastExprToType(From, ToType, CK_Unknown);
break;
case ICK_Floating_Integral:
if (ToType->isRealFloatingType())
ImpCastExprToType(From, ToType, CK_IntegralToFloating);
else
ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
break;
case ICK_Compatible_Conversion:
ImpCastExprToType(From, ToType, CK_NoOp);
break;
case ICK_Pointer_Conversion: {
if (SCS.IncompatibleObjC) {
// Diagnose incompatible Objective-C conversions
Diag(From->getSourceRange().getBegin(),
diag::ext_typecheck_convert_incompatible_pointer)
<< From->getType() << ToType << Action
<< From->getSourceRange();
}
CastKind Kind = CK_Unknown;
CXXCastPath BasePath;
if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
return true;
ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
break;
}
case ICK_Pointer_Member: {
CastKind Kind = CK_Unknown;
CXXCastPath BasePath;
if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
IgnoreBaseAccess))
return true;
if (CheckExceptionSpecCompatibility(From, ToType))
return true;
ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
break;
}
case ICK_Boolean_Conversion: {
CastKind Kind = CK_Unknown;
if (FromType->isMemberPointerType())
Kind = CK_MemberPointerToBoolean;
ImpCastExprToType(From, Context.BoolTy, Kind);
break;
}
case ICK_Derived_To_Base: {
CXXCastPath BasePath;
if (CheckDerivedToBaseConversion(From->getType(),
ToType.getNonReferenceType(),
From->getLocStart(),
From->getSourceRange(),
&BasePath,
IgnoreBaseAccess))
return true;
ImpCastExprToType(From, ToType.getNonReferenceType(),
CK_DerivedToBase, CastCategory(From),
&BasePath);
break;
}
case ICK_Vector_Conversion:
ImpCastExprToType(From, ToType, CK_BitCast);
break;
case ICK_Vector_Splat:
ImpCastExprToType(From, ToType, CK_VectorSplat);
break;
case ICK_Complex_Real:
ImpCastExprToType(From, ToType, CK_Unknown);
break;
case ICK_Lvalue_To_Rvalue:
case ICK_Array_To_Pointer:
case ICK_Function_To_Pointer:
case ICK_Qualification:
case ICK_Num_Conversion_Kinds:
assert(false && "Improper second standard conversion");
break;
}
switch (SCS.Third) {
case ICK_Identity:
// Nothing to do.
break;
case ICK_Qualification: {
// The qualification keeps the category of the inner expression, unless the
// target type isn't a reference.
ExprValueKind VK = ToType->isReferenceType() ?
CastCategory(From) : VK_RValue;
ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
CK_NoOp, VK);
if (SCS.DeprecatedStringLiteralToCharPtr)
Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
<< ToType.getNonReferenceType();
break;
}
default:
assert(false && "Improper third standard conversion");
break;
}
return false;
}
ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
SourceLocation KWLoc,
SourceLocation LParen,
ParsedType Ty,
SourceLocation RParen) {
QualType T = GetTypeFromParser(Ty);
// According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
// all traits except __is_class, __is_enum and __is_union require a the type
// to be complete.
if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
if (RequireCompleteType(KWLoc, T,
diag::err_incomplete_type_used_in_type_trait_expr))
return ExprError();
}
// There is no point in eagerly computing the value. The traits are designed
// to be used from type trait templates, so Ty will be a template parameter
// 99% of the time.
return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
RParen, Context.BoolTy));
}
QualType Sema::CheckPointerToMemberOperands(
Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
const char *OpSpelling = isIndirect ? "->*" : ".*";
// C++ 5.5p2
// The binary operator .* [p3: ->*] binds its second operand, which shall
// be of type "pointer to member of T" (where T is a completely-defined
// class type) [...]
QualType RType = rex->getType();
const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
if (!MemPtr) {
Diag(Loc, diag::err_bad_memptr_rhs)
<< OpSpelling << RType << rex->getSourceRange();
return QualType();
}
QualType Class(MemPtr->getClass(), 0);
if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
return QualType();
// C++ 5.5p2
// [...] to its first operand, which shall be of class T or of a class of
// which T is an unambiguous and accessible base class. [p3: a pointer to
// such a class]
QualType LType = lex->getType();
if (isIndirect) {
if (const PointerType *Ptr = LType->getAs<PointerType>())
LType = Ptr->getPointeeType().getNonReferenceType();
else {
Diag(Loc, diag::err_bad_memptr_lhs)
<< OpSpelling << 1 << LType
<< FixItHint::CreateReplacement(SourceRange(Loc), ".*");
return QualType();
}
}
if (!Context.hasSameUnqualifiedType(Class, LType)) {
// If we want to check the hierarchy, we need a complete type.
if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
<< OpSpelling << (int)isIndirect)) {
return QualType();
}
CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
/*DetectVirtual=*/false);
// FIXME: Would it be useful to print full ambiguity paths, or is that
// overkill?
if (!IsDerivedFrom(LType, Class, Paths) ||
Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
<< (int)isIndirect << lex->getType();
return QualType();
}
// Cast LHS to type of use.
QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
ExprValueKind VK =
isIndirect ? VK_RValue : CastCategory(lex);
CXXCastPath BasePath;
BuildBasePathArray(Paths, BasePath);
ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
}
if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
// Diagnose use of pointer-to-member type which when used as
// the functional cast in a pointer-to-member expression.
Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
return QualType();
}
// C++ 5.5p2
// The result is an object or a function of the type specified by the
// second operand.
// The cv qualifiers are the union of those in the pointer and the left side,
// in accordance with 5.5p5 and 5.2.5.
// FIXME: This returns a dereferenced member function pointer as a normal
// function type. However, the only operation valid on such functions is
// calling them. There's also a GCC extension to get a function pointer to the
// thing, which is another complication, because this type - unlike the type
// that is the result of this expression - takes the class as the first
// argument.
// We probably need a "MemberFunctionClosureType" or something like that.
QualType Result = MemPtr->getPointeeType();
Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
return Result;
}
/// \brief Try to convert a type to another according to C++0x 5.16p3.
///
/// This is part of the parameter validation for the ? operator. If either
/// value operand is a class type, the two operands are attempted to be
/// converted to each other. This function does the conversion in one direction.
/// It returns true if the program is ill-formed and has already been diagnosed
/// as such.
static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
SourceLocation QuestionLoc,
bool &HaveConversion,
QualType &ToType) {
HaveConversion = false;
ToType = To->getType();
InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
SourceLocation());
// C++0x 5.16p3
// The process for determining whether an operand expression E1 of type T1
// can be converted to match an operand expression E2 of type T2 is defined
// as follows:
// -- If E2 is an lvalue:
bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
if (ToIsLvalue) {
// E1 can be converted to match E2 if E1 can be implicitly converted to
// type "lvalue reference to T2", subject to the constraint that in the
// conversion the reference must bind directly to E1.
QualType T = Self.Context.getLValueReferenceType(ToType);
InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
if (InitSeq.isDirectReferenceBinding()) {
ToType = T;
HaveConversion = true;
return false;
}
if (InitSeq.isAmbiguous())
return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
}
// -- If E2 is an rvalue, or if the conversion above cannot be done:
// -- if E1 and E2 have class type, and the underlying class types are
// the same or one is a base class of the other:
QualType FTy = From->getType();
QualType TTy = To->getType();
const RecordType *FRec = FTy->getAs<RecordType>();
const RecordType *TRec = TTy->getAs<RecordType>();
bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Self.IsDerivedFrom(FTy, TTy);
if (FRec && TRec &&
(FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
// E1 can be converted to match E2 if the class of T2 is the
// same type as, or a base class of, the class of T1, and
// [cv2 > cv1].
if (FRec == TRec || FDerivedFromT) {
if (TTy.isAtLeastAsQualifiedAs(FTy)) {
InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
HaveConversion = true;
return false;
}
if (InitSeq.isAmbiguous())
return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
}
}
return false;
}
// -- Otherwise: E1 can be converted to match E2 if E1 can be
// implicitly converted to the type that expression E2 would have
// if E2 were converted to an rvalue (or the type it has, if E2 is
// an rvalue).
//
// This actually refers very narrowly to the lvalue-to-rvalue conversion, not
// to the array-to-pointer or function-to-pointer conversions.
if (!TTy->getAs<TagType>())
TTy = TTy.getUnqualifiedType();
InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
ToType = TTy;
if (InitSeq.isAmbiguous())
return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
return false;
}
/// \brief Try to find a common type for two according to C++0x 5.16p5.
///
/// This is part of the parameter validation for the ? operator. If either
/// value operand is a class type, overload resolution is used to find a
/// conversion to a common type.
static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
SourceLocation Loc) {
Expr *Args[2] = { LHS, RHS };
OverloadCandidateSet CandidateSet(Loc);
Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
OverloadCandidateSet::iterator Best;
switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
case OR_Success:
// We found a match. Perform the conversions on the arguments and move on.
if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Best->Conversions[0], Sema::AA_Converting) ||
Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Best->Conversions[1], Sema::AA_Converting))
break;
return false;
case OR_No_Viable_Function:
Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
<< LHS->getType() << RHS->getType()
<< LHS->getSourceRange() << RHS->getSourceRange();
return true;
case OR_Ambiguous:
Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
<< LHS->getType() << RHS->getType()
<< LHS->getSourceRange() << RHS->getSourceRange();
// FIXME: Print the possible common types by printing the return types of
// the viable candidates.
break;
case OR_Deleted:
assert(false && "Conditional operator has only built-in overloads");
break;
}
return true;
}
/// \brief Perform an "extended" implicit conversion as returned by
/// TryClassUnification.
static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
SourceLocation());
InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
if (Result.isInvalid())
return true;
E = Result.takeAs<Expr>();
return false;
}
/// \brief Check the operands of ?: under C++ semantics.
///
/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
/// extension. In this case, LHS == Cond. (But they're not aliases.)
QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
SourceLocation QuestionLoc) {
// FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
// interface pointers.
// C++0x 5.16p1
// The first expression is contextually converted to bool.
if (!Cond->isTypeDependent()) {
if (CheckCXXBooleanCondition(Cond))
return QualType();
}
// Either of the arguments dependent?
if (LHS->isTypeDependent() || RHS->isTypeDependent())
return Context.DependentTy;
// C++0x 5.16p2
// If either the second or the third operand has type (cv) void, ...
QualType LTy = LHS->getType();
QualType RTy = RHS->getType();
bool LVoid = LTy->isVoidType();
bool RVoid = RTy->isVoidType();
if (LVoid || RVoid) {
// ... then the [l2r] conversions are performed on the second and third
// operands ...
DefaultFunctionArrayLvalueConversion(LHS);
DefaultFunctionArrayLvalueConversion(RHS);
LTy = LHS->getType();
RTy = RHS->getType();
// ... and one of the following shall hold:
// -- The second or the third operand (but not both) is a throw-
// expression; the result is of the type of the other and is an rvalue.
bool LThrow = isa<CXXThrowExpr>(LHS);
bool RThrow = isa<CXXThrowExpr>(RHS);
if (LThrow && !RThrow)
return RTy;
if (RThrow && !LThrow)
return LTy;
// -- Both the second and third operands have type void; the result is of
// type void and is an rvalue.
if (LVoid && RVoid)
return Context.VoidTy;
// Neither holds, error.
Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
<< (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
<< LHS->getSourceRange() << RHS->getSourceRange();
return QualType();
}
// Neither is void.
// C++0x 5.16p3
// Otherwise, if the second and third operand have different types, and
// either has (cv) class type, and attempt is made to convert each of those
// operands to the other.
if (!Context.hasSameType(LTy, RTy) &&
(LTy->isRecordType() || RTy->isRecordType())) {
ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
// These return true if a single direction is already ambiguous.
QualType L2RType, R2LType;
bool HaveL2R, HaveR2L;
if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
return QualType();
if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
return QualType();
// If both can be converted, [...] the program is ill-formed.
if (HaveL2R && HaveR2L) {
Diag(QuestionLoc, diag::err_conditional_ambiguous)
<< LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
return QualType();
}
// If exactly one conversion is possible, that conversion is applied to
// the chosen operand and the converted operands are used in place of the
// original operands for the remainder of this section.
if (HaveL2R) {
if (ConvertForConditional(*this, LHS, L2RType))
return QualType();
LTy = LHS->getType();
} else if (HaveR2L) {
if (ConvertForConditional(*this, RHS, R2LType))
return QualType();
RTy = RHS->getType();
}
}
// C++0x 5.16p4
// If the second and third operands are lvalues and have the same type,
// the result is of that type [...]
bool Same = Context.hasSameType(LTy, RTy);
if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
RHS->isLvalue(Context) == Expr::LV_Valid)
return LTy;
// C++0x 5.16p5
// Otherwise, the result is an rvalue. If the second and third operands<|fim▁hole|> // to be applied to the operands. If the overload resolution fails, the
// program is ill-formed.
if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
return QualType();
}
// C++0x 5.16p6
// LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
// conversions are performed on the second and third operands.
DefaultFunctionArrayLvalueConversion(LHS);
DefaultFunctionArrayLvalueConversion(RHS);
LTy = LHS->getType();
RTy = RHS->getType();
// After those conversions, one of the following shall hold:
// -- The second and third operands have the same type; the result
// is of that type. If the operands have class type, the result
// is a prvalue temporary of the result type, which is
// copy-initialized from either the second operand or the third
// operand depending on the value of the first operand.
if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
if (LTy->isRecordType()) {
// The operands have class type. Make a temporary copy.
InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
ExprResult LHSCopy = PerformCopyInitialization(Entity,
SourceLocation(),
Owned(LHS));
if (LHSCopy.isInvalid())
return QualType();
ExprResult RHSCopy = PerformCopyInitialization(Entity,
SourceLocation(),
Owned(RHS));
if (RHSCopy.isInvalid())
return QualType();
LHS = LHSCopy.takeAs<Expr>();
RHS = RHSCopy.takeAs<Expr>();
}
return LTy;
}
// Extension: conditional operator involving vector types.
if (LTy->isVectorType() || RTy->isVectorType())
return CheckVectorOperands(QuestionLoc, LHS, RHS);
// -- The second and third operands have arithmetic or enumeration type;
// the usual arithmetic conversions are performed to bring them to a
// common type, and the result is of that type.
if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
UsualArithmeticConversions(LHS, RHS);
return LHS->getType();
}
// -- The second and third operands have pointer type, or one has pointer
// type and the other is a null pointer constant; pointer conversions
// and qualification conversions are performed to bring them to their
// composite pointer type. The result is of the composite pointer type.
// -- The second and third operands have pointer to member type, or one has
// pointer to member type and the other is a null pointer constant;
// pointer to member conversions and qualification conversions are
// performed to bring them to a common type, whose cv-qualification
// shall match the cv-qualification of either the second or the third
// operand. The result is of the common type.
bool NonStandardCompositeType = false;
QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
isSFINAEContext()? 0 : &NonStandardCompositeType);
if (!Composite.isNull()) {
if (NonStandardCompositeType)
Diag(QuestionLoc,
diag::ext_typecheck_cond_incompatible_operands_nonstandard)
<< LTy << RTy << Composite
<< LHS->getSourceRange() << RHS->getSourceRange();
return Composite;
}
// Similarly, attempt to find composite type of two objective-c pointers.
Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
if (!Composite.isNull())
return Composite;
Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
<< LHS->getType() << RHS->getType()
<< LHS->getSourceRange() << RHS->getSourceRange();
return QualType();
}
/// \brief Find a merged pointer type and convert the two expressions to it.
///
/// This finds the composite pointer type (or member pointer type) for @p E1
/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
/// type and returns it.
/// It does not emit diagnostics.
///
/// \param Loc The location of the operator requiring these two expressions to
/// be converted to the composite pointer type.
///
/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
/// a non-standard (but still sane) composite type to which both expressions
/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
/// will be set true.
QualType Sema::FindCompositePointerType(SourceLocation Loc,
Expr *&E1, Expr *&E2,
bool *NonStandardCompositeType) {
if (NonStandardCompositeType)
*NonStandardCompositeType = false;
assert(getLangOptions().CPlusPlus && "This function assumes C++");
QualType T1 = E1->getType(), T2 = E2->getType();
if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
!T2->isAnyPointerType() && !T2->isMemberPointerType())
return QualType();
// C++0x 5.9p2
// Pointer conversions and qualification conversions are performed on
// pointer operands to bring them to their composite pointer type. If
// one operand is a null pointer constant, the composite pointer type is
// the type of the other operand.
if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
if (T2->isMemberPointerType())
ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
else
ImpCastExprToType(E1, T2, CK_IntegralToPointer);
return T2;
}
if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
if (T1->isMemberPointerType())
ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
else
ImpCastExprToType(E2, T1, CK_IntegralToPointer);
return T1;
}
// Now both have to be pointers or member pointers.
if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
(!T2->isPointerType() && !T2->isMemberPointerType()))
return QualType();
// Otherwise, of one of the operands has type "pointer to cv1 void," then
// the other has type "pointer to cv2 T" and the composite pointer type is
// "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
// Otherwise, the composite pointer type is a pointer type similar to the
// type of one of the operands, with a cv-qualification signature that is
// the union of the cv-qualification signatures of the operand types.
// In practice, the first part here is redundant; it's subsumed by the second.
// What we do here is, we build the two possible composite types, and try the
// conversions in both directions. If only one works, or if the two composite
// types are the same, we have succeeded.
// FIXME: extended qualifiers?
typedef llvm::SmallVector<unsigned, 4> QualifierVector;
QualifierVector QualifierUnion;
typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
ContainingClassVector;
ContainingClassVector MemberOfClass;
QualType Composite1 = Context.getCanonicalType(T1),
Composite2 = Context.getCanonicalType(T2);
unsigned NeedConstBefore = 0;
do {
const PointerType *Ptr1, *Ptr2;
if ((Ptr1 = Composite1->getAs<PointerType>()) &&
(Ptr2 = Composite2->getAs<PointerType>())) {
Composite1 = Ptr1->getPointeeType();
Composite2 = Ptr2->getPointeeType();
// If we're allowed to create a non-standard composite type, keep track
// of where we need to fill in additional 'const' qualifiers.
if (NonStandardCompositeType &&
Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
NeedConstBefore = QualifierUnion.size();
QualifierUnion.push_back(
Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
continue;
}
const MemberPointerType *MemPtr1, *MemPtr2;
if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
(MemPtr2 = Composite2->getAs<MemberPointerType>())) {
Composite1 = MemPtr1->getPointeeType();
Composite2 = MemPtr2->getPointeeType();
// If we're allowed to create a non-standard composite type, keep track
// of where we need to fill in additional 'const' qualifiers.
if (NonStandardCompositeType &&
Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
NeedConstBefore = QualifierUnion.size();
QualifierUnion.push_back(
Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
MemPtr2->getClass()));
continue;
}
// FIXME: block pointer types?
// Cannot unwrap any more types.
break;
} while (true);
if (NeedConstBefore && NonStandardCompositeType) {
// Extension: Add 'const' to qualifiers that come before the first qualifier
// mismatch, so that our (non-standard!) composite type meets the
// requirements of C++ [conv.qual]p4 bullet 3.
for (unsigned I = 0; I != NeedConstBefore; ++I) {
if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
*NonStandardCompositeType = true;
}
}
}
// Rewrap the composites as pointers or member pointers with the union CVRs.
ContainingClassVector::reverse_iterator MOC
= MemberOfClass.rbegin();
for (QualifierVector::reverse_iterator
I = QualifierUnion.rbegin(),
E = QualifierUnion.rend();
I != E; (void)++I, ++MOC) {
Qualifiers Quals = Qualifiers::fromCVRMask(*I);
if (MOC->first && MOC->second) {
// Rebuild member pointer type
Composite1 = Context.getMemberPointerType(
Context.getQualifiedType(Composite1, Quals),
MOC->first);
Composite2 = Context.getMemberPointerType(
Context.getQualifiedType(Composite2, Quals),
MOC->second);
} else {
// Rebuild pointer type
Composite1
= Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
Composite2
= Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
}
}
// Try to convert to the first composite pointer type.
InitializedEntity Entity1
= InitializedEntity::InitializeTemporary(Composite1);
InitializationKind Kind
= InitializationKind::CreateCopy(Loc, SourceLocation());
InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
if (E1ToC1 && E2ToC1) {
// Conversion to Composite1 is viable.
if (!Context.hasSameType(Composite1, Composite2)) {
// Composite2 is a different type from Composite1. Check whether
// Composite2 is also viable.
InitializedEntity Entity2
= InitializedEntity::InitializeTemporary(Composite2);
InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
if (E1ToC2 && E2ToC2) {
// Both Composite1 and Composite2 are viable and are different;
// this is an ambiguity.
return QualType();
}
}
// Convert E1 to Composite1
ExprResult E1Result
= E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
if (E1Result.isInvalid())
return QualType();
E1 = E1Result.takeAs<Expr>();
// Convert E2 to Composite1
ExprResult E2Result
= E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
if (E2Result.isInvalid())
return QualType();
E2 = E2Result.takeAs<Expr>();
return Composite1;
}
// Check whether Composite2 is viable.
InitializedEntity Entity2
= InitializedEntity::InitializeTemporary(Composite2);
InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
if (!E1ToC2 || !E2ToC2)
return QualType();
// Convert E1 to Composite2
ExprResult E1Result
= E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
if (E1Result.isInvalid())
return QualType();
E1 = E1Result.takeAs<Expr>();
// Convert E2 to Composite2
ExprResult E2Result
= E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
if (E2Result.isInvalid())
return QualType();
E2 = E2Result.takeAs<Expr>();
return Composite2;
}
ExprResult Sema::MaybeBindToTemporary(Expr *E) {
if (!Context.getLangOptions().CPlusPlus)
return Owned(E);
assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
const RecordType *RT = E->getType()->getAs<RecordType>();
if (!RT)
return Owned(E);
// If this is the result of a call or an Objective-C message send expression,
// our source might actually be a reference, in which case we shouldn't bind.
if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
if (CE->getCallReturnType()->isReferenceType())
return Owned(E);
} else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
if (MD->getResultType()->isReferenceType())
return Owned(E);
}
}
// That should be enough to guarantee that this type is complete.
// If it has a trivial destructor, we can avoid the extra copy.
CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
return Owned(E);
CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
ExprTemporaries.push_back(Temp);
if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
MarkDeclarationReferenced(E->getExprLoc(), Destructor);
CheckDestructorAccess(E->getExprLoc(), Destructor,
PDiag(diag::err_access_dtor_temp)
<< E->getType());
}
// FIXME: Add the temporary to the temporaries vector.
return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
}
Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
assert(SubExpr && "sub expression can't be null!");
// Check any implicit conversions within the expression.
CheckImplicitConversions(SubExpr);
unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
assert(ExprTemporaries.size() >= FirstTemporary);
if (ExprTemporaries.size() == FirstTemporary)
return SubExpr;
Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
&ExprTemporaries[FirstTemporary],
ExprTemporaries.size() - FirstTemporary);
ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
ExprTemporaries.end());
return E;
}
ExprResult
Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) {
if (SubExpr.isInvalid())
return ExprError();
return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
}
FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
assert(ExprTemporaries.size() >= FirstTemporary);
unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
CXXTemporary **Temporaries =
NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
ExprTemporaries.end());
return E;
}
ExprResult
Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
tok::TokenKind OpKind, ParsedType &ObjectType,
bool &MayBePseudoDestructor) {
// Since this might be a postfix expression, get rid of ParenListExprs.
ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
if (Result.isInvalid()) return ExprError();
Base = Result.get();
QualType BaseType = Base->getType();
MayBePseudoDestructor = false;
if (BaseType->isDependentType()) {
// If we have a pointer to a dependent type and are using the -> operator,
// the object type is the type that the pointer points to. We might still
// have enough information about that type to do something useful.
if (OpKind == tok::arrow)
if (const PointerType *Ptr = BaseType->getAs<PointerType>())
BaseType = Ptr->getPointeeType();
ObjectType = ParsedType::make(BaseType);
MayBePseudoDestructor = true;
return Owned(Base);
}
// C++ [over.match.oper]p8:
// [...] When operator->returns, the operator-> is applied to the value
// returned, with the original second operand.
if (OpKind == tok::arrow) {
// The set of types we've considered so far.
llvm::SmallPtrSet<CanQualType,8> CTypes;
llvm::SmallVector<SourceLocation, 8> Locations;
CTypes.insert(Context.getCanonicalType(BaseType));
while (BaseType->isRecordType()) {
Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
if (Result.isInvalid())
return ExprError();
Base = Result.get();
if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Locations.push_back(OpCall->getDirectCallee()->getLocation());
BaseType = Base->getType();
CanQualType CBaseType = Context.getCanonicalType(BaseType);
if (!CTypes.insert(CBaseType)) {
Diag(OpLoc, diag::err_operator_arrow_circular);
for (unsigned i = 0; i < Locations.size(); i++)
Diag(Locations[i], diag::note_declared_at);
return ExprError();
}
}
if (BaseType->isPointerType())
BaseType = BaseType->getPointeeType();
}
// We could end up with various non-record types here, such as extended
// vector types or Objective-C interfaces. Just return early and let
// ActOnMemberReferenceExpr do the work.
if (!BaseType->isRecordType()) {
// C++ [basic.lookup.classref]p2:
// [...] If the type of the object expression is of pointer to scalar
// type, the unqualified-id is looked up in the context of the complete
// postfix-expression.
//
// This also indicates that we should be parsing a
// pseudo-destructor-name.
ObjectType = ParsedType();
MayBePseudoDestructor = true;
return Owned(Base);
}
// The object type must be complete (or dependent).
if (!BaseType->isDependentType() &&
RequireCompleteType(OpLoc, BaseType,
PDiag(diag::err_incomplete_member_access)))
return ExprError();
// C++ [basic.lookup.classref]p2:
// If the id-expression in a class member access (5.2.5) is an
// unqualified-id, and the type of the object expression is of a class
// type C (or of pointer to a class type C), the unqualified-id is looked
// up in the scope of class C. [...]
ObjectType = ParsedType::make(BaseType);
return move(Base);
}
ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
Expr *MemExpr) {
SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
<< isa<CXXPseudoDestructorExpr>(MemExpr)
<< FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
return ActOnCallExpr(/*Scope*/ 0,
MemExpr,
/*LPLoc*/ ExpectedLParenLoc,
MultiExprArg(),
/*CommaLocs*/ 0,
/*RPLoc*/ ExpectedLParenLoc);
}
ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeTypeInfo,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage Destructed,
bool HasTrailingLParen) {
TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
// C++ [expr.pseudo]p2:
// The left-hand side of the dot operator shall be of scalar type. The
// left-hand side of the arrow operator shall be of pointer to scalar type.
// This scalar type is the object type.
QualType ObjectType = Base->getType();
if (OpKind == tok::arrow) {
if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
ObjectType = Ptr->getPointeeType();
} else if (!Base->isTypeDependent()) {
// The user wrote "p->" when she probably meant "p."; fix it.
Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
<< ObjectType << true
<< FixItHint::CreateReplacement(OpLoc, ".");
if (isSFINAEContext())
return ExprError();
OpKind = tok::period;
}
}
if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
<< ObjectType << Base->getSourceRange();
return ExprError();
}
// C++ [expr.pseudo]p2:
// [...] The cv-unqualified versions of the object type and of the type
// designated by the pseudo-destructor-name shall be the same type.
if (DestructedTypeInfo) {
QualType DestructedType = DestructedTypeInfo->getType();
SourceLocation DestructedTypeStart
= DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
<< ObjectType << DestructedType << Base->getSourceRange()
<< DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
// Recover by setting the destructed type to the object type.
DestructedType = ObjectType;
DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
DestructedTypeStart);
Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
}
}
// C++ [expr.pseudo]p2:
// [...] Furthermore, the two type-names in a pseudo-destructor-name of the
// form
//
// ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
//
// shall designate the same scalar type.
if (ScopeTypeInfo) {
QualType ScopeType = ScopeTypeInfo->getType();
if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
!Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
diag::err_pseudo_dtor_type_mismatch)
<< ObjectType << ScopeType << Base->getSourceRange()
<< ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
ScopeType = QualType();
ScopeTypeInfo = 0;
}
}
Expr *Result
= new (Context) CXXPseudoDestructorExpr(Context, Base,
OpKind == tok::arrow, OpLoc,
SS.getScopeRep(), SS.getRange(),
ScopeTypeInfo,
CCLoc,
TildeLoc,
Destructed);
if (HasTrailingLParen)
return Owned(Result);
return DiagnoseDtorReference(Destructed.getLocation(), Result);
}
ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName,
bool HasTrailingLParen) {
assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
"Invalid first type name in pseudo-destructor");
assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
"Invalid second type name in pseudo-destructor");
// C++ [expr.pseudo]p2:
// The left-hand side of the dot operator shall be of scalar type. The
// left-hand side of the arrow operator shall be of pointer to scalar type.
// This scalar type is the object type.
QualType ObjectType = Base->getType();
if (OpKind == tok::arrow) {
if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
ObjectType = Ptr->getPointeeType();
} else if (!ObjectType->isDependentType()) {
// The user wrote "p->" when she probably meant "p."; fix it.
Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
<< ObjectType << true
<< FixItHint::CreateReplacement(OpLoc, ".");
if (isSFINAEContext())
return ExprError();
OpKind = tok::period;
}
}
// Compute the object type that we should use for name lookup purposes. Only
// record types and dependent types matter.
ParsedType ObjectTypePtrForLookup;
if (!SS.isSet()) {
if (const Type *T = ObjectType->getAs<RecordType>())
ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
else if (ObjectType->isDependentType())
ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
}
// Convert the name of the type being destructed (following the ~) into a
// type (with source-location information).
QualType DestructedType;
TypeSourceInfo *DestructedTypeInfo = 0;
PseudoDestructorTypeStorage Destructed;
if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
ParsedType T = getTypeName(*SecondTypeName.Identifier,
SecondTypeName.StartLocation,
S, &SS, true, ObjectTypePtrForLookup);
if (!T &&
((SS.isSet() && !computeDeclContext(SS, false)) ||
(!SS.isSet() && ObjectType->isDependentType()))) {
// The name of the type being destroyed is a dependent name, and we
// couldn't find anything useful in scope. Just store the identifier and
// it's location, and we'll perform (qualified) name lookup again at
// template instantiation time.
Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
SecondTypeName.StartLocation);
} else if (!T) {
Diag(SecondTypeName.StartLocation,
diag::err_pseudo_dtor_destructor_non_type)
<< SecondTypeName.Identifier << ObjectType;
if (isSFINAEContext())
return ExprError();
// Recover by assuming we had the right type all along.
DestructedType = ObjectType;
} else
DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
} else {
// Resolve the template-id to a type.
TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
ASTTemplateArgsPtr TemplateArgsPtr(*this,
TemplateId->getTemplateArgs(),
TemplateId->NumArgs);
TypeResult T = ActOnTemplateIdType(TemplateId->Template,
TemplateId->TemplateNameLoc,
TemplateId->LAngleLoc,
TemplateArgsPtr,
TemplateId->RAngleLoc);
if (T.isInvalid() || !T.get()) {
// Recover by assuming we had the right type all along.
DestructedType = ObjectType;
} else
DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
}
// If we've performed some kind of recovery, (re-)build the type source
// information.
if (!DestructedType.isNull()) {
if (!DestructedTypeInfo)
DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
SecondTypeName.StartLocation);
Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
}
// Convert the name of the scope type (the type prior to '::') into a type.
TypeSourceInfo *ScopeTypeInfo = 0;
QualType ScopeType;
if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
FirstTypeName.Identifier) {
if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
ParsedType T = getTypeName(*FirstTypeName.Identifier,
FirstTypeName.StartLocation,
S, &SS, false, ObjectTypePtrForLookup);
if (!T) {
Diag(FirstTypeName.StartLocation,
diag::err_pseudo_dtor_destructor_non_type)
<< FirstTypeName.Identifier << ObjectType;
if (isSFINAEContext())
return ExprError();
// Just drop this type. It's unnecessary anyway.
ScopeType = QualType();
} else
ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
} else {
// Resolve the template-id to a type.
TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
ASTTemplateArgsPtr TemplateArgsPtr(*this,
TemplateId->getTemplateArgs(),
TemplateId->NumArgs);
TypeResult T = ActOnTemplateIdType(TemplateId->Template,
TemplateId->TemplateNameLoc,
TemplateId->LAngleLoc,
TemplateArgsPtr,
TemplateId->RAngleLoc);
if (T.isInvalid() || !T.get()) {
// Recover by dropping this type.
ScopeType = QualType();
} else
ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
}
}
if (!ScopeType.isNull() && !ScopeTypeInfo)
ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
FirstTypeName.StartLocation);
return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
ScopeTypeInfo, CCLoc, TildeLoc,
Destructed, HasTrailingLParen);
}
CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
NamedDecl *FoundDecl,
CXXMethodDecl *Method) {
if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
FoundDecl, Method))
assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
MemberExpr *ME =
new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
SourceLocation(), Method->getType());
QualType ResultType = Method->getCallResultType();
MarkDeclarationReferenced(Exp->getLocStart(), Method);
CXXMemberCallExpr *CE =
new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
Exp->getLocEnd());
return CE;
}
ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
if (!FullExpr) return ExprError();
return MaybeCreateCXXExprWithTemporaries(FullExpr);
}<|fim▁end|>
|
// do not have the same type, and either has (cv) class type, ...
if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
// ... overload resolution is used to determine the conversions (if any)
|
<|file_name|>bundesliga_de.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from resources.lib.parser import cParser
from resources.lib.handler.requestHandler import cRequestHandler
from resources.lib.gui.guiElement import cGuiElement
from resources.lib.gui.gui import cGui
from resources.lib.util import cUtil
from resources.lib.handler.ParameterHandler import ParameterHandler
SITE_IDENTIFIER = 'bundesliga_de'
SITE_NAME = 'Bundesliga.de'
SITE_ICON = 'bl.png'
URL_MAIN = 'http://www.bundesliga.de'
URL_TV = 'http://www.bundesliga.de/de/service/?action=teaserbox&type=video&language=de&amount=25&category='
URL_GET_STREAM = 'http://btd-flv-lbwww-01.odmedia.net/bundesliga/'
def load():
oGui = cGui()
__createMainMenuItem(oGui, 'Aktuell', 'new')
__createMainMenuItem(oGui, 'Spieltag', 'spieltag')
__createMainMenuItem(oGui, 'Stars', 'stars')
__createMainMenuItem(oGui, 'Stories', 'stories')
__createMainMenuItem(oGui, 'Historie', 'historie')
__createMainMenuItem(oGui, 'Partner', 'partner')
__createMainMenuItem(oGui, 'Vereine', 'clubs')
oGui.setEndOfDirectory()
def __createMainMenuItem(oGui, sTitle, sPlaylistId):
oGuiElement = cGuiElement()
oGuiElement.setSiteName(SITE_IDENTIFIER)
oGuiElement.setFunction('listVideos')
oGuiElement.setTitle(sTitle)
oOutputParameterHandler = ParameterHandler()
oOutputParameterHandler.setParam('playlistId', sPlaylistId)
oGui.addFolder(oGuiElement, oOutputParameterHandler)
def listVideos():
oGui = cGui()
params = ParameterHandler()
if (params.exist('playlistId')):
sPlaylistId = params.getValue('playlistId')
if not params.exist('sUrl'):
sUrl = URL_TV + str(sPlaylistId)
else:
sUrl = params.getValue('sUrl')
if sPlaylistId == 'spieltag':
oParser = cParser()
if not params.exist('saison'):
oRequest = cRequestHandler('http://www.bundesliga.de/de/bundesliga-tv/index.php')
sHtmlContent = oRequest.request()
sPattern = 'data-season="([^"]+)" class="active grey-gradient"'
aResult = oParser.parse(sHtmlContent, sPattern)
saison = aResult[1][0]
else:
saison = params.getValue('saison')
oRequest = cRequestHandler(sUrl+'&season='+saison+'&matchday=1')
sHtmlContent = oRequest.request()
if sHtmlContent.find('"message":"nothing found"') != -1:
return False
#ausgewählte Saison
for matchDay in range(1,35):
oGuiElement = cGuiElement()
oGuiElement.setSiteName(SITE_IDENTIFIER)
oGuiElement.setFunction('listVideos')
oGuiElement.setTitle('%s Spieltag Saison %s' % (matchDay,saison))
sUrl = sUrl+'&season='+saison+'&matchday='+str(matchDay)
oOutputParameterHandler = ParameterHandler()
oOutputParameterHandler.setParam('sUrl', sUrl)
oOutputParameterHandler.setParam('saison', saison)
oOutputParameterHandler.setParam('matchDay', matchDay)
oOutputParameterHandler.setParam('playlistId', 'spieltagEinzeln')
oGui.addFolder(oGuiElement, oOutputParameterHandler)
#ältere Saison
oGuiElement = cGuiElement()
oGuiElement.setSiteName(SITE_IDENTIFIER)
oGuiElement.setFunction('listVideos')
lastSaison = str(int(saison) - 1)
oGuiElement.setTitle('* Saison %s/%s *' % (lastSaison,saison))
oOutputParameterHandler = ParameterHandler()
oOutputParameterHandler.setParam('sUrl', sUrl)
oOutputParameterHandler.setParam('saison', lastSaison)
oOutputParameterHandler.setParam('playlistId', 'spieltag')
oGui.addFolder(oGuiElement, oOutputParameterHandler)
elif sPlaylistId == 'clubs':
sPattern = '<li data-club="([^"]+)" data-name="([^"]+)".*?src="([^"]+)"'
oRequest = cRequestHandler('http://www.bundesliga.de/de/bundesliga-tv/index.php')
sHtmlContent = oRequest.request()
oParser = cParser()
aResult = oParser.parse(sHtmlContent, sPattern)
if (aResult[0] == False):
return False
for aEntry in aResult[1]:<|fim▁hole|> oGuiElement.setFunction('listVideos')
oGuiElement.setTitle((aEntry[1]))
sThumbnail = URL_MAIN + str(aEntry[2]).replace('variant27x27.','')
oGuiElement.setThumbnail(sThumbnail)
sUrl = sUrl +'&club='+str(aEntry[0])
oOutputParameterHandler = ParameterHandler()
oOutputParameterHandler.setParam('sUrl', sUrl)
oOutputParameterHandler.setParam('playlistId', 'clubVideos')
oGui.addFolder(oGuiElement, oOutputParameterHandler)
else:
sPattern = 'btd-teaserbox-entry.*?<a href="([^"]+)".*?<h3 class=.*?>([^<]+)<.*?src="([^"]+).*?class="teaser-text">([^<]+)'
oRequest = cRequestHandler(sUrl)
sHtmlContent = oRequest.request()
sHtmlContent = sHtmlContent.replace('\\"','"').replace('\\/','/')
oParser = cParser()
aResult = oParser.parse(sHtmlContent, sPattern)
if (aResult[0] == False):
return False
for aEntry in aResult[1]:
sThumbnail = URL_MAIN + str(aEntry[2])
sUrl = URL_MAIN + str(aEntry[0])
sTitle = cUtil().unescape(str(aEntry[1]).decode('unicode-escape')).encode('utf-8')
sDescription = cUtil().unescape(str(aEntry[3]).decode('unicode-escape')).encode('utf-8')
oGuiElement = cGuiElement()
oGuiElement.setSiteName(SITE_IDENTIFIER)
oGuiElement.setFunction('play')
oGuiElement.setTitle(sTitle)
oGuiElement.setDescription(sDescription)
oGuiElement.setThumbnail(sThumbnail)
oOutputParameterHandler = ParameterHandler()
oOutputParameterHandler.setParam('sUrl', sUrl)
oOutputParameterHandler.setParam('sTitle', sTitle)
oGui.addFolder(oGuiElement, oOutputParameterHandler, bIsFolder = False)
oGui.setView('movies')
oGui.setEndOfDirectory()
def play():
params = ParameterHandler()
if (params.exist('sUrl') and params.exist('sTitle')):
sUrl = params.getValue('sUrl')
sTitle = params.getValue('sTitle')
print sUrl
oRequest = cRequestHandler(sUrl)
sHtmlContent = oRequest.request()
sPattern = ': "([^\."]+)\.flv"'
oParser = cParser()
aResult = oParser.parse(sHtmlContent, sPattern)
if (aResult[0] == True):
sStreamUrl = URL_GET_STREAM + str(aResult[1][0])+'_HD.flv?autostart=true'
result = {}
result['streamUrl'] = sStreamUrl
result['resolved'] = True
return result
return False<|fim▁end|>
|
oGuiElement = cGuiElement()
oGuiElement.setSiteName(SITE_IDENTIFIER)
|
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models
from django.contrib.auth import models as auth
import datetime
from application import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
typeChoices = (
('task', 'Task'),
('userStory', 'User Story'),
)
statusChoices = (
('toDo', 'To do'),
('inProgress', 'in progress'),
('done', 'Done'),
)
categoryChoices = (
('frontend', 'Frontend'),
('backend', 'Backend'),
('design', 'Design'),
)
purposeChoices = (
('bugfix', 'Bugfix'),
('feature', 'Feature'),
)
class WorkGroup(models.Model):
name = models.CharField(
max_length=200,
unique = True,
)
def __unicode__(self):
return u'%s' % (self.name)
class TaskCard(models.Model):
<|fim▁hole|> on_delete=models.PROTECT,
)
processor = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='processingTasks',
blank=True,
null=True,
)
createTime = models.DateTimeField(
auto_now_add=True,
)
startTime = models.DateField(
null=True,
blank=True,
)
#endTime = models.DateTimeField()
#sprint = models.ForeignKey(Sprint)
title = models.CharField(
max_length=200,
)
taskType = models.CharField(
max_length=15,
choices=typeChoices,
default='task',
)
taskPurpose = models.CharField(
max_length=15,
choices=purposeChoices,
blank=True,
null=True,
)
taskCategory = models.CharField(
max_length=15,
choices=categoryChoices,
blank=True,
null=True,
)
description = models.TextField()
status = models.CharField(
max_length=15,
choices=statusChoices,
blank=True,
null=True,
)
group = models.ForeignKey(
WorkGroup,
null=True,
blank=True,
)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if self.startTime is None and self.processor is not None:
self.startTime = datetime.date.today()
self.status = 'in progress'
if self.status is None:
self.status = statusChoices[0][1]
if self.group is None:
self.group = self.creator.taskCardUser.workGroup
super(TaskCard, self).save(*args, **kwargs)
def commentsDescending(self, *args, **kwargs):
return self.comments.order_by('-published',)
class TaskCardUser(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
related_name='taskCardUser'
)
workGroup = models.ForeignKey(
WorkGroup,
related_name='taskCardUser'
)
def __unicode__(self):
return u'%s' % (self.user)
#@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def connectTaskCardUser(sender, instance, created, **kwargs):
if created:
TaskCardUser.objects.create(user=instance, workGroup=WorkGroup.objects.get(id=1))
post_save.connect(connectTaskCardUser, sender=settings.AUTH_USER_MODEL)
class Comment(models.Model):
taskCard = models.ForeignKey(
TaskCard,
related_name = 'comments',
)
author = models.ForeignKey(
settings.AUTH_USER_MODEL
)
published = models.DateTimeField(
null=True,
blank=True,
)
text = models.CharField(
max_length=255,
)
def save(self, *args, **kwargs):
self.published = datetime.datetime.now()
super(Comment, self).save(*args, **kwargs)
class Meta:
unique_together = ('taskCard', 'published')
#class Sprint(models.Model):
# startTime = models.DateTimeField()
# endTime = models.DateTimeField()<|fim▁end|>
|
creator = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='createdTasks',
|
<|file_name|>boss_unsok.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2012-2013 JadeCore <http://www.pandashan.com/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "GameObjectAI.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "heart_of_fear.h"
// Zorlok - 62980
class boss_unsok : public CreatureScript
{
public:
boss_unsok() : CreatureScript("boss_unsok") { }<|fim▁hole|> {
pInstance = creature->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_unsokAI(creature);
}
};
void AddSC_boss_unsok()
{
new boss_unsok();
}<|fim▁end|>
|
struct boss_unsokAI : public BossAI
{
boss_unsokAI(Creature* creature) : BossAI(creature, DATA_UNSOK)
|
<|file_name|>configuration.ts<|end_file_name|><|fim▁begin|>import Adapter from '../../../../src/core/adapters/configuration';
import SearchAdapter from '../../../../src/core/adapters/search';
import { DEFAULT_AREA } from '../../../../src/core/reducers/data/area';
import { DEFAULT_COLLECTION } from '../../../../src/core/reducers/data/collections';
import * as PageReducer from '../../../../src/core/reducers/data/page';
import * as PastPurchaseReducer from '../../../../src/core/reducers/data/past-purchases';
import suite from '../../_suite';
suite('Configuration Adapter', ({ expect, stub }) => {
describe('initialState()', () => {
it('should return initialState based on defaults', () => {
const category = 'cat';
const sort = 'prices';
const config = <any>{
autocomplete: {
category
},
search: {
sort
}
};
expect(Adapter.initialState(config)).to.eql({
data: {
present: {
area: DEFAULT_AREA,
autocomplete: {
suggestions: [],
navigations: [],
products: [],
category: {
field: category,
values: []
},
searchCharMinLimit: 1,
showCategoryValuesForFirstMatch: false,
template: {},
},
fields: [],
collections: {
selected: DEFAULT_COLLECTION,
allIds: [DEFAULT_COLLECTION],
byId: {
[DEFAULT_COLLECTION]: {
name: DEFAULT_COLLECTION
}
}
},
sorts: {
selected: 0,
items: [sort]
},
page: {
...PageReducer.DEFAULTS,
sizes: {
selected: 0,
items: [PageReducer.DEFAULT_PAGE_SIZE]
}
},
pastPurchases: {
...PastPurchaseReducer.DEFAULTS,
page: {
...PastPurchaseReducer.DEFAULTS.page,
sizes: {
selected: 0,
items: [PastPurchaseReducer.DEFAULT_PAGE_SIZE]
}
}
}
}
},
session: {
config
}
});
});
it('should return initialState based on config', () => {
const area = 'test';
const collection = {
default: 'All the depts',
options: ['All the depts', 'idk']
};
const category = 'whatevs';
const fields = ['a', 'b', 'c'];
const pageSize = {
default: 50,
options: [10, 20, 50]
};
const sort = {
default: 'stuff',
options: [{ field: 'stuff', descending: true }, { field: 'other stuff' }]
};
const config = <any>{
area,
collection,
autocomplete: {
category
},
search: {
fields,
pageSize,
sort
}
};
const state = {
data: {
present: {
area,
autocomplete: {
suggestions: [],
navigations: [],
products: [],
category: {
field: category,
values: []
},
searchCharMinLimit: 1,
showCategoryValuesForFirstMatch: false,
template: {},
},
fields,
collections: {
selected: collection.default,
allIds: collection.options,
byId: {
[collection.options[0]]: {
name: collection.options[0]
},
[collection.options[1]]: {
name: collection.options[1]
}
}
},
sorts: {
selected: 0,
items: sort.options
},
page: {
...PageReducer.DEFAULTS,
sizes: {
selected: 2,
items: pageSize.options
}
},
pastPurchases: {
...PastPurchaseReducer.DEFAULTS,
page: {
...PastPurchaseReducer.DEFAULTS.page,
sizes: {
selected: 2,
items: pageSize.options
}
}
}
}
},
session: {
config
}
};
expect(Adapter.initialState(config)).to.eql(state);
});
});
describe('extractCollection()', () => {
it('should return default', () => {
const defaultCollection = 'All';
expect(Adapter.extractCollection(<any>{
collection: {
default: defaultCollection
}
})).to.eq(defaultCollection);
});
it('should return collection', () => {
const collection = 'All';
expect(Adapter.extractCollection(<any>{ collection })).to.eq(collection);
});
});
describe('extractPageSizes()', () => {
const defaultValue = 0;
it('should do nothing if state is not an object', () => {
const pageSizes = Adapter.extractPageSizes(<any>{
search: {
pageSize: false,
}
}, defaultValue);
expect(pageSizes).to.eql({ selected: 0, items: [defaultValue] });
});
it('should default items to defaultValue', () => {
const pageSizes = Adapter.extractPageSizes(<any>{
search: {
pageSize: {},
}
}, defaultValue);
expect(pageSizes).to.eql({ selected: 0, items: [defaultValue] });
});
});
describe('extractSorts()', () => {
it('should do nothing if state does not contain default or options', () => {
const sort = {};
const sorts = Adapter.extractSorts(<any>{ search: { sort } });
expect(sorts).to.eql({ selected: 0, items: [sort] });
});
it('should default selected to empty object', () => {
const sorts = Adapter.extractSorts(<any>{
search: {
sort: {
options: false,
},
}
});
expect(sorts).to.eql({ selected: 0, items: [] });
});
it('should return selected sorts', () => {
const sort = {
default: false,
options: [
{
field: true,
descending: true
},
{}
]
};
expect(Adapter.extractSorts(<any>{
search: {
sort
}
})).to.eql({ selected: 1, items: sort.options });
});
});
describe('extractNavigationsPinned()', () => {
it('should return pinned navigations', () => {
const pinned = 'nav';
expect(Adapter.extractNavigationsPinned(<any>{
recommendations: {
iNav: {
navigations: {
pinned
}
}
}
})).to.eq(pinned);
});
});
describe('extractRefinementsPinned()', () => {
it('should return pinned refinements', () => {
const pinned = 'nav';
expect(Adapter.extractRefinementsPinned(<any>{
recommendations: {
iNav: {
refinements: {
pinned
}
}
}
})).to.eq(pinned);
});
});
describe('extractIndexedState()', () => {
it('should return indexed state', () => {
const collectionDefault = 'Im a collection';
expect(Adapter.extractIndexedState(<any>{ default: collectionDefault })).to.eql({
selected: collectionDefault,
allIds: [collectionDefault]
});
});
});
describe('extractLanguage()', () => {
it('should return global language', () => {
const language = 'en';
expect(Adapter.extractLanguage(<any>{ language })).to.eq(language);
});<|fim▁hole|> const language = 'fr';
expect(Adapter.extractAutocompleteLanguage(<any>{ autocomplete: { language } })).to.eq(language);
});
});
describe('extractAutocompleteProductLanguage()', () => {
it('should return autocomplete product language', () => {
const language = 'fr';
// tslint:disable-next-line max-line-length
expect(Adapter.extractAutocompleteProductLanguage(<any>{ autocomplete: { products: { language } } })).to.eq(language);
});
});
describe('extractAutocompleteArea()', () => {
it('should return autocomplete area', () => {
const area = 'myProductionArea';
expect(Adapter.extractAutocompleteArea(<any>{ autocomplete: { area } })).to.eq(area);
});
});
describe('extractAutocompleteProductArea()', () => {
it('should return autocomplete product area', () => {
const area = 'myProductionArea';
expect(Adapter.extractAutocompleteProductArea(<any>{ autocomplete: { products: { area } } })).to.eq(area);
});
});
describe('extractAutocompleteSuggestionCount()', () => {
it('should return number of autocomplete suggestions to request', () => {
const suggestionCount = 30;
// tslint:disable-next-line max-line-length
expect(Adapter.extractAutocompleteSuggestionCount(<any>{ autocomplete: { suggestionCount } })).to.eq(suggestionCount);
});
});
describe('extractAutocompleteNavigationCount()', () => {
it('should return number of autocomplete navigations to request', () => {
const navigationCount = 14;
// tslint:disable-next-line max-line-length
expect(Adapter.extractAutocompleteNavigationCount(<any>{ autocomplete: { navigationCount } })).to.eq(navigationCount);
});
});
describe('extractAutocompleteAutoFill()', () => {
it('should return hoverAutoFill boolean', () => {
const hoverAutoFill = true;
// tslint:disable-next-line max-line-length
expect(Adapter.extractAutocompleteHoverAutoFill(<any>{ autocomplete: { hoverAutoFill } })).to.eq(hoverAutoFill);
});
});
describe('extractAutocompleteProductCount()', () => {
it('should return number of autocomplete products to request', () => {
const count = 23;
expect(Adapter.extractAutocompleteProductCount(<any>{ autocomplete: { products: { count } } })).to.eq(count);
});
});
describe('isAutocompleteAlphabeticallySorted()', () => {
it('should return whether to sort autocomplete suggestions alphabetically', () => {
expect(Adapter.isAutocompleteAlphabeticallySorted(<any>{ autocomplete: { alphabetical: true } })).to.be.true;
expect(Adapter.isAutocompleteAlphabeticallySorted(<any>{ autocomplete: { alphabetical: false } })).to.be.false;
});
});
describe('isAutocompleteMatchingFuzzily()', () => {
it('should return whether to use fuzzy matching for autocomplete suggestions', () => {
expect(Adapter.isAutocompleteMatchingFuzzily(<any>{ autocomplete: { fuzzy: true } })).to.be.true;
expect(Adapter.isAutocompleteMatchingFuzzily(<any>{ autocomplete: { fuzzy: false } })).to.be.false;
});
});
describe('extractAutocompleteNavigationLabels()', () => {
it('should return the configured autocomplete navigation labels', () => {
const labels = { a: 'b' };
// tslint:disable-next-line max-line-length
expect(Adapter.extractAutocompleteNavigationLabels(<any>{ autocomplete: { navigations: labels } })).to.eql(labels);
});
});
describe('extractAutocompleteNavigationLabels()', () => {
it('should return the configured autocomplete navigation labels', () => {
const maxRefinements = 3;
// tslint:disable-next-line max-line-length
expect(Adapter.extractMaxRefinements(<any>{ search: { maxRefinements } })).to.eql(maxRefinements);
});
});
describe('extractSecuredPayload', () => {
it('should return securedPayload', () => {
const securedPayload = { a: 1 };
// tslint:disable-next-line max-line-length
expect(Adapter.extractSecuredPayload(<any>{ recommendations: { pastPurchases: { securedPayload } } })).to.eql(securedPayload);
});
it('should handle securedPayload being a function', () => {
const payload = { a: 1 };
const securedPayload = stub().returns(payload);
// tslint:disable-next-line max-line-length
expect(Adapter.extractSecuredPayload(<any>{ recommendations: { pastPurchases: { securedPayload } } })).to.eql(payload);
expect(securedPayload).to.be.calledOnce;
});
});
describe('extractProductCount', () => {
it('should return product count', () => {
const productCount = 3;
// tslint:disable-next-line max-line-length
expect(Adapter.extractPastPurchaseProductCount(<any>{ recommendations: { pastPurchases: { productCount } } })).to.eql(productCount);
});
});
describe('shouldAddPastPurchaseBias()', () => {
it('should return true if requesting positive number of biases', () => {
// tslint:disable-next-line max-line-length
expect(Adapter.shouldAddPastPurchaseBias(<any>{ recommendations: { pastPurchases: { biasCount: 3 } } })).to.be.true;
});
it('should return false if requesting zero biases', () => {
// tslint:disable-next-line max-line-length
expect(Adapter.shouldAddPastPurchaseBias(<any>{ recommendations: { pastPurchases: { biasCount: 0 } } })).to.be.false;
});
});
describe('isRealTimeBiasEnabled()', () => {
it('should return config.personalization.realTimeBiasing casted to Boolean (truthy)', () => {
// tslint:disable-next-line max-line-length
expect(Adapter.isRealTimeBiasEnabled(<any>{ personalization: { realTimeBiasing: { attributes: {} } } })).to.be.true;
});
it('should return config.personalization.realTimeBiasing casted to Boolean (falsy)', () => {
// tslint:disable-next-line max-line-length
expect(Adapter.isRealTimeBiasEnabled(<any>{ personalization: { realTimeBiasing: { attributes: null } } })).to.be.false;
});
});
describe('extractRealTimeBiasingExpiry()', () => {
it('should return the expiry time for real time biasing', () => {
const expiry = 3;
// tslint:disable-next-line max-line-length
expect(Adapter.extractRealTimeBiasingExpiry(<any>{ personalization: { realTimeBiasing: { expiry } } })).to.eq(expiry);
});
});
describe('searchOverrides()', () => {
it('should return the search overrides function', () => {
const state: any = { search: { overrides: (r) => r } };
expect(Adapter.searchOverrides(state)).to.eql(state.search.overrides);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { search: { overrides } };
const o: any = { c: 'd' };
expect(Adapter.searchOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
search: {
overrides
}
};
expect(Adapter.searchOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('autocompleteSuggestionsOverrides()', () => {
it('should return the autocomplete suggestions overrides function', () => {
const state: any = { autocomplete: { overrides: { suggestions: (r) => r } } };
expect(Adapter.autocompleteSuggestionsOverrides(state)).to.eql(state.autocomplete.overrides.suggestions);
});
it('should return a function that mixes in the overrides with a given object', () => {
const suggestions: any = { a: 'b' };
const state: any = { autocomplete: { overrides: { suggestions } } };
const o: any = { c: 'd' };
expect(Adapter.autocompleteSuggestionsOverrides(state)(o)).to.eql({ ...o, ...suggestions });
});
it('should return a normalized function', () => {
const overrides = { c: 'd' };
const config: any = {
autocomplete: {
overrides: {
suggestions: overrides
}
}
};
expect(Adapter.autocompleteSuggestionsOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('autocompleteProductsOverrides()', () => {
it('should return the autocomplete products overrides function', () => {
const state: any = { autocomplete: { overrides: { products: (r) => r } } };
expect(Adapter.autocompleteProductsOverrides(state)).to.eq(state.autocomplete.overrides.products);
});
it('should return a function that mixes in the overrides with a given object', () => {
const products: any = { a: 'b' };
const state: any = { autocomplete: { overrides: { products } } };
const o: any = { c: 'd' };
expect(Adapter.autocompleteProductsOverrides(state)(o)).to.eql({ ...o, ...products });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
autocomplete: {
overrides: {
products: overrides
}
}
};
expect(Adapter.autocompleteProductsOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('collectionOverrides()', () => {
it('should return the collections overrides function', () => {
const state: any = { collections: { overrides: (r) => r } };
expect(Adapter.collectionOverrides(state)).to.eq(state.collections.overrides);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { collections: { overrides } };
const o: any = { c: 'd' };
expect(Adapter.collectionOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
collections: {
overrides
}
};
expect(Adapter.collectionOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('detailsOverrides()', () => {
it('should return the details overrides function', () => {
const state: any = { details: { overrides: (r) => r } };
expect(Adapter.detailsOverrides(state)).to.eq(state.details.overrides);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { details: { overrides } };
const o: any = { c: 'd' };
expect(Adapter.detailsOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
details: {
overrides
}
};
expect(Adapter.detailsOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('refinementsOverrides', () => {
it('should return the refinements overrides function', () => {
const state: any = { refinements: { overrides: (r) => r } };
expect(Adapter.refinementsOverrides(state)).to.eq(state.refinements.overrides);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { refinements: { overrides } };
const o: any = { c: 'd' };
expect(Adapter.refinementsOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
refinements: {
overrides
}
};
expect(Adapter.refinementsOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('pastPurchaseAutocompleteOverrides', () => {
it('should return the pastPurchases autocomplete overrides function', () => {
const state: any = { recommendations: { pastPurchases: { overrides: { autocomplete: (r) => r } } } };
expect(Adapter.pastPurchaseAutocompleteOverrides(state))
.to.eq(state.recommendations.pastPurchases.overrides.autocomplete);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { recommendations: { pastPurchases: { overrides: { autocomplete: overrides } } } };
const o: any = { c: 'd' };
expect(Adapter.pastPurchaseAutocompleteOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
recommendations: {
pastPurchases: {
overrides: {
autocomplete: overrides
}
}
}
};
expect(Adapter.pastPurchaseAutocompleteOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('pastPurchaseOverrides', () => {
it('should return the pastPurchases products overrides function', () => {
const state: any = { recommendations: { pastPurchases: { overrides: { products: (r) => r } } } };
expect(Adapter.pastPurchaseOverrides(state)).to.eq(state.recommendations.pastPurchases.overrides.products);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { recommendations: { pastPurchases: { overrides: { products: overrides } } } };
const o: any = { c: 'd' };
expect(Adapter.pastPurchaseOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
recommendations: {
pastPurchases: {
overrides: {
products: overrides
}
}
}
};
expect(Adapter.pastPurchaseOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('recommendationsNavigationsOverrides', () => {
it('should return the recommendations navigations overrides function', () => {
const state: any = { recommendations: { overrides: { navigations: (r) => r } } };
expect(Adapter.recommendationsNavigationsOverrides(state))
.to.eq(state.recommendations.overrides.navigations);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { recommendations: { overrides: { navigations: overrides } } };
const o: any = { c: 'd' };
expect(Adapter.recommendationsNavigationsOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
recommendations: {
overrides: {
navigations: overrides
}
}
};
expect(Adapter.recommendationsNavigationsOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('recommendationsIdsOverrides', () => {
it('should return the recommendations ids overrides function', () => {
const state: any = { recommendations: { overrides: { ids: (r) => r } } };
expect(Adapter.recommendationsIdsOverrides(state))
.to.eq(state.recommendations.overrides.ids);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { recommendations: { overrides: { ids: overrides } } };
const o: any = { c: 'd' };
expect(Adapter.recommendationsIdsOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
recommendations: {
overrides: {
ids: overrides
}
}
};
expect(Adapter.recommendationsIdsOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('recommendationsProductsOverrides', () => {
it('should return the recommendations products overrides function', () => {
const state: any = { recommendations: { overrides: { products: (r) => r } } };
expect(Adapter.recommendationsProductsOverrides(state))
.to.eq(state.recommendations.overrides.products);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { recommendations: { overrides: { products: overrides } } };
const o: any = { c: 'd' };
expect(Adapter.recommendationsProductsOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
recommendations: {
overrides: {
products: overrides
}
}
};
expect(Adapter.recommendationsProductsOverrides(config)(<any>{})).to.eql(overrides);
});
});
describe('recommendationsSuggestionsOverrides', () => {
it('should return the recommendations autocompleteSuggestions overrides function', () => {
const state: any = { recommendations: { overrides: { autocompleteSuggestions: (r) => r } } };
expect(Adapter.recommendationsSuggestionsOverrides(state))
.to.eq(state.recommendations.overrides.autocompleteSuggestions);
});
it('should return a function that mixes in the overrides with a given object', () => {
const overrides: any = { a: 'b' };
const state: any = { recommendations: { overrides: { autocompleteSuggestions: overrides } } };
const o: any = { c: 'd' };
expect(Adapter.recommendationsSuggestionsOverrides(state)(o)).to.eql({ ...o, ...overrides });
});
it('should return a normalized function', () => {
const overrides = { a: 'b' };
const config: any = {
recommendations: {
overrides: {
autocompleteSuggestions: overrides
}
}
};
expect(Adapter.recommendationsSuggestionsOverrides(config)(<any>{})).to.eql(overrides);
});
});
});<|fim▁end|>
|
});
describe('extractAutocompleteLanguage()', () => {
it('should return autocomplete language', () => {
|
<|file_name|>example_svc_dsls.go<|end_file_name|><|fim▁begin|>package testdata
import (
. "goa.design/goa/v3/dsl"<|fim▁hole|> Title("conflict with API name and service names")
})
var _ = Service("aloha", func() {}) // same as API name
var _ = Service("alohaapi", func() {}) // API name + 'api' suffix
var _ = Service("alohaapi1", func() {}) // API name + 'api' suffix + sequential no.
}
var ConflictWithGoifiedAPINameAndServiceNamesDSL = func() {
var _ = API("good-by", func() {
Title("conflict with goified API name and goified service names")
})
var _ = Service("good-by-", func() {}) // Goify name is same as API name
var _ = Service("good-by-api", func() {}) // API name + 'api' suffix
var _ = Service("good-by-api-1", func() {}) // API name + 'api' suffix + sequential no.
}<|fim▁end|>
|
)
var ConflictWithAPINameAndServiceNameDSL = func() {
var _ = API("aloha", func() {
|
<|file_name|>FESpace_imp.hpp<|end_file_name|><|fim▁begin|>/**
* @file FESpace_imp.hpp
* @brief Implementation of the functional space class methods
* @author Carlo Marcati
* @date 2013-09-08
*/
/* 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/>.
*/<|fim▁hole|>#ifndef __FESPACE_IMP_HPP__
#define __FESPACE_IMP_HPP__ 1
namespace Tspeed{
template<int N, typename Q, typename S>
FESpace<N,Q,S>::FESpace(Mesh_ptr m):M_mesh(m),M_quad(),M_sh(),M_nln((N+1)*(N+2)/2),M_nqn2d(Q::nqn2d),M_ne(M_mesh->ne())
{
for(int i=0; i<M_nln; ++i)
{
M_B.col(i) = M_sh.phi(i,M_quad.int_nodes().col(0), M_quad.int_nodes().col(1));
M_G[i].row(0) = M_sh.grad(i,M_quad.int_nodes().col(0), M_quad.int_nodes().col(1)).col(0).transpose();
M_G[i].row(1) = M_sh.grad(i,M_quad.int_nodes().col(0), M_quad.int_nodes().col(1)).col(1).transpose();
M_vert_basis(i,0) = M_sh.phi(i,0.2,0.2);
M_vert_basis(i,1) = M_sh.phi(i,0.8,0.2);
M_vert_basis(i,2) = M_sh.phi(i,0.2,0.8);
M_vert_basis(i,3) = M_sh.phi(i,0.5,0.5);
for(int iedg=0; iedg<3; ++iedg)
{
M_Bedge[iedg].col(i) = M_sh.phi (i, M_quad.edge_nodes(iedg).col(0), M_quad.edge_nodes(iedg).col(1));
M_Gedge[i*3+iedg].row(0) = M_sh.grad(i, M_quad.edge_nodes(iedg).col(0), M_quad.edge_nodes(iedg).col(1)).col(0);
M_Gedge[i*3+iedg].row(1) = M_sh.grad(i, M_quad.edge_nodes(iedg).col(0), M_quad.edge_nodes(iedg).col(1)).col(1);
}
}
base_mass_and_inv();
std::cout << "FESpace :: " << (N+1)*(N+2)/2*M_mesh->ne() << " dof per component." << std::endl;
};
template<int N, typename Q, typename S>
void FESpace<N,Q,S>::base_mass_and_inv()
{
if(S::is_orthonormal)
{
M_base_mass = Eigen::MatrixXd::Identity(S::gdl, S::gdl);
}
else
{
M_base_mass = Eigen::MatrixXd::Zero(S::gdl, S::gdl);
for(int i=0; i<S::gdl ; ++i)
{
for (int j = 0; j<S::gdl ; ++j)
{
for(int k = 0; k<Q::nqn2d ; ++k)
M_base_mass(i,j) += M_B(k,i)*M_B(k,j)*M_quad.iweight(k);
}
}
}
M_base_invmass = M_base_mass.inverse();
};
template<int N, typename Q, typename S>
void FESpace<N,Q,S>::points_out(std::string const &fname)const
{
std::ofstream outf(fname);
Geo::Point p0(0.2,0.2),p1(0.8,0.2),p2(0.2,0.8),p3(0.5,0.5);
for(auto ie: M_mesh->elements())
{
outf << ie.map(p0).x() << " " << ie.map(p0).y() << std::endl;
outf << ie.map(p1).x() << " " << ie.map(p1).y() << std::endl;
outf << ie.map(p2).x() << " " << ie.map(p2).y() << std::endl;
outf << ie.map(p3).x() << " " << ie.map(p3).y() << std::endl;
}
outf.close();
}
template<int N, typename Q, typename S>
void FESpace<N,Q,S>::field_out(std::string const &fname, Eigen::VectorXd const &uh, unsigned int step)const
{
//std::ofstream outf_s1(fname+"u_x_"+std::to_string(step)+".field");
//std::ofstream outf_s2(fname+"u_y_"+std::to_string(step)+".field");
std::ofstream outf_v(fname+"u_"+std::to_string(step)+".field");
double valx, valy;
for(auto ie: M_mesh->elements())
{
for(int i = 0; i<4 ; ++i)
{
valx = M_vert_basis.col(i).dot(uh.segment(ie.id()*M_nln,M_nln));
valy = M_vert_basis.col(i).dot(uh.segment(ie.id()*M_nln+M_ne*M_nln,M_nln));
//outf_s1 << valx << std::endl;
//outf_s2 << valy << std::endl;
outf_v << valx << " " << valy << std::endl;
}
}
//outf_s1.close();
//outf_s2.close();
outf_v.close();
}
template<int N, typename Q, typename S>
double FESpace<N,Q,S>::L2error(std::function<std::array<double,2>(double,double)> const & uex, Eigen::VectorXd const & uh)const
{
Eigen::MatrixXd local_exact = Eigen::MatrixXd::Zero(M_nqn2d,2);
Eigen::MatrixXd local_aprox = Eigen::MatrixXd::Zero(M_nqn2d,2);
std::array<double,2 > F;
Geo::Point p;
double error = 0;
double error_loc = 0;
for(auto ie: M_mesh->elements())
{
error_loc = 0;
local_aprox.col(0) = M_B*uh.segment(ie.id()*M_nln, M_nln);
local_aprox.col(1) = M_B*uh.segment(M_nln*M_ne+ie.id()*M_nln, M_nln);
for(int i=0; i<M_nqn2d; ++i)
{
p = ie.map(M_quad.inode(i));
F = uex(p.x(), p.y());
//local_exact(i,0) = F[0];
//local_exact(i,1) = F[1];
error_loc += ((local_aprox(i,0) - F[0])*(local_aprox(i,0)-F[0])+(local_aprox(i,1) - F[1])*(local_aprox(i,1)-F[1]))*M_quad.iweight(i);
}
//std::cout << "********" << error_loc << std::endl;
error += error_loc*ie.detJ();
}
return std::sqrt(error);
};
template<int N, typename Q, typename S>
Eigen::VectorXd FESpace<N,Q,S>::transform(std::function<std::array<double,2>(double,double)> const & fun)const
{
Eigen::VectorXd uh(2*M_ne*M_nln);
unsigned int startIndex;
unsigned int size = M_nln;
Eigen::VectorXd rhs(M_nln);
for(auto ie: M_mesh->elements())
{
startIndex = ie.id()*M_nln;
rhs = M_loc_rhs(ie,fun);
//std::cout << ie.id() << ": " << std::endl;
//std::cout << ie.Jac() << std::endl << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << std::endl;
//std::cout << rhs << std::endl;
//std::cout << std::endl;
//invM = 1./ie.detJ()*Eigen::MatrixXd::Identity(M_nln,M_nln);
uh.segment(startIndex, size) = 1./ie.detJ()*M_base_invmass * rhs.segment(0, size);
uh.segment(startIndex + M_ne*M_nln, size) = 1./ie.detJ()*M_base_invmass * rhs.segment(M_nln, size);
}
return uh;
}
template<int N, typename Q, typename S>
Eigen::VectorXd FESpace<N,Q,S>::M_loc_rhs(Geo::Triangle const & ie , std::function<std::array<double,2>(double,double)> const & fun)const
{
double dx;
Geo::Point p;
std::array<double,2> F;
Eigen::VectorXd out(2*M_nln);
out = Eigen::VectorXd::Zero(2*M_nln);
for(unsigned int i=0; i<Q::nqn2d; ++i)
{
dx = std::abs(ie.detJ())*M_quad.iweight(i);
p = ie.map(M_quad.inode(i));
F = fun(p.x(),p.y());
out.segment(0,M_nln) += F[0]*dx*M_B.row(i);
out.segment(M_nln,M_nln) += F[1]*dx*M_B.row(i);
}
//std::cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" <<std::endl;
//std::cout << *out << std::endl;
//std::cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" <<std::endl;
return out;
}
}
#endif<|fim▁end|>
| |
<|file_name|>ZipError.js<|end_file_name|><|fim▁begin|>/*
Copyright 2012-2013, Polyvi Inc. (http://www.xface3.com)
This program is distributed under the terms of the GNU General Public License.
This file is part of xFace.
xFace 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.
xFace 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 xFace. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @module zip
*/
/**
* 该类定义一些常量,用于标识压缩和解压失败的错误信息(Android, iOS, WP8)<br/>
* 相关参考: {{#crossLink "Zip"}}{{/crossLink}}
* @class ZipError
* @static
* @platform Android, iOS, WP8
* @since 3.0.0
*/
var ZipError = function() {<|fim▁hole|>/**
* 待压缩的文件或文件夹不存在(Android, iOS, WP8)
* @property FILE_NOT_EXIST
* @type Number
* @static
* @final
* @platform Android, iOS, WP8
* @since 3.0.0
*/
ZipError.FILE_NOT_EXIST = 1;
/**
* 压缩文件出错.(Android, iOS, WP8)
* @property COMPRESS_FILE_ERROR
* @type Number
* @static
* @final
* @platform Android, iOS, WP8
* @since 3.0.0
*/
ZipError.COMPRESS_FILE_ERROR = 2;
/**
* 解压文件出错.(Android, iOS, WP8)
* @property UNZIP_FILE_ERROR
* @type Number
* @static
* @final
* @platform Android, iOS, WP8
* @since 3.0.0
*/
ZipError.UNZIP_FILE_ERROR = 3;
/**
* 文件类型错误,不支持的文件类型(Android, iOS, WP8)
* @property FILE_TYPE_ERROR
* @type Number
* @static
* @final
* @platform Android, iOS, WP8
* @since 3.0.0
*/
ZipError.FILE_TYPE_ERROR = 4;
/**
* 位置错误(Android, iOS, WP8)
* @property UNKNOWN_ERR
* @type Number
* @static
* @final
* @platform Android, iOS, WP8
* @since 3.0.0
*/
ZipError.UNKNOWN_ERR = 5;
module.exports = ZipError;<|fim▁end|>
|
};
|
<|file_name|>preferences.js<|end_file_name|><|fim▁begin|>import { t } from '../../core/localizer';
import { uiPane } from '../pane';
import { uiSectionPrivacy } from '../sections/privacy';
export function uiPanePreferences(context) {
let preferencesPane = uiPane('preferences', context)
.key(t('preferences.key'))
.label(t.html('preferences.title'))
.description(t.html('preferences.description'))
.iconName('fas-user-cog')
.sections([
uiSectionPrivacy(context)<|fim▁hole|>
return preferencesPane;
}<|fim▁end|>
|
]);
|
<|file_name|>amo.js<|end_file_name|><|fim▁begin|>module.exports = { domain:"messages",
locale_data:{ messages:{ "":{ domain:"messages",
plural_forms:"nplurals=2; plural=(n != 1);",
lang:"el" },
"%(addonName)s %(startSpan)sby %(authorList)s%(endSpan)s":[ "%(addonName)s %(startSpan)s από %(authorList)s%(endSpan)s" ],
"Extension Metadata":[ "Μεταδεδομένα επέκτασης" ],
Screenshots:[ "Στιγμιότυπα" ],
"About this extension":[ "Σχετικά με την επέκταση" ],
"Rate your experience":[ "Αξιολογήστε την εμπειρία σας" ],
Category:[ "Κατηγορία" ],
"Used by":[ "Χρήση από" ],
Sentiment:[ "Αίσθηση" ],
Back:[ "Πίσω" ],
Submit:[ "Υποβολή" ],
"Please enter some text":[ "Παρακαλώ εισάγετε κείμενο" ],
"Write a review":[ "Γράψτε μια κριτική" ],
"Tell the world why you think this extension is fantastic!":[ "Πείτε στον κόσμο γιατί θεωρείτε ότι αυτή η επέκταση είναι φανταστική!" ],
"Privacy policy":[ "Πολιτική απορρήτου" ],
"Legal notices":[ "Νομικές σημειώσεις" ],
"View desktop site":[ "Προβολή ιστοσελίδας για υπολογιστές" ],
"Browse in your language":[ "Περιήγηση στη γλώσσα σας" ],
"Firefox Add-ons":[ "Πρόσθετα Firefox" ],
"How are you enjoying your experience with %(addonName)s?":[ "Απολαμβάνετε την εμπειρία σας με το %(addonName)s;" ],
"screenshot %(imageNumber)s of %(totalImages)s":[ "Στιγμιότυπο %(imageNumber)s από %(totalImages)s" ],
"Average rating: %(rating)s out of 5":[ "Μέση βαθμολογία: %(rating)s από 5" ],
"No ratings":[ "Καμία κριτική" ],
"%(users)s user":[ "%(users)s χρήστης",
"%(users)s χρήστες" ],
"Log out":[ "Αποσύνδεση" ],
"Log in/Sign up":[ "Σύνδεση/Εγγραφή" ],
"Add-ons for Firefox":[ "Πρόσθετα για το Firefox" ],
"What do you want Firefox to do?":[ "Τι θέλετε να κάνει το Firefox;" ],
"Block ads":[ "Αποκλεισμός διαφημίσεων" ],
Screenshot:[ "Στιγμιότυπο οθόνης" ],
"Save stuff":[ "Αποθήκευση στοιχείων" ],
"Shop online":[ "Διαδικτυακές αγορές" ],
"Be social":[ "Κοινωνικοποίηση" ],
"Share stuff":[ "Κοινή χρήση στοιχείων" ],
"Browse all extensions":[ "Περιήγηση σε όλες τις επεκτάσεις" ],
"How do you want Firefox to look?":[ "Τι εμφάνιση θέλετε να έχει το Firefox;" ],
Wild:[ "Άγρια" ],
Abstract:[ "Αφηρημένη" ],
Fashionable:[ "Μοδάτη" ],
Scenic:[ "Σκηνική" ],
Sporty:[ "Αθλητική" ],
Mystical:[ "Μυστική" ],
"Browse all themes":[ "Περιήγηση σε όλα τα θέματα" ],
"Downloading %(name)s.":[ "Γίνεται λήψη του %(name)s." ],
"Installing %(name)s.":[ "Γίνεται εγκατάσταση του %(name)s." ],
"%(name)s is installed and enabled. Click to uninstall.":[ "Το %(name)s έχει εγκατασταθεί και ενεργοποιηθεί. Κάντε κλικ για απεγκατάσταση." ],
"%(name)s is disabled. Click to enable.":[ "Το %(name)s έχει απενεργοποιηθεί. Κάντε κλικ για ενεργοποίηση." ],
"Uninstalling %(name)s.":[ "Γίνεται απεγκατάσταση του %(name)s." ],
"%(name)s is uninstalled. Click to install.":[ "Το %(name)s έχει απεγκατασταθεί. Κάντε κλικ για εγκατάσταση." ],
"Install state for %(name)s is unknown.":[ "Η κατάσταση εγκατάστασης για το %(name)s είναι άγνωστη." ],
Previous:[ "Προηγούμενη" ],
Next:[ "Επόμενη" ],
"Page %(currentPage)s of %(totalPages)s":[ "Σελίδα %(currentPage)s από %(totalPages)s" ],
"Your search for \"%(query)s\" returned %(count)s result.":[ "Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτέλεσμα.",
"Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτελέσματα." ],
"Searching...":[ "Αναζήτηση..." ],
"No results were found for \"%(query)s\".":[ "Δεν βρέθηκε κανένα αποτέλεσμα για το \"%(query)s\"." ],
"Please supply a valid search":[ "Παρακαλώ κάντε μια έγκυρη αναζήτηση" ] } },
_momentDefineLocale:function anonymous() {
//! moment.js locale configuration
//! locale : Greek [el]
//! author : Aggelos Karalias : https://github.com/mehiel
;(function (global, factory) {<|fim▁hole|> factory(global.moment)
}(this, (function (moment) { 'use strict';
function isFunction(input) {
return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}
var el = moment.defineLocale('el', {
monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'),
monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'),
months : function (momentToFormat, format) {
if (/D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
return this._monthsGenitiveEl[momentToFormat.month()];
} else {
return this._monthsNominativeEl[momentToFormat.month()];
}
},
monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),
weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'),
weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),
weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),
meridiem : function (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'μμ' : 'ΜΜ';
} else {
return isLower ? 'πμ' : 'ΠΜ';
}
},
isPM : function (input) {
return ((input + '').toLowerCase()[0] === 'μ');
},
meridiemParse : /[ΠΜ]\.?Μ?\.?/i,
longDateFormat : {
LT : 'h:mm A',
LTS : 'h:mm:ss A',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY h:mm A',
LLLL : 'dddd, D MMMM YYYY h:mm A'
},
calendarEl : {
sameDay : '[Σήμερα {}] LT',
nextDay : '[Αύριο {}] LT',
nextWeek : 'dddd [{}] LT',
lastDay : '[Χθες {}] LT',
lastWeek : function () {
switch (this.day()) {
case 6:
return '[το προηγούμενο] dddd [{}] LT';
default:
return '[την προηγούμενη] dddd [{}] LT';
}
},
sameElse : 'L'
},
calendar : function (key, mom) {
var output = this._calendarEl[key],
hours = mom && mom.hours();
if (isFunction(output)) {
output = output.apply(mom);
}
return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις'));
},
relativeTime : {
future : 'σε %s',
past : '%s πριν',
s : 'λίγα δευτερόλεπτα',
m : 'ένα λεπτό',
mm : '%d λεπτά',
h : 'μία ώρα',
hh : '%d ώρες',
d : 'μία μέρα',
dd : '%d μέρες',
M : 'ένας μήνας',
MM : '%d μήνες',
y : 'ένας χρόνος',
yy : '%d χρόνια'
},
ordinalParse: /\d{1,2}η/,
ordinal: '%dη',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4st is the first week of the year.
}
});
return el;
})));
} }<|fim▁end|>
|
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
|
<|file_name|>block.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Layout for CSS block-level elements.
//!
//! As a terminology note, the term *absolute positioning* here refers to elements with position
//! `absolute` or `fixed`. The term *positioned element* refers to elements with position
//! `relative`, `absolute`, and `fixed`. The term *containing block* (occasionally abbreviated as
//! *CB*) is the containing block for the current flow, which differs from the static containing
//! block if the flow is absolutely-positioned.
//!
//! "CSS 2.1" or "CSS 2.2" refers to the editor's draft of the W3C "Cascading Style Sheets Level 2
//! Revision 2 (CSS 2.2) Specification" available here:
//!
//! http://dev.w3.org/csswg/css2/
//!
//! "INTRINSIC" refers to L. David Baron's "More Precise Definitions of Inline Layout and Table
//! Layout" available here:
//!
//! http://dbaron.org/css/intrinsic/
//!
//! "CSS-SIZING" refers to the W3C "CSS Intrinsic & Extrinsic Sizing Module Level 3" document
//! available here:
//!
//! http://dev.w3.org/csswg/css-sizing/
#![deny(unsafe_block)]
use construct::FlowConstructor;
use context::LayoutContext;
use display_list_builder::{BlockFlowDisplayListBuilding, FragmentDisplayListBuilding};
use floats::{ClearBoth, ClearLeft, ClearRight, FloatKind, FloatLeft, Floats, PlacementInfo};
use flow::{BaseFlow, BlockFlowClass, FlowClass, Flow, ImmutableFlowUtils};
use flow::{MutableFlowUtils, PreorderFlowTraversal, PostorderFlowTraversal, mut_base};
use flow;
use fragment::{Fragment, ImageFragment, InlineBlockFragment, ScannedTextFragment};
use layout_debug;
use model::{Auto, IntrinsicISizes, MarginCollapseInfo, MarginsCollapse, MarginsCollapseThrough};
use model::{MaybeAuto, NoCollapsibleMargins, Specified, specified, specified_or_none};
use table::ColumnInlineSize;
use wrapper::ThreadSafeLayoutNode;
use geom::Size2D;
use gfx::display_list::BlockLevel;
use serialize::{Encoder, Encodable};
use servo_msg::compositor_msg::LayerId;
use servo_util::geometry::{Au, MAX_AU, MAX_RECT};
use servo_util::logical_geometry::{LogicalPoint, LogicalRect, LogicalSize};
use servo_util::opts;
use std::cmp::{max, min};
use std::fmt;
use style::computed_values::{LPA_Auto, LPA_Length, LPA_Percentage, LPN_Length, LPN_None};
use style::computed_values::{LPN_Percentage, LP_Length, LP_Percentage, box_sizing, clear};
use style::computed_values::{display, float, overflow, position};
/// Information specific to floated blocks.
#[deriving(Clone, Encodable)]
pub struct FloatedBlockInfo {
/// The amount of inline size that is available for the float.
pub containing_inline_size: Au,
/// The float ceiling, relative to `BaseFlow::position::cur_b` (i.e. the top part of the border
/// box).
pub float_ceiling: Au,
/// Index into the fragment list for inline floats
pub index: Option<uint>,
/// Left or right?
pub float_kind: FloatKind,
}
impl FloatedBlockInfo {
pub fn new(float_kind: FloatKind) -> FloatedBlockInfo {
FloatedBlockInfo {
containing_inline_size: Au(0),
float_ceiling: Au(0),
index: None,
float_kind: float_kind,
}
}
}
/// The solutions for the block-size-and-margins constraint equation.
struct BSizeConstraintSolution {
block_start: Au,
_block_end: Au,
block_size: Au,
margin_block_start: Au,
margin_block_end: Au
}
impl BSizeConstraintSolution {
fn new(block_start: Au, block_end: Au, block_size: Au, margin_block_start: Au, margin_block_end: Au)
-> BSizeConstraintSolution {
BSizeConstraintSolution {
block_start: block_start,
_block_end: block_end,
block_size: block_size,
margin_block_start: margin_block_start,
margin_block_end: margin_block_end,
}
}
/// Solve the vertical constraint equation for absolute non-replaced elements.
///
/// CSS Section 10.6.4
/// Constraint equation:
/// block-start + block-end + block-size + margin-block-start + margin-block-end
/// = absolute containing block block-size - (vertical padding and border)
/// [aka available_block-size]
///
/// Return the solution for the equation.
fn solve_vertical_constraints_abs_nonreplaced(block_size: MaybeAuto,
block_start_margin: MaybeAuto,
block_end_margin: MaybeAuto,
block_start: MaybeAuto,
block_end: MaybeAuto,
content_block_size: Au,
available_block_size: Au,
static_b_offset: Au)
-> BSizeConstraintSolution {
// Distance from the block-start edge of the Absolute Containing Block to the
// block-start margin edge of a hypothetical box that would have been the
// first box of the element.
let static_position_block_start = static_b_offset;
let (block_start, block_end, block_size, margin_block_start, margin_block_end) = match (block_start, block_end, block_size) {
(Auto, Auto, Auto) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let block_start = static_position_block_start;
// Now it is the same situation as block-start Specified and block-end
// and block-size Auto.
let block_size = content_block_size;
let sum = block_start + block_size + margin_block_start + margin_block_end;
(block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end)
}
(Specified(block_start), Specified(block_end), Specified(block_size)) => {
match (block_start_margin, block_end_margin) {
(Auto, Auto) => {
let total_margin_val = available_block_size - block_start - block_end - block_size;
(block_start, block_end, block_size,
total_margin_val.scale_by(0.5),
total_margin_val.scale_by(0.5))
}
(Specified(margin_block_start), Auto) => {
let sum = block_start + block_end + block_size + margin_block_start;
(block_start, block_end, block_size, margin_block_start, available_block_size - sum)
}
(Auto, Specified(margin_block_end)) => {
let sum = block_start + block_end + block_size + margin_block_end;
(block_start, block_end, block_size, available_block_size - sum, margin_block_end)
}
(Specified(margin_block_start), Specified(margin_block_end)) => {
// Values are over-constrained. Ignore value for 'block-end'.
let sum = block_start + block_size + margin_block_start + margin_block_end;
(block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end)
}
}
}
// For the rest of the cases, auto values for margin are set to 0
// If only one is Auto, solve for it
(Auto, Specified(block_end), Specified(block_size)) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let sum = block_end + block_size + margin_block_start + margin_block_end;
(available_block_size - sum, block_end, block_size, margin_block_start, margin_block_end)
}
(Specified(block_start), Auto, Specified(block_size)) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let sum = block_start + block_size + margin_block_start + margin_block_end;
(block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end)
}
(Specified(block_start), Specified(block_end), Auto) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let sum = block_start + block_end + margin_block_start + margin_block_end;
(block_start, block_end, available_block_size - sum, margin_block_start, margin_block_end)
}
// If block-size is auto, then block-size is content block-size. Solve for the
// non-auto value.
(Specified(block_start), Auto, Auto) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let block_size = content_block_size;
let sum = block_start + block_size + margin_block_start + margin_block_end;
(block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end)
}
(Auto, Specified(block_end), Auto) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let block_size = content_block_size;
let sum = block_end + block_size + margin_block_start + margin_block_end;
(available_block_size - sum, block_end, block_size, margin_block_start, margin_block_end)
}
(Auto, Auto, Specified(block_size)) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let block_start = static_position_block_start;
let sum = block_start + block_size + margin_block_start + margin_block_end;
(block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end)
}
};
BSizeConstraintSolution::new(block_start, block_end, block_size, margin_block_start, margin_block_end)
}
/// Solve the vertical constraint equation for absolute replaced elements.
///
/// Assumption: The used value for block-size has already been calculated.
///
/// CSS Section 10.6.5
/// Constraint equation:
/// block-start + block-end + block-size + margin-block-start + margin-block-end
/// = absolute containing block block-size - (vertical padding and border)
/// [aka available_block-size]
///
/// Return the solution for the equation.
fn solve_vertical_constraints_abs_replaced(block_size: Au,
block_start_margin: MaybeAuto,
block_end_margin: MaybeAuto,
block_start: MaybeAuto,
block_end: MaybeAuto,
_: Au,
available_block_size: Au,
static_b_offset: Au)
-> BSizeConstraintSolution {
// Distance from the block-start edge of the Absolute Containing Block to the
// block-start margin edge of a hypothetical box that would have been the
// first box of the element.
let static_position_block_start = static_b_offset;
let (block_start, block_end, block_size, margin_block_start, margin_block_end) = match (block_start, block_end) {
(Auto, Auto) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let block_start = static_position_block_start;
let sum = block_start + block_size + margin_block_start + margin_block_end;
(block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end)
}
(Specified(block_start), Specified(block_end)) => {
match (block_start_margin, block_end_margin) {
(Auto, Auto) => {
let total_margin_val = available_block_size - block_start - block_end - block_size;
(block_start, block_end, block_size,
total_margin_val.scale_by(0.5),
total_margin_val.scale_by(0.5))
}
(Specified(margin_block_start), Auto) => {
let sum = block_start + block_end + block_size + margin_block_start;
(block_start, block_end, block_size, margin_block_start, available_block_size - sum)
}
(Auto, Specified(margin_block_end)) => {
let sum = block_start + block_end + block_size + margin_block_end;
(block_start, block_end, block_size, available_block_size - sum, margin_block_end)
}
(Specified(margin_block_start), Specified(margin_block_end)) => {
// Values are over-constrained. Ignore value for 'block-end'.
let sum = block_start + block_size + margin_block_start + margin_block_end;
(block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end)
}
}
}
// If only one is Auto, solve for it
(Auto, Specified(block_end)) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let sum = block_end + block_size + margin_block_start + margin_block_end;
(available_block_size - sum, block_end, block_size, margin_block_start, margin_block_end)
}
(Specified(block_start), Auto) => {
let margin_block_start = block_start_margin.specified_or_zero();
let margin_block_end = block_end_margin.specified_or_zero();
let sum = block_start + block_size + margin_block_start + margin_block_end;
(block_start, available_block_size - sum, block_size, margin_block_start, margin_block_end)
}
};
BSizeConstraintSolution::new(block_start, block_end, block_size, margin_block_start, margin_block_end)
}
}
/// Performs block-size calculations potentially multiple times, taking
/// (assuming an horizontal writing mode) `height`, `min-height`, and `max-height`
/// into account. After each call to `next()`, the caller must call `.try()` with the
/// current calculated value of `height`.
///
/// See CSS 2.1 § 10.7.
struct CandidateBSizeIterator {
block_size: MaybeAuto,
max_block_size: Option<Au>,
min_block_size: Au,
candidate_value: Au,
status: CandidateBSizeIteratorStatus,
}
impl CandidateBSizeIterator {
/// Creates a new candidate block-size iterator. `block_container_block-size` is `None` if the block-size
/// of the block container has not been determined yet. It will always be `Some` in the case of
/// absolutely-positioned containing blocks.
pub fn new(fragment: &Fragment, block_container_block_size: Option<Au>)
-> CandidateBSizeIterator {
// Per CSS 2.1 § 10.7, (assuming an horizontal writing mode,)
// percentages in `min-height` and `max-height` refer to the height of
// the containing block.
// If that is not determined yet by the time we need to resolve
// `min-height` and `max-height`, percentage values are ignored.
let block_size = match (fragment.style.content_block_size(), block_container_block_size) {
(LPA_Percentage(percent), Some(block_container_block_size)) => {
Specified(block_container_block_size.scale_by(percent))
}
(LPA_Percentage(_), None) | (LPA_Auto, _) => Auto,
(LPA_Length(length), _) => Specified(length),
};
let max_block_size = match (fragment.style.max_block_size(), block_container_block_size) {
(LPN_Percentage(percent), Some(block_container_block_size)) => {
Some(block_container_block_size.scale_by(percent))
}
(LPN_Percentage(_), None) | (LPN_None, _) => None,
(LPN_Length(length), _) => Some(length),
};
let min_block_size = match (fragment.style.min_block_size(), block_container_block_size) {
(LP_Percentage(percent), Some(block_container_block_size)) => {
block_container_block_size.scale_by(percent)
}
(LP_Percentage(_), None) => Au(0),
(LP_Length(length), _) => length,
};
// If the style includes `box-sizing: border-box`, subtract the border and padding.
let adjustment_for_box_sizing = match fragment.style.get_box().box_sizing {
box_sizing::border_box => fragment.border_padding.block_start_end(),
box_sizing::content_box => Au(0),
};
return CandidateBSizeIterator {
block_size: block_size.map(|size| adjust(size, adjustment_for_box_sizing)),
max_block_size: max_block_size.map(|size| adjust(size, adjustment_for_box_sizing)),
min_block_size: adjust(min_block_size, adjustment_for_box_sizing),
candidate_value: Au(0),
status: InitialCandidateBSizeStatus,
};
fn adjust(size: Au, delta: Au) -> Au {
max(size - delta, Au(0))
}
}
}
impl Iterator<MaybeAuto> for CandidateBSizeIterator {
fn next(&mut self) -> Option<MaybeAuto> {
self.status = match self.status {
InitialCandidateBSizeStatus => TryingBSizeCandidateBSizeStatus,
TryingBSizeCandidateBSizeStatus => {
match self.max_block_size {
Some(max_block_size) if self.candidate_value > max_block_size => {
TryingMaxCandidateBSizeStatus
}
_ if self.candidate_value < self.min_block_size => TryingMinCandidateBSizeStatus,
_ => FoundCandidateBSizeStatus,
}
}
TryingMaxCandidateBSizeStatus => {
if self.candidate_value < self.min_block_size {
TryingMinCandidateBSizeStatus
} else {
FoundCandidateBSizeStatus
}
}
TryingMinCandidateBSizeStatus | FoundCandidateBSizeStatus => {
FoundCandidateBSizeStatus
}
};
match self.status {
TryingBSizeCandidateBSizeStatus => Some(self.block_size),
TryingMaxCandidateBSizeStatus => {
Some(Specified(self.max_block_size.unwrap()))
}
TryingMinCandidateBSizeStatus => {
Some(Specified(self.min_block_size))
}
FoundCandidateBSizeStatus => None,
InitialCandidateBSizeStatus => fail!(),
}
}
}
enum CandidateBSizeIteratorStatus {
InitialCandidateBSizeStatus,
TryingBSizeCandidateBSizeStatus,
TryingMaxCandidateBSizeStatus,
TryingMinCandidateBSizeStatus,
FoundCandidateBSizeStatus,
}
// A helper function used in block-size calculation.
fn translate_including_floats(cur_b: &mut Au, delta: Au, floats: &mut Floats) {
*cur_b = *cur_b + delta;
let writing_mode = floats.writing_mode;
floats.translate(LogicalSize::new(writing_mode, Au(0), -delta));
}
/// The real assign-block-sizes traversal for flows with position 'absolute'.
///
/// This is a traversal of an Absolute Flow tree.
/// - Relatively positioned flows and the Root flow start new Absolute flow trees.
/// - The kids of a flow in this tree will be the flows for which it is the
/// absolute Containing Block.
/// - Thus, leaf nodes and inner non-root nodes are all Absolute Flows.
///
/// A Flow tree can have several Absolute Flow trees (depending on the number
/// of relatively positioned flows it has).
///
/// Note that flows with position 'fixed' just form a flat list as they all
/// have the Root flow as their CB.
struct AbsoluteAssignBSizesTraversal<'a>(&'a LayoutContext<'a>);
impl<'a> PreorderFlowTraversal for AbsoluteAssignBSizesTraversal<'a> {
#[inline]
fn process(&self, flow: &mut Flow) {
let block_flow = flow.as_block();
// The root of the absolute flow tree is definitely not absolutely
// positioned. Nothing to process here.
if block_flow.is_root_of_absolute_flow_tree() {
return;
}
let AbsoluteAssignBSizesTraversal(ref ctx) = *self;
block_flow.calculate_abs_block_size_and_margins(*ctx);
}
}
/// The store-overflow traversal particular to absolute flows.
///
/// Propagate overflow up the Absolute flow tree and update overflow up to and
/// not including the root of the Absolute flow tree.
/// After that, it is up to the normal store-overflow traversal to propagate
/// it further up.
struct AbsoluteStoreOverflowTraversal<'a>{
layout_context: &'a LayoutContext<'a>,
}
impl<'a> PostorderFlowTraversal for AbsoluteStoreOverflowTraversal<'a> {
#[inline]
fn process(&self, flow: &mut Flow) {
// This will be taken care of by the normal store-overflow traversal.
if flow.is_root_of_absolute_flow_tree() {
return;
}
flow.store_overflow(self.layout_context);
}
}
enum BlockType {
BlockReplacedType,
BlockNonReplacedType,
AbsoluteReplacedType,
AbsoluteNonReplacedType,
FloatReplacedType,
FloatNonReplacedType,
}
#[deriving(Clone, PartialEq)]
pub enum MarginsMayCollapseFlag {
MarginsMayCollapse,
MarginsMayNotCollapse,
}
#[deriving(PartialEq)]
enum FormattingContextType {
NonformattingContext,
BlockFormattingContext,
OtherFormattingContext,
}
// Propagates the `layers_needed_for_descendants` flag appropriately from a child. This is called
// as part of block-size assignment.
//
// If any fixed descendants of kids are present, this kid needs a layer.
//
// FIXME(#2006, pcwalton): This is too layer-happy. Like WebKit, we shouldn't do this unless
// the positioned descendants are actually on top of the fixed kids.
//
// TODO(#1244, #2007, pcwalton): Do this for CSS transforms and opacity too, at least if they're
// animating.
fn propagate_layer_flag_from_child(layers_needed_for_descendants: &mut bool, kid: &mut Flow) {
if kid.is_absolute_containing_block() {
let kid_base = flow::mut_base(kid);
if kid_base.flags.needs_layer() {
*layers_needed_for_descendants = true
}
} else {
let kid_base = flow::mut_base(kid);
if kid_base.flags.layers_needed_for_descendants() {
*layers_needed_for_descendants = true
}
}
}
// A block formatting context.
#[deriving(Encodable)]
pub struct BlockFlow {
/// Data common to all flows.
pub base: BaseFlow,
/// The associated fragment.
pub fragment: Fragment,
/// Static y offset of an absolute flow from its CB.
pub static_b_offset: Au,
/// The sum of the inline-sizes of all logically left floats that precede this block. This is
/// used to speculatively lay out block formatting contexts.
inline_size_of_preceding_left_floats: Au,
/// The sum of the inline-sizes of all logically right floats that precede this block. This is
/// used to speculatively lay out block formatting contexts.
inline_size_of_preceding_right_floats: Au,
/// Additional floating flow members.
pub float: Option<Box<FloatedBlockInfo>>,
/// Various flags.
pub flags: BlockFlowFlags,
}
bitflags! {
flags BlockFlowFlags: u8 {
#[doc="If this is set, then this block flow is the root flow."]
static IsRoot = 0x01,
}
}
impl<'a,E,S> Encodable<S,E> for BlockFlowFlags where S: Encoder<E> {
fn encode(&self, e: &mut S) -> Result<(),E> {
self.bits().encode(e)
}
}
impl BlockFlow {
pub fn from_node(constructor: &mut FlowConstructor, node: &ThreadSafeLayoutNode) -> BlockFlow {
BlockFlow {
base: BaseFlow::new((*node).clone()),
fragment: Fragment::new(constructor, node),
static_b_offset: Au::new(0),
inline_size_of_preceding_left_floats: Au(0),
inline_size_of_preceding_right_floats: Au(0),
float: None,
flags: BlockFlowFlags::empty(),
}
}
pub fn from_node_and_fragment(node: &ThreadSafeLayoutNode, fragment: Fragment) -> BlockFlow {
BlockFlow {
base: BaseFlow::new((*node).clone()),
fragment: fragment,
static_b_offset: Au::new(0),
inline_size_of_preceding_left_floats: Au(0),
inline_size_of_preceding_right_floats: Au(0),
float: None,
flags: BlockFlowFlags::empty(),
}
}
pub fn float_from_node(constructor: &mut FlowConstructor,
node: &ThreadSafeLayoutNode,
float_kind: FloatKind)
-> BlockFlow {
let base = BaseFlow::new((*node).clone());
BlockFlow {
fragment: Fragment::new(constructor, node),
static_b_offset: Au::new(0),
inline_size_of_preceding_left_floats: Au(0),
inline_size_of_preceding_right_floats: Au(0),
float: Some(box FloatedBlockInfo::new(float_kind)),
base: base,
flags: BlockFlowFlags::empty(),
}
}
pub fn float_from_node_and_fragment(node: &ThreadSafeLayoutNode,
fragment: Fragment,
float_kind: FloatKind)
-> BlockFlow {
let base = BaseFlow::new((*node).clone());
BlockFlow {
fragment: fragment,
static_b_offset: Au::new(0),
inline_size_of_preceding_left_floats: Au(0),
inline_size_of_preceding_right_floats: Au(0),
float: Some(box FloatedBlockInfo::new(float_kind)),
base: base,
flags: BlockFlowFlags::empty(),
}
}
/// Return the type of this block.
///
/// This determines the algorithm used to calculate inline-size, block-size, and the
/// relevant margins for this Block.
fn block_type(&self) -> BlockType {
if self.is_absolutely_positioned() {
if self.is_replaced_content() {
AbsoluteReplacedType
} else {
AbsoluteNonReplacedType
}
} else if self.is_float() {
if self.is_replaced_content() {
FloatReplacedType
} else {
FloatNonReplacedType
}
} else {
if self.is_replaced_content() {
BlockReplacedType
} else {
BlockNonReplacedType
}
}
}
/// Compute the used value of inline-size for this Block.
pub fn compute_used_inline_size(&mut self,
ctx: &LayoutContext,
containing_block_inline_size: Au) {
let block_type = self.block_type();
match block_type {
AbsoluteReplacedType => {
let inline_size_computer = AbsoluteReplaced;
inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size);
}
AbsoluteNonReplacedType => {
let inline_size_computer = AbsoluteNonReplaced;
inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size);
}
FloatReplacedType => {
let inline_size_computer = FloatReplaced;
inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size);
}
FloatNonReplacedType => {
let inline_size_computer = FloatNonReplaced;
inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size);
}
BlockReplacedType => {
let inline_size_computer = BlockReplaced;
inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size);
}
BlockNonReplacedType => {
let inline_size_computer = BlockNonReplaced;
inline_size_computer.compute_used_inline_size(self, ctx, containing_block_inline_size);
}
}
}
/// Return this flow's fragment.
pub fn fragment<'a>(&'a mut self) -> &'a mut Fragment {
&mut self.fragment
}
/// Return the static x offset from the appropriate Containing Block for this flow.
pub fn static_i_offset(&self) -> Au {
if self.is_fixed() {
self.base.fixed_static_i_offset
} else {
self.base.absolute_static_i_offset
}
}
/// Return the size of the Containing Block for this flow.
///
/// Right now, this only gets the Containing Block size for absolutely
/// positioned elements.
/// Note: Assume this is called in a top-down traversal, so it is ok to
/// reference the CB.
#[inline]
pub fn containing_block_size(&mut self, viewport_size: Size2D<Au>) -> LogicalSize<Au> {
assert!(self.is_absolutely_positioned());
if self.is_fixed() {
// Initial containing block is the CB for the root
LogicalSize::from_physical(self.base.writing_mode, viewport_size)
} else {
self.base.absolute_cb.generated_containing_block_rect().size
}
}
/// Traverse the Absolute flow tree in preorder.
///
/// Traverse all your direct absolute descendants, who will then traverse
/// their direct absolute descendants.
/// Also, set the static y offsets for each descendant (using the value
/// which was bubbled up during normal assign-block-size).
///
/// Return true if the traversal is to continue or false to stop.
fn traverse_preorder_absolute_flows<T:PreorderFlowTraversal>(&mut self,
traversal: &mut T) {
let flow = self as &mut Flow;
traversal.process(flow);
let cb_block_start_edge_offset = flow.generated_containing_block_rect().start.b;
let mut descendant_offset_iter = mut_base(flow).abs_descendants.iter_with_offset();
// Pass in the respective static y offset for each descendant.
for (ref mut descendant_link, ref y_offset) in descendant_offset_iter {
let block = descendant_link.as_block();
// The stored y_offset is wrt to the flow box.
// Translate it to the CB (which is the padding box).
block.static_b_offset = **y_offset - cb_block_start_edge_offset;
block.traverse_preorder_absolute_flows(traversal);
}
}
/// Traverse the Absolute flow tree in postorder.
///
/// Return true if the traversal is to continue or false to stop.
fn traverse_postorder_absolute_flows<T:PostorderFlowTraversal>(&mut self,
traversal: &mut T) {
let flow = self as &mut Flow;
for descendant_link in mut_base(flow).abs_descendants.iter() {
let block = descendant_link.as_block();
block.traverse_postorder_absolute_flows(traversal);
}
traversal.process(flow)
}
/// Return true if this has a replaced fragment.
///
/// The only two types of replaced fragments currently are text fragments
/// and image fragments.
fn is_replaced_content(&self) -> bool {
match self.fragment.specific {
ScannedTextFragment(_) | ImageFragment(_) | InlineBlockFragment(_) => true,
_ => false,
}
}
/// Return shrink-to-fit inline-size.
///
/// This is where we use the preferred inline-sizes and minimum inline-sizes
/// calculated in the bubble-inline-sizes traversal.
pub fn get_shrink_to_fit_inline_size(&self, available_inline_size: Au) -> Au {
let content_intrinsic_inline_sizes = self.content_intrinsic_inline_sizes();
min(content_intrinsic_inline_sizes.preferred_inline_size,
max(content_intrinsic_inline_sizes.minimum_inline_size, available_inline_size))
}
/// If this is the root flow, shifts all kids down and adjusts our size to account for
/// root flow margins, which should never be collapsed according to CSS § 8.3.1.
///
/// TODO(#2017, pcwalton): This is somewhat inefficient (traverses kids twice); can we do
/// better?
fn adjust_fragments_for_collapsed_margins_if_root(&mut self) {
if !self.is_root() {
return
}
let (block_start_margin_value, block_end_margin_value) = match self.base.collapsible_margins {
MarginsCollapseThrough(_) => fail!("Margins unexpectedly collapsed through root flow."),
MarginsCollapse(block_start_margin, block_end_margin) => {
(block_start_margin.collapse(), block_end_margin.collapse())
}
NoCollapsibleMargins(block_start, block_end) => (block_start, block_end),
};
// Shift all kids down (or up, if margins are negative) if necessary.
if block_start_margin_value != Au(0) {
for kid in self.base.child_iter() {
let kid_base = flow::mut_base(kid);
kid_base.position.start.b = kid_base.position.start.b + block_start_margin_value
}
}
self.base.position.size.block = self.base.position.size.block + block_start_margin_value +
block_end_margin_value;
self.fragment.border_box.size.block = self.fragment.border_box.size.block + block_start_margin_value +
block_end_margin_value;
}
/// Assign block-size for current flow.
///
/// * Collapse margins for flow's children and set in-flow child flows' block offsets now that
/// we know their block-sizes.
/// * Calculate and set the block-size of the current flow.
/// * Calculate block-size, vertical margins, and block offset for the flow's box using CSS §
/// 10.6.7.
///
/// For absolute flows, we store the calculated content block-size for the flow. We defer the
/// calculation of the other values until a later traversal.
///
/// `inline(always)` because this is only ever called by in-order or non-in-order top-level
/// methods.
#[inline(always)]
pub fn assign_block_size_block_base<'a>(&mut self,
layout_context: &'a LayoutContext<'a>,
margins_may_collapse: MarginsMayCollapseFlag) {
let _scope = layout_debug_scope!("assign_block_size_block_base {:x}", self.base.debug_id());
// Our current border-box position.
let mut cur_b = Au(0);
// Absolute positioning establishes a block formatting context. Don't propagate floats
// in or out. (But do propagate them between kids.)
if self.is_absolutely_positioned() || margins_may_collapse != MarginsMayCollapse {
self.base.floats = Floats::new(self.fragment.style.writing_mode);
}
let mut margin_collapse_info = MarginCollapseInfo::new();
self.base.floats.translate(LogicalSize::new(
self.fragment.style.writing_mode, -self.fragment.inline_start_offset(), Au(0)));
// The sum of our block-start border and block-start padding.
let block_start_offset = self.fragment.border_padding.block_start;
translate_including_floats(&mut cur_b, block_start_offset, &mut self.base.floats);
let can_collapse_block_start_margin_with_kids =
margins_may_collapse == MarginsMayCollapse &&
!self.is_absolutely_positioned() &&
self.fragment.border_padding.block_start == Au(0);
margin_collapse_info.initialize_block_start_margin(
&self.fragment,
can_collapse_block_start_margin_with_kids);
// At this point, `cur_b` is at the content edge of our box. Now iterate over children.
let mut floats = self.base.floats.clone();
let mut layers_needed_for_descendants = false;
for kid in self.base.child_iter() {
if kid.is_absolutely_positioned() {
// Assume that the *hypothetical box* for an absolute flow starts immediately after
// the block-end border edge of the previous flow.
flow::mut_base(kid).position.start.b = cur_b;
kid.assign_block_size_for_inorder_child_if_necessary(layout_context);
propagate_layer_flag_from_child(&mut layers_needed_for_descendants, kid);
// Skip the collapsing and float processing for absolute flow kids and continue
// with the next flow.
continue
}
// Assign block-size now for the child if it was impacted by floats and we couldn't
// before.
flow::mut_base(kid).floats = floats.clone();
if kid.is_float() {
flow::mut_base(kid).position.start.b = cur_b;
{
let kid_block = kid.as_block();
kid_block.float.as_mut().unwrap().float_ceiling =
margin_collapse_info.current_float_ceiling();
}
propagate_layer_flag_from_child(&mut layers_needed_for_descendants, kid);
let need_to_process_child_floats =
kid.assign_block_size_for_inorder_child_if_necessary(layout_context);
assert!(need_to_process_child_floats); // As it was a float itself...
let kid_base = flow::mut_base(kid);
floats = kid_base.floats.clone();
continue
}
// If we have clearance, assume there are no floats in.
//
// FIXME(#2008, pcwalton): This could be wrong if we have `clear: left` or `clear:
// right` and there are still floats to impact, of course. But this gets complicated
// with margin collapse. Possibly the right thing to do is to lay out the block again
// in this rare case. (Note that WebKit can lay blocks out twice; this may be related,
// although I haven't looked into it closely.)
if kid.float_clearance() != clear::none {
flow::mut_base(kid).floats = Floats::new(self.fragment.style.writing_mode)
}
// Lay the child out if this was an in-order traversal.
let need_to_process_child_floats =
kid.assign_block_size_for_inorder_child_if_necessary(layout_context);
// Mark flows for layerization if necessary to handle painting order correctly.
propagate_layer_flag_from_child(&mut layers_needed_for_descendants, kid);
// Handle any (possibly collapsed) top margin.
let delta = margin_collapse_info.advance_block_start_margin(
&flow::base(kid).collapsible_margins);
translate_including_floats(&mut cur_b, delta, &mut floats);
// Clear past the floats that came in, if necessary.
let clearance = match kid.float_clearance() {
clear::none => Au(0),
clear::left => floats.clearance(ClearLeft),
clear::right => floats.clearance(ClearRight),
clear::both => floats.clearance(ClearBoth),
};
translate_including_floats(&mut cur_b, clearance, &mut floats);
// At this point, `cur_b` is at the border edge of the child.
flow::mut_base(kid).position.start.b = cur_b;
// Now pull out the child's outgoing floats. We didn't do this immediately after the
// `assign_block_size_for_inorder_child_if_necessary` call because clearance on a block
// operates on the floats that come *in*, not the floats that go *out*.
if need_to_process_child_floats {
floats = flow::mut_base(kid).floats.clone()
}
// Move past the child's border box. Do not use the `translate_including_floats`
// function here because the child has already translated floats past its border box.
let kid_base = flow::mut_base(kid);
cur_b = cur_b + kid_base.position.size.block;
// Handle any (possibly collapsed) block-end margin.
let delta =
margin_collapse_info.advance_block_end_margin(&kid_base.collapsible_margins);
translate_including_floats(&mut cur_b, delta, &mut floats);
}
// Mark ourselves for layerization if that will be necessary to paint in the proper order
// (CSS 2.1, Appendix E).
self.base.flags.set_layers_needed_for_descendants(layers_needed_for_descendants);
// Collect various offsets needed by absolutely positioned descendants.
(&mut *self as &mut Flow).collect_static_block_offsets_from_children();
// Add in our block-end margin and compute our collapsible margins.
let can_collapse_block_end_margin_with_kids =
margins_may_collapse == MarginsMayCollapse &&
!self.is_absolutely_positioned() &&
self.fragment.border_padding.block_end == Au(0);
let (collapsible_margins, delta) =
margin_collapse_info.finish_and_compute_collapsible_margins(
&self.fragment,
can_collapse_block_end_margin_with_kids);
self.base.collapsible_margins = collapsible_margins;
translate_including_floats(&mut cur_b, delta, &mut floats);
// FIXME(#2003, pcwalton): The max is taken here so that you can scroll the page, but this
// is not correct behavior according to CSS 2.1 § 10.5. Instead I think we should treat the
// root element as having `overflow: scroll` and use the layers-based scrolling
// infrastructure to make it scrollable.
let mut block_size = cur_b - block_start_offset;
let is_root = self.is_root();
if is_root {
let screen_size = LogicalSize::from_physical(
self.fragment.style.writing_mode, layout_context.shared.screen_size);
block_size = Au::max(screen_size.block, block_size)
}
if is_root || self.formatting_context_type() != NonformattingContext ||
self.is_absolutely_positioned() {
// The content block-size includes all the floats per CSS 2.1 § 10.6.7. The easiest way
// to handle this is to just treat this as clearance.
block_size = block_size + floats.clearance(ClearBoth);
}
if self.is_absolutely_positioned() {
// Fixed position layers get layers.
if self.is_fixed() {
self.base.flags.set_needs_layer(true)
}
// Store the content block-size for use in calculating the absolute flow's dimensions
// later.
self.fragment.border_box.size.block = block_size;
return
}
// Compute any explicitly-specified block size.
// Can't use `for` because we assign to `candidate_block_size_iterator.candidate_value`.
let mut candidate_block_size_iterator = CandidateBSizeIterator::new(
&self.fragment,
self.base.block_container_explicit_block_size);
loop {
match candidate_block_size_iterator.next() {
Some(candidate_block_size) => {
candidate_block_size_iterator.candidate_value = match candidate_block_size {
Auto => block_size,
Specified(value) => value
}
}
None => break,
}
}
// Adjust `cur_b` as necessary to account for the explicitly-specified block-size.
block_size = candidate_block_size_iterator.candidate_value;
let delta = block_size - (cur_b - block_start_offset);
translate_including_floats(&mut cur_b, delta, &mut floats);
// Take border and padding into account.
let block_end_offset = self.fragment.border_padding.block_end;
translate_including_floats(&mut cur_b, block_end_offset, &mut floats);
// Now that `cur_b` is at the block-end of the border box, compute the final border box
// position.
self.fragment.border_box.size.block = cur_b;
self.fragment.border_box.start.b = Au(0);
self.base.position.size.block = cur_b;
// Store the current set of floats in the flow so that flows that come later in the
// document can access them.
self.base.floats = floats.clone();
self.adjust_fragments_for_collapsed_margins_if_root();
if self.is_root_of_absolute_flow_tree() {
// Assign block-sizes for all flows in this absolute flow tree.
// This is preorder because the block-size of an absolute flow may depend on
// the block-size of its containing block, which may also be an absolute flow.
self.traverse_preorder_absolute_flows(&mut AbsoluteAssignBSizesTraversal(
layout_context));
// Store overflow for all absolute descendants.
self.traverse_postorder_absolute_flows(&mut AbsoluteStoreOverflowTraversal {
layout_context: layout_context,
});
}
}
/// Add placement information about current float flow for use by the parent.
///
/// Also, use information given by parent about other floats to find out our relative position.
///
/// This does not give any information about any float descendants because they do not affect
/// elements outside of the subtree rooted at this float.
///
/// This function is called on a kid flow by a parent. Therefore, `assign_block_size_float` was
/// already called on this kid flow by the traversal function. So, the values used are
/// well-defined.
pub fn place_float(&mut self) {
let block_size = self.fragment.border_box.size.block;
let clearance = match self.fragment.clear() {
None => Au(0),
Some(clear) => self.base.floats.clearance(clear),
};
let float_info: FloatedBlockInfo = (**self.float.as_ref().unwrap()).clone();
let info = PlacementInfo {
size: LogicalSize::new(
self.fragment.style.writing_mode,
self.base.position.size.inline,
block_size + self.fragment.margin.block_start_end()),
ceiling: clearance + float_info.float_ceiling,
max_inline_size: float_info.containing_inline_size,
kind: float_info.float_kind,
};
// Place the float and return the `Floats` back to the parent flow.
// After, grab the position and use that to set our position.
self.base.floats.add_float(&info);
// Move in from the margin edge, as per CSS 2.1 § 9.5, floats may not overlap anything on
// their margin edges.
let float_offset = self.base.floats.last_float_pos().unwrap();
let writing_mode = self.base.floats.writing_mode;
let margin_offset = LogicalPoint::new(writing_mode,
Au(0),
self.fragment.margin.block_start);
self.base.position = self.base.position.translate(&float_offset).translate(&margin_offset);
}
/// Calculate and set the block-size, offsets, etc. for absolutely positioned flow.
///
/// The layout for its in-flow children has been done during normal layout.
/// This is just the calculation of:
/// + block-size for the flow
/// + y-coordinate of the flow wrt its Containing Block.
/// + block-size, vertical margins, and y-coordinate for the flow's box.
fn calculate_abs_block_size_and_margins(&mut self, ctx: &LayoutContext) {
let containing_block_block_size = self.containing_block_size(ctx.shared.screen_size).block;
let static_b_offset = self.static_b_offset;
// This is the stored content block-size value from assign-block-size
let content_block_size = self.fragment.content_box().size.block;
let mut solution = None;
{
// Non-auto margin-block-start and margin-block-end values have already been
// calculated during assign-inline-size.
let margin = self.fragment.style().logical_margin();
let margin_block_start = match margin.block_start {
LPA_Auto => Auto,
_ => Specified(self.fragment.margin.block_start)
};
let margin_block_end = match margin.block_end {
LPA_Auto => Auto,
_ => Specified(self.fragment.margin.block_end)
};
let block_start;
let block_end;
{
let position = self.fragment.style().logical_position();
block_start = MaybeAuto::from_style(position.block_start, containing_block_block_size);
block_end = MaybeAuto::from_style(position.block_end, containing_block_block_size);
}
let available_block_size = containing_block_block_size - self.fragment.border_padding.block_start_end();
if self.is_replaced_content() {
// Calculate used value of block-size just like we do for inline replaced elements.
// TODO: Pass in the containing block block-size when Fragment's
// assign-block-size can handle it correctly.
self.fragment.assign_replaced_block_size_if_necessary(containing_block_block_size);
// TODO: Right now, this content block-size value includes the
// margin because of erroneous block-size calculation in fragment.
// Check this when that has been fixed.
let block_size_used_val = self.fragment.border_box.size.block;
solution = Some(BSizeConstraintSolution::solve_vertical_constraints_abs_replaced(
block_size_used_val,
margin_block_start,
margin_block_end,
block_start,
block_end,
content_block_size,
available_block_size,
static_b_offset));
} else {
let mut candidate_block_size_iterator =
CandidateBSizeIterator::new(&self.fragment, Some(containing_block_block_size));
// Can't use `for` because we assign to
// `candidate_block_size_iterator.candidate_value`.
loop {
match candidate_block_size_iterator.next() {
Some(block_size_used_val) => {
solution =
Some(BSizeConstraintSolution::
solve_vertical_constraints_abs_nonreplaced(
block_size_used_val,
margin_block_start,
margin_block_end,
block_start,
block_end,
content_block_size,
available_block_size,
static_b_offset));
candidate_block_size_iterator.candidate_value
= solution.unwrap().block_size;
}
None => break,
}
}
}
}
let solution = solution.unwrap();
self.fragment.margin.block_start = solution.margin_block_start;
self.fragment.margin.block_end = solution.margin_block_end;
self.fragment.border_box.start.b = Au(0);
self.base.position.start.b = solution.block_start + self.fragment.margin.block_start;
let block_size = solution.block_size + self.fragment.border_padding.block_start_end();
self.fragment.border_box.size.block = block_size;
self.base.position.size.block = block_size;
}
// Our inline-size was set to the inline-size of the containing block by the flow's parent.
// This computes the real value, and is run in the `AssignISizes` traversal.
pub fn propagate_and_compute_used_inline_size(&mut self, layout_context: &LayoutContext) {
let containing_block_inline_size = self.base.block_container_inline_size;
self.compute_used_inline_size(layout_context, containing_block_inline_size);
if self.is_float() {
self.float.as_mut().unwrap().containing_inline_size = containing_block_inline_size;
}
}
/// Return the block-start outer edge of the hypothetical box for an absolute flow.
///
/// This is wrt its parent flow box.
///
/// During normal layout assign-block-size, the absolute flow's position is
/// roughly set to its static position (the position it would have had in
/// the normal flow).
pub fn get_hypothetical_block_start_edge(&self) -> Au {
self.base.position.start.b
}
/// Assigns the computed inline-start content edge and inline-size to all the children of this
/// block flow. Also computes whether each child will be impacted by floats.
///
/// `#[inline(always)]` because this is called only from block or table inline-size assignment
/// and the code for block layout is significantly simpler.
#[inline(always)]
pub fn propagate_assigned_inline_size_to_children(
&mut self,
inline_start_content_edge: Au,
content_inline_size: Au,
optional_column_inline_sizes: Option<&[ColumnInlineSize]>) {
// Keep track of whether floats could impact each child.
let mut inline_start_floats_impact_child = self.base.flags.impacted_by_left_floats();
let mut inline_end_floats_impact_child = self.base.flags.impacted_by_right_floats();
let absolute_static_i_offset = if self.is_positioned() {
// This flow is the containing block. The static inline offset will be the inline-start
// padding edge.
self.fragment.border_padding.inline_start
- self.fragment.style().logical_border_width().inline_start
} else {
// For kids, the inline-start margin edge will be at our inline-start content edge. The
// current static offset is at our inline-start margin edge. So move in to the
// inline-start content edge.
self.base.absolute_static_i_offset + inline_start_content_edge
};
let fixed_static_i_offset = self.base.fixed_static_i_offset + inline_start_content_edge;
let flags = self.base.flags.clone();
// This value is used only for table cells.
let mut inline_start_margin_edge = inline_start_content_edge;
// Remember the inline-sizes of the last left and right floats, if there were any. These
// are used for estimating the inline-sizes of block formatting contexts. (We estimate that
// the inline-size of any block formatting context that we see will be based on the
// inline-size of the containing block as well as the last float seen before it in each
// direction.)
let mut inline_size_of_preceding_left_floats = Au(0);
let mut inline_size_of_preceding_right_floats = Au(0);
if self.formatting_context_type() == NonformattingContext {
inline_size_of_preceding_left_floats = self.inline_size_of_preceding_left_floats;
inline_size_of_preceding_right_floats = self.inline_size_of_preceding_right_floats;
}
// Calculate non-auto block size to pass to children.
let content_block_size = self.fragment.style().content_block_size();
let explicit_content_size = match (content_block_size,
self.base.block_container_explicit_block_size) {
(LPA_Percentage(percent), Some(container_size)) => {
Some(container_size.scale_by(percent))
}
(LPA_Percentage(_), None) | (LPA_Auto, _) => None,
(LPA_Length(length), _) => Some(length),
};
for (i, kid) in self.base.child_iter().enumerate() {
{
let kid_base = flow::mut_base(kid);
kid_base.block_container_explicit_block_size = explicit_content_size;
kid_base.absolute_static_i_offset = absolute_static_i_offset;
kid_base.fixed_static_i_offset = fixed_static_i_offset;
}
match kid.float_kind() {
float::none => {}
float::left => {
inline_size_of_preceding_left_floats = inline_size_of_preceding_left_floats +
flow::base(kid).intrinsic_inline_sizes.preferred_inline_size;
}
float::right => {
inline_size_of_preceding_right_floats = inline_size_of_preceding_right_floats +
flow::base(kid).intrinsic_inline_sizes.preferred_inline_size;
}
}
// The inline-start margin edge of the child flow is at our inline-start content edge,
// and its inline-size is our content inline-size.
flow::mut_base(kid).position.start.i = inline_start_content_edge;
flow::mut_base(kid).block_container_inline_size = content_inline_size;
// Determine float impaction.
match kid.float_clearance() {
clear::none => {}
clear::left => {
inline_start_floats_impact_child = false;
inline_size_of_preceding_left_floats = Au(0);
}
clear::right => {
inline_end_floats_impact_child = false;
inline_size_of_preceding_right_floats = Au(0);
}
clear::both => {
inline_start_floats_impact_child = false;
inline_end_floats_impact_child = false;
inline_size_of_preceding_left_floats = Au(0);
inline_size_of_preceding_right_floats = Au(0);
}
}
{
let kid_base = flow::mut_base(kid);
inline_start_floats_impact_child = inline_start_floats_impact_child ||
kid_base.flags.has_left_floated_descendants();
inline_end_floats_impact_child = inline_end_floats_impact_child ||
kid_base.flags.has_right_floated_descendants();
kid_base.flags.set_impacted_by_left_floats(inline_start_floats_impact_child);
kid_base.flags.set_impacted_by_right_floats(inline_end_floats_impact_child);
}
if kid.is_block_flow() {
let kid_block = kid.as_block();
kid_block.inline_size_of_preceding_left_floats =
inline_size_of_preceding_left_floats;
kid_block.inline_size_of_preceding_right_floats =
inline_size_of_preceding_right_floats;
}
// Handle tables.
match optional_column_inline_sizes {
Some(ref column_inline_sizes) => {
propagate_column_inline_sizes_to_child(kid,
i,
content_inline_size,
*column_inline_sizes,
&mut inline_start_margin_edge)
}
None => {}
}
// Per CSS 2.1 § 16.3.1, text alignment propagates to all children in flow.
//
// TODO(#2018, pcwalton): Do this in the cascade instead.
flow::mut_base(kid).flags.propagate_text_alignment_from_parent(flags.clone())
}
}
/// Determines the type of formatting context this is. See the definition of
/// `FormattingContextType`.
fn formatting_context_type(&self) -> FormattingContextType {
let style = self.fragment.style();
if style.get_box().float != float::none {
return OtherFormattingContext
}
match style.get_box().display {
display::table_cell | display::table_caption | display::inline_block => {
OtherFormattingContext
}
_ if style.get_box().overflow != overflow::visible => BlockFormattingContext,
_ => NonformattingContext,
}
}
/// Per CSS 2.1 § 9.5, block formatting contexts' inline widths and positions are affected by
/// the presence of floats. This is the part of the assign-heights traversal that computes
/// the final inline position and width for such flows.
///
/// Note that this is part of the assign-block-sizes traversal, not the assign-inline-sizes
/// traversal as one might expect. That is because, in general, float placement cannot occur
/// until heights are assigned. To work around this unfortunate circular dependency, by the
/// time we get here we have already estimated the width of the block formatting context based
/// on the floats we could see at the time of inline-size assignment. The job of this function,
/// therefore, is not only to assign the final size but also to perform the layout again for
/// this block formatting context if our speculation was wrong.
fn assign_inline_position_for_formatting_context(&mut self) {
debug_assert!(self.formatting_context_type() != NonformattingContext);
let info = PlacementInfo {
size: LogicalSize::new(
self.fragment.style.writing_mode,
self.base.position.size.inline + self.fragment.margin.inline_start_end() +
self.fragment.border_padding.inline_start_end(),
self.fragment.border_box.size.block),
ceiling: self.base.position.start.b,
max_inline_size: MAX_AU,
kind: FloatLeft,
};
// Offset our position by whatever displacement is needed to not impact the floats.
let rect = self.base.floats.place_between_floats(&info);
self.base.position.start.i = self.base.position.start.i + rect.start.i;
// TODO(pcwalton): If the inline-size of this flow is different from the size we estimated
// earlier, lay it out again.
}
fn is_inline_block(&self) -> bool {
self.fragment.style().get_box().display == display::inline_block
}
/// Computes the content portion (only) of the intrinsic inline sizes of this flow. This is
/// used for calculating shrink-to-fit width. Assumes that intrinsic sizes have already been
/// computed for this flow.
fn content_intrinsic_inline_sizes(&self) -> IntrinsicISizes {
let surrounding_inline_size = self.fragment.surrounding_intrinsic_inline_size();
IntrinsicISizes {
minimum_inline_size: self.base.intrinsic_inline_sizes.minimum_inline_size -
surrounding_inline_size,
preferred_inline_size: self.base.intrinsic_inline_sizes.preferred_inline_size -
surrounding_inline_size,
}
}
}
impl Flow for BlockFlow {
fn class(&self) -> FlowClass {
BlockFlowClass
}
fn as_block<'a>(&'a mut self) -> &'a mut BlockFlow {
self
}
fn as_immutable_block<'a>(&'a self) -> &'a BlockFlow {
self
}
/// Returns the direction that this flow clears floats in, if any.
fn float_clearance(&self) -> clear::T {
self.fragment.style().get_box().clear
}
fn float_kind(&self) -> float::T {
self.fragment.style().get_box().float
}
/// Pass 1 of reflow: computes minimum and preferred inline-sizes.
///
/// Recursively (bottom-up) determine the flow's minimum and preferred inline-sizes. When
/// called on this flow, all child flows have had their minimum and preferred inline-sizes set.
/// This function must decide minimum/preferred inline-sizes based on its children's
/// inline-sizes and the dimensions of any fragments it is responsible for flowing.
fn bubble_inline_sizes(&mut self) {
let _scope = layout_debug_scope!("block::bubble_inline_sizes {:x}", self.base.debug_id());
let mut flags = self.base.flags;
flags.set_has_left_floated_descendants(false);
flags.set_has_right_floated_descendants(false);
// If this block has a fixed width, just use that for the minimum
// and preferred width, rather than bubbling up children inline
// width.
let fixed_width = match self.fragment.style().get_box().width {
LPA_Length(_) => true,
_ => false,
};
// Find the maximum inline-size from children.
let mut computation = self.fragment.compute_intrinsic_inline_sizes();
let mut left_float_width = Au(0);
let mut right_float_width = Au(0);
for kid in self.base.child_iter() {
let is_absolutely_positioned = kid.is_absolutely_positioned();
let float_kind = kid.float_kind();
let child_base = flow::mut_base(kid);
if !is_absolutely_positioned && !fixed_width {
computation.content_intrinsic_sizes.minimum_inline_size =
max(computation.content_intrinsic_sizes.minimum_inline_size,
child_base.intrinsic_inline_sizes.minimum_inline_size);
match float_kind {
float::none => {
computation.content_intrinsic_sizes.preferred_inline_size =
max(computation.content_intrinsic_sizes.preferred_inline_size,
child_base.intrinsic_inline_sizes.preferred_inline_size);
}
float::left => {
left_float_width = left_float_width +
child_base.intrinsic_inline_sizes.preferred_inline_size;
}
float::right => {
right_float_width = right_float_width +
child_base.intrinsic_inline_sizes.preferred_inline_size;
}
}
}
flags.union_floated_descendants_flags(child_base.flags);
}
// FIXME(pcwalton): This should consider all float descendants, not just children.
// FIXME(pcwalton): This is not well-spec'd; INTRINSIC specifies to do this, but CSS-SIZING
// says not to. In practice, Gecko and WebKit both do this.
computation.content_intrinsic_sizes.preferred_inline_size =
max(computation.content_intrinsic_sizes.preferred_inline_size,
left_float_width + right_float_width);
self.base.intrinsic_inline_sizes = computation.finish();
match self.fragment.style().get_box().float {
float::none => {}
float::left => flags.set_has_left_floated_descendants(true),
float::right => flags.set_has_right_floated_descendants(true),
}
self.base.flags = flags
}
/// Recursively (top-down) determines the actual inline-size of child contexts and fragments.
/// When called on this context, the context has had its inline-size set by the parent context.
///
/// Dual fragments consume some inline-size first, and the remainder is assigned to all child
/// (block) contexts.
fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
let _scope = layout_debug_scope!("block::assign_inline_sizes {:x}", self.base.debug_id());
debug!("assign_inline_sizes({}): assigning inline_size for flow",
if self.is_float() {
"float"
} else {
"block"
});
self.base.floats = Floats::new(self.base.writing_mode);
if self.is_root() {
debug!("Setting root position");
self.base.position.start = LogicalPoint::zero(self.base.writing_mode);
self.base.block_container_inline_size = LogicalSize::from_physical(
self.base.writing_mode, layout_context.shared.screen_size).inline;
// The root element is never impacted by floats.
self.base.flags.set_impacted_by_left_floats(false);
self.base.flags.set_impacted_by_right_floats(false);
}
// Our inline-size was set to the inline-size of the containing block by the flow's parent.
// Now compute the real value.
self.propagate_and_compute_used_inline_size(layout_context);
// Formatting contexts are never impacted by floats.
match self.formatting_context_type() {
NonformattingContext => {}
BlockFormattingContext => {
self.base.flags.set_impacted_by_left_floats(false);
self.base.flags.set_impacted_by_right_floats(false);
// We can't actually compute the inline-size of this block now, because floats
// might affect it. Speculate that its inline-size is equal to the inline-size
// computed above minus the inline-size of the previous left and/or right floats.
self.fragment.border_box.size.inline =
self.fragment.border_box.size.inline -
self.inline_size_of_preceding_left_floats -
self.inline_size_of_preceding_right_floats;
}
OtherFormattingContext => {
self.base.flags.set_impacted_by_left_floats(false);
self.base.flags.set_impacted_by_right_floats(false);
}
}
// Move in from the inline-start border edge.
let inline_start_content_edge = self.fragment.border_box.start.i +
self.fragment.border_padding.inline_start;
let padding_and_borders = self.fragment.border_padding.inline_start_end();
let content_inline_size = self.fragment.border_box.size.inline - padding_and_borders;
self.propagate_assigned_inline_size_to_children(inline_start_content_edge,
content_inline_size,
None);
}
/// Assigns block-sizes in-order; or, if this is a float, places the float. The default
/// implementation simply assigns block-sizes if this flow is impacted by floats. Returns true
/// if this child affected the floats in the flow somehow or false otherwise; thus, if true,
/// then the parent flow is expected to take the `floats` member of this flow into account.
///
/// This is called on child flows by the parent. Hence, we can assume that `assign_block_size`
/// has already been called on the child (because of the bottom-up traversal).
fn assign_block_size_for_inorder_child_if_necessary<'a>(&mut self,
layout_context: &'a LayoutContext<'a>)
-> bool {
if self.is_float() {
self.place_float();
return true
}
let is_formatting_context = self.formatting_context_type() != NonformattingContext;
if is_formatting_context {
self.assign_inline_position_for_formatting_context();
}
if self.base.flags.impacted_by_floats() {
self.assign_block_size(layout_context);
return true
}
if is_formatting_context {
// If this is a formatting context and was *not* impacted by floats, then we must
// translate the floats past us.
let writing_mode = self.base.floats.writing_mode;
let delta = self.base.position.size.block;
self.base.floats.translate(LogicalSize::new(writing_mode, Au(0), -delta));
return true
}
false
}
fn assign_block_size<'a>(&mut self, ctx: &'a LayoutContext<'a>) {
if self.is_replaced_content() {
let _scope = layout_debug_scope!("assign_replaced_block_size_if_necessary {:x}",
self.base.debug_id());
// Assign block-size for fragment if it is an image fragment.
let containing_block_block_size =
self.base.block_container_explicit_block_size.unwrap_or(Au(0));
self.fragment.assign_replaced_block_size_if_necessary(containing_block_block_size);
self.base.position.size.block = self.fragment.border_box.size.block;
} else if self.is_root() || self.is_float() || self.is_inline_block() {
// Root element margins should never be collapsed according to CSS § 8.3.1.
debug!("assign_block_size: assigning block_size for root flow");
self.assign_block_size_block_base(ctx, MarginsMayNotCollapse);
} else {
debug!("assign_block_size: assigning block_size for block");
self.assign_block_size_block_base(ctx, MarginsMayCollapse);
}
}
fn compute_absolute_position(&mut self) {
// FIXME(#2795): Get the real container size
let container_size = Size2D::zero();
if self.is_root() {
self.base.clip_rect = MAX_RECT;
}
if self.is_absolutely_positioned() {
let position_start = self.base.position.start.to_physical(
self.base.writing_mode, container_size);
self.base
.absolute_position_info
.absolute_containing_block_position = if self.is_fixed() {
// The viewport is initially at (0, 0).
position_start
} else {
// Absolute position of the containing block + position of absolute flow w/r/t the
// containing block.
self.base.absolute_position_info.absolute_containing_block_position
+ position_start
};
// Set the absolute position, which will be passed down later as part
// of containing block details for absolute descendants.
self.base.abs_position =
self.base.absolute_position_info.absolute_containing_block_position;
}
// For relatively-positioned descendants, the containing block formed by a block is just
// the content box. The containing block for absolutely-positioned descendants, on the
// other hand, is only established if we are positioned.
let relative_offset =
self.fragment.relative_position(&self.base
.absolute_position_info
.relative_containing_block_size);
if self.is_positioned() {
self.base.absolute_position_info.absolute_containing_block_position =
self.base.abs_position
+ (self.generated_containing_block_rect().start
+ relative_offset).to_physical(self.base.writing_mode, container_size)
}
// Compute absolute position info for children.
let mut absolute_position_info = self.base.absolute_position_info;
absolute_position_info.relative_containing_block_size = self.fragment.content_box().size;
absolute_position_info.layers_needed_for_positioned_flows =
self.base.flags.layers_needed_for_descendants();
// Compute the clipping rectangle for children.
let this_position = self.base.abs_position;
let clip_rect = self.fragment.clip_rect_for_children(self.base.clip_rect, this_position);
// Process children.
let writing_mode = self.base.writing_mode;
for kid in self.base.child_iter() {
if !kid.is_absolutely_positioned() {
let kid_base = flow::mut_base(kid);
kid_base.abs_position =
this_position +
(kid_base.position.start + relative_offset).to_physical(writing_mode,
container_size);
kid_base.absolute_position_info = absolute_position_info
}
flow::mut_base(kid).clip_rect = clip_rect
}
// Process absolute descendant links.
for absolute_descendant in self.base.abs_descendants.iter() {
flow::mut_base(absolute_descendant).absolute_position_info = absolute_position_info
}
}
fn mark_as_root(&mut self) {
self.flags.insert(IsRoot)
}
/// Return true if store overflow is delayed for this flow.
///
/// Currently happens only for absolutely positioned flows.
fn is_store_overflow_delayed(&mut self) -> bool {
self.is_absolutely_positioned()
}
fn is_root(&self) -> bool {
self.flags.contains(IsRoot)
}
fn is_float(&self) -> bool {
self.float.is_some()
}
/// The 'position' property of this flow.
fn positioning(&self) -> position::T {
self.fragment.style.get_box().position
}
/// Return true if this is the root of an Absolute flow tree.
///
/// It has to be either relatively positioned or the Root flow.
fn is_root_of_absolute_flow_tree(&self) -> bool {
self.is_relatively_positioned() || self.is_root()
}
/// Return the dimensions of the containing block generated by this flow for absolutely-
/// positioned descendants. For block flows, this is the padding box.
fn generated_containing_block_rect(&self) -> LogicalRect<Au> {
self.fragment.border_box - self.fragment.style().logical_border_width()
}
fn layer_id(&self, fragment_index: uint) -> LayerId {
// FIXME(#2010, pcwalton): This is a hack and is totally bogus in the presence of pseudo-
// elements. But until we have incremental reflow we can't do better--we recreate the flow
// for every DOM node so otherwise we nuke layers on every reflow.
LayerId(self.fragment.node.id() as uint, fragment_index)
}
fn is_absolute_containing_block(&self) -> bool {
self.is_positioned()
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
if self.is_absolutely_positioned() &&
self.fragment.style().logical_position().inline_start == LPA_Auto &&
self.fragment.style().logical_position().inline_end == LPA_Auto {
self.base.position.start.i = inline_position
}
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
if self.is_absolutely_positioned() &&
self.fragment.style().logical_position().block_start == LPA_Auto &&
self.fragment.style().logical_position().block_end == LPA_Auto {
self.base.position.start.b = block_position
}
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
if self.is_float() {
// TODO(#2009, pcwalton): This is a pseudo-stacking context. We need to merge `z-index:
// auto` kids into the parent stacking context, when that is supported.
self.build_display_list_for_floating_block(layout_context)
} else if self.is_absolutely_positioned() {
self.build_display_list_for_absolutely_positioned_block(layout_context)
} else {
self.build_display_list_for_block(layout_context, BlockLevel)
}
if opts::get().validate_display_list_geometry {
self.base.validate_display_list_geometry();
}
}
}
impl fmt::Show for BlockFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} - {:x}: frag={} ({})", self.class(), self.base.debug_id(), self.fragment, self.base)
}
}
/// The inputs for the inline-sizes-and-margins constraint equation.
#[deriving(Show)]
pub struct ISizeConstraintInput {
pub computed_inline_size: MaybeAuto,
pub inline_start_margin: MaybeAuto,
pub inline_end_margin: MaybeAuto,
pub inline_start: MaybeAuto,
pub inline_end: MaybeAuto,
pub available_inline_size: Au,
pub static_i_offset: Au,
}
impl ISizeConstraintInput {
pub fn new(computed_inline_size: MaybeAuto,
inline_start_margin: MaybeAuto,
inline_end_margin: MaybeAuto,
inline_start: MaybeAuto,
inline_end: MaybeAuto,
available_inline_size: Au,
static_i_offset: Au)
-> ISizeConstraintInput {
ISizeConstraintInput {
computed_inline_size: computed_inline_size,
inline_start_margin: inline_start_margin,
inline_end_margin: inline_end_margin,
inline_start: inline_start,
inline_end: inline_end,
available_inline_size: available_inline_size,
static_i_offset: static_i_offset,
}
}
}
/// The solutions for the inline-size-and-margins constraint equation.
#[deriving(Show)]
pub struct ISizeConstraintSolution {
pub inline_start: Au,
pub inline_end: Au,
pub inline_size: Au,
pub margin_inline_start: Au,
pub margin_inline_end: Au
}
impl ISizeConstraintSolution {
pub fn new(inline_size: Au, margin_inline_start: Au, margin_inline_end: Au) -> ISizeConstraintSolution {
ISizeConstraintSolution {
inline_start: Au(0),
inline_end: Au(0),
inline_size: inline_size,
margin_inline_start: margin_inline_start,
margin_inline_end: margin_inline_end,
}
}
fn for_absolute_flow(inline_start: Au,
inline_end: Au,
inline_size: Au,
margin_inline_start: Au,
margin_inline_end: Au)
-> ISizeConstraintSolution {
ISizeConstraintSolution {
inline_start: inline_start,
inline_end: inline_end,
inline_size: inline_size,
margin_inline_start: margin_inline_start,
margin_inline_end: margin_inline_end,
}
}
}
// Trait to encapsulate the ISize and Margin calculation.
//
// CSS Section 10.3
pub trait ISizeAndMarginsComputer {
/// Compute the inputs for the ISize constraint equation.
///
/// This is called only once to compute the initial inputs. For calculations involving
/// minimum and maximum inline-size, we don't need to recompute these.
fn compute_inline_size_constraint_inputs(&self,
block: &mut BlockFlow,
parent_flow_inline_size: Au,
layout_context: &LayoutContext)
-> ISizeConstraintInput {
let containing_block_inline_size =
self.containing_block_inline_size(block, parent_flow_inline_size, layout_context);
block.fragment.compute_block_direction_margins(containing_block_inline_size);
block.fragment.compute_inline_direction_margins(containing_block_inline_size);
block.fragment.compute_border_and_padding(containing_block_inline_size);
let mut computed_inline_size = self.initial_computed_inline_size(block,
parent_flow_inline_size,
layout_context);
let style = block.fragment.style();
match (computed_inline_size, style.get_box().box_sizing) {
(Specified(size), box_sizing::border_box) => {
computed_inline_size =
Specified(size - block.fragment.border_padding.inline_start_end())
}
(Auto, box_sizing::border_box) | (_, box_sizing::content_box) => {}
}
// The text alignment of a block flow is the text alignment of its box's style.
block.base.flags.set_text_align(style.get_inheritedtext().text_align);
let margin = style.logical_margin();
let position = style.logical_position();
let available_inline_size = containing_block_inline_size -
block.fragment.border_padding.inline_start_end();
return ISizeConstraintInput::new(
computed_inline_size,
MaybeAuto::from_style(margin.inline_start, containing_block_inline_size),
MaybeAuto::from_style(margin.inline_end, containing_block_inline_size),
MaybeAuto::from_style(position.inline_start, containing_block_inline_size),
MaybeAuto::from_style(position.inline_end, containing_block_inline_size),
available_inline_size,
block.static_i_offset());
}
/// Set the used values for inline-size and margins from the relevant constraint equation.
/// This is called only once.
///
/// Set:
/// * Used values for content inline-size, inline-start margin, and inline-end margin for this
/// flow's box;
/// * Inline-start coordinate of this flow's box;
/// * Inline-start coordinate of the flow with respect to its containing block (if this is an<|fim▁hole|> solution: ISizeConstraintSolution) {
let inline_size;
let extra_inline_size_from_margin;
{
let fragment = block.fragment();
fragment.margin.inline_start = solution.margin_inline_start;
fragment.margin.inline_end = solution.margin_inline_end;
// Left border edge.
fragment.border_box.start.i = fragment.margin.inline_start;
// The associated fragment has the border box of this flow.
inline_size = solution.inline_size + fragment.border_padding.inline_start_end();
fragment.border_box.size.inline = inline_size;
// To calculate the total size of this block, we also need to account for any additional
// size contribution from positive margins. Negative margins means the block isn't made
// larger at all by the margin.
extra_inline_size_from_margin = max(Au(0), fragment.margin.inline_start) +
max(Au(0), fragment.margin.inline_end);
}
// We also resize the block itself, to ensure that overflow is not calculated
// as the inline-size of our parent. We might be smaller and we might be larger if we
// overflow.
flow::mut_base(block).position.size.inline = inline_size + extra_inline_size_from_margin;
}
/// Set the x coordinate of the given flow if it is absolutely positioned.
fn set_flow_x_coord_if_necessary(&self, _: &mut BlockFlow, _: ISizeConstraintSolution) {}
/// Solve the inline-size and margins constraints for this block flow.
fn solve_inline_size_constraints(&self,
block: &mut BlockFlow,
input: &ISizeConstraintInput)
-> ISizeConstraintSolution;
fn initial_computed_inline_size(&self,
block: &mut BlockFlow,
parent_flow_inline_size: Au,
ctx: &LayoutContext)
-> MaybeAuto {
MaybeAuto::from_style(block.fragment().style().content_inline_size(),
self.containing_block_inline_size(block,
parent_flow_inline_size,
ctx))
}
fn containing_block_inline_size(&self,
_: &mut BlockFlow,
parent_flow_inline_size: Au,
_: &LayoutContext)
-> Au {
parent_flow_inline_size
}
/// Compute the used value of inline-size, taking care of min-inline-size and max-inline-size.
///
/// CSS Section 10.4: Minimum and Maximum inline-sizes
fn compute_used_inline_size(&self,
block: &mut BlockFlow,
ctx: &LayoutContext,
parent_flow_inline_size: Au) {
let mut input = self.compute_inline_size_constraint_inputs(block,
parent_flow_inline_size,
ctx);
let containing_block_inline_size = self.containing_block_inline_size(
block,
parent_flow_inline_size,
ctx);
let mut solution = self.solve_inline_size_constraints(block, &input);
// If the tentative used inline-size is greater than 'max-inline-size', inline-size should
// be recalculated, but this time using the computed value of 'max-inline-size' as the
// computed value for 'inline-size'.
match specified_or_none(block.fragment().style().max_inline_size(),
containing_block_inline_size) {
Some(max_inline_size) if max_inline_size < solution.inline_size => {
input.computed_inline_size = Specified(max_inline_size);
solution = self.solve_inline_size_constraints(block, &input);
}
_ => {}
}
// If the resulting inline-size is smaller than 'min-inline-size', inline-size should be
// recalculated, but this time using the value of 'min-inline-size' as the computed value
// for 'inline-size'.
let computed_min_inline_size = specified(block.fragment().style().min_inline_size(),
containing_block_inline_size);
if computed_min_inline_size > solution.inline_size {
input.computed_inline_size = Specified(computed_min_inline_size);
solution = self.solve_inline_size_constraints(block, &input);
}
self.set_inline_size_constraint_solutions(block, solution);
self.set_flow_x_coord_if_necessary(block, solution);
}
/// Computes inline-start and inline-end margins and inline-size.
///
/// This is used by both replaced and non-replaced Blocks.
///
/// CSS 2.1 Section 10.3.3.
/// Constraint Equation: margin-inline-start + margin-inline-end + inline-size =
/// available_inline-size
/// where available_inline-size = CB inline-size - (horizontal border + padding)
fn solve_block_inline_size_constraints(&self,
_: &mut BlockFlow,
input: &ISizeConstraintInput)
-> ISizeConstraintSolution {
let (computed_inline_size, inline_start_margin, inline_end_margin, available_inline_size) =
(input.computed_inline_size,
input.inline_start_margin,
input.inline_end_margin,
input.available_inline_size);
// If inline-size is not 'auto', and inline-size + margins > available_inline-size, all
// 'auto' margins are treated as 0.
let (inline_start_margin, inline_end_margin) = match computed_inline_size {
Auto => (inline_start_margin, inline_end_margin),
Specified(inline_size) => {
let inline_start = inline_start_margin.specified_or_zero();
let inline_end = inline_end_margin.specified_or_zero();
if (inline_start + inline_end + inline_size) > available_inline_size {
(Specified(inline_start), Specified(inline_end))
} else {
(inline_start_margin, inline_end_margin)
}
}
};
// Invariant: inline-start_margin + inline-size + inline-end_margin ==
// available_inline-size
let (inline_start_margin, inline_size, inline_end_margin) =
match (inline_start_margin, computed_inline_size, inline_end_margin) {
// If all have a computed value other than 'auto', the system is
// over-constrained so we discard the end margin.
(Specified(margin_start), Specified(inline_size), Specified(_margin_end)) =>
(margin_start, inline_size, available_inline_size -
(margin_start + inline_size)),
// If exactly one value is 'auto', solve for it
(Auto, Specified(inline_size), Specified(margin_end)) =>
(available_inline_size - (inline_size + margin_end), inline_size, margin_end),
(Specified(margin_start), Auto, Specified(margin_end)) =>
(margin_start, available_inline_size - (margin_start + margin_end),
margin_end),
(Specified(margin_start), Specified(inline_size), Auto) =>
(margin_start, inline_size, available_inline_size -
(margin_start + inline_size)),
// If inline-size is set to 'auto', any other 'auto' value becomes '0',
// and inline-size is solved for
(Auto, Auto, Specified(margin_end)) =>
(Au::new(0), available_inline_size - margin_end, margin_end),
(Specified(margin_start), Auto, Auto) =>
(margin_start, available_inline_size - margin_start, Au::new(0)),
(Auto, Auto, Auto) =>
(Au::new(0), available_inline_size, Au::new(0)),
// If inline-start and inline-end margins are auto, they become equal
(Auto, Specified(inline_size), Auto) => {
let margin = (available_inline_size - inline_size).scale_by(0.5);
(margin, inline_size, margin)
}
};
ISizeConstraintSolution::new(inline_size, inline_start_margin, inline_end_margin)
}
}
/// The different types of Blocks.
///
/// They mainly differ in the way inline-size and block-sizes and margins are calculated
/// for them.
pub struct AbsoluteNonReplaced;
pub struct AbsoluteReplaced;
pub struct BlockNonReplaced;
pub struct BlockReplaced;
pub struct FloatNonReplaced;
pub struct FloatReplaced;
impl ISizeAndMarginsComputer for AbsoluteNonReplaced {
/// Solve the horizontal constraint equation for absolute non-replaced elements.
///
/// CSS Section 10.3.7
/// Constraint equation:
/// inline-start + inline-end + inline-size + margin-inline-start + margin-inline-end
/// = absolute containing block inline-size - (horizontal padding and border)
/// [aka available_inline-size]
///
/// Return the solution for the equation.
fn solve_inline_size_constraints(&self,
block: &mut BlockFlow,
input: &ISizeConstraintInput)
-> ISizeConstraintSolution {
let &ISizeConstraintInput {
computed_inline_size,
inline_start_margin,
inline_end_margin,
inline_start,
inline_end,
available_inline_size,
static_i_offset,
..
} = input;
// TODO: Check for direction of parent flow (NOT Containing Block)
// when right-to-left is implemented.
// Assume direction is 'ltr' for now
// Distance from the inline-start edge of the Absolute Containing Block to the
// inline-start margin edge of a hypothetical box that would have been the
// first box of the element.
let static_position_inline_start = static_i_offset;
let (inline_start, inline_end, inline_size, margin_inline_start, margin_inline_end) = match (inline_start, inline_end, computed_inline_size) {
(Auto, Auto, Auto) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
let inline_start = static_position_inline_start;
// Now it is the same situation as inline-start Specified and inline-end
// and inline-size Auto.
// Set inline-end to zero to calculate inline-size
let inline_size = block.get_shrink_to_fit_inline_size(
available_inline_size - (inline_start + margin_start + margin_end));
let sum = inline_start + inline_size + margin_start + margin_end;
(inline_start, available_inline_size - sum, inline_size, margin_start, margin_end)
}
(Specified(inline_start), Specified(inline_end), Specified(inline_size)) => {
match (inline_start_margin, inline_end_margin) {
(Auto, Auto) => {
let total_margin_val = available_inline_size - inline_start - inline_end - inline_size;
if total_margin_val < Au(0) {
// margin-inline-start becomes 0 because direction is 'ltr'.
// TODO: Handle 'rtl' when it is implemented.
(inline_start, inline_end, inline_size, Au(0), total_margin_val)
} else {
// Equal margins
(inline_start, inline_end, inline_size,
total_margin_val.scale_by(0.5),
total_margin_val.scale_by(0.5))
}
}
(Specified(margin_start), Auto) => {
let sum = inline_start + inline_end + inline_size + margin_start;
(inline_start, inline_end, inline_size, margin_start, available_inline_size - sum)
}
(Auto, Specified(margin_end)) => {
let sum = inline_start + inline_end + inline_size + margin_end;
(inline_start, inline_end, inline_size, available_inline_size - sum, margin_end)
}
(Specified(margin_start), Specified(margin_end)) => {
// Values are over-constrained.
// Ignore value for 'inline-end' cos direction is 'ltr'.
// TODO: Handle 'rtl' when it is implemented.
let sum = inline_start + inline_size + margin_start + margin_end;
(inline_start, available_inline_size - sum, inline_size, margin_start, margin_end)
}
}
}
// For the rest of the cases, auto values for margin are set to 0
// If only one is Auto, solve for it
(Auto, Specified(inline_end), Specified(inline_size)) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
let sum = inline_end + inline_size + margin_start + margin_end;
(available_inline_size - sum, inline_end, inline_size, margin_start, margin_end)
}
(Specified(inline_start), Auto, Specified(inline_size)) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
let sum = inline_start + inline_size + margin_start + margin_end;
(inline_start, available_inline_size - sum, inline_size, margin_start, margin_end)
}
(Specified(inline_start), Specified(inline_end), Auto) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
let sum = inline_start + inline_end + margin_start + margin_end;
(inline_start, inline_end, available_inline_size - sum, margin_start, margin_end)
}
// If inline-size is auto, then inline-size is shrink-to-fit. Solve for the
// non-auto value.
(Specified(inline_start), Auto, Auto) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
// Set inline-end to zero to calculate inline-size
let inline_size = block.get_shrink_to_fit_inline_size(
available_inline_size - (inline_start + margin_start + margin_end));
let sum = inline_start + inline_size + margin_start + margin_end;
(inline_start, available_inline_size - sum, inline_size, margin_start, margin_end)
}
(Auto, Specified(inline_end), Auto) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
// Set inline-start to zero to calculate inline-size
let inline_size = block.get_shrink_to_fit_inline_size(
available_inline_size - (inline_end + margin_start + margin_end));
let sum = inline_end + inline_size + margin_start + margin_end;
(available_inline_size - sum, inline_end, inline_size, margin_start, margin_end)
}
(Auto, Auto, Specified(inline_size)) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
// Setting 'inline-start' to static position because direction is 'ltr'.
// TODO: Handle 'rtl' when it is implemented.
let inline_start = static_position_inline_start;
let sum = inline_start + inline_size + margin_start + margin_end;
(inline_start, available_inline_size - sum, inline_size, margin_start, margin_end)
}
};
ISizeConstraintSolution::for_absolute_flow(inline_start, inline_end, inline_size, margin_inline_start, margin_inline_end)
}
fn containing_block_inline_size(&self, block: &mut BlockFlow, _: Au, ctx: &LayoutContext) -> Au {
block.containing_block_size(ctx.shared.screen_size).inline
}
fn set_flow_x_coord_if_necessary(&self,
block: &mut BlockFlow,
solution: ISizeConstraintSolution) {
// Set the x-coordinate of the absolute flow wrt to its containing block.
block.base.position.start.i = solution.inline_start;
}
}
impl ISizeAndMarginsComputer for AbsoluteReplaced {
/// Solve the horizontal constraint equation for absolute replaced elements.
///
/// `static_i_offset`: total offset of current flow's hypothetical
/// position (static position) from its actual Containing Block.
///
/// CSS Section 10.3.8
/// Constraint equation:
/// inline-start + inline-end + inline-size + margin-inline-start + margin-inline-end
/// = absolute containing block inline-size - (horizontal padding and border)
/// [aka available_inline-size]
///
/// Return the solution for the equation.
fn solve_inline_size_constraints(&self, _: &mut BlockFlow, input: &ISizeConstraintInput)
-> ISizeConstraintSolution {
let &ISizeConstraintInput {
computed_inline_size,
inline_start_margin,
inline_end_margin,
inline_start,
inline_end,
available_inline_size,
static_i_offset,
..
} = input;
// TODO: Check for direction of static-position Containing Block (aka
// parent flow, _not_ the actual Containing Block) when right-to-left
// is implemented
// Assume direction is 'ltr' for now
// TODO: Handle all the cases for 'rtl' direction.
let inline_size = match computed_inline_size {
Specified(w) => w,
_ => fail!("{} {}",
"The used value for inline_size for absolute replaced flow",
"should have already been calculated by now.")
};
// Distance from the inline-start edge of the Absolute Containing Block to the
// inline-start margin edge of a hypothetical box that would have been the
// first box of the element.
let static_position_inline_start = static_i_offset;
let (inline_start, inline_end, inline_size, margin_inline_start, margin_inline_end) = match (inline_start, inline_end) {
(Auto, Auto) => {
let inline_start = static_position_inline_start;
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
let sum = inline_start + inline_size + margin_start + margin_end;
(inline_start, available_inline_size - sum, inline_size, margin_start, margin_end)
}
// If only one is Auto, solve for it
(Auto, Specified(inline_end)) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
let sum = inline_end + inline_size + margin_start + margin_end;
(available_inline_size - sum, inline_end, inline_size, margin_start, margin_end)
}
(Specified(inline_start), Auto) => {
let margin_start = inline_start_margin.specified_or_zero();
let margin_end = inline_end_margin.specified_or_zero();
let sum = inline_start + inline_size + margin_start + margin_end;
(inline_start, available_inline_size - sum, inline_size, margin_start, margin_end)
}
(Specified(inline_start), Specified(inline_end)) => {
match (inline_start_margin, inline_end_margin) {
(Auto, Auto) => {
let total_margin_val = available_inline_size - inline_start - inline_end - inline_size;
if total_margin_val < Au(0) {
// margin-inline-start becomes 0 because direction is 'ltr'.
(inline_start, inline_end, inline_size, Au(0), total_margin_val)
} else {
// Equal margins
(inline_start, inline_end, inline_size,
total_margin_val.scale_by(0.5),
total_margin_val.scale_by(0.5))
}
}
(Specified(margin_start), Auto) => {
let sum = inline_start + inline_end + inline_size + margin_start;
(inline_start, inline_end, inline_size, margin_start, available_inline_size - sum)
}
(Auto, Specified(margin_end)) => {
let sum = inline_start + inline_end + inline_size + margin_end;
(inline_start, inline_end, inline_size, available_inline_size - sum, margin_end)
}
(Specified(margin_start), Specified(margin_end)) => {
// Values are over-constrained.
// Ignore value for 'inline-end' cos direction is 'ltr'.
let sum = inline_start + inline_size + margin_start + margin_end;
(inline_start, available_inline_size - sum, inline_size, margin_start, margin_end)
}
}
}
};
ISizeConstraintSolution::for_absolute_flow(inline_start, inline_end, inline_size, margin_inline_start, margin_inline_end)
}
/// Calculate used value of inline-size just like we do for inline replaced elements.
fn initial_computed_inline_size(&self,
block: &mut BlockFlow,
_: Au,
layout_context: &LayoutContext)
-> MaybeAuto {
let containing_block_inline_size =
block.containing_block_size(layout_context.shared.screen_size).inline;
let fragment = block.fragment();
fragment.assign_replaced_inline_size_if_necessary(containing_block_inline_size);
// For replaced absolute flow, the rest of the constraint solving will
// take inline-size to be specified as the value computed here.
Specified(fragment.content_inline_size())
}
fn containing_block_inline_size(&self, block: &mut BlockFlow, _: Au, ctx: &LayoutContext) -> Au {
block.containing_block_size(ctx.shared.screen_size).inline
}
fn set_flow_x_coord_if_necessary(&self, block: &mut BlockFlow, solution: ISizeConstraintSolution) {
// Set the x-coordinate of the absolute flow wrt to its containing block.
block.base.position.start.i = solution.inline_start;
}
}
impl ISizeAndMarginsComputer for BlockNonReplaced {
/// Compute inline-start and inline-end margins and inline-size.
fn solve_inline_size_constraints(&self,
block: &mut BlockFlow,
input: &ISizeConstraintInput)
-> ISizeConstraintSolution {
self.solve_block_inline_size_constraints(block, input)
}
}
impl ISizeAndMarginsComputer for BlockReplaced {
/// Compute inline-start and inline-end margins and inline-size.
///
/// ISize has already been calculated. We now calculate the margins just
/// like for non-replaced blocks.
fn solve_inline_size_constraints(&self,
block: &mut BlockFlow,
input: &ISizeConstraintInput)
-> ISizeConstraintSolution {
match input.computed_inline_size {
Specified(_) => {},
Auto => fail!("BlockReplaced: inline_size should have been computed by now")
};
self.solve_block_inline_size_constraints(block, input)
}
/// Calculate used value of inline-size just like we do for inline replaced elements.
fn initial_computed_inline_size(&self,
block: &mut BlockFlow,
parent_flow_inline_size: Au,
_: &LayoutContext)
-> MaybeAuto {
let fragment = block.fragment();
fragment.assign_replaced_inline_size_if_necessary(parent_flow_inline_size);
// For replaced block flow, the rest of the constraint solving will
// take inline-size to be specified as the value computed here.
Specified(fragment.content_inline_size())
}
}
impl ISizeAndMarginsComputer for FloatNonReplaced {
/// CSS Section 10.3.5
///
/// If inline-size is computed as 'auto', the used value is the 'shrink-to-fit' inline-size.
fn solve_inline_size_constraints(&self,
block: &mut BlockFlow,
input: &ISizeConstraintInput)
-> ISizeConstraintSolution {
let (computed_inline_size, inline_start_margin, inline_end_margin, available_inline_size) = (input.computed_inline_size,
input.inline_start_margin,
input.inline_end_margin,
input.available_inline_size);
let margin_inline_start = inline_start_margin.specified_or_zero();
let margin_inline_end = inline_end_margin.specified_or_zero();
let available_inline_size_float = available_inline_size - margin_inline_start - margin_inline_end;
let shrink_to_fit = block.get_shrink_to_fit_inline_size(available_inline_size_float);
let inline_size = computed_inline_size.specified_or_default(shrink_to_fit);
debug!("assign_inline_sizes_float -- inline_size: {}", inline_size);
ISizeConstraintSolution::new(inline_size, margin_inline_start, margin_inline_end)
}
}
impl ISizeAndMarginsComputer for FloatReplaced {
/// CSS Section 10.3.5
///
/// If inline-size is computed as 'auto', the used value is the 'shrink-to-fit' inline-size.
fn solve_inline_size_constraints(&self, _: &mut BlockFlow, input: &ISizeConstraintInput)
-> ISizeConstraintSolution {
let (computed_inline_size, inline_start_margin, inline_end_margin) = (input.computed_inline_size,
input.inline_start_margin,
input.inline_end_margin);
let margin_inline_start = inline_start_margin.specified_or_zero();
let margin_inline_end = inline_end_margin.specified_or_zero();
let inline_size = match computed_inline_size {
Specified(w) => w,
Auto => fail!("FloatReplaced: inline_size should have been computed by now")
};
debug!("assign_inline_sizes_float -- inline_size: {}", inline_size);
ISizeConstraintSolution::new(inline_size, margin_inline_start, margin_inline_end)
}
/// Calculate used value of inline-size just like we do for inline replaced elements.
fn initial_computed_inline_size(&self,
block: &mut BlockFlow,
parent_flow_inline_size: Au,
_: &LayoutContext)
-> MaybeAuto {
let fragment = block.fragment();
fragment.assign_replaced_inline_size_if_necessary(parent_flow_inline_size);
// For replaced block flow, the rest of the constraint solving will
// take inline-size to be specified as the value computed here.
Specified(fragment.content_inline_size())
}
}
fn propagate_column_inline_sizes_to_child(kid: &mut Flow,
child_index: uint,
content_inline_size: Au,
column_inline_sizes: &[ColumnInlineSize],
inline_start_margin_edge: &mut Au) {
// If kid is table_rowgroup or table_row, the column inline-sizes info should be copied from
// its parent.
//
// FIXME(pcwalton): This seems inefficient. Reference count it instead?
let inline_size = if kid.is_table() || kid.is_table_rowgroup() || kid.is_table_row() {
*kid.column_inline_sizes() = column_inline_sizes.iter().map(|&x| x).collect();
// ISize of kid flow is our content inline-size.
content_inline_size
} else if kid.is_table_cell() {
column_inline_sizes[child_index].minimum_length
} else {
// ISize of kid flow is our content inline-size.
content_inline_size
};
{
let kid_base = flow::mut_base(kid);
kid_base.position.start.i = *inline_start_margin_edge;
kid_base.block_container_inline_size = inline_size;
}
if kid.is_table_cell() {
*inline_start_margin_edge = *inline_start_margin_edge + inline_size
}
}<|fim▁end|>
|
/// absolute flow).
fn set_inline_size_constraint_solutions(&self,
block: &mut BlockFlow,
|
<|file_name|>khr_technique_webgl.py<|end_file_name|><|fim▁begin|>import base64
import os
import re
import bpy
import gpu
LAMP_TYPES = [
gpu.GPU_DYNAMIC_LAMP_DYNVEC,
gpu.GPU_DYNAMIC_LAMP_DYNCO,
gpu.GPU_DYNAMIC_LAMP_DYNIMAT,
gpu.GPU_DYNAMIC_LAMP_DYNPERSMAT,
gpu.GPU_DYNAMIC_LAMP_DYNENERGY,
gpu.GPU_DYNAMIC_LAMP_DYNENERGY,
gpu.GPU_DYNAMIC_LAMP_DYNCOL,
gpu.GPU_DYNAMIC_LAMP_DISTANCE,
gpu.GPU_DYNAMIC_LAMP_ATT1,
gpu.GPU_DYNAMIC_LAMP_ATT2,
gpu.GPU_DYNAMIC_LAMP_SPOTSIZE,
gpu.GPU_DYNAMIC_LAMP_SPOTBLEND,
]
MIST_TYPES = [
gpu.GPU_DYNAMIC_MIST_ENABLE,
gpu.GPU_DYNAMIC_MIST_START,
gpu.GPU_DYNAMIC_MIST_DISTANCE,
gpu.GPU_DYNAMIC_MIST_INTENSITY,
gpu.GPU_DYNAMIC_MIST_TYPE,
gpu.GPU_DYNAMIC_MIST_COLOR,
]
WORLD_TYPES = [
gpu.GPU_DYNAMIC_HORIZON_COLOR,
gpu.GPU_DYNAMIC_AMBIENT_COLOR,
]
MATERIAL_TYPES = [
gpu.GPU_DYNAMIC_MAT_DIFFRGB,
gpu.GPU_DYNAMIC_MAT_REF,
gpu.GPU_DYNAMIC_MAT_SPECRGB,
gpu.GPU_DYNAMIC_MAT_SPEC,
gpu.GPU_DYNAMIC_MAT_HARD,
gpu.GPU_DYNAMIC_MAT_EMIT,
gpu.GPU_DYNAMIC_MAT_AMB,
gpu.GPU_DYNAMIC_MAT_ALPHA,
]
TYPE_TO_NAME = {
gpu.GPU_DYNAMIC_OBJECT_VIEWMAT: 'view_mat',
gpu.GPU_DYNAMIC_OBJECT_MAT: 'model_mat',
gpu.GPU_DYNAMIC_OBJECT_VIEWIMAT: 'inv_view_mat',
gpu.GPU_DYNAMIC_OBJECT_IMAT: 'inv_model_mat',
gpu.GPU_DYNAMIC_OBJECT_COLOR: 'color',
gpu.GPU_DYNAMIC_OBJECT_AUTOBUMPSCALE: 'auto_bump_scale',
gpu.GPU_DYNAMIC_MIST_ENABLE: 'use_mist',
gpu.GPU_DYNAMIC_MIST_START: 'start',
gpu.GPU_DYNAMIC_MIST_DISTANCE: 'depth',
gpu.GPU_DYNAMIC_MIST_INTENSITY: 'intensity',
gpu.GPU_DYNAMIC_MIST_TYPE: 'falloff',
gpu.GPU_DYNAMIC_MIST_COLOR: 'color',
gpu.GPU_DYNAMIC_HORIZON_COLOR: 'horizon_color',
gpu.GPU_DYNAMIC_AMBIENT_COLOR: 'ambient_color',
gpu.GPU_DYNAMIC_LAMP_DYNVEC: 'dynvec',
gpu.GPU_DYNAMIC_LAMP_DYNCO: 'dynco',
gpu.GPU_DYNAMIC_LAMP_DYNIMAT: 'dynimat',
gpu.GPU_DYNAMIC_LAMP_DYNPERSMAT: 'dynpersmat',
gpu.GPU_DYNAMIC_LAMP_DYNENERGY: 'energy',
gpu.GPU_DYNAMIC_LAMP_DYNCOL: 'color',
gpu.GPU_DYNAMIC_LAMP_DISTANCE: 'distance',
gpu.GPU_DYNAMIC_LAMP_ATT1: 'linear_attenuation',
gpu.GPU_DYNAMIC_LAMP_ATT2: 'quadratic_attenuation',
gpu.GPU_DYNAMIC_LAMP_SPOTSIZE: 'spot_size',
gpu.GPU_DYNAMIC_LAMP_SPOTBLEND: 'spot_blend',
gpu.GPU_DYNAMIC_MAT_DIFFRGB: 'diffuse_color',
gpu.GPU_DYNAMIC_MAT_REF: 'diffuse_intensity',
gpu.GPU_DYNAMIC_MAT_SPECRGB: 'specular_color',
gpu.GPU_DYNAMIC_MAT_SPEC: 'specular_intensity',
gpu.GPU_DYNAMIC_MAT_HARD: 'specular_hardness',
gpu.GPU_DYNAMIC_MAT_EMIT: 'emit',
gpu.GPU_DYNAMIC_MAT_AMB: 'ambient',
gpu.GPU_DYNAMIC_MAT_ALPHA: 'alpha',
}
TYPE_TO_SEMANTIC = {
gpu.GPU_DYNAMIC_LAMP_DYNVEC: 'BL_DYNVEC',
gpu.GPU_DYNAMIC_LAMP_DYNCO: 'MODELVIEW', # dynco gets extracted from the matrix
gpu.GPU_DYNAMIC_LAMP_DYNIMAT: 'BL_DYNIMAT',
gpu.GPU_DYNAMIC_LAMP_DYNPERSMAT: 'BL_DYNPERSMAT',
gpu.CD_ORCO: 'POSITION',
gpu.CD_MTFACE: 'TEXCOORD_0',
-1: 'NORMAL' # Hack until the gpu module has something for normals
}
DATATYPE_TO_CONVERTER = {
gpu.GPU_DATA_1I: lambda x: x,
gpu.GPU_DATA_1F: lambda x: x,
gpu.GPU_DATA_2F: list,
gpu.GPU_DATA_3F: list,<|fim▁hole|>DATATYPE_TO_GLTF_TYPE = {
gpu.GPU_DATA_1I: 5124, # INT
gpu.GPU_DATA_1F: 5126, # FLOAT
gpu.GPU_DATA_2F: 35664, # FLOAT_VEC2
gpu.GPU_DATA_3F: 35665, # FLOAT_VEC3
gpu.GPU_DATA_4F: 35666, # FLOAT_VEC4
gpu.GPU_DATA_9F: 35675, # FLOAT_MAT3
gpu.GPU_DATA_16F: 35676, # FLOAT_MAT4
}
def vs_to_130(data):
data['attributes'].append({
'varname': 'bl_Vertex',
'type': gpu.CD_ORCO,
'datatype': gpu.GPU_DATA_4F
})
data['attributes'].append({
'varname': 'bl_Normal',
'type': -1,
'datatype': gpu.GPU_DATA_3F
})
data['uniforms'].append({
'varname': 'bl_ModelViewMatrix',
'type': 0,
'datatype': gpu.GPU_DATA_16F,
})
data['uniforms'].append({
'varname': 'bl_ProjectionMatrix',
'type': 0,
'datatype': gpu.GPU_DATA_16F,
})
data['uniforms'].append({
'varname': 'bl_NormalMatrix',
'type': 0,
'datatype': gpu.GPU_DATA_9F,
})
src = '#version 130\n'
src += 'in vec4 bl_Vertex;\n'
src += 'in vec3 bl_Normal;\n'
src += 'uniform mat4 bl_ModelViewMatrix;\n'
src += 'uniform mat4 bl_ProjectionMatrix;\n'
src += 'uniform mat3 bl_NormalMatrix;\n'
src += data['vertex']
src = re.sub(r'#ifdef USE_OPENSUBDIV([^#]*)#endif', '', src)
src = re.sub(r'#ifndef USE_OPENSUBDIV([^#]*)#endif', r'\1', src)
src = re.sub(r'#ifdef CLIP_WORKAROUND(.*?)#endif', '', src, 0, re.DOTALL)
src = re.sub(r'\bvarying\b', 'out', src)
src = re.sub(r'\bgl_(?!Position)(.*?)\b', r'bl_\1', src)
data['vertex'] = src
def fs_to_130(data):
src = '#version 130\n'
src += 'out vec4 frag_color;\n'
src += 'uniform mat4 bl_ProjectionMatrix;\n'
src += 'uniform mat4 bl_ModelViewMatrix;\n'
src += 'uniform mat4 bl_ModelViewMatrixInverse;\n'
src += 'uniform mat3 bl_NormalMatrix;\n'
src += 'uniform mat4 bl_ProjectionMatrixInverse;\n'
src += data['fragment']
src = re.sub(r'\bvarying\b', 'in', src)
src = re.sub(r'\bgl_FragColor\b', 'frag_color', src)
src = re.sub(r'\bgl_(?!FrontFacing)(.*?)\b', r'bl_\1', src)
# Cannot support node_bsdf functions without resolving use of gl_Light
src = re.sub(r'void node_((bsdf)|(subsurface))_.*?^}', '', src, 0, re.DOTALL | re.MULTILINE)
# Need to gather light data from more general uniforms
light_count = 0
light_map = {}
decl_start_str = 'void main()\n{\n'
for uniform in data['uniforms']:
if uniform['type'] == gpu.GPU_DYNAMIC_LAMP_DYNCO:
lamp_name = uniform['lamp'].name
if lamp_name not in light_map:
light_map[lamp_name] = light_count
light_count += 1
light_index = light_map[lamp_name]
varname = 'light{}_transform'.format(light_index)
uniform['datatype'] = gpu.GPU_DATA_16F
src = src.replace(
'uniform vec3 {};'.format(uniform['varname']),
'uniform mat4 {};'.format(varname)
)
var_decl_start = src.find(decl_start_str) + len(decl_start_str)
decl_str = '\tvec3 {} = {}[3].xyz;\n'.format(uniform['varname'], varname)
src = src[:var_decl_start] + decl_str + src[var_decl_start:]
uniform['varname'] = varname
data['fragment'] = src.replace('\r\r\n', '')
def vs_to_web(data):
src = data['vertex']
precision_block = '\n'
for data_type in ('float', 'int'):
precision_block += 'precision mediump {};\n'.format(data_type)
src = src.replace('#version 130', '#version 100\n' + precision_block)
src = re.sub(r'\bin\b', 'attribute', src)
src = re.sub(r'\bout\b', 'varying', src)
data['vertex'] = src
def fs_to_web(data):
src = data['fragment']
precision_block = '\n'
for data_type in ('float', 'int'):
precision_block += 'precision mediump {};\n'.format(data_type)
header = '#version 100\n'
header += '#extension GL_OES_standard_derivatives: enable\n'
header += precision_block
src = src.replace('#version 130', header)
src = re.sub(r'\bin\b', 'varying', src)
src = src.replace('out vec4 frag_color;\n', '')
src = re.sub(r'\bfrag_color\b', 'gl_FragColor', src)
# TODO: This should be fixed in Blender
src = src.replace('blend = (normalize(vec).z + 1)', 'blend = (normalize(vec).z + 1.0)')
# TODO: This likely breaks shadows
src = src.replace('sampler2DShadow', 'sampler2D')
src = src.replace('shadow2DProj', 'texture2DProj')
data['fragment'] = src
def to_130(data):
vs_to_130(data)
fs_to_130(data)
def to_web(data):
to_130(data)
vs_to_web(data)
fs_to_web(data)
class KhrTechniqueWebgl:
ext_meta = {
'name': 'KHR_technique_webgl',
'url': (
'https://github.com/KhronosGroup/glTF/tree/master/extensions/'
'Khronos/KHR_technique_webgl'
),
'isDraft': True,
'settings': {
'embed_shaders': bpy.props.BoolProperty(
name='Embed Shader Data',
description='Embed shader data into the glTF file instead of a separate file',
default=False
)
}
}
settings = None
def export_material(self, state, material):
shader_data = gpu.export_shader(bpy.context.scene, material)
if state['settings']['asset_profile'] == 'DESKTOP':
to_130(shader_data)
else:
to_web(shader_data)
if self.settings.embed_shaders is True:
fs_bytes = shader_data['fragment'].encode()
fs_uri = 'data:text/plain;base64,' + base64.b64encode(fs_bytes).decode('ascii')
vs_bytes = shader_data['vertex'].encode()
vs_uri = 'data:text/plain;base64,' + base64.b64encode(vs_bytes).decode('ascii')
else:
names = [
bpy.path.clean_name(name) + '.glsl'
for name in (material.name+'VS', material.name+'FS')
]
data = (shader_data['vertex'], shader_data['fragment'])
for name, data in zip(names, data):
filename = os.path.join(state['settings']['gltf_output_dir'], name)
with open(filename, 'w') as fout:
fout.write(data)
vs_uri, fs_uri = names
state['output']['shaders'].append({
'type': 35632,
'uri': fs_uri,
'name': material.name + 'FS',
})
state['output']['shaders'].append({
'type': 35633,
'uri': vs_uri,
'name': material.name + 'VS',
})
# Handle programs
state['output']['programs'].append({
'attributes': [a['varname'] for a in shader_data['attributes']],
'fragmentShader': 'shaders_{}FS'.format(material.name),
'vertexShader': 'shaders_{}VS'.format(material.name),
'name': material.name,
})
# Handle parameters/values
values = {}
parameters = {}
for attribute in shader_data['attributes']:
name = attribute['varname']
semantic = TYPE_TO_SEMANTIC[attribute['type']]
_type = DATATYPE_TO_GLTF_TYPE[attribute['datatype']]
parameters[name] = {'semantic': semantic, 'type': _type}
for uniform in shader_data['uniforms']:
valname = TYPE_TO_NAME.get(uniform['type'], uniform['varname'])
rnaname = valname
semantic = None
node = None
value = None
if uniform['varname'] == 'bl_ModelViewMatrix':
semantic = 'MODELVIEW'
elif uniform['varname'] == 'bl_ProjectionMatrix':
semantic = 'PROJECTION'
elif uniform['varname'] == 'bl_NormalMatrix':
semantic = 'MODELVIEWINVERSETRANSPOSE'
else:
if uniform['type'] in LAMP_TYPES:
node = uniform['lamp'].name
valname = node + '_' + valname
semantic = TYPE_TO_SEMANTIC.get(uniform['type'], None)
if not semantic:
lamp_obj = bpy.data.objects[node]
value = getattr(lamp_obj.data, rnaname)
elif uniform['type'] in MIST_TYPES:
valname = 'mist_' + valname
mist_settings = bpy.context.scene.world.mist_settings
if valname == 'mist_color':
value = bpy.context.scene.world.horizon_color
else:
value = getattr(mist_settings, rnaname)
if valname == 'mist_falloff':
if value == 'QUADRATIC':
value = 0.0
elif value == 'LINEAR':
value = 1.0
else:
value = 2.0
elif uniform['type'] in WORLD_TYPES:
world = bpy.context.scene.world
value = getattr(world, rnaname)
elif uniform['type'] in MATERIAL_TYPES:
converter = DATATYPE_TO_CONVERTER[uniform['datatype']]
value = converter(getattr(material, rnaname))
values[valname] = value
elif uniform['type'] == gpu.GPU_DYNAMIC_SAMPLER_2DIMAGE:
texture_slots = [
slot for slot in material.texture_slots
if slot and slot.texture.type == 'IMAGE'
]
for slot in texture_slots:
if slot.texture.image.name == uniform['image'].name:
value = 'texture_' + slot.texture.name
values[uniform['varname']] = value
else:
print('Unconverted uniform:', uniform)
parameter = {}
if semantic:
parameter['semantic'] = semantic
if node:
parameter['node'] = 'node_' + node
elif value:
parameter['value'] = DATATYPE_TO_CONVERTER[uniform['datatype']](value)
else:
parameter['value'] = None
if uniform['type'] == gpu.GPU_DYNAMIC_SAMPLER_2DIMAGE:
parameter['type'] = 35678 # SAMPLER_2D
else:
parameter['type'] = DATATYPE_TO_GLTF_TYPE[uniform['datatype']]
parameters[valname] = parameter
uniform['valname'] = valname
# Handle techniques
tech_name = 'techniques_' + material.name
state['output']['techniques'].append({
'parameters': parameters,
'program': 'programs_' + material.name,
'attributes': {a['varname']: a['varname'] for a in shader_data['attributes']},
'uniforms': {u['varname']: u['valname'] for u in shader_data['uniforms']},
'name': material.name,
})
return {'technique': tech_name, 'values': values, 'name': material.name}
def export(self, state):
state['output']['techniques'] = []
state['output']['shaders'] = []
state['output']['programs'] = []
state['output']['materials'] = [
self.export_material(state, bl_mat) for bl_mat in state['input']['materials']
]<|fim▁end|>
|
gpu.GPU_DATA_4F: list,
}
|
<|file_name|>autoderef-and-borrow-method-receiver.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
<|fim▁hole|>}
impl Foo {
pub fn f(&self) {}
}
fn g(x: &mut Foo) {
x.f();
}
pub fn main() {
}<|fim▁end|>
|
struct Foo {
x: isize,
|
<|file_name|>valkyrie.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2.7
# Uploads Scrypt mining farm status to CouchDB database for detailed logging.
# Written by Vishakh.
# https://github.com/vishakh/valkyrie
# Based on open source code by etkeh <https://github.com/setkeh>
import datetime
import json
import logging
import socket
import subprocess
import sys
import time
import couchdb
def readHostsFile(filename):
hosts = []
json_data = open( filename )
data = json.load(json_data)
for name in data:
info = data[name]
host = info['host']
port = info['port']
hosts.append([host, port, name])
return hosts
def readConfigFile(filename):
json_data = open( filename )
data = json.load(json_data)
couchdb_server = data['couchdb_server']
couchdb_database = data['couchdb_database']
socket_timeout = int(data['socket_timeout'])
log_interval = int(data['log_interval'])
temperature_script = None
if 'temperature_script' in data:
temperature_script = data['temperature_script']
return couchdb_server, couchdb_database, socket_timeout, log_interval, temperature_script
def linesplit(socket):
buffer = socket.recv(4096)
done = False
while not done:
more = socket.recv(4096)
if not more:
done = True
else:
buffer = buffer + more
if buffer:
return buffer
def makerpccall(api_command, api_ip, api_port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(socket_timeout)
s.connect((api_ip, int(api_port)))
if len(api_command) == 2:
s.send(json.dumps({"command": api_command[0], "parameter": api_command[1]}))
else:
s.send(json.dumps({"command": api_command[0]}))
resp = linesplit(s)
resp = resp.replace('\x00', '')
resp = json.loads(resp)
s.close()
return resp
def tryDBConnect():
server = couchdb.Server(url=couchdb_server)
db = server[couchdb_database]
return db, server
def connectToDB():
log.info("Connecting to DB.")
while True:
try:
db, server = tryDBConnect()
log.info("DB connect successful.")
return server, db
except:
e = sys.exc_info()[0]
log.error("Could not connect to DB.")
log.info(e)
log.info("Will retry after sleep..")
time.sleep(log_interval)
def runIteration():
log.info('Running iteration')
try:
utctime = str(datetime.datetime.utcnow())
unix_time = str(time.time())
miners = {}
total_hashrate = 0.0
total_miners = 0
total_gpus = 0
temperature = None
for host, port, name in hosts:
try:
log.info('Querying %s at %s:%s' % (name, host, port))
currenthost = {}
command = 'summary'<|fim▁hole|> currenthost[command] = summary
command = 'config'
response = makerpccall([command], host, port)
config = response['CONFIG']
currenthost[command] = config
command = 'pools'
response = makerpccall([command], host, port)
pools = response['POOLS']
currenthost[command] = pools
command = 'devs'
response = makerpccall([command], host, port)
devices = response['DEVS']
currenthost[command] = devices
command = 'coin'
response = makerpccall([command], host, port)
devdetails = response['COIN']
currenthost[command] = devdetails
miners[name] = currenthost
temperature = None
try:
if temperature_script is not None:
temperature = subprocess.check_output(temperature_script).strip()
temperature = temperature.replace('\r', '').replace('\n', '')
else:
log.info('Skipping temperature recording as no script is provided.')
except:
log.warn('Could not get farm temperature.')
e = sys.exc_info()[0]
log.info(e)
# Cumulative statistics
hashrate = summary['MHS 5s']
if (type(hashrate) == str or type(hashrate) is None) and ('E' in hashrate or 'e' in hashrate):
hashrate = float(hashrate[:-1])/10
total_hashrate += hashrate
total_miners += 1
gpus = len(devices)
total_gpus += gpus
except:
log.error("Could not fetch data from host " + name + " at host " + host + " and port " + port)
e = sys.exc_info()
log.info(e)
record = {'_id': unix_time, 'unixtime': unix_time, 'utctime': utctime, 'total_hashrate': total_hashrate,
'total_miners': total_miners,
'total_gpus': total_gpus, 'temperature': temperature, 'miners': miners}
try:
db[unix_time] = record
db.commit()
except:
log.warn('Could not write to database. Attempting to reconnect for next iteration..')
connectToDB()
except:
e = sys.exc_info()
log.error("Error during iteration")
logging.exception(e)
log.info('Done with iteration.')
log = logging.getLogger('Valkyrie')
log.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s %(filename)s %(lineno)d - %(levelname)s - %(message)s"))
log.addHandler(handler)
config_file = sys.argv[1]
hosts_file = sys.argv[2]
hosts = readHostsFile(hosts_file)
couchdb_server, couchdb_database, socket_timeout, log_interval, temperature_script = readConfigFile(config_file)
server, db = connectToDB()
while True:
runIteration()
log.info('Sleeping for %s seconds.'%log_interval)
time.sleep(log_interval)<|fim▁end|>
|
response = makerpccall([command], host, port)
summary = response['SUMMARY'][0]
|
<|file_name|>BSDismemberSkinInstance.cpp<|end_file_name|><|fim▁begin|>/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved. Please see niflib.h for license. */
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script. Only //
// add custom code in the designated areas or it will be overwritten during //
// the next update. //
//-----------------------------------NOTICE----------------------------------//
//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//
#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/BSDismemberSkinInstance.h"
#include "../../include/gen/BodyPartList.h"
using namespace Niflib;
//Definition of TYPE constant
const Type BSDismemberSkinInstance::TYPE("BSDismemberSkinInstance", &NiSkinInstance::TYPE);
BSDismemberSkinInstance::BSDismemberSkinInstance() : numPartitions((int) 0)
{
//--BEGIN CONSTRUCTOR CUSTOM CODE--//
//--END CUSTOM CODE--//
}
BSDismemberSkinInstance::~BSDismemberSkinInstance()
{
//--BEGIN DESTRUCTOR CUSTOM CODE--//
//--END CUSTOM CODE--//
}
const Type & BSDismemberSkinInstance::GetType() const
{
return TYPE;
}
NiObject * BSDismemberSkinInstance::Create()
{
return new BSDismemberSkinInstance;
}
void BSDismemberSkinInstance::Read(istream& in, list<unsigned int> & link_stack, const NifInfo & info)
{
//--BEGIN PRE-READ CUSTOM CODE--//
//--END CUSTOM CODE--//
NiSkinInstance::Read(in, link_stack, info);
NifStream(numPartitions, in, info);
partitions.resize(numPartitions);
for(unsigned int i1 = 0; i1 < partitions.size(); i1++)
{
NifStream(partitions[i1].partFlag, in, info);
NifStream(partitions[i1].bodyPart, in, info);
};
//--BEGIN POST-READ CUSTOM CODE--//
//--END CUSTOM CODE--//
}
void BSDismemberSkinInstance::Write(ostream& out, const map<NiObjectRef, unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info) const
{
//--BEGIN PRE-WRITE CUSTOM CODE--//
//--END CUSTOM CODE--//
NiSkinInstance::Write(out, link_map, missing_link_stack, info);
numPartitions = (int) (partitions.size());
NifStream(numPartitions, out, info);
for(unsigned int i1 = 0; i1 < partitions.size(); i1++)
{
NifStream(partitions[i1].partFlag, out, info);
NifStream(partitions[i1].bodyPart, out, info);
};
//--BEGIN POST-WRITE CUSTOM CODE--//
//--END CUSTOM CODE--//
}
std::string BSDismemberSkinInstance::asString(bool verbose) const
{
//--BEGIN PRE-STRING CUSTOM CODE--//
//--END CUSTOM CODE--//
stringstream out;
unsigned int array_output_count = 0;
out << NiSkinInstance::asString(verbose);
numPartitions = (int) (partitions.size());
out << " Num Partitions: " << numPartitions << endl;
array_output_count = 0;
for(unsigned int i1 = 0; i1 < partitions.size(); i1++)
{
if(!verbose && (array_output_count > MAXARRAYDUMP))
{
out << "<Data Truncated. Use verbose mode to see complete listing.>" << endl;
break;
};
out << " Part Flag: " << partitions[i1].partFlag << endl;<|fim▁hole|> return out.str();
//--BEGIN POST-STRING CUSTOM CODE--//
//--END CUSTOM CODE--//
}
void BSDismemberSkinInstance::FixLinks(const map<unsigned int, NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info)
{
//--BEGIN PRE-FIXLINKS CUSTOM CODE--//
//--END CUSTOM CODE--//
NiSkinInstance::FixLinks(objects, link_stack, missing_link_stack, info);
//--BEGIN POST-FIXLINKS CUSTOM CODE--//
//--END CUSTOM CODE--//
}
std::list<NiObjectRef> BSDismemberSkinInstance::GetRefs() const
{
list<Ref<NiObject> > refs;
refs = NiSkinInstance::GetRefs();
return refs;
}
std::list<NiObject *> BSDismemberSkinInstance::GetPtrs() const
{
list<NiObject *> ptrs;
ptrs = NiSkinInstance::GetPtrs();
return ptrs;
}
/***Begin Example Naive Implementation****
vector<BodyPartList > BSDismemberSkinInstance::GetPartitions() const {
return partitions;
}
void BSDismemberSkinInstance::SetPartitions( const vector<BodyPartList >& value ) {
partitions = value;
}
****End Example Naive Implementation***/
//--BEGIN MISC CUSTOM CODE--//
vector<BodyPartList > BSDismemberSkinInstance::GetPartitions() const
{
return partitions;
}
void BSDismemberSkinInstance::SetPartitions(const vector<BodyPartList >& value)
{
partitions = value;
}
//--END CUSTOM CODE--//<|fim▁end|>
|
out << " Body Part: " << partitions[i1].bodyPart << endl;
};
|
<|file_name|>phenomic.js<|end_file_name|><|fim▁begin|>export type PhenomicDB = {
destroy: () => Promise<*>,
put: (sub: string | Array<string>, key: string, value: any) => Promise<*>,<|fim▁hole|> sub: string | Array<string>,
config: LevelStreamConfig,
filter?: string,
filterValue: string
) => Promise<*>
};
export type PhenomicInputPlugins = {
plugins?: Array<(arg: PhenomicInputConfig) => PhenomicPlugin>,
presets?: Array<(arg: PhenomicInputConfig) => PhenomicInputPlugins>
};
export type PhenomicInputConfig = {
path?: string,
outdir?: string,
port?: number,
bundleName?: string,
plugins?: Array<(arg: PhenomicInputConfig) => PhenomicPlugin>,
presets?: Array<(arg: PhenomicInputConfig) => PhenomicInputPlugins>
};
export type PhenomicContentFile = {
name: string,
fullpath: string
// exists: boolean,
// type: string
};
type PhenomicTransformResult = {
data: Object,
partial: Object
};
type PhenomicHtmlPropsType = {
body: React$Element<*>,
state?: React$Element<*>,
script: React$Element<*>
};
type PhenomicHtmlType = (props: PhenomicHtmlPropsType) => React$Element<*>;
type PhenomicPluginRenderHTMLType = (
config: PhenomicConfig,
props?: { body?: string, state?: Object },
html?: PhenomicHtmlType
) => string;
export type PhenomicPlugin = {
name: string,
// transformer
supportedFileTypes?: Array<string>,
transform?: ({
config?: PhenomicConfig,
file: PhenomicContentFile,
contents: Buffer
}) => Promise<PhenomicTransformResult> | PhenomicTransformResult,
// api
define?: (api: express$Application, db: PhenomicDB) => mixed,
// collector
collect?: (db: PhenomicDB, fileName: string, parsed: Object) => Array<mixed>,
// bunder
buildForPrerendering?: Function,
// renderer
getRoutes?: Function,
renderServer?: Function,
renderHTML?: PhenomicPluginRenderHTMLType,
// common
addDevServerMiddlewares?: (
config: PhenomicConfig
) => Array<express$Middleware | Promise<express$Middleware>>
};
export type PhenomicPlugins = Array<PhenomicPlugin>;
export type PhenomicPresets = Array<PhenomicPreset>;
export type PhenomicExtensions = PhenomicPreset;
export type PhenomicConfig = {
path: string,
outdir: string,
port: number,
bundleName: string,
plugins: Array<PhenomicPlugin>
};
export type PhenomicQueryConfig = {
collection?: string,
id?: string,
after?: string,
by?: string,
value?: string,
limit?: number
};
export type PhenomicRoute = {
path: string,
params?: { [key: string]: any },
component: {
getQueries?: (props: { params: { [key: string]: any } }) => {
[key: string]: PhenomicQueryConfig
}
},
collection?: string | PhenomicQueryConfig
};
// @todo why this inconsistency?
export type PhenomicFetch =
| IsomorphicFetch
| ((config: PhenomicQueryConfig) => Promise<any>);
export type phenomic$Query = string;
export type phenomic$Queries = Array<phenomic$Query>;<|fim▁end|>
|
get: (sub: string | Array<string>, key: string) => Promise<*>,
getPartial: (sub: string | Array<string>, key: string) => Promise<*>,
getList: (
|
<|file_name|>ItemRTMHarvester.java<|end_file_name|><|fim▁begin|>package com.orcinuss.reinforcedtools.item.tools;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import java.util.Set;
public class ItemRTMHarvester extends ItemTool{
private static final Set blocksToBreak = Sets.newHashSet(new Block[]{Blocks.glowstone});
public EnumRarity rarity;
public ItemRTMHarvester(Item.ToolMaterial material)
{
this(material, EnumRarity.common);
}<|fim▁hole|> this.rarity = rarity;
this.maxStackSize = 1;
}
}<|fim▁end|>
|
public ItemRTMHarvester(Item.ToolMaterial material, EnumRarity rarity ){
super(0.0F, material, blocksToBreak);
|
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
flask.ext.hippocket.tasks
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by Sean Vieira.
:license: MIT, see LICENSE for more details.
"""
from flask import Blueprint, Markup, request, render_template
from itertools import chain
from os import path<|fim▁hole|>from pkgutil import walk_packages
from werkzeug.utils import import_string
from werkzeug.exceptions import default_exceptions, HTTPException
def autoload(app, apps_package="apps", module_name="routes", blueprint_name="routes", on_error=None):
"""Automatically load Blueprints from the specified package and registers them with Flask."""
if not apps_package:
raise ValueError("No apps package provided - unable to begin autoload")
if isinstance(apps_package, basestring):
package_code = import_string(apps_package)
else:
#: `apps_package` can be the already imported parent package
#: (i.e. the following is a licit pattern)::
#:
#: import app_package
#: # do something else with app_package
#: autoload(app, app_package)
package_code = apps_package
apps_package = apps_package.__name__
package_paths = package_code.__path__
package_paths = [path.join(app.root_path, p) for p in package_paths]
root = apps_package
apps_package = apps_package + u"." if not apps_package.endswith(".") else apps_package
if on_error is None:
on_error = lambda name: app.logger.warn("Unable to import {name}.".format(name=name))
_to_import = "{base}.{module}.{symbol}"
import_template = lambda base: _to_import.format(base=base,
module=module_name,
symbol=blueprint_name)
#: Autoloaded apps must be Python packages
#: The root of the package is also inspected for a routing file
package_contents = chain([[None, root, True]],
walk_packages(path=package_paths, prefix=apps_package, onerror=on_error))
for _, sub_app_name, is_pkg in package_contents:
if not is_pkg:
continue
sub_app_import_path = import_template(base=sub_app_name)
sub_app = import_string(sub_app_import_path)
if isinstance(sub_app, Blueprint):
app.register_blueprint(sub_app)
else:
app.logger.warn(("Failed to register {name} - "
"it does not match the registration pattern.").format(name=sub_app_name))
def setup_errors(app, error_template="errors.html"):
"""Add a handler for each of the available HTTP error responses."""
def error_handler(error):
if isinstance(error, HTTPException):
description = error.get_description(request.environ)
code = error.code
name = error.name
else:
description = error
code = 500
name = "Internal Server Error"
return render_template(error_template,
code=code,
name=Markup(name),
description=Markup(description))
for exception in default_exceptions:
app.register_error_handler(exception, error_handler)<|fim▁end|>
| |
<|file_name|>paths.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.pipeline import ClientRawResponse
from .. import models
class Paths(object):
"""Paths operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An objec model deserializer.
"""
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.config = config
def get_boolean_true(
self, bool_path=False, custom_headers=None, raw=False, **operation_config):
"""
Get true Boolean value on path
:param bool_path: true boolean value
:type bool_path: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/bool/true/{boolPath}'
path_format_arguments = {
'boolPath': self._serialize.url("bool_path", bool_path, 'bool')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_boolean_false(
self, bool_path=False, custom_headers=None, raw=False, **operation_config):
"""
Get false Boolean value on path
:param bool_path: false boolean value
:type bool_path: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/bool/false/{boolPath}'
path_format_arguments = {
'boolPath': self._serialize.url("bool_path", bool_path, 'bool')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_int_one_million(
self, int_path=1000000, custom_headers=None, raw=False, **operation_config):
"""
Get '1000000' integer value
:param int_path: '1000000' integer value
:type int_path: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/int/1000000/{intPath}'
path_format_arguments = {
'intPath': self._serialize.url("int_path", int_path, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_int_negative_one_million(
self, int_path=-1000000, custom_headers=None, raw=False, **operation_config):
"""
Get '-1000000' integer value
:param int_path: '-1000000' integer value
:type int_path: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/int/-1000000/{intPath}'
path_format_arguments = {
'intPath': self._serialize.url("int_path", int_path, 'int')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_ten_billion(
self, long_path=10000000000, custom_headers=None, raw=False, **operation_config):
"""
Get '10000000000' 64 bit integer value
:param long_path: '10000000000' 64 bit integer value
:type long_path: long
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/long/10000000000/{longPath}'
path_format_arguments = {
'longPath': self._serialize.url("long_path", long_path, 'long')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_negative_ten_billion(
self, long_path=-10000000000, custom_headers=None, raw=False, **operation_config):
"""
Get '-10000000000' 64 bit integer value
:param long_path: '-10000000000' 64 bit integer value
:type long_path: long
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/long/-10000000000/{longPath}'
path_format_arguments = {
'longPath': self._serialize.url("long_path", long_path, 'long')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def float_scientific_positive(
self, float_path=1.034E+20, custom_headers=None, raw=False, **operation_config):
"""
Get '1.034E+20' numeric value
:param float_path: '1.034E+20'numeric value
:type float_path: float
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/float/1.034E+20/{floatPath}'
path_format_arguments = {
'floatPath': self._serialize.url("float_path", float_path, 'float')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def float_scientific_negative(
self, float_path=-1.034E-20, custom_headers=None, raw=False, **operation_config):
"""
Get '-1.034E-20' numeric value
:param float_path: '-1.034E-20'numeric value
:type float_path: float
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/float/-1.034E-20/{floatPath}'
path_format_arguments = {
'floatPath': self._serialize.url("float_path", float_path, 'float')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def double_decimal_positive(
self, double_path=9999999.999, custom_headers=None, raw=False, **operation_config):
"""
Get '9999999.999' numeric value
:param double_path: '9999999.999'numeric value
:type double_path: float
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/double/9999999.999/{doublePath}'
path_format_arguments = {
'doublePath': self._serialize.url("double_path", double_path, 'float')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def double_decimal_negative(
self, double_path=-9999999.999, custom_headers=None, raw=False, **operation_config):
"""
Get '-9999999.999' numeric value
:param double_path: '-9999999.999'numeric value
:type double_path: float
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/double/-9999999.999/{doublePath}'
path_format_arguments = {
'doublePath': self._serialize.url("double_path", double_path, 'float')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def string_unicode(
self, string_path="啊齄丂狛狜隣郎隣兀﨩", custom_headers=None, raw=False, **operation_config):
"""
Get '啊齄丂狛狜隣郎隣兀﨩' multi-byte string value
:param string_path: '啊齄丂狛狜隣郎隣兀﨩'multi-byte string value
:type string_path: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""<|fim▁hole|> }
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def string_url_encoded(
self, string_path="begin!*'();:@ &=+$,/?#[]end", custom_headers=None, raw=False, **operation_config):
"""
Get 'begin!*'();:@ &=+$,/?#[]end
:param string_path: 'begin!*'();:@ &=+$,/?#[]end' url encoded string
value
:type string_path: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/begin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend/{stringPath}'
path_format_arguments = {
'stringPath': self._serialize.url("string_path", string_path, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def string_empty(
self, string_path="", custom_headers=None, raw=False, **operation_config):
"""
Get ''
:param string_path: '' string value
:type string_path: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/empty/{stringPath}'
path_format_arguments = {
'stringPath': self._serialize.url("string_path", string_path, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def string_null(
self, string_path, custom_headers=None, raw=False, **operation_config):
"""
Get null (should throw)
:param string_path: null string value
:type string_path: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/null/{stringPath}'
path_format_arguments = {
'stringPath': self._serialize.url("string_path", string_path, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def enum_valid(
self, enum_path, custom_headers=None, raw=False, **operation_config):
"""
Get using uri with 'green color' in path parameter
:param enum_path: send the value green. Possible values include: 'red
color', 'green color', 'blue color'
:type enum_path: str or :class:`UriColor
<fixtures.acceptancetestsurl.models.UriColor>`
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/enum/green%20color/{enumPath}'
path_format_arguments = {
'enumPath': self._serialize.url("enum_path", enum_path, 'UriColor')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def enum_null(
self, enum_path, custom_headers=None, raw=False, **operation_config):
"""
Get null (should throw on the client before the request is sent on
wire)
:param enum_path: send null should throw. Possible values include:
'red color', 'green color', 'blue color'
:type enum_path: str or :class:`UriColor
<fixtures.acceptancetestsurl.models.UriColor>`
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/null/{enumPath}'
path_format_arguments = {
'enumPath': self._serialize.url("enum_path", enum_path, 'UriColor')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def byte_multi_byte(
self, byte_path, custom_headers=None, raw=False, **operation_config):
"""
Get '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte array
:param byte_path: '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte
array
:type byte_path: bytearray
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/byte/multibyte/{bytePath}'
path_format_arguments = {
'bytePath': self._serialize.url("byte_path", byte_path, 'bytearray')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def byte_empty(
self, byte_path=bytearray("", encoding="utf-8"), custom_headers=None, raw=False, **operation_config):
"""
Get '' as byte array
:param byte_path: '' as byte array
:type byte_path: bytearray
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/byte/empty/{bytePath}'
path_format_arguments = {
'bytePath': self._serialize.url("byte_path", byte_path, 'bytearray')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def byte_null(
self, byte_path, custom_headers=None, raw=False, **operation_config):
"""
Get null as byte array (should throw)
:param byte_path: null as byte array (should throw)
:type byte_path: bytearray
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/byte/null/{bytePath}'
path_format_arguments = {
'bytePath': self._serialize.url("byte_path", byte_path, 'bytearray')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def date_valid(
self, date_path, custom_headers=None, raw=False, **operation_config):
"""
Get '2012-01-01' as date
:param date_path: '2012-01-01' as date
:type date_path: date
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/date/2012-01-01/{datePath}'
path_format_arguments = {
'datePath': self._serialize.url("date_path", date_path, 'date')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def date_null(
self, date_path, custom_headers=None, raw=False, **operation_config):
"""
Get null as date - this should throw or be unusable on the client
side, depending on date representation
:param date_path: null as date (should throw)
:type date_path: date
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/date/null/{datePath}'
path_format_arguments = {
'datePath': self._serialize.url("date_path", date_path, 'date')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def date_time_valid(
self, date_time_path, custom_headers=None, raw=False, **operation_config):
"""
Get '2012-01-01T01:01:01Z' as date-time
:param date_time_path: '2012-01-01T01:01:01Z' as date-time
:type date_time_path: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/datetime/2012-01-01T01%3A01%3A01Z/{dateTimePath}'
path_format_arguments = {
'dateTimePath': self._serialize.url("date_time_path", date_time_path, 'iso-8601')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def date_time_null(
self, date_time_path, custom_headers=None, raw=False, **operation_config):
"""
Get null as date-time, should be disallowed or throw depending on
representation of date-time
:param date_time_path: null as date-time
:type date_time_path: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/datetime/null/{dateTimePath}'
path_format_arguments = {
'dateTimePath': self._serialize.url("date_time_path", date_time_path, 'iso-8601')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [400]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def base64_url(
self, base64_url_path, custom_headers=None, raw=False, **operation_config):
"""
Get 'lorem' encoded value as 'bG9yZW0' (base64url)
:param base64_url_path: base64url encoded value
:type base64_url_path: bytes
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/string/bG9yZW0/{base64UrlPath}'
path_format_arguments = {
'base64UrlPath': self._serialize.url("base64_url_path", base64_url_path, 'base64')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def array_csv_in_path(
self, array_path, custom_headers=None, raw=False, **operation_config):
"""
Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' ,
null, ''] using the csv-array format
:param array_path: an array of string ['ArrayPath1', 'begin!*'();:@
&=+$,/?#[]end' , null, ''] using the csv-array format
:type array_path: list of str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath}'
path_format_arguments = {
'arrayPath': self._serialize.url("array_path", array_path, '[str]', div=',')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def unix_time_url(
self, unix_time_url_path, custom_headers=None, raw=False, **operation_config):
"""
Get the date 2016-04-13 encoded value as '1460505600' (Unix time)
:param unix_time_url_path: Unix time encoded value
:type unix_time_url_path: datetime
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/paths/int/1460505600/{unixTimeUrlPath}'
path_format_arguments = {
'unixTimeUrlPath': self._serialize.url("unix_time_url_path", unix_time_url_path, 'unix-time')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response<|fim▁end|>
|
# Construct URL
url = '/paths/string/unicode/{stringPath}'
path_format_arguments = {
'stringPath': self._serialize.url("string_path", string_path, 'str')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.